1use 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
30fn 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) }
35fn enc_txt_opt(s: &Option<String>) -> Result<Option<String>, String> {
37 s.as_deref().map(enc_txt).transpose()
38}
39
40pub(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#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct PendingChannelKey {
53 pub id: i64,
55 pub channel_id: String,
56 pub epoch: u64,
57 pub key: [u8; 32],
58 pub sender: String,
60 pub received_at: i64,
61}
62
63const MAX_PARKED_PER_CHANNEL: usize = 4;
69const MAX_PARKED_PER_COMMUNITY: usize = 64;
70
71pub 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 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
124pub fn get_pending_channel_keys(community_id: &str) -> Result<Vec<PendingChannelKey>, String> {
126 let conn = super::get_db_connection_guard_static()?;
127 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 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
155pub 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 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 if dec_key(¤t)? != 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
208pub 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
216pub 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
227pub 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#[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
251fn 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 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
273pub 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 store_epoch_key_tx(&tx, community_id, channel_id, new_epoch, new_key)?;
290 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
316pub 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 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
367pub 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
393pub 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
415pub 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
426pub 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
436pub 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
451pub 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
481pub 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
506pub 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
514pub 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
525pub 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
535pub 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
552pub 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
572pub 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
580pub 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
588pub 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
602pub 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
614pub 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
626pub 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
652pub 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
667struct 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
686pub 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
692fn 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 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
711pub 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
721pub 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
737pub 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
752pub 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#[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 pub expires_at: i64,
776 pub sent_at: i64,
778 pub ends_at: i64,
781}
782
783pub 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 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 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 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
830pub 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
850pub 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
858const INVITE_LIFETIME_FROM: &str = "CASE WHEN sent_at > 0 THEN sent_at ELSE received_at END";
860
861pub 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
871pub 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
888pub 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
911pub 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
950pub 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
967pub 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
978pub 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
991pub 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#[derive(Debug, Clone, serde::Serialize)]
1021pub struct PublicInviteRecord {
1022 pub token: String,
1024 pub community_id: String,
1025 pub url: String,
1026 pub expires_at: Option<i64>,
1027 pub created_at: i64,
1028 pub label: Option<String>,
1030 #[serde(default)]
1032 pub join_count: u64,
1033}
1034
1035pub 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 let enc_token = enc_txt(token)?;
1048 let enc_url = enc_txt(url)?;
1049 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
1061pub fn list_public_invites(community_id: &str) -> Result<Vec<PublicInviteRecord>, String> {
1063 let conn = super::get_db_connection_guard_static()?;
1064 let mut stmt = conn
1065 .prepare(
1066 "SELECT token, community_id, url, expires_at, created_at, label
1067 FROM community_public_invites WHERE community_id = ?1 ORDER BY created_at DESC",
1068 )
1069 .map_err(|e| e.to_string())?;
1070 let rows = stmt
1071 .query_map(params![community_id], |r| {
1072 Ok(PublicInviteRecord {
1073 token: dec_txt(&r.get::<_, String>(0)?),
1074 community_id: r.get(1)?,
1075 url: dec_txt(&r.get::<_, String>(2)?),
1076 expires_at: r.get(3)?,
1077 created_at: r.get(4)?,
1078 label: r.get::<_, Option<String>>(5)?.map(|s| dec_txt(&s)),
1079 join_count: 0,
1080 })
1081 })
1082 .map_err(|e| e.to_string())?;
1083 let mut out = Vec::new();
1084 for row in rows {
1085 out.push(row.map_err(|e| e.to_string())?);
1086 }
1087 if let Some(me) = crate::state::my_public_key() {
1089 if let Ok(counts) = community_invite_join_counts(community_id, &me) {
1090 let unlabeled = out.iter().filter(|r| r.label.as_deref().is_none_or(str::is_empty)).count();
1093 for rec in &mut out {
1094 match rec.label.as_deref() {
1095 Some(l) if !l.is_empty() => rec.join_count = counts.get(l).copied().unwrap_or(0),
1096 _ if unlabeled == 1 => rec.join_count = counts.get("").copied().unwrap_or(0),
1097 _ => {}
1098 }
1099 }
1100 }
1101 }
1102 Ok(out)
1103}
1104
1105pub fn delete_public_invite(token: &str) -> Result<(), String> {
1107 let conn = super::get_write_connection_guard_static()?;
1108 let rows: Vec<(i64, String)> = {
1111 let mut stmt = conn
1112 .prepare("SELECT rowid, token FROM community_public_invites")
1113 .map_err(|e| e.to_string())?;
1114 let mapped = stmt
1115 .query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)))
1116 .map_err(|e| e.to_string())?;
1117 mapped.filter_map(|r| r.ok()).collect()
1118 };
1119 for (rowid, stored) in rows {
1120 if dec_txt(&stored) == token {
1121 conn.execute("DELETE FROM community_public_invites WHERE rowid = ?1", params![rowid])
1122 .map_err(|e| format!("delete public invite: {e}"))?;
1123 }
1124 }
1125 Ok(())
1126}
1127
1128pub fn list_all_public_invites() -> Result<Vec<PublicInviteRecord>, String> {
1130 let conn = super::get_db_connection_guard_static()?;
1131 let mut stmt = conn
1132 .prepare(
1133 "SELECT token, community_id, url, expires_at, created_at, label
1134 FROM community_public_invites ORDER BY created_at DESC",
1135 )
1136 .map_err(|e| e.to_string())?;
1137 let rows = stmt
1138 .query_map([], |r| {
1139 Ok(PublicInviteRecord {
1140 token: dec_txt(&r.get::<_, String>(0)?),
1141 community_id: r.get(1)?,
1142 url: dec_txt(&r.get::<_, String>(2)?),
1143 expires_at: r.get(3)?,
1144 created_at: r.get(4)?,
1145 label: r.get::<_, Option<String>>(5)?.map(|s| dec_txt(&s)),
1146 join_count: 0,
1147 })
1148 })
1149 .map_err(|e| e.to_string())?;
1150 let mut out = Vec::new();
1151 for row in rows {
1152 out.push(row.map_err(|e| e.to_string())?);
1153 }
1154 Ok(out)
1155}
1156
1157pub fn delete_community(community_id: &str) -> Result<(), String> {
1162 let out = delete_community_inner(community_id, false);
1163 crate::community::v2::realtime::invalidate_held_v2_community(community_id);
1164 out
1165}
1166
1167pub fn delete_community_retain_keys(community_id: &str) -> Result<(), String> {
1173 let out = delete_community_inner(community_id, true);
1174 crate::community::v2::realtime::invalidate_held_v2_community(community_id);
1175 out
1176}
1177
1178fn delete_community_inner(community_id: &str, retain_keys: bool) -> Result<(), String> {
1179 let conn = super::get_write_connection_guard_static()?;
1180 let tx = conn.unchecked_transaction().map_err(|e| format!("delete community tx: {e}"))?;
1183 for sql in [
1184 Some("DELETE FROM communities WHERE community_id = ?1"),
1185 Some("DELETE FROM community_channels WHERE community_id = ?1"),
1186 (!retain_keys).then_some("DELETE FROM community_epoch_keys WHERE community_id = ?1"),
1190 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:%')"),
1192 Some("DELETE FROM community_public_invites WHERE community_id = ?1"),
1193 Some("DELETE FROM community_invite_link_sets WHERE community_id = ?1"),
1194 Some("DELETE FROM pending_community_invites WHERE community_id = ?1"),
1195 Some("DELETE FROM pending_channel_keys WHERE community_id = ?1"),
1201 Some("DELETE FROM community_edition_heads WHERE community_id = ?1"),
1204 Some("DELETE FROM community_bans WHERE community_id = ?1"),
1205 Some("DELETE FROM community_writers WHERE community_id = ?1"),
1206 Some("DELETE FROM community_held_wraps WHERE community_id = ?1"),
1207 Some("DELETE FROM community_control_wraps WHERE community_id = ?1"),
1209 Some("DELETE FROM settings WHERE key LIKE 'ctl_reads:' || ?1 || '%'"),
1210 Some("DELETE FROM settings WHERE key LIKE 'pln_reads:' || ?1 || '%'"),
1211 Some("DELETE FROM community_guestbook_wraps WHERE community_id = ?1"),
1212 Some("DELETE FROM settings WHERE key = 'gbk_reads:' || ?1"),
1213 Some("DELETE FROM settings WHERE key = 'gb_reads:' || ?1"),
1214 Some("DELETE FROM community_audit_local WHERE community_id = ?1"),
1215 Some("DELETE FROM settings WHERE key LIKE 'writer_postable:' || ?1 || ':%'"),
1216 Some("DELETE FROM settings WHERE key LIKE 'writer_cert:' || ?1 || ':%'"),
1217 Some("DELETE FROM settings WHERE key LIKE 'writer_retract:' || ?1 || ':%'"),
1218 Some("DELETE FROM settings WHERE key LIKE 'writer_retract_by:' || ?1 || ':%'"),
1219 Some("DELETE FROM community_owed_authors WHERE book IN (SELECT book FROM community_guestbook_books WHERE community_id = ?1)"),
1220 Some("DELETE FROM settings WHERE key = 'departures_seen:' || ?1"),
1221 Some("DELETE FROM community_departures_seen WHERE book IN (SELECT book FROM community_guestbook_books WHERE community_id = ?1)"),
1222 ]
1223 .into_iter()
1224 .flatten()
1225 {
1226 tx.execute(sql, params![community_id])
1227 .map_err(|e| format!("delete community: {e}"))?;
1228 }
1229 tx.commit().map_err(|e| format!("delete community commit: {e}"))?;
1230 roster_cache().lock().unwrap_or_else(|e| e.into_inner()).moved(community_id);
1231 departures_seen_cache().lock().unwrap_or_else(|e| e.into_inner()).moved(community_id);
1232 if let Some(cid) = crate::community::id32_from_hex(community_id) {
1233 banlist_cache().write().unwrap_or_else(|e| e.into_inner()).remove(&cid);
1234 }
1235 forget_community_channels(community_id);
1236 Ok(())
1241}
1242
1243pub fn community_member_activity(community_id: &str) -> Result<Vec<(String, u64)>, String> {
1250 community_member_activity_capped(community_id, true)
1251}
1252
1253pub fn community_member_activity_capped(community_id: &str, capped: bool) -> Result<Vec<(String, u64)>, String> {
1258 member_activity(community_id, capped, false)
1259}
1260
1261pub fn community_member_activity_strict(community_id: &str) -> Result<Vec<(String, u64)>, String> {
1264 member_activity(community_id, false, true)
1265}
1266
1267fn activity_sql(placeholders: &str) -> String {
1270 let sys = crate::stored_event::event_kind::APPLICATION_SPECIFIC;
1271 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")
1272}
1273
1274fn flagged_sql(placeholders: &str, strict: bool) -> String {
1277 let sys = crate::stored_event::event_kind::APPLICATION_SPECIFIC;
1278 let read = |sign: &str| format!("SELECT npub FROM events WHERE chat_id IN ({placeholders}) AND kind != {sys} AND npub IS NOT NULL AND {sign}");
1279 if strict { format!("{} UNION {}", read(HELD_POST), read(WRITER_POST)) } else { format!("SELECT DISTINCT npub FROM ({})", read(HELD_POST)) }
1280}
1281
1282pub(crate) const HELD_POST: &str = "instr(tags, '[\"unauthorized\"]') > 0";
1285pub(crate) const WRITER_POST: &str = "instr(tags, '[\"writer\"]') > 0";
1286
1287fn member_activity(community_id: &str, capped: bool, strict: bool) -> Result<Vec<(String, u64)>, String> {
1290 let grant_stamp = if strict { 0 } else { now_secs() as u64 };
1291 const COMMUNITY_MEMBER_CAP: usize = 500;
1294 use std::collections::HashMap;
1295
1296 if !community_held(&CommunityId(hex_id_to_32(community_id)?))? {
1298 return Ok(Vec::new());
1299 }
1300
1301 let chat_ints = community_chat_row_ids(community_id)?;
1302
1303 let sys = crate::stored_event::event_kind::APPLICATION_SPECIFIC;
1306
1307 let mut active: HashMap<String, u64> = HashMap::new();
1312 let mut left: HashMap<String, u64> = HashMap::new();
1313 if !chat_ints.is_empty() {
1316 let conn = super::get_db_connection_guard_static()?;
1317 let placeholders = chat_ints.iter().map(|_| "?").collect::<Vec<_>>().join(",");
1318
1319 {
1320 let mut stmt = conn.prepare(&activity_sql(&placeholders)).map_err(|e| e.to_string())?;
1322 let rows = stmt
1323 .query_map(rusqlite::params_from_iter(chat_ints.iter()), |r| {
1324 Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.max(0) as u64))
1325 })
1326 .map_err(|e| e.to_string())?;
1327 for row in rows {
1328 let (npub, at) = row.map_err(|e| e.to_string())?;
1329 let newest = active.entry(npub).or_insert(at);
1330 *newest = (*newest).max(at);
1331 }
1332 }
1333
1334 {
1337 let excluded = if strict { format!("({HELD_POST} OR {WRITER_POST})") } else { HELD_POST.to_string() };
1338 let mut stmt = conn.prepare(&flagged_sql(&placeholders, strict)).map_err(|e| e.to_string())?;
1339 let binds = chat_ints.iter().chain(chat_ints.iter().filter(|_| strict));
1340 let flagged: Vec<String> = stmt.query_map(rusqlite::params_from_iter(binds), |r| r.get(0)).map_err(|e| e.to_string())?.flatten().collect();
1341 let sql = format!("SELECT MAX(created_at) FROM events WHERE chat_id IN ({placeholders}) AND kind != {sys} AND npub = ? AND NOT {excluded}");
1342 for npub in flagged {
1343 let mut args: Vec<rusqlite::types::Value> = chat_ints.iter().map(|i| rusqlite::types::Value::Integer(*i)).collect();
1344 args.push(npub.clone().into());
1345 let newest: Option<i64> = conn.query_row(&sql, rusqlite::params_from_iter(args), |r| r.get(0)).map_err(|e| e.to_string())?;
1346 match newest {
1347 Some(at) => active.insert(npub, at.max(0) as u64),
1348 None => active.remove(&npub),
1349 };
1350 }
1351 }
1352
1353 {
1355 let sql = format!(
1356 "SELECT npub, created_at, tags FROM events \
1357 WHERE chat_id IN ({placeholders}) AND kind = {sys} AND npub IS NOT NULL AND npub != ''"
1358 );
1359 let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
1360 let rows = stmt
1361 .query_map(rusqlite::params_from_iter(chat_ints.iter()), |r| {
1362 Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.max(0) as u64, r.get::<_, String>(2)?))
1363 })
1364 .map_err(|e| e.to_string())?
1365 .collect::<Result<Vec<_>, _>>()
1366 .map_err(|e| e.to_string())?;
1367 drop(stmt);
1369 drop(conn);
1370 for (npub, at, tags_json) in rows {
1371 let etype = serde_json::from_str::<Vec<Vec<String>>>(&tags_json)
1373 .ok()
1374 .and_then(|tags| {
1375 tags.into_iter()
1376 .find(|t| t.first().map(|s| s == "event-type").unwrap_or(false))
1377 .and_then(|t| t.into_iter().nth(1))
1378 });
1379 match etype.as_deref() {
1380 Some("1") => {
1381 let e = active.entry(npub).or_insert(0);
1382 if at > *e { *e = at; }
1383 }
1384 Some("0") => {
1385 let e = left.entry(npub).or_insert(0);
1386 if at > *e { *e = at; }
1387 }
1388 _ => {}
1389 }
1390 }
1391 }
1392 }
1393
1394 let banned: std::collections::HashSet<String> = banned_set(community_id)
1396 .iter()
1397 .filter_map(|b| PublicKey::from_slice(b).ok())
1398 .filter_map(|pk| pk.to_bech32().ok())
1399 .collect();
1400
1401 let mut out: Vec<(String, u64)> = active
1403 .into_iter()
1404 .filter(|(npub, at)| !banned.contains(npub) && left.get(npub).is_none_or(|l| at >= l))
1405 .collect();
1406
1407 {
1414 let mut present: std::collections::HashSet<String> = out.iter().map(|(n, _)| n.clone()).collect();
1415 let mut reassert = |npub: String| {
1416 if !banned.contains(&npub) && present.insert(npub.clone()) {
1417 out.push((npub, grant_stamp));
1418 }
1419 };
1420 if let Ok(roles) = get_community_roles(community_id) {
1421 for g in &roles.grants {
1422 if g.role_ids.is_empty() {
1423 continue; }
1425 if let Some(b32) = PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()) {
1426 reassert(b32);
1427 }
1428 }
1429 }
1430 }
1431 out.sort_by_key(|m| std::cmp::Reverse(m.1));
1432 if capped {
1433 out.truncate(COMMUNITY_MEMBER_CAP);
1434 }
1435 Ok(out)
1436}
1437
1438pub fn community_invite_join_counts(
1444 community_id: &str,
1445 inviter: &PublicKey,
1446) -> Result<std::collections::HashMap<String, u64>, String> {
1447 use std::collections::{HashMap, HashSet};
1448 hex_id_to_32(community_id)?;
1449 let (hex, npub) = (inviter.to_hex(), inviter.to_bech32().unwrap_or_default());
1451 let (events, _) = get_guestbook(community_id)?;
1452 let mut per_label: HashMap<String, HashSet<PublicKey>> = HashMap::new();
1453 for e in &events {
1454 let crate::community::v2::guestbook::GuestbookEntry::Join { member, invited_by: Some((by, label)), .. } = &e.entry else {
1455 continue;
1456 };
1457 if by.eq_ignore_ascii_case(&hex) || *by == npub {
1458 per_label.entry(label.clone()).or_default().insert(*member);
1459 }
1460 }
1461 Ok(per_label.into_iter().map(|(k, v)| (k, v.len() as u64)).collect())
1462}
1463
1464#[derive(Debug, Clone)]
1468pub struct AuthorFootprint {
1469 pub npub: String,
1470 pub messages: u64,
1471 pub first_secs: u64,
1472 pub last_secs: u64,
1473}
1474
1475pub fn community_chat_row_ids(community_id: &str) -> Result<Vec<i64>, String> {
1479 let channel_ids = community_channel_ids(community_id)?;
1480 Ok(channel_ids.iter().filter_map(|c| super::id_cache::get_chat_id_by_identifier(c).ok()).collect())
1481}
1482
1483pub fn community_channel_ids(community_id: &str) -> Result<Vec<String>, String> {
1485 let conn = super::get_db_connection_guard_static()?;
1486 let mut stmt = conn
1487 .prepare("SELECT channel_id FROM community_channels WHERE community_id = ?1")
1488 .map_err(|e| e.to_string())?;
1489 let rows = stmt
1490 .query_map(params![community_id], |r| r.get::<_, String>(0))
1491 .map_err(|e| e.to_string())?;
1492 rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
1493}
1494
1495#[derive(Debug, Clone)]
1498pub struct StoredPolicy {
1499 pub policy_id: String,
1502 pub bytes: String,
1505 pub hash: String,
1506 pub enabled: bool,
1507 pub updated_at: u64,
1508}
1509
1510pub fn get_community_policies(community_id: &str) -> Result<Vec<StoredPolicy>, String> {
1513 let conn = super::get_db_connection_guard_static()?;
1514 let mut stmt = conn
1515 .prepare(
1516 "SELECT policy_id, bytes, hash, enabled, updated_at FROM community_policies \
1517 WHERE community_id = ?1 ORDER BY policy_id",
1518 )
1519 .map_err(|e| e.to_string())?;
1520 let rows = stmt
1521 .query_map(params![community_id], |r| {
1522 Ok(StoredPolicy {
1523 policy_id: r.get::<_, String>(0)?,
1524 bytes: dec_txt(&r.get::<_, String>(1)?),
1525 hash: r.get::<_, String>(2)?,
1526 enabled: r.get::<_, i64>(3)? != 0,
1527 updated_at: r.get::<_, i64>(4)?.max(0) as u64,
1528 })
1529 })
1530 .map_err(|e| e.to_string())?;
1531 rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
1532}
1533
1534pub fn set_community_policy(
1537 community_id: &str,
1538 policy_id: &str,
1539 bytes: &str,
1540 hash: &str,
1541 enabled: bool,
1542 updated_at: u64,
1543) -> Result<(), String> {
1544 let _seal = crate::crypto::gate::sealing();
1545 let conn = super::get_write_connection_guard_static()?;
1546 conn.execute(
1547 "INSERT INTO community_policies (community_id, policy_id, bytes, hash, enabled, updated_at)
1548 VALUES (?1, ?2, ?3, ?4, ?5, ?6)
1549 ON CONFLICT(community_id, policy_id) DO UPDATE SET bytes=?3, hash=?4, enabled=?5, updated_at=?6",
1550 params![community_id, policy_id, enc_txt(bytes)?, hash, enabled as i64, updated_at as i64],
1551 )
1552 .map_err(|e| format!("save policy: {e}"))?;
1553 Ok(())
1554}
1555
1556pub fn delete_community_policy(community_id: &str, policy_id: &str) -> Result<(), String> {
1557 let conn = super::get_write_connection_guard_static()?;
1558 conn.execute(
1559 "DELETE FROM community_policies WHERE community_id = ?1 AND policy_id = ?2",
1560 params![community_id, policy_id],
1561 )
1562 .map_err(|e| format!("delete policy: {e}"))?;
1563 Ok(())
1564}
1565
1566#[derive(Debug, Clone)]
1569pub struct PolicyMessage {
1570 pub id: String,
1573 pub npub: String,
1574 pub channel_id: String,
1576 pub at_ms: u64,
1578 pub text: String,
1579 pub mentions: u32,
1581}
1582
1583pub fn community_policy_messages(community_id: &str, limit: usize) -> Result<Vec<PolicyMessage>, String> {
1587 let channel_ids: Vec<String> = {
1588 let conn = super::get_db_connection_guard_static()?;
1589 let mut stmt = conn
1590 .prepare("SELECT channel_id FROM community_channels WHERE community_id = ?1")
1591 .map_err(|e| e.to_string())?;
1592 let rows = stmt.query_map(params![community_id], |r| r.get::<_, String>(0)).map_err(|e| e.to_string())?;
1593 rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())?
1594 };
1595 if channel_ids.is_empty() || limit == 0 {
1596 return Ok(Vec::new());
1597 }
1598 let mut chat_to_channel: std::collections::HashMap<i64, String> = std::collections::HashMap::new();
1600 for c in &channel_ids {
1601 if let Ok(row) = super::id_cache::get_chat_id_by_identifier(c) {
1602 chat_to_channel.insert(row, c.clone());
1603 }
1604 }
1605 if chat_to_channel.is_empty() {
1606 return Ok(Vec::new());
1607 }
1608 let text = crate::stored_event::event_kind::PRIVATE_DIRECT_MESSAGE;
1609 let chat_ints: Vec<i64> = chat_to_channel.keys().copied().collect();
1610 let rows: Vec<(String, String, i64, i64, String)> = {
1611 let conn = super::get_db_connection_guard_static()?;
1612 let placeholders = chat_ints.iter().map(|_| "?").collect::<Vec<_>>().join(",");
1613 let sql = format!(
1614 "SELECT id, npub, chat_id, created_at, content FROM events \
1615 WHERE chat_id IN ({placeholders}) AND kind = {text} \
1616 AND npub IS NOT NULL AND npub != '' \
1617 ORDER BY created_at DESC LIMIT {limit}"
1618 );
1619 let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
1620 let mapped = stmt
1621 .query_map(rusqlite::params_from_iter(chat_ints.iter()), |r| {
1622 Ok((
1623 r.get::<_, String>(0)?,
1624 r.get::<_, String>(1)?,
1625 r.get::<_, i64>(2)?,
1626 r.get::<_, i64>(3)?,
1627 r.get::<_, String>(4)?,
1628 ))
1629 })
1630 .map_err(|e| e.to_string())?;
1631 mapped.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())?
1632 };
1633 let mut out: Vec<PolicyMessage> = crate::crypto::open_batch(|at_rest| rows
1634 .into_iter()
1635 .filter_map(|(id, npub, chat_id, created_at, content)| {
1636 let channel_id = chat_to_channel.get(&chat_id)?.clone();
1637 let content = at_rest.open_or_keep(content);
1638 let mentions = crate::community::policy::matchers::count_mentions(&content);
1643 Some(PolicyMessage {
1644 id,
1645 npub,
1646 channel_id,
1647 at_ms: (created_at.max(0) as u64).saturating_mul(1000),
1648 text: content,
1649 mentions,
1650 })
1651 })
1652 .collect());
1653 out.reverse(); Ok(out)
1655}
1656
1657pub fn community_author_footprints(community_id: &str) -> Result<Vec<AuthorFootprint>, String> {
1661 let chat_ints = community_chat_row_ids(community_id)?;
1662 if chat_ints.is_empty() {
1663 return Ok(Vec::new());
1664 }
1665 let text = crate::stored_event::event_kind::PRIVATE_DIRECT_MESSAGE;
1666 let file = crate::stored_event::event_kind::FILE_ATTACHMENT;
1667 let conn = super::get_db_connection_guard_static()?;
1668 let placeholders = chat_ints.iter().map(|_| "?").collect::<Vec<_>>().join(",");
1669 let sql = format!(
1670 "SELECT npub, COUNT(*), MIN(created_at), MAX(created_at) FROM events \
1671 WHERE chat_id IN ({placeholders}) AND kind IN ({text}, {file}) \
1672 AND npub IS NOT NULL AND npub != '' \
1673 GROUP BY npub"
1674 );
1675 let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
1676 let rows = stmt
1677 .query_map(rusqlite::params_from_iter(chat_ints.iter()), |r| {
1678 Ok(AuthorFootprint {
1679 npub: r.get::<_, String>(0)?,
1680 messages: r.get::<_, i64>(1)?.max(0) as u64,
1681 first_secs: r.get::<_, i64>(2)?.max(0) as u64,
1682 last_secs: r.get::<_, i64>(3)?.max(0) as u64,
1683 })
1684 })
1685 .map_err(|e| e.to_string())?;
1686 rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
1687}
1688
1689pub fn community_recent_texts(community_id: &str, limit: usize) -> Result<Vec<(String, u64, String)>, String> {
1694 let chat_ints = community_chat_row_ids(community_id)?;
1695 if chat_ints.is_empty() || limit == 0 {
1696 return Ok(Vec::new());
1697 }
1698 let text = crate::stored_event::event_kind::PRIVATE_DIRECT_MESSAGE;
1699 let rows: Vec<(String, u64, String)> = {
1700 let conn = super::get_db_connection_guard_static()?;
1701 let placeholders = chat_ints.iter().map(|_| "?").collect::<Vec<_>>().join(",");
1702 let sql = format!(
1703 "SELECT npub, created_at, content FROM events \
1704 WHERE chat_id IN ({placeholders}) AND kind = {text} \
1705 AND npub IS NOT NULL AND npub != '' \
1706 ORDER BY created_at DESC LIMIT {limit}"
1707 );
1708 let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
1709 let mapped = stmt
1710 .query_map(rusqlite::params_from_iter(chat_ints.iter()), |r| {
1711 Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.max(0) as u64, r.get::<_, String>(2)?))
1712 })
1713 .map_err(|e| e.to_string())?;
1714 mapped.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())?
1715 };
1716 Ok(crate::crypto::open_batch(|at_rest| {
1717 rows.into_iter().map(|(npub, at, content)| (npub, at, at_rest.open_or_keep(content))).collect()
1718 }))
1719}
1720
1721type BanSet = std::sync::Arc<std::collections::HashSet<[u8; 32]>>;
1734struct BanlistCache;
1735type BanlistMap = std::sync::RwLock<std::collections::HashMap<[u8; 32], BanSet>>;
1736
1737fn banlist_cache() -> std::sync::Arc<BanlistMap> {
1738 crate::db::current_session().scoped::<BanlistCache, BanlistMap>()
1739}
1740
1741fn empty_ban_set() -> BanSet {
1743 static EMPTY: std::sync::LazyLock<BanSet> = std::sync::LazyLock::new(Default::default);
1744 std::sync::Arc::clone(&EMPTY)
1745}
1746
1747fn ban_set_from_hexes(hexes: &[String]) -> BanSet {
1748 let set: std::collections::HashSet<[u8; 32]> =
1749 hexes.iter().filter_map(|h| crate::simd::hex::hex_to_bytes_32_checked(h)).collect();
1750 if set.is_empty() { empty_ban_set() } else { std::sync::Arc::new(set) }
1751}
1752
1753pub fn clear_banlist_cache() {
1755 *banlist_cache().write().unwrap_or_else(|e| e.into_inner()) = Default::default();
1756}
1757
1758pub fn banned_set_of(community: &[u8; 32]) -> BanSet {
1760 let cache = banlist_cache();
1761 if let Some(set) = cache.read().unwrap_or_else(|e| e.into_inner()).get(community) {
1762 return std::sync::Arc::clone(set);
1763 }
1764 let set = ban_set_from_hexes(&get_community_banlist(&crate::simd::hex::bytes_to_hex_32(community)).unwrap_or_default());
1765 cache.write().unwrap_or_else(|e| e.into_inner()).insert(*community, std::sync::Arc::clone(&set));
1766 set
1767}
1768
1769pub fn banned_set(community_id: &str) -> BanSet {
1772 match crate::community::id32_from_hex(community_id) {
1773 Some(cid) => banned_set_of(&cid),
1774 None => ban_set_from_hexes(&get_community_banlist(community_id).unwrap_or_default()),
1775 }
1776}
1777
1778pub fn is_author_banned(community_id: &str, author: &PublicKey) -> bool {
1781 let set = banned_set(community_id);
1782 !set.is_empty() && set.contains(author.as_bytes())
1783}
1784
1785pub fn is_author_banned_in(community: &[u8; 32], author: &PublicKey) -> bool {
1787 let set = banned_set_of(community);
1788 !set.is_empty() && set.contains(author.as_bytes())
1789}
1790
1791fn forget_console_verdict(community_id: &str) {
1797 crate::VectorCore::invalidate_raid_report(community_id);
1798}
1799
1800pub fn set_community_banlist(community_id: &str, banned_hex: &[String], at: i64) -> Result<bool, String> {
1803 let before: std::collections::BTreeSet<String> = get_community_banlist(community_id).unwrap_or_default().into_iter().collect();
1804 let _seal = crate::crypto::gate::sealing();
1805 let conn = super::get_write_connection_guard_static()?;
1806 let current_at: Option<i64> = conn
1813 .query_row("SELECT banlist_at FROM communities WHERE community_id = ?1", params![community_id], |r| r.get(0))
1814 .optional()
1815 .map_err(|e| format!("read banlist_at: {e}"))?
1816 .flatten();
1817 if current_at.is_some_and(|have| have > at) {
1818 crate::log_warn!(
1819 "[Banlist] refused a stale edition (v{at} behind held v{}) — un-banning is the fail-open direction",
1820 current_at.unwrap_or(0)
1821 );
1822 return Ok(false);
1823 }
1824 let tx = conn.unchecked_transaction().map_err(|e| format!("banlist tx: {e}"))?;
1830 tx.execute("DELETE FROM community_bans WHERE community_id = ?1", params![community_id])
1831 .map_err(|e| format!("clear banlist: {e}"))?;
1832 {
1833 let mut ins = tx
1834 .prepare("INSERT INTO community_bans (community_id, npub) VALUES (?1, ?2)")
1835 .map_err(|e| format!("prepare banlist insert: {e}"))?;
1836 let joinable: std::collections::BTreeSet<String> = banned_hex
1840 .iter()
1841 .map(|hex| {
1842 PublicKey::from_hex(hex)
1843 .ok()
1844 .and_then(|pk| pk.to_bech32().ok())
1845 .unwrap_or_else(|| hex.clone())
1846 })
1847 .collect();
1848 crate::crypto::seal_batch(|seal| {
1849 for npub in &joinable {
1850 ins.execute(params![community_id, seal.seal(npub)?])
1851 .map_err(|e| format!("insert ban: {e}"))?;
1852 }
1853 Ok::<_, String>(())
1854 })?;
1855 }
1856 tx.execute(
1857 "UPDATE communities SET banlist_at = ?1 WHERE community_id = ?2",
1858 params![at, community_id],
1859 )
1860 .map_err(|e| format!("set banlist_at: {e}"))?;
1861 tx.commit().map_err(|e| format!("commit banlist: {e}"))?;
1862 forget_console_verdict(community_id);
1863 if let Some(cid) = crate::community::id32_from_hex(community_id) {
1866 banlist_cache().write().unwrap_or_else(|e| e.into_inner()).insert(cid, ban_set_from_hexes(banned_hex));
1867 }
1868 Ok(before != banned_hex.iter().cloned().collect())
1869}
1870
1871pub fn get_community_ban_marks(community_id: &str) -> Result<std::collections::BTreeMap<String, u64>, String> {
1876 let conn = super::get_db_connection_guard_static()?;
1877 let json: Option<String> = conn
1878 .query_row(
1879 "SELECT banlist_marks FROM communities WHERE community_id = ?1",
1880 params![community_id],
1881 |r| r.get(0),
1882 )
1883 .optional()
1884 .map_err(|e| format!("get ban marks: {e}"))?;
1885 Ok(json.and_then(|j| serde_json::from_str(&dec_txt(&j)).ok()).unwrap_or_default())
1886}
1887
1888pub fn merge_community_ban_marks(community_id: &str, marks: &std::collections::BTreeMap<String, u64>) -> Result<bool, String> {
1893 let _seal = crate::crypto::gate::sealing();
1894 if marks.is_empty() {
1895 return Ok(false);
1896 }
1897 let mut stored = get_community_ban_marks(community_id)?;
1898 let mut changed = false;
1899 for (npub, at) in marks {
1900 let slot = stored.entry(npub.clone()).or_insert(0);
1901 if *at > *slot {
1902 *slot = *at;
1903 changed = true;
1904 }
1905 }
1906 if !changed {
1907 return Ok(false);
1908 }
1909 let json = enc_txt(&serde_json::to_string(&stored).map_err(|e| e.to_string())?)?;
1910 let conn = super::get_write_connection_guard_static()?;
1911 conn.execute(
1912 "UPDATE communities SET banlist_marks = ?1 WHERE community_id = ?2",
1913 params![json, community_id],
1914 )
1915 .map_err(|e| format!("set ban marks: {e}"))?;
1916 Ok(true)
1917}
1918
1919pub fn get_community_banlist_at(community_id: &str) -> Result<i64, String> {
1922 let conn = super::get_db_connection_guard_static()?;
1923 let at: Option<i64> = conn
1924 .query_row(
1925 "SELECT banlist_at FROM communities WHERE community_id = ?1",
1926 params![community_id],
1927 |r| r.get(0),
1928 )
1929 .optional()
1930 .map_err(|e| format!("get banlist_at: {e}"))?;
1931 Ok(at.unwrap_or(0))
1932}
1933
1934pub fn set_community_roles(
1939 community_id: &str,
1940 roles: &crate::community::roles::CommunityRoles,
1941 at: i64,
1942) -> Result<(), String> {
1943 let _seal = crate::crypto::gate::sealing();
1944 forget_console_verdict(community_id);
1945 let json = enc_txt(&serde_json::to_string(roles).map_err(|e| e.to_string())?)?;
1946 let conn = super::get_write_connection_guard_static()?;
1947 conn.execute(
1948 "UPDATE communities SET roles = ?1, roles_at = ?2 WHERE community_id = ?3",
1949 params![json, at, community_id],
1950 )
1951 .map_err(|e| format!("set roles: {e}"))?;
1952 roster_cache().lock().unwrap_or_else(|e| e.into_inner()).moved(community_id);
1953 drop(conn);
1954 bump_membership_generation();
1955 Ok(())
1956}
1957
1958type RosterCache = Parsed<std::sync::Arc<crate::community::roles::CommunityRoles>, 16>;
1960
1961fn roster_cache() -> std::sync::Arc<std::sync::Mutex<RosterCache>> {
1962 struct Key;
1963 super::current_session().scoped::<Key, std::sync::Mutex<RosterCache>>()
1964}
1965
1966pub fn get_community_roles(
1967 community_id: &str,
1968) -> Result<crate::community::roles::CommunityRoles, String> {
1969 get_community_roles_shared(community_id).map(std::sync::Arc::unwrap_or_clone)
1970}
1971
1972pub fn get_community_roles_shared(community_id: &str) -> Result<std::sync::Arc<crate::community::roles::CommunityRoles>, String> {
1974 let cache = roster_cache();
1975 let generation = {
1976 let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
1977 if let Some(hit) = held.get(community_id) {
1978 return Ok(hit);
1979 }
1980 held.generation(community_id)
1981 };
1982 let json = {
1983 let conn = super::get_db_connection_guard_static()?;
1984 stored_roles(&conn, community_id).map_err(|e| format!("get roles: {e}"))?
1985 };
1986 let roles = std::sync::Arc::new(parse_roles(json, dec_txt));
1987 cache.lock().unwrap_or_else(|e| e.into_inner()).put(community_id, generation, roles.clone());
1988 Ok(roles)
1989}
1990
1991fn stored_roles(conn: &rusqlite::Connection, community_id: &str) -> rusqlite::Result<Option<String>> {
1993 conn.query_row("SELECT roles FROM communities WHERE community_id = ?1", params![community_id], |r| r.get(0))
1994 .optional()
1995}
1996
1997fn parse_roles(json: Option<String>, open: impl FnOnce(&str) -> String) -> crate::community::roles::CommunityRoles {
1999 json.and_then(|j| serde_json::from_str(&open(&j)).ok()).unwrap_or_default()
2000}
2001
2002pub fn get_community_roles_at(community_id: &str) -> Result<i64, String> {
2004 let conn = super::get_db_connection_guard_static()?;
2005 let at: Option<i64> = conn
2006 .query_row(
2007 "SELECT roles_at FROM communities WHERE community_id = ?1",
2008 params![community_id],
2009 |r| r.get(0),
2010 )
2011 .optional()
2012 .map_err(|e| format!("get roles_at: {e}"))?;
2013 Ok(at.unwrap_or(0))
2014}
2015
2016pub fn set_edition_head(community_id: &str, entity_id: &str, version: u64, self_hash: &[u8; 32]) -> Result<(), String> {
2021 set_edition_head_inner(community_id, entity_id, version, self_hash, None, None, None)
2022}
2023
2024pub fn set_edition_head_with_id(community_id: &str, entity_id: &str, version: u64, self_hash: &[u8; 32], inner_id: &[u8; 32]) -> Result<(), String> {
2027 set_edition_head_inner(community_id, entity_id, version, self_hash, Some(inner_id), None, None)
2028}
2029
2030pub fn delete_edition_head(community_id: &str, entity_id: &str) -> Result<(), String> {
2044 let conn = super::get_write_connection_guard_static()?;
2045 conn.execute(
2046 "DELETE FROM community_edition_heads WHERE community_id = ?1 AND entity_id = ?2",
2047 params![community_id, entity_id],
2048 )
2049 .map_err(|e| format!("delete edition head: {e}"))?;
2050 Ok(())
2051}
2052
2053pub 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> {
2054 set_edition_head_inner(community_id, entity_id, version, self_hash, Some(inner_id), Some(author), Some(epoch))
2055}
2056
2057#[allow(clippy::too_many_arguments)]
2061pub 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> {
2062 set_family_head_on(&*super::get_write_connection_guard_static()?, community_id, entity_id, version, self_hash, inner_id, author, epoch, family)
2063}
2064
2065#[allow(clippy::too_many_arguments)]
2066fn 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> {
2067 conn.execute(
2068 "INSERT INTO community_edition_heads (community_id, entity_id, version, self_hash, inner_id, epoch, author, family)
2069 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
2070 ON CONFLICT(community_id, entity_id) DO UPDATE SET
2071 version = excluded.version,
2072 self_hash = excluded.self_hash,
2073 inner_id = excluded.inner_id,
2074 epoch = excluded.epoch,
2075 author = excluded.author,
2076 family = excluded.family
2077 WHERE NOT (community_edition_heads.family IS 'a' AND excluded.family IS NOT 'a')
2078 AND (excluded.epoch > community_edition_heads.epoch
2079 OR (excluded.epoch = community_edition_heads.epoch AND excluded.version > community_edition_heads.version)
2080 OR (excluded.family = 'a' AND community_edition_heads.family IS NOT NULL AND community_edition_heads.family IS NOT 'a'))",
2081 params![community_id, entity_id, version as i64, self_hash.as_slice(), inner_id.as_slice(), epoch as i64, author.as_slice(), family],
2082 )
2083 .map_err(|e| format!("set edition head: {e}"))?;
2084 Ok(())
2085}
2086
2087type HeldFloorRow = (u64, u64, Vec<u8>, Option<Vec<u8>>, Option<Vec<u8>>, Option<String>);
2089
2090pub struct FloorWrites<'c> {
2092 conn: &'c rusqlite::Connection,
2093 community_id: &'c str,
2094 held: std::collections::HashMap<String, HeldFloorRow>,
2096 touched: std::collections::HashSet<String>,
2098}
2099
2100impl FloorWrites<'_> {
2101 #[allow(clippy::too_many_arguments)]
2103 fn already(&self, entity_id: &str, version: u64, self_hash: &[u8; 32], inner_id: &[u8; 32], author: &[u8; 32], epoch: u64, family: &str) -> bool {
2104 !self.touched.contains(entity_id)
2105 && self.held.get(entity_id).is_some_and(|(e, v, h, i, a, f)| {
2106 *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)
2107 })
2108 }
2109
2110 #[allow(clippy::too_many_arguments)]
2111 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> {
2112 if self.already(entity_id, version, self_hash, inner_id, author, epoch, family) {
2113 return Ok(());
2114 }
2115 self.touched.insert(entity_id.to_string());
2116 set_family_head_on(self.conn, self.community_id, entity_id, version, self_hash, inner_id, author, epoch, family)
2117 }
2118
2119 #[allow(clippy::too_many_arguments)]
2120 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> {
2121 if self.already(entity_id, version, self_hash, inner_id, author, epoch, family) {
2122 return Ok(());
2123 }
2124 self.touched.insert(entity_id.to_string());
2125 converge_family_head_on(self.conn, self.community_id, entity_id, version, self_hash, inner_id, author, epoch, Some(family))
2126 }
2127
2128 #[allow(clippy::too_many_arguments)]
2129 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> {
2130 if self.already(entity_id, version, self_hash, inner_id, author, epoch, family) {
2131 return Ok(());
2132 }
2133 self.touched.insert(entity_id.to_string());
2134 rebase_edition_head_on(self.conn, self.community_id, entity_id, version, self_hash, inner_id, author, epoch, family)
2135 }
2136}
2137
2138pub fn write_folded_heads(community_id: &str, write: impl FnOnce(&mut FloorWrites<'_>) -> Result<(), String>) -> Result<(), String> {
2140 let conn = super::get_write_connection_guard_static()?;
2141 let tx = conn.unchecked_transaction().map_err(|e| format!("floor writes tx: {e}"))?;
2142 let held = {
2143 let mut stmt = tx
2144 .prepare_cached("SELECT entity_id, epoch, version, self_hash, inner_id, author, family FROM community_edition_heads WHERE community_id = ?1")
2145 .map_err(|e| format!("floor writes: {e}"))?;
2146 let rows = stmt
2147 .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)?))))
2148 .map_err(|e| format!("floor writes: {e}"))?;
2149 rows.collect::<Result<_, _>>().map_err(|e| format!("floor writes: {e}"))?
2150 };
2151 let mut writes = FloorWrites { conn: &tx, community_id, held, touched: Default::default() };
2152 write(&mut writes)?;
2153 tx.commit().map_err(|e| format!("floor writes commit: {e}"))
2154}
2155
2156pub const FLOOR_AUTHORITY: &str = "a";
2158pub const FLOOR_CONTROL: &str = "c";
2160
2161pub fn edition_head_families(community_id: &str) -> Result<std::collections::HashMap<String, String>, String> {
2163 let conn = super::get_db_connection_guard_static()?;
2164 let mut stmt = conn
2165 .prepare("SELECT entity_id, family FROM community_edition_heads WHERE community_id = ?1 AND family IS NOT NULL")
2166 .map_err(|e| e.to_string())?;
2167 let rows = stmt
2168 .query_map(params![community_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))
2169 .map_err(|e| e.to_string())?;
2170 rows.collect::<Result<_, _>>().map_err(|e| e.to_string())
2171}
2172
2173fn 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> {
2174 let conn = super::get_write_connection_guard_static()?;
2175 conn.execute(
2181 "INSERT INTO community_edition_heads (community_id, entity_id, version, self_hash, inner_id, epoch, author)
2182 VALUES (?1, ?2, ?3, ?4, ?5, COALESCE(?6, (SELECT server_root_epoch FROM communities WHERE community_id = ?1), 0), ?7)
2183 ON CONFLICT(community_id, entity_id) DO UPDATE SET
2184 version = excluded.version,
2185 self_hash = excluded.self_hash,
2186 inner_id = excluded.inner_id,
2187 epoch = excluded.epoch,
2188 author = excluded.author
2189 WHERE excluded.epoch > community_edition_heads.epoch
2190 OR (excluded.epoch = community_edition_heads.epoch AND excluded.version > community_edition_heads.version)",
2191 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())],
2192 )
2193 .map_err(|e| format!("set edition head: {e}"))?;
2194 Ok(())
2195}
2196
2197pub 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> {
2204 converge_family_head_at_epoch(community_id, entity_id, version, self_hash, inner_id, author, epoch, None)
2205}
2206
2207#[allow(clippy::too_many_arguments)]
2209pub 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> {
2210 converge_family_head_on(&*super::get_write_connection_guard_static()?, community_id, entity_id, version, self_hash, inner_id, author, epoch, family)
2211}
2212
2213#[allow(clippy::too_many_arguments)]
2214fn 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> {
2215 conn.execute(
2216 "UPDATE community_edition_heads
2217 SET self_hash = ?4, inner_id = ?5, author = ?7
2218 WHERE community_id = ?1 AND entity_id = ?2
2219 AND version = ?3
2220 AND epoch = ?6
2221 AND (?8 IS NULL OR family IS NULL OR family = ?8)
2222 AND (self_hash IS NOT ?4 OR inner_id IS NOT ?5 OR author IS NOT ?7)",
2223 params![community_id, entity_id, version as i64, self_hash.as_slice(), inner_id.as_slice(), epoch as i64, author.as_slice(), family],
2224 )
2225 .map_err(|e| format!("converge edition head: {e}"))?;
2226 Ok(())
2227}
2228
2229#[allow(clippy::too_many_arguments)]
2235pub 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> {
2236 rebase_edition_head_on(&*super::get_write_connection_guard_static()?, community_id, entity_id, version, self_hash, inner_id, author, epoch, family)
2237}
2238
2239#[allow(clippy::too_many_arguments)]
2240fn 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> {
2241 conn.execute(
2242 "UPDATE community_edition_heads
2243 SET version = ?3, self_hash = ?4, inner_id = ?5, author = ?7, family = COALESCE(family, ?8)
2244 WHERE community_id = ?1 AND entity_id = ?2 AND epoch = ?6 AND (family IS NULL OR family = ?8)",
2245 params![community_id, entity_id, version as i64, self_hash.as_slice(), inner_id.as_slice(), epoch as i64, author.as_slice(), family],
2246 )
2247 .map_err(|e| format!("rebase edition head: {e}"))?;
2248 Ok(())
2249}
2250
2251#[allow(clippy::too_many_arguments)]
2255pub 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> {
2256 let conn = super::get_write_connection_guard_static()?;
2257 conn.execute(
2258 "UPDATE community_edition_heads SET self_hash = ?6, inner_id = ?7, author = ?8
2259 WHERE community_id = ?1 AND entity_id = ?2 AND epoch = ?3 AND version = ?4 AND self_hash = ?5",
2260 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()],
2261 )
2262 .map_err(|e| format!("heal edition head: {e}"))?;
2263 Ok(())
2264}
2265
2266pub fn get_edition_head_inner_id(community_id: &str, entity_id: &str) -> Result<Option<[u8; 32]>, String> {
2268 let conn = super::get_db_connection_guard_static()?;
2269 let row: Option<Option<Vec<u8>>> = conn
2270 .query_row(
2271 "SELECT inner_id FROM community_edition_heads WHERE community_id = ?1 AND entity_id = ?2",
2272 params![community_id, entity_id],
2273 |r| r.get(0),
2274 )
2275 .optional()
2276 .map_err(|e| format!("get edition head inner_id: {e}"))?;
2277 match row.flatten() {
2278 Some(blob) if blob.len() == 32 => {
2279 let mut h = [0u8; 32];
2280 h.copy_from_slice(&blob);
2281 Ok(Some(h))
2282 }
2283 _ => Ok(None),
2284 }
2285}
2286
2287pub fn get_edition_head(community_id: &str, entity_id: &str) -> Result<Option<(u64, [u8; 32])>, String> {
2290 let conn = super::get_db_connection_guard_static()?;
2291 let row: Option<(i64, Vec<u8>)> = conn
2292 .query_row(
2293 "SELECT version, self_hash FROM community_edition_heads WHERE community_id = ?1 AND entity_id = ?2",
2294 params![community_id, entity_id],
2295 |r| Ok((r.get(0)?, r.get(1)?)),
2296 )
2297 .optional()
2298 .map_err(|e| format!("get edition head: {e}"))?;
2299 match row {
2300 Some((v, hash)) if hash.len() == 32 => {
2301 let mut h = [0u8; 32];
2302 h.copy_from_slice(&hash);
2303 Ok(Some((v as u64, h)))
2304 }
2305 _ => Ok(None),
2306 }
2307}
2308
2309pub fn edition_head_entity_ids(community_id: &str) -> Result<std::collections::HashSet<String>, String> {
2314 let conn = super::get_db_connection_guard_static()?;
2315 let mut stmt = conn
2316 .prepare("SELECT entity_id FROM community_edition_heads WHERE community_id = ?1")
2317 .map_err(|e| e.to_string())?;
2318 let rows = stmt
2319 .query_map(params![community_id], |r| r.get::<_, String>(0))
2320 .map_err(|e| e.to_string())?;
2321 let mut out = std::collections::HashSet::new();
2322 for row in rows {
2323 out.insert(row.map_err(|e| e.to_string())?);
2324 }
2325 Ok(out)
2326}
2327
2328
2329type EditionHeadFull = (u64, u64, [u8; 32], Option<[u8; 32]>, Option<[u8; 32]>, Option<FloorFamily>);
2338
2339#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2341pub enum FloorFamily {
2342 Authority,
2343 Control,
2344 Other,
2346}
2347
2348impl FloorFamily {
2349 pub fn of(family: &str) -> Self {
2350 match family {
2351 FLOOR_AUTHORITY => FloorFamily::Authority,
2352 FLOOR_CONTROL => FloorFamily::Control,
2353 _ => FloorFamily::Other,
2354 }
2355 }
2356}
2357type EditionHead = (u64, u64, [u8; 32]);
2359
2360pub fn get_all_edition_heads_full(community_id: &str) -> Result<std::collections::HashMap<String, EditionHeadFull>, String> {
2361 let conn = super::get_db_connection_guard_static()?;
2362 let mut stmt = conn
2363 .prepare("SELECT entity_id, epoch, version, self_hash, inner_id, author, family FROM community_edition_heads WHERE community_id = ?1")
2364 .map_err(|e| e.to_string())?;
2365 let rows = stmt
2366 .query_map(params![community_id], |r| {
2367 Ok((
2368 r.get::<_, String>(0)?,
2369 r.get::<_, i64>(1)?,
2370 r.get::<_, i64>(2)?,
2371 r.get::<_, Vec<u8>>(3)?,
2372 r.get::<_, Option<Vec<u8>>>(4)?,
2373 r.get::<_, Option<Vec<u8>>>(5)?,
2374 r.get::<_, Option<String>>(6)?,
2375 ))
2376 })
2377 .map_err(|e| e.to_string())?;
2378 let blob32 = |b: Option<Vec<u8>>| {
2379 b.and_then(|b| {
2380 (b.len() == 32).then(|| {
2381 let mut i = [0u8; 32];
2382 i.copy_from_slice(&b);
2383 i
2384 })
2385 })
2386 };
2387 let mut out = std::collections::HashMap::new();
2388 for row in rows {
2389 let (entity, epoch, version, hash, inner, author, family) = row.map_err(|e| e.to_string())?;
2390 if hash.len() == 32 {
2391 let mut h = [0u8; 32];
2392 h.copy_from_slice(&hash);
2393 out.insert(entity, (epoch as u64, version as u64, h, blob32(inner), blob32(author), family.as_deref().map(FloorFamily::of)));
2394 }
2395 }
2396 Ok(out)
2397}
2398
2399pub fn get_all_edition_heads_epoched(community_id: &str) -> Result<std::collections::HashMap<String, EditionHead>, String> {
2400 let conn = super::get_db_connection_guard_static()?;
2401 let mut stmt = conn
2402 .prepare("SELECT entity_id, epoch, version, self_hash FROM community_edition_heads WHERE community_id = ?1")
2403 .map_err(|e| e.to_string())?;
2404 let rows = stmt
2405 .query_map(params![community_id], |r| {
2406 Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?, r.get::<_, i64>(2)?, r.get::<_, Vec<u8>>(3)?))
2407 })
2408 .map_err(|e| e.to_string())?;
2409 let mut out = std::collections::HashMap::new();
2410 for row in rows {
2411 let (entity, epoch, version, hash) = row.map_err(|e| e.to_string())?;
2412 if hash.len() == 32 {
2413 let mut h = [0u8; 32];
2414 h.copy_from_slice(&hash);
2415 out.insert(entity, (epoch as u64, version as u64, h));
2416 }
2417 }
2418 Ok(out)
2419}
2420
2421pub fn get_community_banlist(community_id: &str) -> Result<Vec<String>, String> {
2423 let _seal = crate::crypto::gate::sealing();
2425 let conn = super::get_db_connection_guard_static()?;
2426 let mut stmt = conn
2427 .prepare("SELECT npub FROM community_bans WHERE community_id = ?1")
2428 .map_err(|e| format!("prepare get banlist: {e}"))?;
2429 let rows = stmt
2430 .query_map(params![community_id], |r| r.get::<_, String>(0))
2431 .map_err(|e| format!("get banlist: {e}"))?;
2432 let mut out: Vec<String> = crate::crypto::open_batch(|at_rest| {
2434 rows.flatten()
2435 .map(|b| at_rest.open_or_keep(b))
2436 .map(|b| PublicKey::parse(&b).map(|pk| pk.to_hex()).unwrap_or(b))
2437 .collect()
2438 });
2439 if !out.is_empty() {
2440 return Ok(out);
2441 }
2442 drop(stmt);
2447 let legacy: Option<String> = conn
2448 .query_row(
2449 "SELECT banlist FROM communities WHERE community_id = ?1 AND banlist IS NOT NULL AND banlist != ''",
2450 params![community_id],
2451 |r| r.get(0),
2452 )
2453 .optional()
2454 .map_err(|e| format!("read legacy banlist: {e}"))?
2455 .flatten();
2456 let Some(blob) = legacy else { return Ok(out) };
2457 let decoded = dec_txt(&blob);
2458 let Ok(list) = serde_json::from_str::<Vec<String>>(&decoded) else { return Ok(out) };
2459 if list.is_empty() {
2460 return Ok(out);
2461 }
2462 let tx = conn.unchecked_transaction().map_err(|e| format!("adopt tx: {e}"))?;
2463 {
2464 let mut ins = tx
2465 .prepare("INSERT INTO community_bans (community_id, npub) VALUES (?1, ?2)")
2466 .map_err(|e| format!("prepare adopt: {e}"))?;
2467 let joinable: std::collections::BTreeSet<String> = list
2468 .iter()
2469 .map(|hex| {
2470 PublicKey::from_hex(hex)
2471 .ok()
2472 .and_then(|pk| pk.to_bech32().ok())
2473 .unwrap_or_else(|| hex.clone())
2474 })
2475 .collect();
2476 crate::crypto::seal_batch(|seal| {
2477 for npub in &joinable {
2478 ins.execute(params![community_id, seal.seal(npub)?]).map_err(|e| format!("adopt ban: {e}"))?;
2479 }
2480 Ok::<_, String>(())
2481 })?;
2482 }
2483 tx.execute("UPDATE communities SET banlist = '[]' WHERE community_id = ?1", params![community_id])
2485 .map_err(|e| format!("retire legacy banlist: {e}"))?;
2486 tx.commit().map_err(|e| format!("commit adopt: {e}"))?;
2487 crate::log_info!("[Banlist] adopted {} legacy ban(s) into community_bans", list.len());
2488 out = list;
2489 Ok(out)
2490}
2491
2492pub fn set_community_invite_registry(community_id: &str, link_locators: &[String]) -> Result<(), String> {
2496 let _seal = crate::crypto::gate::sealing();
2497 let json = enc_txt(&serde_json::to_string(link_locators).map_err(|e| e.to_string())?)?;
2498 let conn = super::get_write_connection_guard_static()?;
2499 conn.execute(
2500 "UPDATE communities SET invite_registry = ?1 WHERE community_id = ?2",
2501 params![json, community_id],
2502 )
2503 .map_err(|e| format!("set invite registry: {e}"))?;
2504 crate::notify::invalidate_communities();
2506 Ok(())
2507}
2508
2509pub fn community_ids_beyond_group_chat() -> Result<std::collections::HashSet<[u8; 32]>, String> {
2512 let conn = super::get_db_connection_guard_static()?;
2513 let mut stmt = conn
2514 .prepare(
2515 "SELECT c.community_id, c.invite_registry,
2516 (SELECT COUNT(*) FROM community_channels ch WHERE ch.community_id = c.community_id)
2517 FROM communities c",
2518 )
2519 .map_err(|e| format!("prepare community kinds: {e}"))?;
2520 let rows = stmt
2521 .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, i64>(2)?)))
2522 .map_err(|e| format!("query community kinds: {e}"))?
2523 .collect::<Result<Vec<_>, _>>()
2524 .map_err(|e| format!("read community kinds: {e}"))?;
2525 drop(stmt);
2527 drop(conn);
2528 let mut out = std::collections::HashSet::new();
2529 for (id, registry, channels) in rows {
2530 let links: Vec<String> = serde_json::from_str(&dec_txt(®istry)).unwrap_or_default();
2531 if channels > 1 || !links.is_empty() {
2532 out.extend(crate::community::id32_from_hex(&id));
2533 }
2534 }
2535 Ok(out)
2536}
2537
2538pub fn get_community_invite_registry(community_id: &str) -> Result<Vec<String>, String> {
2541 let conn = super::get_db_connection_guard_static()?;
2542 let json: Option<String> = conn
2543 .query_row(
2544 "SELECT invite_registry FROM communities WHERE community_id = ?1",
2545 params![community_id],
2546 |r| r.get(0),
2547 )
2548 .optional()
2549 .map_err(|e| format!("get invite registry: {e}"))?;
2550 Ok(json.and_then(|j| serde_json::from_str(&dec_txt(&j)).ok()).unwrap_or_default())
2551}
2552
2553pub struct InviteLinkSetRow {
2556 pub creator_hex: String,
2557 pub locators: Vec<String>,
2558}
2559
2560pub fn invite_link_set_creators(community_id: &str) -> Result<Vec<String>, String> {
2563 let conn = super::get_write_connection_guard_static()?;
2564 let mut stmt = conn
2565 .prepare("SELECT creator FROM community_invite_link_sets WHERE community_id = ?1")
2566 .map_err(|e| e.to_string())?;
2567 let rows = stmt
2568 .query_map(params![community_id], |r| r.get::<_, String>(0))
2569 .map_err(|e| e.to_string())?
2570 .filter_map(|r| r.ok())
2571 .map(|stored| dec_txt(&stored))
2572 .collect();
2573 Ok(rows)
2574}
2575
2576pub fn replace_invite_link_sets(community_id: &str, sets: &[InviteLinkSetRow]) -> Result<(), String> {
2580 let _seal = crate::crypto::gate::sealing();
2581 let mut conn = super::get_write_connection_guard_static()?;
2582 let tx = conn.transaction().map_err(|e| format!("invite-link-sets tx: {e}"))?;
2583 tx.execute("DELETE FROM community_invite_link_sets WHERE community_id = ?1", params![community_id])
2584 .map_err(|e| format!("clear invite-link-sets: {e}"))?;
2585 for s in sets {
2586 if s.locators.is_empty() {
2587 continue; }
2589 let enc_creator = enc_txt(&s.creator_hex)?;
2590 let enc_locators = enc_txt(&serde_json::to_string(&s.locators).map_err(|e| e.to_string())?)?;
2591 tx.execute(
2594 "INSERT INTO community_invite_link_sets (community_id, creator, locators) VALUES (?1, ?2, ?3)",
2595 params![community_id, enc_creator, enc_locators],
2596 )
2597 .map_err(|e| format!("insert invite-link-set: {e}"))?;
2598 }
2599 tx.commit().map_err(|e| format!("commit invite-link-sets: {e}"))?;
2600 Ok(())
2601}
2602
2603pub fn get_invite_link_sets(community_id: &str) -> Result<Vec<InviteLinkSetRow>, String> {
2606 let conn = super::get_db_connection_guard_static()?;
2607 let mut stmt = conn
2608 .prepare("SELECT creator, locators FROM community_invite_link_sets WHERE community_id = ?1")
2609 .map_err(|e| format!("prepare invite-link-sets: {e}"))?;
2610 let rows = stmt
2611 .query_map(params![community_id], |r| {
2612 let creator_hex: String = r.get(0)?;
2613 let json: String = r.get(1)?;
2614 Ok((creator_hex, json))
2615 })
2616 .map_err(|e| format!("query invite-link-sets: {e}"))?;
2617 let mut out = Vec::new();
2618 for row in rows {
2619 let (creator_hex, json) = row.map_err(|e| format!("row invite-link-sets: {e}"))?;
2620 let locators: Vec<String> = serde_json::from_str(&dec_txt(&json)).unwrap_or_default();
2621 out.push(InviteLinkSetRow { creator_hex: dec_txt(&creator_hex), locators });
2622 }
2623 Ok(out)
2624}
2625
2626pub fn set_community_dissolved(community_id: &str) -> Result<bool, String> {
2634 let conn = super::get_write_connection_guard_static()?;
2635 let changed = conn
2636 .execute(
2637 "UPDATE communities SET dissolved = 1 WHERE community_id = ?1 AND dissolved = 0",
2638 params![community_id],
2639 )
2640 .map_err(|e| format!("set dissolved: {e}"))?;
2641 crate::community::v2::realtime::invalidate_held_v2_community(community_id);
2642 Ok(changed > 0)
2643}
2644
2645pub fn get_community_dissolved(community_id: &str) -> Result<bool, String> {
2648 let conn = super::get_db_connection_guard_static()?;
2649 let v: Option<i64> = conn
2650 .query_row(
2651 "SELECT dissolved FROM communities WHERE community_id = ?1",
2652 params![community_id],
2653 |r| r.get(0),
2654 )
2655 .optional()
2656 .map_err(|e| format!("get dissolved: {e}"))?;
2657 Ok(v.unwrap_or(0) != 0)
2658}
2659
2660pub fn list_community_ids() -> Result<Vec<CommunityId>, String> {
2662 let conn = super::get_db_connection_guard_static()?;
2663 let mut stmt = conn
2664 .prepare("SELECT community_id FROM communities ORDER BY created_at")
2665 .map_err(|e| e.to_string())?;
2666 let rows = stmt
2667 .query_map([], |r| r.get::<_, String>(0))
2668 .map_err(|e| e.to_string())?;
2669 let mut ids = Vec::new();
2670 for row in rows {
2671 ids.push(CommunityId(hex_id_to_32(&row.map_err(|e| e.to_string())?)?));
2672 }
2673 Ok(ids)
2674}
2675
2676pub fn held_channel_ids() -> Result<std::collections::HashSet<String>, String> {
2678 let conn = super::get_db_connection_guard_static()?;
2679 let mut stmt = conn
2680 .prepare("SELECT ch.channel_id FROM community_channels ch JOIN communities c ON c.community_id = ch.community_id")
2681 .map_err(|e| e.to_string())?;
2682 let rows = stmt.query_map([], |r| r.get::<_, String>(0)).map_err(|e| e.to_string())?;
2683 rows.collect::<Result<_, _>>().map_err(|e| e.to_string())
2684}
2685
2686pub fn held_community_relays() -> Result<std::collections::HashSet<String>, String> {
2688 let sealed: Vec<String> = {
2689 let conn = super::get_db_connection_guard_static()?;
2690 let mut stmt = conn.prepare("SELECT relays FROM communities").map_err(|e| e.to_string())?;
2691 let rows = stmt.query_map([], |r| r.get::<_, String>(0)).map_err(|e| e.to_string())?;
2692 rows.collect::<Result<_, _>>().map_err(|e| e.to_string())?
2693 };
2694 Ok(crate::crypto::open_batch(|o| {
2695 sealed
2696 .into_iter()
2697 .filter_map(|s| serde_json::from_str::<Vec<String>>(&o.open_or_keep(s)).ok())
2698 .flatten()
2699 .collect()
2700 }))
2701}
2702
2703pub fn community_image(community_id: &str, banner: bool) -> Result<Option<crate::community::CommunityImage>, String> {
2705 let sql = if banner {
2706 "SELECT banner FROM communities WHERE community_id = ?1"
2707 } else {
2708 "SELECT icon FROM communities WHERE community_id = ?1"
2709 };
2710 let sealed: Option<String> = {
2711 let conn = super::get_db_connection_guard_static()?;
2712 conn.query_row(sql, params![community_id], |r| r.get::<_, Option<String>>(0))
2713 .optional()
2714 .map_err(|e| e.to_string())?
2715 .flatten()
2716 };
2717 let Some(sealed) = sealed else { return Ok(None) };
2718 let json = crate::crypto::open_batch(|o| o.open_or_keep(sealed));
2719 serde_json::from_str(&json).map(Some).map_err(|e| format!("community image json: {e}"))
2720}
2721
2722pub fn community_held(id: &CommunityId) -> Result<bool, String> {
2733 let conn = super::get_db_connection_guard_static()?;
2734 conn.query_row("SELECT 1 FROM communities WHERE community_id = ?1", params![id.to_hex()], |_| Ok(()))
2735 .optional()
2736 .map(|row| row.is_some())
2737 .map_err(|e| e.to_string())
2738}
2739
2740#[derive(serde::Serialize, serde::Deserialize, Default)]
2743struct CommunityMetaStash {
2744 #[serde(default, skip_serializing_if = "Option::is_none")]
2745 custom: Option<serde_json::Map<String, serde_json::Value>>,
2746 #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
2747 extra: serde_json::Map<String, serde_json::Value>,
2748 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2751 categories: Vec<CategoryStash>,
2752}
2753
2754#[derive(serde::Serialize, serde::Deserialize)]
2755struct CategoryStash {
2756 id: String,
2757 name: String,
2758 #[serde(default, skip_serializing_if = "Option::is_none")]
2759 position: Option<String>,
2760 #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
2761 extra: serde_json::Map<String, serde_json::Value>,
2762}
2763
2764#[derive(serde::Serialize, serde::Deserialize, Default)]
2766struct ChannelMetaStash {
2767 #[serde(default, skip_serializing_if = "Option::is_none")]
2768 voice: Option<bool>,
2769 #[serde(default, skip_serializing_if = "Option::is_none")]
2770 custom: Option<serde_json::Map<String, serde_json::Value>>,
2771 #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
2772 extra: serde_json::Map<String, serde_json::Value>,
2773 #[serde(default, skip_serializing_if = "Option::is_none")]
2774 sealed: Option<crate::community::v2::community::SealedMeta>,
2775}
2776
2777pub fn save_community_v2(c: &crate::community::v2::community::CommunityV2) -> Result<(), String> {
2780 let _seal = crate::crypto::gate::sealing();
2781 let conn = super::get_write_connection_guard_static()?;
2782 let id_hex = crate::simd::hex::bytes_to_hex_32(&c.identity.community_id.0);
2783 let relays_json = serde_json::to_string(&c.relays).map_err(|e| e.to_string())?;
2784 let created = (c.created_at_ms / 1000) as i64;
2785
2786 let enc_root = enc_key(&c.community_root)?;
2787 let enc_name = enc_txt(&c.name)?;
2788 let enc_relays = enc_txt(&relays_json)?;
2789 let enc_desc = enc_txt_opt(&c.description)?;
2790 let enc_owner_pk = enc_txt(&crate::simd::hex::bytes_to_hex_32(&c.identity.owner_xonly))?;
2791 let enc_owner_salt = enc_txt(&crate::simd::hex::bytes_to_hex_32(&c.identity.owner_salt))?;
2792 let icon_json = c.icon.as_ref().map(|i| serde_json::to_string(i).map_err(|e| e.to_string())).transpose()?;
2795 let banner_json = c.banner.as_ref().map(|b| serde_json::to_string(b).map_err(|e| e.to_string())).transpose()?;
2796 let enc_icon = enc_txt_opt(&icon_json)?;
2797 let enc_banner = enc_txt_opt(&banner_json)?;
2798 let categories: Vec<CategoryStash> = c
2799 .categories
2800 .iter()
2801 .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() })
2802 .collect();
2803 let stash_json = (c.meta_custom.is_some() || !c.meta_extra.is_empty() || !categories.is_empty())
2804 .then(|| serde_json::to_string(&CommunityMetaStash { custom: c.meta_custom.clone(), extra: c.meta_extra.clone(), categories }).map_err(|e| e.to_string()))
2805 .transpose()?;
2806 let enc_stash = enc_txt_opt(&stash_json)?;
2807 let enc_control_pk = enc_txt_opt(&c.control_pk.map(|p| p.to_hex()))?;
2810 let enc_control_root = c.control_root.as_ref().map(enc_key).transpose()?;
2811
2812 let tx = conn.unchecked_transaction().map_err(|e| format!("save v2 community tx: {e}"))?;
2813 tx.execute(
2814 "INSERT INTO communities
2815 (community_id, server_root_key, name, relays, created_at, description,
2816 server_root_epoch, dissolved, protocol, owner_pubkey, owner_salt, icon, banner, meta_extra,
2817 control_pk, control_root)
2818 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 2, ?9, ?10, ?11, ?12, ?13, ?14, ?15)
2819 ON CONFLICT(community_id) DO UPDATE SET
2820 server_root_key=?2, name=?3, relays=?4, description=?6,
2821 server_root_epoch=?7, dissolved=?8, protocol=2, owner_pubkey=?9, owner_salt=?10,
2822 icon=?11, banner=?12, meta_extra=?13, control_pk=?14, control_root=?15",
2823 params![
2824 id_hex, enc_root, enc_name, enc_relays, created, enc_desc,
2825 c.root_epoch.0 as i64, c.dissolved as i64, enc_owner_pk, enc_owner_salt,
2826 enc_icon, enc_banner, enc_stash, enc_control_pk, enc_control_root,
2827 ],
2828 )
2829 .map_err(|e| format!("save v2 community: {e}"))?;
2830
2831 for ch in &c.channels {
2832 let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
2833 let owner_of: Option<String> = tx
2839 .query_row("SELECT community_id FROM community_channels WHERE channel_id=?1", params![ch_hex], |r| r.get(0))
2840 .optional()
2841 .map_err(|e| format!("channel ownership check: {e}"))?;
2842 if let Some(existing) = owner_of.filter(|existing| *existing != id_hex) {
2843 crate::log_warn!(
2850 "[v2:{}] channel {} not saved: its row belongs to community {} (unflipped migration, or a hijack attempt)",
2851 &id_hex[..8],
2852 &ch_hex[..8],
2853 &existing[..8.min(existing.len())]
2854 );
2855 continue;
2856 }
2857 let stored_key = ch.key.unwrap_or(c.community_root);
2861 let enc_ch_key = enc_key(&stored_key)?;
2862 let enc_ch_name = enc_txt(&ch.name)?;
2863 let ch_stash_json = (ch.voice.is_some() || ch.meta_custom.is_some() || !ch.meta_extra.is_empty() || ch.sealed.is_some())
2864 .then(|| {
2865 serde_json::to_string(&ChannelMetaStash { voice: ch.voice, custom: ch.meta_custom.clone(), extra: ch.meta_extra.clone(), sealed: ch.sealed.clone() })
2866 .map_err(|e| e.to_string())
2867 })
2868 .transpose()?;
2869 let enc_ch_stash = enc_txt_opt(&ch_stash_json)?;
2870 tx.execute(
2871 "INSERT INTO community_channels
2872 (channel_id, community_id, channel_key, epoch, name, created_at, private, meta_extra)
2873 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
2874 ON CONFLICT(channel_id) DO UPDATE SET
2875 channel_key=?3, epoch=?4, name=?5, private=?7, meta_extra=?8",
2876 params![ch_hex, id_hex, enc_ch_key, ch.epoch.0 as i64, enc_ch_name, created, ch.private as i64, enc_ch_stash],
2877 )
2878 .map_err(|e| format!("save v2 channel: {e}"))?;
2879 }
2880
2881 let keep: Vec<String> = c.channels.iter().map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0)).collect();
2886 if keep.is_empty() {
2887 tx.execute("DELETE FROM community_channels WHERE community_id=?1", params![id_hex])
2888 .map_err(|e| format!("prune v2 channels: {e}"))?;
2889 } else {
2890 let placeholders = std::iter::repeat_n("?", keep.len()).collect::<Vec<_>>().join(",");
2891 let sql = format!("DELETE FROM community_channels WHERE community_id=? AND channel_id NOT IN ({placeholders})");
2892 let mut binds: Vec<String> = Vec::with_capacity(keep.len() + 1);
2893 binds.push(id_hex.clone());
2894 binds.extend(keep);
2895 tx.execute(&sql, rusqlite::params_from_iter(binds.iter()))
2896 .map_err(|e| format!("prune v2 channels: {e}"))?;
2897 }
2898
2899 tx.commit().map_err(|e| format!("commit v2 community: {e}"))?;
2900 crate::community::v2::realtime::invalidate_held_v2_community(&id_hex);
2901 forget_community_channels(&id_hex);
2904 Ok(())
2905}
2906
2907pub fn load_community_v2(id: &CommunityId) -> Result<Option<crate::community::v2::community::CommunityV2>, String> {
2909 use crate::community::v2::community::{ChannelV2, CommunityV2};
2910 use crate::community::v2::control::CommunityIdentity;
2911 let conn = super::get_db_connection_guard_static()?;
2912 let id_hex = id.to_hex();
2913
2914 let row = conn
2915 .query_row(
2916 "SELECT server_root_key, name, relays, created_at, description,
2917 server_root_epoch, dissolved, owner_pubkey, owner_salt,
2918 icon, banner, meta_extra, control_pk, control_root
2919 FROM communities WHERE community_id = ?1",
2920 params![id_hex],
2921 |r| {
2922 Ok((
2923 r.get::<_, Vec<u8>>(0)?,
2924 r.get::<_, String>(1)?,
2925 r.get::<_, String>(2)?,
2926 r.get::<_, i64>(3)?,
2927 r.get::<_, Option<String>>(4)?,
2928 r.get::<_, i64>(5)?,
2929 r.get::<_, i64>(6)?,
2930 r.get::<_, Option<String>>(7)?,
2931 r.get::<_, Option<String>>(8)?,
2932 r.get::<_, Option<String>>(9)?,
2933 r.get::<_, Option<String>>(10)?,
2934 r.get::<_, Option<String>>(11)?,
2935 r.get::<_, Option<String>>(12)?,
2936 r.get::<_, Option<Vec<u8>>>(13)?,
2937 ))
2938 },
2939 )
2940 .optional()
2941 .map_err(|e| e.to_string())?;
2942 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
2943 else {
2944 return Ok(None);
2945 };
2946 let (Some(owner_pk_e), Some(owner_salt_e)) = (owner_pk_e, owner_salt_e) else {
2947 return Err("v2 community row is missing its owner commitment".to_string());
2948 };
2949
2950 let dk = |o: &mut crate::crypto::AtRestOpener, b: &[u8]| to_32(&o.open_blob_or_keep(b));
2952 let dt = |o: &mut crate::crypto::AtRestOpener, s: &str| o.open_or_keep(s.to_string());
2953 crate::crypto::open_batch(|o| {
2954 let community_root = dk(o, &root_blob)?;
2955 let owner_xonly = parse_hex32(&dt(o, &owner_pk_e))?;
2956 let owner_salt = parse_hex32(&dt(o, &owner_salt_e))?;
2957 let identity = CommunityIdentity { community_id: *id, owner_xonly, owner_salt };
2958 let relays: Vec<String> = serde_json::from_str(&dt(o, &relays_e)).unwrap_or_default();
2959
2960 let mut channels = Vec::new();
2961 {
2962 let mut stmt = conn
2963 .prepare(
2964 "SELECT channel_id, channel_key, epoch, name, private, meta_extra
2965 FROM community_channels WHERE community_id = ?1 ORDER BY created_at",
2966 )
2967 .map_err(|e| e.to_string())?;
2968 let rows = stmt
2969 .query_map(params![id_hex], |r| {
2970 Ok((
2971 r.get::<_, String>(0)?,
2972 r.get::<_, Vec<u8>>(1)?,
2973 r.get::<_, i64>(2)?,
2974 r.get::<_, String>(3)?,
2975 r.get::<_, i64>(4)?,
2976 r.get::<_, Option<String>>(5)?,
2977 ))
2978 })
2979 .map_err(|e| e.to_string())?;
2980 for row in rows {
2981 let (ch_hex, key_blob, epoch, name_e, private, ch_stash_e) = row.map_err(|e| e.to_string())?;
2982 let private = private != 0;
2983 let key = dk(o, &key_blob)?;
2984 let ch_stash: ChannelMetaStash = ch_stash_e
2987 .map(|s| dt(o, &s))
2988 .and_then(|j| serde_json::from_str(&j).ok())
2989 .unwrap_or_default();
2990 channels.push(ChannelV2 {
2991 id: ChannelId(hex_id_to_32(&ch_hex)?),
2992 name: dt(o, &name_e),
2993 private,
2994 key: (private && key != community_root).then_some(key),
3001 epoch: Epoch(epoch as u64),
3002 voice: ch_stash.voice,
3003 meta_custom: ch_stash.custom,
3004 meta_extra: ch_stash.extra,
3005 writers: None,
3006 sealed: ch_stash.sealed,
3007 });
3008 }
3009 }
3010 {
3011 let mut stmt = conn
3012 .prepare("SELECT channel_id, content FROM community_writers WHERE community_id = ?1")
3013 .map_err(|e| e.to_string())?;
3014 let rows = stmt
3015 .query_map(params![id_hex], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))
3016 .map_err(|e| e.to_string())?;
3017 for row in rows {
3018 let (ch_hex, content) = row.map_err(|e| e.to_string())?;
3019 let Some(ch) = channels.iter_mut().find(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0) == ch_hex) else { continue };
3020 ch.writers = crate::community::v2::writers::Ledger::parse(&dt(o, &content)).filter(|l| l.channel == ch.id.0);
3021 }
3022 }
3023 channels.shrink_to_fit();
3025
3026 let icon = icon_e
3029 .map(|s| dt(o, &s))
3030 .and_then(|j| serde_json::from_str::<crate::community::v2::control::ImageRef>(&j).ok());
3031 let banner = banner_e
3032 .map(|s| dt(o, &s))
3033 .and_then(|j| serde_json::from_str::<crate::community::v2::control::ImageRef>(&j).ok());
3034 let stash: CommunityMetaStash = stash_e
3035 .map(|s| dt(o, &s))
3036 .and_then(|j| serde_json::from_str(&j).ok())
3037 .unwrap_or_default();
3038
3039 let control_pk = control_pk_e
3044 .as_deref()
3045 .and_then(|e| nostr_sdk::prelude::PublicKey::from_hex(&dt(o, e)).ok());
3046 let control_root = match (control_pk, control_root_b) {
3047 (Some(pk), Some(blob)) => dk(o, &blob).ok().filter(|cr| {
3048 crate::community::v2::derive::control_signer_group_key(cr, id, Epoch(root_epoch as u64)).pk() == pk
3049 }),
3050 _ => None,
3051 };
3052
3053 Ok(Some(CommunityV2 {
3054 identity,
3055 community_root,
3056 root_epoch: Epoch(root_epoch as u64),
3057 control_pk,
3058 control_root,
3059 name: dt(o, &name_e),
3060 description: desc_e.map(|d| dt(o, &d)),
3061 icon,
3062 banner,
3063 meta_custom: stash.custom,
3064 meta_extra: stash.extra,
3065 relays,
3066 channels,
3067 categories: stash
3068 .categories
3069 .into_iter()
3070 .filter_map(|k| {
3071 let id = crate::simd::hex::hex_to_bytes_32_checked(&k.id)?;
3072 Some(crate::community::v2::community::CategoryV2 { id, name: k.name, position: k.position, extra: k.extra })
3073 })
3074 .collect(),
3075 dissolved: dissolved != 0,
3076 created_at_ms: (created as u64).saturating_mul(1000),
3077 }))
3078 })
3079}
3080fn parse_hex32(hex: &str) -> Result<[u8; 32], String> {
3081 if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
3082 return Err("stored value is not 32-byte hex".to_string());
3083 }
3084 Ok(crate::simd::hex::hex_to_bytes_32(hex))
3085}
3086
3087struct Parsed<T, const CAP: usize> {
3092 generations: std::collections::HashMap<String, u64>,
3093 slots: Vec<(String, u64, T)>,
3095}
3096
3097impl<T, const CAP: usize> Default for Parsed<T, CAP> {
3098 fn default() -> Self {
3099 Parsed { generations: Default::default(), slots: Vec::new() }
3100 }
3101}
3102
3103impl<T: Clone, const CAP: usize> Parsed<T, CAP> {
3104 fn generation(&self, community_id: &str) -> u64 {
3105 self.generations.get(community_id).copied().unwrap_or(0)
3106 }
3107
3108 fn get(&mut self, community_id: &str) -> Option<T> {
3109 let generation = self.generation(community_id);
3110 let i = self.slots.iter().position(|(id, g, _)| id == community_id && *g == generation)?;
3111 let slot = self.slots.remove(i);
3112 let held = slot.2.clone();
3113 self.slots.push(slot);
3114 Some(held)
3115 }
3116
3117 fn put(&mut self, community_id: &str, generation: u64, held: T) {
3118 if generation != self.generation(community_id) {
3119 return;
3120 }
3121 self.slots.retain(|(id, ..)| id != community_id);
3122 if self.slots.len() >= CAP {
3123 self.slots.remove(0);
3124 }
3125 self.slots.push((community_id.to_string(), generation, held));
3126 }
3127
3128 fn moved(&mut self, community_id: &str) -> u64 {
3130 let generation = self.generation(community_id) + 1;
3131 self.generations.insert(community_id.to_string(), generation);
3132 self.slots.retain(|(id, ..)| id != community_id);
3133 generation
3134 }
3135}
3136
3137#[derive(Clone, Default)]
3139pub struct Guestbook {
3140 events: Vec<crate::community::v2::guestbook::GuestbookEvent>,
3141 by_id: std::collections::HashMap<[u8; 32], u32>,
3142}
3143
3144impl Guestbook {
3145 fn new(given: Vec<crate::community::v2::guestbook::GuestbookEvent>) -> Self {
3147 let mut book = Guestbook { events: Vec::with_capacity(given.len()), by_id: std::collections::HashMap::with_capacity(given.len()) };
3148 for ev in given {
3149 if !book.by_id.contains_key(&ev.rumor_id) {
3150 book.by_id.insert(ev.rumor_id, book.events.len() as u32);
3151 book.events.push(ev);
3152 }
3153 }
3154 book
3155 }
3156
3157 pub fn get(&self, rumor_id: &[u8; 32]) -> Option<&crate::community::v2::guestbook::GuestbookEvent> {
3158 self.by_id.get(rumor_id).map(|&i| &self.events[i as usize])
3159 }
3160
3161 pub fn into_events(self) -> Vec<crate::community::v2::guestbook::GuestbookEvent> {
3162 self.events
3163 }
3164
3165 fn upsert(&mut self, ev: &crate::community::v2::guestbook::GuestbookEvent) {
3167 match self.by_id.get(&ev.rumor_id) {
3168 Some(&i) => self.events[i as usize] = ev.clone(),
3169 None => {
3170 self.by_id.insert(ev.rumor_id, self.events.len() as u32);
3171 self.events.push(ev.clone());
3172 }
3173 }
3174 }
3175}
3176
3177impl std::ops::Deref for Guestbook {
3178 type Target = [crate::community::v2::guestbook::GuestbookEvent];
3179 fn deref(&self) -> &Self::Target {
3180 &self.events
3181 }
3182}
3183
3184type GuestbookShared = (std::sync::Arc<Guestbook>, u64);
3185type GuestbookCache = Parsed<GuestbookShared, 8>;
3186
3187fn guestbook_cache() -> std::sync::Arc<std::sync::Mutex<GuestbookCache>> {
3188 struct Key;
3189 super::current_session().scoped::<Key, std::sync::Mutex<GuestbookCache>>()
3190}
3191
3192pub fn get_guestbook_shared(community_id: &str) -> Result<GuestbookShared, String> {
3194 let cache = guestbook_cache();
3195 let generation = {
3196 let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
3197 if let Some(hit) = held.get(community_id) {
3198 return Ok(hit);
3199 }
3200 held.generation(community_id)
3201 };
3202 let (events, cursor) = read_guestbook(community_id)?;
3203 let shared = (std::sync::Arc::new(Guestbook::new(events)), cursor);
3204 cache.lock().unwrap_or_else(|e| e.into_inner()).put(community_id, generation, shared.clone());
3205 Ok(shared)
3206}
3207
3208pub fn get_guestbook(community_id: &str) -> Result<(Vec<crate::community::v2::guestbook::GuestbookEvent>, u64), String> {
3211 let (events, cursor) = get_guestbook_shared(community_id)?;
3212 Ok((std::sync::Arc::unwrap_or_clone(events).into_events(), cursor))
3213}
3214
3215fn read_guestbook(community_id: &str) -> Result<(Vec<crate::community::v2::guestbook::GuestbookEvent>, u64), String> {
3216 let legacy = {
3217 let conn = super::get_db_connection_guard_static()?;
3218 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)?)))
3219 .optional()
3220 .map_err(|e| format!("load guestbook: {e}"))?
3221 };
3222 let Some((blob, cursor)) = legacy else {
3223 return Ok((Vec::new(), 0));
3224 };
3225 if !blob.is_empty() {
3226 move_guestbook_blob(community_id, &blob)?;
3227 }
3228 let rows: Vec<([u8; 32], Vec<u8>)> = {
3230 let conn = super::get_db_connection_guard_static()?;
3231 let mut stmt = conn
3232 .prepare_cached(
3233 "SELECT e.rumor_id, e.body FROM community_guestbook_events e
3234 JOIN community_guestbook_books b ON b.book = e.book
3235 WHERE b.community_id = ?1 ORDER BY e.seq",
3236 )
3237 .map_err(|e| format!("load guestbook events: {e}"))?;
3238 let rows = stmt
3239 .query_map(params![community_id], |r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, Vec<u8>>(1)?)))
3240 .map_err(|e| format!("load guestbook events: {e}"))?;
3241 rows.filter_map(|r| r.ok()).filter_map(|(id, body)| Some((id.try_into().ok()?, body))).collect()
3242 };
3243 let events = crate::crypto::open_batch(|o| {
3244 rows.into_iter().filter_map(|(id, body)| crate::community::v2::guestbook::event_from_body(id, &o.open_blob_or_keep(&body))).collect()
3245 });
3246 Ok((events, cursor.max(0) as u64))
3247}
3248
3249fn move_guestbook_blob(community_id: &str, blob: &str) -> Result<(), String> {
3252 let Ok(events) = serde_json::from_str::<Vec<crate::community::v2::guestbook::GuestbookEvent>>(&dec_txt(blob)) else {
3253 return Ok(());
3254 };
3255 let _seal = crate::crypto::gate::sealing();
3256 let conn = super::get_write_connection_guard_static()?;
3257 let tx = conn.unchecked_transaction().map_err(|e| format!("move guestbook tx: {e}"))?;
3258 let still: Option<String> = tx
3260 .query_row("SELECT events FROM community_guestbook WHERE community_id = ?1", params![community_id], |r| r.get(0))
3261 .optional()
3262 .map_err(|e| format!("move guestbook: {e}"))?;
3263 if still.as_deref() != Some(blob) {
3264 return Ok(());
3265 }
3266 insert_guestbook_events(&tx, community_id, &events, false)?;
3267 tx.execute("UPDATE community_guestbook SET events = '' WHERE community_id = ?1", params![community_id])
3268 .map_err(|e| format!("move guestbook: {e}"))?;
3269 tx.commit().map_err(|e| format!("move guestbook commit: {e}"))
3270}
3271
3272fn guestbook_book(tx: &rusqlite::Connection, community_id: &str) -> Result<i64, String> {
3274 tx.prepare_cached("INSERT OR IGNORE INTO community_guestbook_books (community_id) VALUES (?1)")
3275 .and_then(|mut s| s.execute(params![community_id]))
3276 .map_err(|e| format!("guestbook book: {e}"))?;
3277 tx.prepare_cached("SELECT book FROM community_guestbook_books WHERE community_id = ?1")
3278 .and_then(|mut s| s.query_row(params![community_id], |r| r.get(0)))
3279 .map_err(|e| format!("guestbook book: {e}"))
3280}
3281
3282fn insert_guestbook_events(tx: &rusqlite::Connection, community_id: &str, events: &[crate::community::v2::guestbook::GuestbookEvent], restamp: bool) -> Result<(), String> {
3285 let book = guestbook_book(tx, community_id)?;
3286 let sql = if restamp {
3287 "INSERT INTO community_guestbook_events (book, rumor_id, body) VALUES (?1, ?2, ?3)
3288 ON CONFLICT (book, rumor_id) DO UPDATE SET body = excluded.body"
3289 } else {
3290 "INSERT OR IGNORE INTO community_guestbook_events (book, rumor_id, body) VALUES (?1, ?2, ?3)"
3291 };
3292 let mut stmt = tx.prepare_cached(sql).map_err(|e| format!("store guestbook event: {e}"))?;
3293 crate::crypto::seal_batch(|sealer| {
3294 for ev in events {
3295 let body = sealer.seal_blob(&crate::community::v2::guestbook::event_body(ev))?;
3296 stmt.execute(params![book, &ev.rumor_id[..], body]).map_err(|e| format!("store guestbook event: {e}"))?;
3297 }
3298 Ok(())
3299 })
3300}
3301
3302struct StandingCache;
3303type StandingMap = std::sync::RwLock<std::collections::HashMap<String, (u64, Option<std::sync::Arc<Vec<crate::community::v2::guestbook::GuestbookEvent>>>)>>;
3305
3306fn standing_cache() -> std::sync::Arc<StandingMap> {
3307 crate::db::current_session().scoped::<StandingCache, StandingMap>()
3308}
3309
3310pub fn get_guestbook_standing(community_id: &str) -> Result<std::sync::Arc<Vec<crate::community::v2::guestbook::GuestbookEvent>>, String> {
3313 let generation = match standing_cache().read().unwrap_or_else(|e| e.into_inner()).get(community_id) {
3314 Some((_, Some(held))) => return Ok(held.clone()),
3315 Some((generation, None)) => *generation,
3316 None => 0,
3317 };
3318 let (events, _) = get_guestbook(community_id)?;
3319 use crate::community::v2::guestbook::GuestbookEntry;
3320 let standing: std::sync::Arc<Vec<_>> = std::sync::Arc::new(
3321 events.into_iter().filter(|e| matches!(e.entry, GuestbookEntry::Timeout { .. } | GuestbookEntry::Nickname { .. })).collect(),
3322 );
3323 let map = standing_cache();
3325 let mut cache = map.write().unwrap_or_else(|e| e.into_inner());
3326 let entry = cache.entry(community_id.to_string()).or_insert((0, None));
3327 if entry.0 == generation {
3328 entry.1 = Some(standing.clone());
3329 }
3330 Ok(standing)
3331}
3332
3333struct MembershipGeneration;
3336
3337pub fn membership_generation() -> u64 {
3339 super::current_session().scoped::<MembershipGeneration, std::sync::atomic::AtomicU64>().load(std::sync::atomic::Ordering::Acquire)
3340}
3341
3342pub fn bump_membership_generation() {
3343 super::current_session().scoped::<MembershipGeneration, std::sync::atomic::AtomicU64>().fetch_add(1, std::sync::atomic::Ordering::AcqRel);
3344}
3345
3346pub fn set_guestbook(
3347 community_id: &str,
3348 events: &[crate::community::v2::guestbook::GuestbookEvent],
3349 cursor_secs: u64,
3350) -> Result<(), String> {
3351 let _seal = crate::crypto::gate::sealing();
3352 forget_console_verdict(community_id);
3353 let conn = super::get_write_connection_guard_static()?;
3354 let tx = conn.unchecked_transaction().map_err(|e| format!("save guestbook tx: {e}"))?;
3355 let book = guestbook_book(&tx, community_id)?;
3356 tx.execute("DELETE FROM community_guestbook_events WHERE book = ?1", params![book])
3357 .map_err(|e| format!("save guestbook: {e}"))?;
3358 tx.execute("DELETE FROM community_guestbook_wraps WHERE community_id = ?1", params![community_id])
3360 .map_err(|e| format!("save guestbook: {e}"))?;
3361 insert_guestbook_events(&tx, community_id, events, false)?;
3362 upsert_guestbook_cursor(&tx, community_id, cursor_secs)?;
3363 tx.commit().map_err(|e| format!("save guestbook commit: {e}"))?;
3364 {
3365 let cache = guestbook_cache();
3366 let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
3367 let generation = held.moved(community_id);
3368 held.put(community_id, generation, (std::sync::Arc::new(Guestbook::new(events.to_vec())), cursor_secs));
3369 }
3370 drop(conn);
3371 guestbook_moved_on(community_id);
3372 Ok(())
3373}
3374
3375pub fn store_guestbook_events(
3378 community_id: &str,
3379 events: &[crate::community::v2::guestbook::GuestbookEvent],
3380 cursor_secs: u64,
3381) -> Result<(), String> {
3382 let _seal = crate::crypto::gate::sealing();
3383 forget_console_verdict(community_id);
3384 let conn = super::get_write_connection_guard_static()?;
3385 let tx = conn.unchecked_transaction().map_err(|e| format!("store guestbook tx: {e}"))?;
3386 insert_guestbook_events(&tx, community_id, events, true)?;
3387 upsert_guestbook_cursor(&tx, community_id, cursor_secs)?;
3388 tx.commit().map_err(|e| format!("store guestbook commit: {e}"))?;
3389 guestbook_written(
3390 community_id,
3391 |held| {
3392 for ev in events {
3393 held.upsert(ev);
3394 }
3395 },
3396 cursor_secs,
3397 );
3398 drop(conn);
3399 guestbook_moved_on(community_id);
3400 Ok(())
3401}
3402
3403fn upsert_guestbook_cursor(tx: &rusqlite::Connection, community_id: &str, cursor_secs: u64) -> Result<(), String> {
3404 tx.prepare_cached(
3405 "INSERT INTO community_guestbook (community_id, events, cursor_secs) VALUES (?1, '', ?2)
3406 ON CONFLICT(community_id) DO UPDATE SET cursor_secs = ?2",
3407 )
3408 .and_then(|mut s| s.execute(params![community_id, cursor_secs as i64]))
3409 .map(|_| ())
3410 .map_err(|e| format!("save guestbook cursor: {e}"))
3411}
3412
3413fn guestbook_written(community_id: &str, apply: impl FnOnce(&mut Guestbook), cursor_secs: u64) {
3416 let cache = guestbook_cache();
3417 let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
3418 let before = held.get(community_id);
3419 let generation = held.moved(community_id);
3420 if let Some((events, _)) = before {
3421 let mut events = std::sync::Arc::unwrap_or_clone(events);
3422 apply(&mut events);
3423 held.put(community_id, generation, (std::sync::Arc::new(events), cursor_secs));
3424 }
3425}
3426
3427fn guestbook_moved_on(community_id: &str) {
3429 let map = standing_cache();
3430 let mut cache = map.write().unwrap_or_else(|e| e.into_inner());
3431 let entry = cache.entry(community_id.to_string()).or_insert((0, None));
3432 *entry = (entry.0 + 1, None);
3433 drop(cache);
3434 bump_membership_generation();
3435}
3436
3437#[cfg(test)]
3438mod tests {
3439 use super::*;
3440
3441 static TEST_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
3442
3443 fn make_test_npub(n: u32) -> String {
3446 const BECH32: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
3447 let mut payload = vec![b'q'; 58];
3448 let mut x = n as u64;
3449 let mut i = 58;
3450 while x > 0 && i > 0 {
3451 i -= 1;
3452 payload[i] = BECH32[(x as usize) % 32];
3453 x /= 32;
3454 }
3455 format!("npub1{}", std::str::from_utf8(&payload).unwrap())
3456 }
3457
3458 fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
3459 let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
3460 crate::db::close_database();
3461 crate::db::clear_id_caches();
3464 let tmp = tempfile::tempdir().unwrap();
3465 let n = TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3466 let account = make_test_npub(n);
3467 std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
3468 crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
3469 crate::db::set_current_account(account.clone()).unwrap();
3470 crate::db::init_database(&account).unwrap();
3471 (tmp, guard)
3472 }
3473
3474 #[test]
3475 fn a_channel_holds_its_newest_dated_wraps_up_to_the_cap() {
3476 let (_tmp, _guard) = init_test_db();
3477 let (cid, ch) = ("c".repeat(64), "d".repeat(64));
3478 for i in 0..MAX_HELD_WRAPS + 2 {
3479 hold_wrap(&cid, &ch, &format!("{i:064x}"), &format!("wrap {i}"), "", 1_000 + i as u64).unwrap();
3480 }
3481 hold_wrap(&cid, &"e".repeat(64), &"f".repeat(64), "another channel's", "", 1).unwrap();
3482 let held = held_wraps(&cid).unwrap();
3483 assert_eq!(held.len(), MAX_HELD_WRAPS + 1, "each channel caps on its own");
3484 assert!(!held.iter().any(|(id, ..)| *id == format!("{:064x}", 0) || *id == format!("{:064x}", 1)), "the oldest-dated go first");
3485 assert!(held.iter().any(|(_, _, wrap)| wrap == "wrap 501"), "opened as it was held");
3486 hold_wrap(&cid, &ch, &format!("{:064x}", 501), "again", "", 1).unwrap();
3487 assert_eq!(held_wraps(&cid).unwrap().iter().filter(|(id, ..)| *id == format!("{:064x}", 501)).count(), 1, "once");
3488 release_held_wrap(&format!("{:064x}", 501)).unwrap();
3489 assert!(held_wrap_ids(&[format!("{:064x}", 501), format!("{:064x}", 500)]) == std::collections::HashSet::from([format!("{:064x}", 500)]));
3490 }
3491
3492 fn v2_fixture(name: &str, relays: &[&str]) -> crate::community::v2::community::CommunityV2 {
3494 let owner = Keys::generate();
3495 let g = crate::community::v2::control::genesis(
3496 &owner,
3497 crate::community::v2::control::CommunityMetadata { name: name.into(), ..Default::default() },
3498 1_000,
3499 )
3500 .unwrap();
3501 let relays = relays.iter().map(|r| r.to_string()).collect();
3502 crate::community::v2::community::CommunityV2::from_genesis(&g, name, None, relays, 1_000)
3503 }
3504
3505 fn v2_bundle(name: &str) -> String {
3508 let bundle = crate::community::v2::service::bundle_of(
3509 &v2_fixture(name, &["wss://r"]),
3510 crate::community::v2::service::BundleAudience::Link,
3511 None,
3512 None,
3513 None,
3514 );
3515 serde_json::to_string(&bundle).unwrap()
3516 }
3517
3518 fn saved_v2(name: &str) -> (crate::community::v2::community::CommunityV2, String, String) {
3519 let c = v2_fixture(name, &["wss://r"]);
3520 save_community_v2(&c).unwrap();
3521 let (cid, ch) = (c.id().to_hex(), c.channels[0].id.to_hex());
3522 (c, cid, ch)
3523 }
3524
3525 fn private_channel(id: u8, key: u8) -> crate::community::v2::community::ChannelV2 {
3527 crate::community::v2::community::ChannelV2 {
3528 id: ChannelId([id; 32]),
3529 name: "staff".into(),
3530 private: true,
3531 key: Some([key; 32]),
3532 epoch: Epoch(0),
3533 voice: None,
3534 meta_custom: None,
3535 meta_extra: Default::default(),
3536 writers: None,
3537 sealed: None,
3538 }
3539 }
3540
3541 fn archived_v2() -> (crate::community::v2::community::CommunityV2, String, String) {
3544 let mut c = v2_fixture("HQ", &["r1"]);
3545 c.channels.push(private_channel(0x61, 0x62));
3546 save_community_v2(&c).unwrap();
3547 let (cid, private) = (c.id().to_hex(), c.channels[1].id.to_hex());
3548 store_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 0, &c.community_root).unwrap();
3549 store_epoch_key(&cid, &private, 0, &[0x62; 32]).unwrap();
3550 (c, cid, private)
3551 }
3552
3553 fn encrypted_community_with_messages(n: usize) -> String {
3554 crate::state::ENCRYPTION_KEY.set([0x55u8; 32], &[]);
3555 crate::state::set_encryption_enabled(true);
3556 let (_, cid, ch) = saved_v2("HQ");
3557 let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
3558 for i in 0..n {
3559 let msg = crate::types::Message {
3560 id: format!("{i:064x}"),
3561 content: format!("message number {i}, a few words long"),
3562 at: 1_700_000_000_000 + i as u64 * 1000,
3563 npub: Some(make_test_npub(i as u32 % 7)),
3564 ..Default::default()
3565 };
3566 rt.block_on(crate::db::events::save_message(&ch, &msg)).unwrap();
3567 }
3568 cid
3569 }
3570
3571 #[test]
3572 fn the_policy_window_and_recent_texts_open_sealed_rows() {
3573 let (_tmp, _guard) = init_test_db();
3574 struct Vault;
3575 impl Drop for Vault {
3576 fn drop(&mut self) {
3577 crate::state::set_encryption_enabled(false);
3578 crate::state::ENCRYPTION_KEY.clear(&[]);
3579 }
3580 }
3581 let _vault = Vault;
3582 let cid = encrypted_community_with_messages(5);
3583 let stored: String = crate::db::get_db_connection_guard_static()
3584 .unwrap()
3585 .query_row("SELECT content FROM events WHERE content != '' LIMIT 1", [], |r| r.get(0))
3586 .unwrap();
3587 assert!(crate::crypto::looks_encrypted(&stored), "the rows read back are sealed on disk");
3588 let window = community_policy_messages(&cid, 100).unwrap();
3589 assert_eq!(window.len(), 5);
3590 assert_eq!(window[0].text, "message number 0, a few words long");
3591 let recent = community_recent_texts(&cid, 100).unwrap();
3592 assert_eq!(recent[0].2, "message number 4, a few words long");
3593 }
3594
3595 #[test]
3596 fn an_authority_floor_takes_a_squatted_coordinate_and_keeps_it() {
3597 let (_tmp, _guard) = init_test_db();
3598 let (cid, entity) = ("f".repeat(64), "a".repeat(64));
3599 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();
3600 let held = || (get_edition_head(&cid, &entity).unwrap().unwrap(), edition_head_families(&cid).unwrap().get(&entity).cloned());
3601 head(50, 0xC0, FLOOR_CONTROL);
3602 head(1, 0xA1, FLOOR_AUTHORITY);
3603 assert_eq!(held(), ((1, [0xA1; 32]), Some("a".into())), "an authority head replaces a control row at any version");
3604 head(99, 0xC1, FLOOR_CONTROL);
3605 assert_eq!(held().0, (1, [0xA1; 32]), "a control head never takes it back");
3606 converge_family_head_at_epoch(&cid, &entity, 1, &[0xC2; 32], &[0xC2; 32], &[0xC2; 32], 0, Some(FLOOR_CONTROL)).unwrap();
3607 assert_eq!(held().0, (1, [0xA1; 32]), "nor converges it");
3608 rebase_edition_head_at_epoch(&cid, &entity, 0, &[0xC3; 32], &[0xC3; 32], &[0xC3; 32], 0, FLOOR_CONTROL).unwrap();
3609 assert_eq!(held().0, (1, [0xA1; 32]), "nor moves it down");
3610 head(1, 0xA0, FLOOR_AUTHORITY);
3611 assert_eq!(held().0, (1, [0xA1; 32]), "within the family the version still only advances");
3612 head(2, 0xA2, FLOOR_AUTHORITY);
3613 assert_eq!(held().0, (2, [0xA2; 32]));
3614 }
3615
3616 #[test]
3617 fn edition_head_round_trips_and_upserts() {
3618 let (_tmp, _guard) = init_test_db();
3619 let cid = "f".repeat(64);
3620 let entity = "a".repeat(64);
3621
3622 assert_eq!(get_edition_head(&cid, &entity).unwrap(), None);
3624
3625 let h1 = [0x11u8; 32];
3627 set_edition_head(&cid, &entity, 1, &h1).unwrap();
3628 assert_eq!(get_edition_head(&cid, &entity).unwrap(), Some((1, h1)));
3629
3630 let h2 = [0x22u8; 32];
3632 set_edition_head(&cid, &entity, 2, &h2).unwrap();
3633 assert_eq!(get_edition_head(&cid, &entity).unwrap(), Some((2, h2)));
3634
3635 set_edition_head(&cid, &entity, 1, &[0xEEu8; 32]).unwrap();
3638 assert_eq!(get_edition_head(&cid, &entity).unwrap(), Some((2, h2)), "rollback to v1 ignored");
3639 set_edition_head(&cid, &entity, 2, &[0xEEu8; 32]).unwrap();
3640 assert_eq!(get_edition_head(&cid, &entity).unwrap(), Some((2, h2)), "equal version is a no-op too");
3641
3642 let other = "b".repeat(64);
3644 assert_eq!(get_edition_head(&cid, &other).unwrap(), None);
3645 }
3646
3647 #[test]
3648 fn a_floor_written_before_families_still_advances() {
3649 let (_tmp, _guard) = init_test_db();
3652 let (cid, entity) = ("c".repeat(64), "e".repeat(64));
3653 set_edition_head(&cid, &entity, 1, &[0x11; 32]).unwrap();
3654 assert_eq!(get_all_edition_heads_full(&cid).unwrap()[&entity].5, None, "a familyless row");
3655 set_family_head_at_epoch(&cid, &entity, 2, &[0x22; 32], &[0x02; 32], &[0xA1; 32], 0, FLOOR_CONTROL).unwrap();
3656 let f = get_all_edition_heads_full(&cid).unwrap()[&entity];
3657 assert_eq!((f.1, f.2, f.5), (2, [0x22; 32], Some(FloorFamily::of(FLOOR_CONTROL))), "it advances, and takes the family");
3658 set_family_head_at_epoch(&cid, "a".repeat(64).as_str(), 1, &[0x33; 32], &[0x03; 32], &[0xA1; 32], 0, FLOOR_AUTHORITY).unwrap();
3660 set_family_head_at_epoch(&cid, "a".repeat(64).as_str(), 2, &[0x44; 32], &[0x04; 32], &[0xA1; 32], 0, FLOOR_CONTROL).unwrap();
3661 assert_eq!(get_all_edition_heads_full(&cid).unwrap()[&"a".repeat(64)].1, 1);
3662 }
3663
3664 #[test]
3665 fn a_floor_keeps_the_author_of_the_head_it_holds() {
3666 let (_tmp, _guard) = init_test_db();
3667 let cid = "c".repeat(64);
3668 let entity = "e".repeat(64);
3669 let author = |b: u8| [b; 32];
3670 let held = |cid: &str| {
3671 let f = get_all_edition_heads_full(cid).unwrap()[&entity];
3672 (f.0, f.1, f.2, f.3, f.4)
3673 };
3674 set_edition_head_at_epoch(&cid, &entity, 1, &[0x11; 32], &[0x01; 32], &author(0xA1), 0).unwrap();
3675 set_edition_head_at_epoch(&cid, &entity, 2, &[0x22; 32], &[0x02; 32], &author(0xB2), 0).unwrap();
3676 assert_eq!(held(&cid), (0, 2, [0x22; 32], Some([0x02; 32]), Some(author(0xB2))), "an advance records its own author");
3677
3678 converge_edition_head_at_epoch(&cid, &entity, 2, &[0x33; 32], &[0xFF; 32], &author(0xC3), 0).unwrap();
3681 assert_eq!(held(&cid), (0, 2, [0x33; 32], Some([0xFF; 32]), Some(author(0xC3))), "a higher id can win on authority");
3682 converge_edition_head_at_epoch(&cid, &entity, 3, &[0x44; 32], &[0x00; 32], &author(0xD4), 0).unwrap();
3683 converge_edition_head_at_epoch(&cid, &entity, 2, &[0x55; 32], &[0x00; 32], &author(0xE5), 1).unwrap();
3684 assert_eq!(held(&cid).2, [0x33; 32], "another version or epoch is never converged onto");
3685
3686 set_edition_head_at_epoch(&cid, &entity, 1, &[0x66; 32], &[0x06; 32], &author(0xF6), 1).unwrap();
3688 assert_eq!(held(&cid), (1, 1, [0x66; 32], Some([0x06; 32]), Some(author(0xF6))));
3689 }
3690
3691 #[test]
3692 fn guestbook_round_trips_events_and_cursor() {
3693 let (_tmp, _guard) = init_test_db();
3694 let member = nostr_sdk::prelude::Keys::generate();
3695 let ev = crate::community::v2::guestbook::GuestbookEvent { epoch: None, observed_at: None,
3696 rumor_id: [7u8; 32],
3697 entry: crate::community::v2::guestbook::GuestbookEntry::Join {
3698 member: member.public_key(),
3699 invited_by: Some(("creator".into(), "label".into())),
3700 at_ms: 1_000,
3701 },
3702 };
3703 let cid = "d".repeat(64);
3704 assert_eq!(get_guestbook(&cid).unwrap(), (Vec::new(), 0), "absent reads as empty at cursor 0");
3705 set_guestbook(&cid, std::slice::from_ref(&ev), 42).unwrap();
3706 let (events, cursor) = read_guestbook(&cid).unwrap();
3707 assert_eq!(events, vec![ev.clone()], "events round-trip through the encrypted blob");
3708 assert_eq!(cursor, 42);
3709 assert_eq!(get_guestbook(&cid).unwrap(), (vec![ev], 42), "and the cached read agrees");
3710 }
3711
3712 fn gb(b: u8, epoch: Option<u64>) -> crate::community::v2::guestbook::GuestbookEvent {
3713 crate::community::v2::guestbook::GuestbookEvent {
3714 rumor_id: [b; 32],
3715 entry: crate::community::v2::guestbook::GuestbookEntry::Join { member: nostr_sdk::prelude::Keys::generate().public_key(), invited_by: None, at_ms: b as u64 * 1000 },
3716 epoch,
3717 observed_at: Some(1_790_000_000 + b as u64),
3718 }
3719 }
3720
3721 #[test]
3722 fn a_guestbook_blob_moves_into_rows_in_order_and_once() {
3723 let (_tmp, _guard) = init_test_db();
3724 let cid = "f".repeat(64);
3725 let events: Vec<_> = [9u8, 3, 7, 1].iter().map(|&b| gb(b, Some(2))).collect();
3726 {
3727 let _seal = crate::crypto::gate::sealing();
3728 let conn = crate::db::get_write_connection_guard_static().unwrap();
3729 conn.execute(
3730 "INSERT INTO community_guestbook (community_id, events, cursor_secs) VALUES (?1, ?2, 55)",
3731 params![cid, enc_txt(&serde_json::to_string(&events).unwrap()).unwrap()],
3732 )
3733 .unwrap();
3734 }
3735 assert_eq!(read_guestbook(&cid).unwrap(), (events.clone(), 55), "arrival order kept");
3736 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();
3737 assert!(blob.is_empty(), "the blob is moved out, not kept beside the rows");
3738 assert_eq!(read_guestbook(&cid).unwrap(), (events, 55), "and reads the same from rows");
3739 }
3740
3741 #[test]
3742 fn a_guestbook_blob_that_does_not_read_is_left_as_it_is() {
3743 let (_tmp, _guard) = init_test_db();
3744 let cid = "c".repeat(64);
3745 {
3746 let conn = crate::db::get_write_connection_guard_static().unwrap();
3747 conn.execute("INSERT INTO community_guestbook (community_id, events, cursor_secs) VALUES (?1, 'not json', 3)", params![cid]).unwrap();
3748 }
3749 assert_eq!(read_guestbook(&cid).unwrap(), (Vec::new(), 3));
3750 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();
3751 assert_eq!(blob, "not json", "nothing it couldn't read is thrown away");
3752 }
3753
3754 #[test]
3755 fn stored_guestbook_events_dedup_restamp_in_place_and_match_the_cache() {
3756 let (_tmp, _guard) = init_test_db();
3757 let cid = "b".repeat(64);
3758 let (a, b, c) = (gb(1, None), gb(2, Some(1)), gb(3, Some(1)));
3759 store_guestbook_events(&cid, &[a.clone(), b.clone()], 10).unwrap();
3760 assert_eq!(get_guestbook(&cid).unwrap().0, vec![a.clone(), b.clone()]);
3761 let a2 = crate::community::v2::guestbook::GuestbookEvent { epoch: Some(4), ..a.clone() };
3763 store_guestbook_events(&cid, &[b.clone(), a2.clone(), c.clone()], 20).unwrap();
3764 let want = (vec![a2, b, c], 20);
3765 assert_eq!(get_guestbook(&cid).unwrap(), want, "the cached copy");
3766 assert_eq!(read_guestbook(&cid).unwrap(), want, "the rows");
3767 let rows: i64 = crate::db::get_db_connection_guard_static().unwrap().query_row("SELECT COUNT(*) FROM community_guestbook_events", [], |r| r.get(0)).unwrap();
3768 assert_eq!(rows, 3);
3769 set_guestbook(&cid, &[want.0[2].clone()], 30).unwrap();
3771 assert_eq!(read_guestbook(&cid).unwrap(), (vec![want.0[2].clone()], 30));
3772 assert_eq!(get_guestbook(&cid).unwrap(), (vec![want.0[2].clone()], 30));
3773 }
3774
3775 #[test]
3776 fn owed_departures_write_only_the_members_that_changed() {
3777 let (_tmp, _guard) = init_test_db();
3778 let cid = "e".repeat(64);
3779 let mut keys: Vec<PublicKey> = (0..3).map(|_| Keys::generate().public_key()).collect();
3780 keys.sort();
3781 let (a, b, c) = (keys[0], keys[1], keys[2]);
3782 let rows = || -> Vec<(i64, Vec<u8>)> {
3783 let conn = crate::db::get_db_connection_guard_static().unwrap();
3784 let mut stmt = conn.prepare("SELECT seq, body FROM community_departures_seen ORDER BY seq").unwrap();
3785 stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?))).unwrap().map(|r| r.unwrap()).collect()
3786 };
3787 let stored = || {
3788 departures_seen_cache().lock().unwrap().moved(&cid);
3789 (*departures_seen(&cid).unwrap().spans).clone()
3790 };
3791 let first: DepartureSpans = [(a, vec![(5, Some(9), false)].into()), (b, vec![(1, None, true)].into())].into_iter().collect();
3792 set_departures_seen(&cid, std::sync::Arc::new(first.clone())).unwrap();
3793 assert_eq!(stored(), first);
3794 let before = rows();
3795 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();
3796 set_departures_seen(&cid, std::sync::Arc::new(second.clone())).unwrap();
3797 let after = rows();
3798 assert_eq!(after.len(), 3);
3799 assert_eq!(after[0], before[0], "an unchanged member's row is left alone");
3800 assert_eq!(after[1].0, before[1].0, "a changed member keeps its row");
3801 assert_ne!(after[1].1, before[1].1);
3802 assert_eq!(stored(), second);
3803 let third: DepartureSpans = [(c, vec![(7, None, false)].into())].into_iter().collect();
3804 set_departures_seen(&cid, std::sync::Arc::new(third.clone())).unwrap();
3805 assert_eq!(rows().iter().map(|r| r.0).collect::<Vec<_>>(), vec![after[2].0], "a member with no spans left goes");
3806 assert_eq!(stored(), third);
3807 let fourth: DepartureSpans = [(a, vec![(5, Some(9), false)].into())].into_iter().collect();
3808 set_departures_seen(&cid, std::sync::Arc::new(fourth.clone())).unwrap();
3809 assert_eq!(rows().len(), 1, "and one after every member written");
3810 assert_eq!(stored(), fourth);
3811 delete_community(&cid).unwrap();
3812 assert!(departures_seen(&cid).unwrap().spans.is_empty());
3813 assert!(rows().is_empty());
3814 }
3815
3816 #[test]
3817 fn owed_departures_kept_in_settings_move_into_sealed_rows() {
3818 let (_tmp, _guard) = init_test_db();
3819 crate::state::ENCRYPTION_KEY.set([0x37u8; 32], &[]);
3820 crate::state::set_encryption_enabled(true);
3821 let cid = "f".repeat(64);
3822 let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
3823 let json = format!(r#"{{"{}":[[5,9,false]],"{}":[[1,null,true],[12,20,false]]}}"#, a.to_hex(), b.to_hex());
3824 super::super::settings::set_sql_setting(format!("departures_seen:{cid}"), json).unwrap();
3825 let want: DepartureSpans = [(a, vec![(5, Some(9), false)].into()), (b, vec![(1, None, true), (12, Some(20), false)].into())].into_iter().collect();
3826 assert_eq!(*departures_seen(&cid).unwrap().spans, want);
3827 assert_eq!(super::super::settings::get_sql_setting(format!("departures_seen:{cid}")).unwrap(), None);
3828 let bodies: Vec<Vec<u8>> = {
3829 let conn = crate::db::get_db_connection_guard_static().unwrap();
3830 let mut stmt = conn.prepare("SELECT body FROM community_departures_seen").unwrap();
3831 stmt.query_map([], |r| r.get(0)).unwrap().map(|r| r.unwrap()).collect()
3832 };
3833 assert_eq!(bodies.len(), 2);
3834 for body in &bodies {
3835 assert!(!body.windows(32).any(|w| w == a.as_bytes() || w == b.as_bytes()), "who left is never stored in the clear");
3836 }
3837 departures_seen_cache().lock().unwrap().moved(&cid);
3838 assert_eq!(*departures_seen(&cid).unwrap().spans, want, "read back from the sealed rows");
3839 crate::state::set_encryption_enabled(false);
3840 }
3841
3842 #[test]
3843 fn a_folds_floor_writes_skip_only_what_is_already_stored() {
3844 let (_tmp, _guard) = init_test_db();
3845 let cid = "c".repeat(64);
3846 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));
3847 let (h4, h5, a) = ([4u8; 32], [5u8; 32], [9u8; 32]);
3848 set_family_head_at_epoch(&cid, "e1", 5, &h5, &[7; 32], &a, 2, FLOOR_CONTROL).unwrap();
3849 set_family_head_at_epoch(&cid, "e2", 3, &h5, &[8; 32], &a, 2, FLOOR_AUTHORITY).unwrap();
3850 write_folded_heads(&cid, |w| {
3851 w.rebase("e1", 4, &h4, &[6; 32], &a, 2, FLOOR_CONTROL)?;
3853 w.set("e1", 5, &h5, &[7; 32], &a, 2, FLOOR_CONTROL)?;
3854 w.converge("e2", 3, &h5, &[1; 32], &a, 2, FLOOR_AUTHORITY)
3856 })
3857 .unwrap();
3858 assert_eq!(row("e1"), Some((2, 5, h5, Some([7; 32]), Some(a))));
3859 assert_eq!(row("e2"), Some((2, 3, h5, Some([1; 32]), Some(a))));
3860 let failed = write_folded_heads(&cid, |w| {
3862 w.set("e3", 1, &h4, &[2; 32], &a, 2, FLOOR_CONTROL)?;
3863 Err("cut short".into())
3864 });
3865 assert!(failed.is_err());
3866 assert_eq!(row("e3"), None);
3867 }
3868
3869 #[test]
3870 fn a_member_list_reads_posts_through_indexes_not_a_scan() {
3871 let (_tmp, _guard) = init_test_db();
3872 let conn = crate::db::get_db_connection_guard_static().unwrap();
3873 let plan = |sql: &str| -> String {
3874 let mut stmt = conn.prepare(&format!("EXPLAIN QUERY PLAN {sql}")).unwrap();
3875 let binds = vec![1i64; stmt.parameter_count()];
3876 stmt.query_map(rusqlite::params_from_iter(binds), |r| r.get::<_, String>(3)).unwrap().map(|r| r.unwrap()).collect::<Vec<_>>().join(" | ") + " "
3877 };
3878 let held = plan(&flagged_sql("?, ?", false));
3879 assert!(held.contains("USING INDEX idx_events_unauthorized ") && !held.contains("writer"), "{held}");
3880 let strict = plan(&flagged_sql("?, ?", true));
3881 assert!(strict.contains("USING INDEX idx_events_unauthorized ") && strict.contains("USING INDEX idx_events_writer_post "), "{strict}");
3882 let activity = plan(&activity_sql("?, ?"));
3883 assert!(activity.contains("idx_events_chat_kind_npub") && !activity.contains("TEMP B-TREE"), "{activity}");
3884 }
3885
3886 #[test]
3887 fn an_owed_author_take_back_widens_narrows_and_settles_as_it_did_in_settings() {
3888 let (_tmp, _guard) = init_test_db();
3889 let (cid, chan) = ("a".repeat(64), "c".repeat(64));
3890 let author = Keys::generate().public_key().to_hex();
3891 let owed = || owed_author_retractions(&cid).unwrap();
3892 owe_author_retraction(&cid, &chan, &author, 10, None).unwrap();
3893 assert_eq!(owed(), vec![(chan.clone(), author.clone(), 10, None, 1)]);
3894 owe_author_retraction(&cid, &chan, &author, 10, Some(20)).unwrap();
3895 assert_eq!(owed(), vec![(chan.clone(), author.clone(), 10, Some(20), 2)], "the same span closing narrows its own owe");
3896 owe_author_retraction(&cid, &chan, &author, 15, Some(30)).unwrap();
3897 assert_eq!(owed(), vec![(chan.clone(), author.clone(), 10, Some(30), 3)]);
3898 owe_author_retraction(&cid, &chan, &author, 5, None).unwrap();
3899 assert_eq!(owed(), vec![(chan.clone(), author.clone(), 5, None, 4)], "any other range widens it");
3900 settle_author_retraction(&cid, &chan, &author, 5, None, 3).unwrap();
3901 assert_eq!(owed().len(), 1, "more was owed since it was read");
3902 settle_author_retraction(&cid, &chan, &author, 5, None, 4).unwrap();
3903 assert!(owed().is_empty());
3904 let other = Keys::generate().public_key().to_hex();
3905 owe_author_retraction(&cid, &chan, &author, 1, None).unwrap();
3906 owe_author_retraction(&cid, &"d".repeat(64), &other, 2, Some(3)).unwrap();
3907 assert_eq!(owed().len(), 2, "one row per author and Channel");
3908 delete_community(&cid).unwrap();
3909 assert!(owed().is_empty());
3910 }
3911
3912 #[test]
3913 fn owed_author_take_backs_kept_in_settings_move_into_sealed_rows() {
3914 let (_tmp, _guard) = init_test_db();
3915 crate::state::ENCRYPTION_KEY.set([0x41u8; 32], &[]);
3916 crate::state::set_encryption_enabled(true);
3917 let (cid, elsewhere, chan) = ("a".repeat(64), "b".repeat(64), "c".repeat(64));
3918 let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
3919 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();
3920 legacy(&cid, &a, "7:3:");
3921 legacy(&cid, &b, "4:1:9");
3922 legacy(&elsewhere, &a, "1:1:");
3923 let mut want = vec![(chan.clone(), a.to_hex(), 7, None, 3), (chan.clone(), b.to_hex(), 4, Some(9), 1)];
3924 want.sort();
3925 assert_eq!(owed_author_retractions(&cid).unwrap(), want);
3926 let conn = crate::db::get_db_connection_guard_static().unwrap();
3927 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();
3928 assert_eq!(left, vec![format!("writer_retract_by:{elsewhere}:{chan}:{}", a.to_hex())], "another community's rows wait for their own read");
3929 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();
3930 drop(conn);
3931 assert_eq!(bodies.len(), 2);
3932 for body in &bodies {
3933 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");
3934 }
3935 legacy(&elsewhere, &b, "2:5:");
3937 owe_author_retraction(&elsewhere, &chan, &b.to_hex(), 1, None).unwrap();
3938 settle_author_retraction(&elsewhere, &chan, &a.to_hex(), 1, None, 1).unwrap();
3939 assert_eq!(owed_author_retractions(&elsewhere).unwrap(), vec![(chan.clone(), b.to_hex(), 1, None, 6)]);
3940 let conn = crate::db::get_db_connection_guard_static().unwrap();
3941 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();
3942 assert!(bodies.iter().all(|body| !body.windows(32).any(|w| w == a.as_bytes() || w == b.as_bytes())), "nor once owed again");
3943 drop(conn);
3944 crate::state::set_encryption_enabled(false);
3945 }
3946
3947 #[test]
3948 fn an_owed_author_body_round_trips_and_refuses_what_it_did_not_write() {
3949 let author = [7u8; 32];
3950 for (since, generation, until) in [(0, 0, None), (1, 2, Some(3)), (u64::MAX, u64::MAX, Some(u64::MAX))] {
3951 let body = author_owed_body(&author, since, generation, until);
3952 assert_ne!(body.len(), 32);
3953 assert_eq!(author_owed_from_body(&body), Some((author, since, generation, until)));
3954 let mut longer = body.clone();
3955 longer.push(0);
3956 assert_eq!(author_owed_from_body(&longer), None, "no trailing bytes");
3957 assert_eq!(author_owed_from_body(&body[..body.len() - 1]), None, "no cut body");
3958 }
3959 let mut flags = author_owed_body(&author, 1, 1, None);
3960 *flags.last_mut().unwrap() = 2;
3961 assert_eq!(author_owed_from_body(&flags), None, "unknown flags");
3962 let mut format = author_owed_body(&author, 1, 1, None);
3963 format[0] = 2;
3964 assert_eq!(author_owed_from_body(&format), None);
3965 }
3966
3967 #[test]
3968 fn an_owed_departure_body_round_trips_and_refuses_what_it_did_not_write() {
3969 let member = Keys::generate().public_key();
3970 for spans in [vec![], vec![(0, None, false)], vec![(1, Some(2), true), (u64::MAX, Some(u64::MAX), false), (300, None, true)]] {
3971 let body = departure_body(&member, &spans);
3972 assert_ne!(body.len(), 32);
3973 assert_eq!(departure_from_body(&body), Some((member, spans.clone())));
3974 let mut longer = body.clone();
3975 longer.push(0);
3976 assert_eq!(departure_from_body(&longer), None, "no trailing bytes");
3977 assert_eq!(departure_from_body(&body[..body.len() - 1]), None, "no cut body");
3978 }
3979 let mut forged = departure_body(&member, &[(1, None, false)]);
3980 forged[33] = 0x7f;
3981 assert_eq!(departure_from_body(&forged), None, "a count beyond the body");
3982 let mut flags = departure_body(&member, &[(1, None, false)]);
3983 flags[34] = 0b100;
3984 assert_eq!(departure_from_body(&flags), None, "unknown flags");
3985 let mut format = departure_body(&member, &[]);
3986 format[0] = 2;
3987 assert_eq!(departure_from_body(&format), None);
3988 }
3989
3990 #[test]
3991 fn guestbook_rows_are_sealed_at_rest() {
3992 let (_tmp, _guard) = init_test_db();
3993 crate::state::ENCRYPTION_KEY.set([0x31u8; 32], &[]);
3994 crate::state::set_encryption_enabled(true);
3995 let cid = "d".repeat(64);
3996 let ev = gb(5, Some(1));
3997 store_guestbook_events(&cid, std::slice::from_ref(&ev), 1).unwrap();
3998 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();
3999 assert_ne!(body, crate::community::v2::guestbook::event_body(&ev), "not stored in the clear");
4000 assert_eq!(read_guestbook(&cid).unwrap().0, vec![ev]);
4001 crate::state::set_encryption_enabled(false);
4002 crate::state::ENCRYPTION_KEY.clear(&[]);
4003 }
4004
4005 #[test]
4006 fn a_guestbook_read_overlapping_a_write_is_never_served_after_it() {
4007 let (_tmp, _guard) = init_test_db();
4008 let ev = |b: u8| crate::community::v2::guestbook::GuestbookEvent {
4009 epoch: None,
4010 observed_at: None,
4011 rumor_id: [b; 32],
4012 entry: crate::community::v2::guestbook::GuestbookEntry::Leave { member: nostr_sdk::prelude::Keys::generate().public_key(), at_ms: b as u64 },
4013 };
4014 let cid = "e".repeat(64);
4015 let (one, two) = (ev(1), ev(2));
4016 set_guestbook(&cid, std::slice::from_ref(&one), 1).unwrap();
4017 assert_eq!(get_guestbook(&cid).unwrap().0, vec![one.clone()]);
4018 let began_under = guestbook_cache().lock().unwrap().generation(&cid);
4020 set_guestbook(&cid, &[one.clone(), two.clone()], 2).unwrap();
4021 guestbook_cache().lock().unwrap().put(&cid, began_under, (std::sync::Arc::new(Guestbook::new(vec![one.clone()])), 1));
4022 assert_eq!(get_guestbook(&cid).unwrap(), (vec![one, two], 2), "the write stands over the late read");
4023 }
4024
4025 #[test]
4026 fn v2_images_round_trip_and_read_as_community_images() {
4027 let (_tmp, _guard) = init_test_db();
4028 let owner = nostr_sdk::prelude::Keys::generate();
4029 let g = crate::community::v2::control::genesis(
4030 &owner,
4031 crate::community::v2::control::CommunityMetadata { name: "Icons".into(), ..Default::default() },
4032 1_000,
4033 )
4034 .unwrap();
4035 let mut c = crate::community::v2::community::CommunityV2::from_genesis(&g, "Icons", None, vec!["wss://r".into()], 1_000);
4036 let mut extra = serde_json::Map::new();
4037 extra.insert("ext".into(), serde_json::Value::String("webp".into()));
4038 c.icon = Some(crate::community::v2::control::ImageRef {
4039 url: "https://blossom.example/abc".into(),
4040 key: "0".repeat(64),
4041 nonce: "1".repeat(32),
4042 hash: "a".repeat(64),
4043 extra,
4044 });
4045 c.meta_custom = Some({
4046 let mut m = serde_json::Map::new();
4047 m.insert("k".into(), serde_json::Value::from("v"));
4048 m
4049 });
4050 c.channels[0].voice = Some(true);
4051 c.channels[0].meta_extra.insert("vnd".into(), serde_json::Value::from(7));
4052 save_community_v2(&c).unwrap();
4053
4054 let re = load_community_v2(c.id()).unwrap().unwrap();
4056 assert_eq!(re.icon, c.icon);
4057 assert_eq!(re.banner, None);
4058 assert_eq!(re.meta_custom, c.meta_custom);
4060 assert_eq!(re.channels[0].voice, Some(true));
4061 assert_eq!(re.channels[0].meta_extra.get("vnd"), Some(&serde_json::Value::from(7)));
4062
4063 let cid = crate::simd::hex::bytes_to_hex_32(&c.id().0);
4066 let img = community_image(&cid, false).unwrap().expect("the v2 icon reads as a CommunityImage");
4067 assert_eq!(img.url, "https://blossom.example/abc");
4068 assert_eq!(img.ext, "webp");
4069 assert_eq!(img.hash, "a".repeat(64));
4070 assert_eq!(community_image(&cid, true).unwrap(), None);
4071 assert_eq!(community_image(&"cd".repeat(32), false).unwrap(), None);
4072 }
4073
4074 #[test]
4075 fn column_reads_and_the_owner_check_serve_a_v2_community() {
4076 use crate::community::roles::{CommunityRoles, MemberGrant, Permissions, Role, RoleScope};
4077 use crate::community::moderation::is_owner_or_admin;
4078 let (_tmp, _guard) = init_test_db();
4079 let owner = nostr_sdk::prelude::Keys::generate();
4080 let g = crate::community::v2::control::genesis(
4081 &owner,
4082 crate::community::v2::control::CommunityMetadata { name: "Two".into(), ..Default::default() },
4083 1_000,
4084 )
4085 .unwrap();
4086 let v2 = crate::community::v2::community::CommunityV2::from_genesis(&g, "Two", None, vec!["wss://two".into()], 1_000);
4087 save_community_v2(&v2).unwrap();
4088 let mut other = v2_fixture("One", &["wss://one"]);
4089 other.channels.push(private_channel(0x71, 0x72));
4090 save_community_v2(&other).unwrap();
4091
4092 crate::db::get_write_connection_guard_static()
4093 .unwrap()
4094 .execute(
4095 "INSERT INTO community_channels (channel_id, community_id, channel_key, epoch, name, created_at)
4096 VALUES (?1, ?2, x'00', 0, 'c', 1)",
4097 params!["ee".repeat(32), "ff".repeat(32)],
4098 )
4099 .unwrap();
4100 let channels = held_channel_ids().unwrap();
4101 assert!(!channels.contains(&"ee".repeat(32)), "a channel whose community is gone is not held");
4102 assert!(channels.contains(&crate::simd::hex::bytes_to_hex_32(&v2.channels[0].id.0)));
4103 assert!(other.channels.iter().all(|ch| channels.contains(&ch.id.to_hex())));
4104 assert_eq!(channels.len(), other.channels.len() + v2.channels.len());
4105 let relays = held_community_relays().unwrap();
4106 assert!(relays.contains("wss://two") && relays.contains("wss://one"));
4107
4108 let cid = crate::simd::hex::bytes_to_hex_32(&v2.id().0);
4109 let (admin, social, stranger) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
4110 let role = |id: &str, perms: u64| Role {
4111 role_id: id.repeat(32), name: id.into(), position: 1, permissions: Permissions(perms),
4112 scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
4113 };
4114 let roles = CommunityRoles {
4115 roles: vec![role("aa", Permissions::ADMIN_ALL), role("bb", 0)],
4116 grants: vec![
4117 MemberGrant { member: admin.to_hex(), role_ids: vec!["aa".repeat(32)] },
4118 MemberGrant { member: social.to_hex(), role_ids: vec!["bb".repeat(32)] },
4119 ],
4120 everyone: None,
4121 overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
4122 };
4123 set_community_roles(&cid, &roles, 1).unwrap();
4124 assert!(is_owner_or_admin(&cid, &owner.public_key().to_hex()), "a v2 owner proves itself from the id");
4125 assert!(is_owner_or_admin(&cid, &admin.to_hex()));
4126 assert!(!is_owner_or_admin(&cid, &social.to_hex()), "a role without management is not admin");
4127 assert!(!is_owner_or_admin(&cid, &stranger.to_hex()));
4128 assert!(!is_owner_or_admin(&"cd".repeat(32), &owner.public_key().to_hex()));
4129 }
4130
4131 #[test]
4132 fn epoch_key_archive_retains_every_epoch() {
4133 let (_tmp, _guard) = init_test_db();
4136 let cid = "f".repeat(64);
4137 let scope = "a".repeat(64);
4138
4139 store_epoch_key(&cid, &scope, 0, &[0xA0u8; 32]).unwrap();
4140 store_epoch_key(&cid, &scope, 1, &[0xA1u8; 32]).unwrap();
4141 store_epoch_key(&cid, &scope, 2, &[0xA2u8; 32]).unwrap();
4142
4143 let held = held_epoch_keys(&cid, &scope).unwrap();
4144 assert_eq!(held.len(), 3, "all three epoch keys retained");
4145 assert_eq!(held[0], (Epoch(0), [0xA0u8; 32]));
4146 assert_eq!(held[1], (Epoch(1), [0xA1u8; 32]));
4147 assert_eq!(held[2], (Epoch(2), [0xA2u8; 32]));
4148
4149 assert_eq!(held_epoch_key(&cid, &scope, 1).unwrap(), Some([0xA1u8; 32]));
4151 assert_eq!(held_epoch_key(&cid, &scope, 9).unwrap(), None, "unheld epoch is None");
4152
4153 store_epoch_key(&cid, &scope, 1, &[0xBBu8; 32]).unwrap();
4155 assert_eq!(held_epoch_key(&cid, &scope, 1).unwrap(), Some([0xBBu8; 32]));
4156 assert_eq!(held_epoch_keys(&cid, &scope).unwrap().len(), 3, "replace didn't add a row");
4157
4158 assert!(held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap().is_empty());
4161 assert_eq!(
4162 held_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 1).unwrap(),
4163 None,
4164 "epoch 1 under a different scope is not the channel's key"
4165 );
4166 }
4167
4168 #[test]
4169 fn at_rest_encryption_wraps_keys_and_metadata_on_disk() {
4170 let (_tmp, _guard) = init_test_db();
4171 crate::state::ENCRYPTION_KEY.set([0x55u8; 32], &[]);
4174 crate::state::set_encryption_enabled(true);
4175
4176 let mut c = v2_fixture("Secret HQ", &["wss://relay.example"]);
4177 c.community_root = [0x42u8; 32];
4178 c.description = Some("top secret".into());
4179 c.channels.push(private_channel(0x61, 0x62));
4180 save_community_v2(&c).unwrap();
4181 let cid = c.id().to_hex();
4182 store_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 0, &c.community_root).unwrap();
4183 set_community_banlist(&cid, &["deadbeef".repeat(8)], 1).unwrap();
4184
4185 {
4188 let conn = crate::db::get_db_connection_guard_static().unwrap();
4189 let (root_len, control_root_len, name, relays, description): (i64, i64, String, String, String) = conn
4190 .query_row(
4191 "SELECT length(server_root_key), length(control_root), name, relays, description
4192 FROM communities WHERE community_id = ?1",
4193 params![cid],
4194 |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
4195 )
4196 .unwrap();
4197 assert_eq!(root_len, 60, "server_root_key must be ciphertext, not a raw 32-byte key");
4198 assert_eq!(control_root_len, 60, "control_root must be ciphertext, not a raw 32-byte key");
4199 for (column, stored, plain) in [
4200 ("name", &name, "Secret HQ"),
4201 ("relays", &relays, r#"["wss://relay.example"]"#),
4202 ("description", &description, "top secret"),
4203 ] {
4204 assert_ne!(stored, plain, "{column} must not be plaintext on disk");
4205 assert!(crate::crypto::looks_encrypted(stored), "{column} column is ciphertext");
4206 }
4207 let (owner_pk, owner_salt, control_pk): (String, String, String) = conn
4208 .query_row(
4209 "SELECT owner_pubkey, owner_salt, control_pk FROM communities WHERE community_id = ?1",
4210 params![cid],
4211 |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
4212 )
4213 .unwrap();
4214 for (column, stored, plain) in [
4215 ("owner_pubkey", &owner_pk, crate::simd::hex::bytes_to_hex_32(&c.identity.owner_xonly)),
4216 ("owner_salt", &owner_salt, crate::simd::hex::bytes_to_hex_32(&c.identity.owner_salt)),
4217 ("control_pk", &control_pk, c.control_pk.unwrap().to_hex()),
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 mut stmt = conn
4223 .prepare("SELECT length(channel_key), name FROM community_channels WHERE community_id = ?1")
4224 .unwrap();
4225 let channels: Vec<(i64, String)> =
4226 stmt.query_map(params![cid], |r| Ok((r.get(0)?, r.get(1)?))).unwrap().map(Result::unwrap).collect();
4227 assert_eq!(channels.len(), 2);
4228 for (key_len, name) in &channels {
4229 assert_eq!(*key_len, 60, "channel_key must be ciphertext, Public placeholder and Private key alike");
4230 assert!(crate::crypto::looks_encrypted(name) && name != "general" && name != "staff", "channel name is ciphertext");
4231 }
4232 let banned_npub: String = conn
4234 .query_row("SELECT npub FROM community_bans WHERE community_id = ?1 LIMIT 1", params![cid], |r| r.get(0))
4235 .unwrap();
4236 assert!(crate::crypto::looks_encrypted(&banned_npub), "who is banned is sealed on disk, got {banned_npub}");
4237 let opened = crate::crypto::maybe_decrypt_text(&banned_npub);
4238 assert!(opened.starts_with("npub1"), "and opens to the form `events.npub` uses");
4239 let key_len: i64 = conn
4240 .query_row(
4241 "SELECT length(key) FROM community_epoch_keys WHERE community_id = ?1 LIMIT 1",
4242 params![cid],
4243 |r| r.get(0),
4244 )
4245 .unwrap();
4246 assert_eq!(key_len, 60, "epoch-archive key must be ciphertext");
4247 }
4248
4249 let loaded = load_community_v2(c.id()).unwrap().unwrap();
4251 assert_eq!(loaded.name, "Secret HQ");
4252 assert_eq!(loaded.description.as_deref(), Some("top secret"));
4253 assert_eq!(loaded.community_root, [0x42u8; 32]);
4254 assert_eq!(loaded.control_root, c.control_root);
4255 assert_eq!(loaded.control_pk, c.control_pk);
4256 assert_eq!(loaded.identity.owner_xonly, c.identity.owner_xonly);
4257 assert_eq!(loaded.identity.owner_salt, c.identity.owner_salt);
4258 assert_eq!(loaded.relays, vec!["wss://relay.example".to_string()]);
4259 assert_eq!(loaded.channels[0].name, "general");
4260 assert_eq!(loaded.channels[1].key, Some([0x62u8; 32]));
4261 assert_eq!(held_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 0).unwrap(), Some([0x42u8; 32]));
4262 assert_eq!(get_community_banlist(&cid).unwrap(), vec!["deadbeef".repeat(8)]);
4263
4264 crate::state::set_encryption_enabled(false);
4265 crate::state::ENCRYPTION_KEY.clear(&[]);
4266 }
4267
4268 #[test]
4269 fn an_encrypted_v2_community_loads_back_whole() {
4270 let (_tmp, _guard) = init_test_db();
4271 struct Vault;
4272 impl Drop for Vault {
4273 fn drop(&mut self) {
4274 crate::state::set_encryption_enabled(false);
4275 crate::state::ENCRYPTION_KEY.clear(&[]);
4276 }
4277 }
4278 let _vault = Vault;
4279 crate::state::ENCRYPTION_KEY.set([0x55u8; 32], &[]);
4280 crate::state::set_encryption_enabled(true);
4281
4282 let owner = nostr_sdk::prelude::Keys::generate();
4283 let g = crate::community::v2::control::genesis(
4284 &owner,
4285 crate::community::v2::control::CommunityMetadata { name: "Sealed".into(), ..Default::default() },
4286 1_000,
4287 )
4288 .unwrap();
4289 let mut v2 = crate::community::v2::community::CommunityV2::from_genesis(&g, "Sealed", Some("about".into()), vec!["wss://r".into()], 1_000);
4290 let mut private = v2.channels[0].clone();
4291 private.id = ChannelId([0x61; 32]);
4292 private.name = "staff".into();
4293 private.private = true;
4294 private.key = Some([0x62; 32]);
4295 v2.channels.push(private);
4296 save_community_v2(&v2).unwrap();
4297
4298 let name: String = crate::db::get_db_connection_guard_static()
4299 .unwrap()
4300 .query_row("SELECT name FROM communities WHERE community_id = ?1", params![v2.id().to_hex()], |r| r.get(0))
4301 .unwrap();
4302 assert!(crate::crypto::looks_encrypted(&name), "sealed on disk");
4303 let loaded = load_community_v2(v2.id()).unwrap().unwrap();
4304 assert_eq!(format!("{loaded:?}"), format!("{v2:?}"), "every field opens back to what was saved");
4305 }
4306
4307 #[test]
4308 fn at_rest_decrypt_tolerates_a_pre_migration_plaintext_row() {
4309 let (_tmp, _guard) = init_test_db();
4312 crate::state::set_encryption_enabled(false);
4313 let mut c = v2_fixture("Legacy HQ", &[]);
4314 c.community_root = [0x42u8; 32];
4315 c.channels.push(private_channel(0x61, 0x62));
4316 save_community_v2(&c).unwrap();
4317
4318 crate::state::ENCRYPTION_KEY.set([0x55u8; 32], &[]);
4319 crate::state::set_encryption_enabled(true);
4320 let loaded = load_community_v2(c.id()).unwrap().unwrap();
4321 assert_eq!(loaded.name, "Legacy HQ", "plaintext name reads through");
4322 assert_eq!(loaded.community_root, [0x42u8; 32], "raw 32-byte key reads through");
4323 assert_eq!(loaded.control_root, c.control_root, "raw 32-byte control root reads through");
4324 assert_eq!(loaded.channels[1].key, Some([0x62u8; 32]), "raw 32-byte channel key reads through");
4325
4326 crate::state::set_encryption_enabled(false);
4327 crate::state::ENCRYPTION_KEY.clear(&[]);
4328 }
4329
4330 #[test]
4331 fn large_epoch_round_trips_losslessly() {
4332 let (_tmp, _guard) = init_test_db();
4334 let mut c = v2_fixture("HQ", &[]);
4335 c.root_epoch = Epoch(u64::MAX - 3);
4336 c.channels[0].epoch = Epoch(u64::MAX - 7);
4337 save_community_v2(&c).unwrap();
4338 let loaded = load_community_v2(c.id()).unwrap().unwrap();
4339 assert_eq!(loaded.root_epoch, Epoch(u64::MAX - 3));
4340 assert_eq!(loaded.channels[0].epoch, Epoch(u64::MAX - 7));
4341 }
4342
4343 #[test]
4344 fn malformed_channel_id_row_errors_not_corrupts() {
4345 let (_tmp, _guard) = init_test_db();
4348 let (c, cid, _) = saved_v2("HQ");
4349 {
4350 let conn = crate::db::get_write_connection_guard_static().unwrap();
4351 conn.execute(
4352 "INSERT OR REPLACE INTO community_channels
4353 (channel_id, community_id, channel_key, epoch, name, created_at)
4354 VALUES (?1, ?2, ?3, 0, 'bad', 0)",
4355 rusqlite::params!["zz_not_hex", cid, &[0u8; 32][..]],
4356 )
4357 .unwrap();
4358 }
4359 assert!(load_community_v2(c.id()).is_err(), "malformed id must error, not corrupt");
4360 }
4361
4362 #[test]
4363 fn message_key_store_take_round_trip() {
4364 let (_tmp, _guard) = init_test_db();
4365 let eph = Keys::generate();
4366 let relays = vec!["wss://r.one".to_string()];
4367 store_message_key("inner_msg_id", "outer_evid", &eph, &relays).unwrap();
4369
4370 let (loaded, outer, r) = take_message_key("inner_msg_id").unwrap().expect("present");
4371 assert_eq!(
4372 loaded.secret_key().as_secret_bytes(),
4373 eph.secret_key().as_secret_bytes()
4374 );
4375 assert_eq!(outer, "outer_evid");
4376 assert_eq!(r, relays);
4377 assert!(take_message_key("inner_msg_id").unwrap().is_none());
4379 }
4380
4381 #[test]
4382 fn missing_community_is_none() {
4383 let (_tmp, _guard) = init_test_db();
4384 let absent = CommunityId([0x33u8; 32]);
4385 assert!(load_community_v2(&absent).unwrap().is_none());
4386 }
4387
4388 #[test]
4389 fn list_ids_reflects_saved() {
4390 let (_tmp, _guard) = init_test_db();
4391 let (a, _, _) = saved_v2("A");
4392 let (b, _, _) = saved_v2("B");
4393 let ids = list_community_ids().unwrap();
4394 assert_eq!(ids.len(), 2);
4395 assert!(ids.contains(a.id()) && ids.contains(b.id()));
4396 }
4397
4398 #[test]
4399 fn delete_community_clears_all_local_state() {
4400 let (_tmp, _guard) = init_test_db();
4401 let (c, cid, private) = archived_v2();
4402 save_public_invite(&"ab".repeat(32), &cid, "url", None, None).unwrap();
4403 save_pending_invite(&"cd".repeat(32), "{}", "npub1x", 0).unwrap();
4404 set_edition_head(&cid, &"a".repeat(64), 3, &[0x11u8; 32]).unwrap();
4405 assert!(!held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap().is_empty());
4406 assert!(!held_epoch_keys(&cid, &private).unwrap().is_empty());
4407
4408 delete_community(&cid).unwrap();
4409 assert!(!community_exists(c.id()).unwrap());
4410 assert!(community_id_for_channel(&c.channels[0].id.to_hex()).unwrap().is_none());
4411 assert!(community_id_for_channel(&private).unwrap().is_none());
4412 assert!(list_public_invites(&cid).unwrap().is_empty());
4413 assert_eq!(get_edition_head(&cid, &"a".repeat(64)).unwrap(), None, "edition heads cleared on delete");
4414 assert!(held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap().is_empty(), "epoch keys cleared on delete");
4415 assert!(held_epoch_keys(&cid, &private).unwrap().is_empty(), "channel epoch keys cleared on delete");
4416 }
4417
4418 #[test]
4419 fn delete_community_retain_keys_drops_state_but_keeps_epoch_keys() {
4420 let (_tmp, _guard) = init_test_db();
4423 let (c, cid, private) = archived_v2();
4424 save_public_invite(&"ab".repeat(32), &cid, "url", None, None).unwrap();
4425 set_edition_head(&cid, &"a".repeat(64), 3, &[0x11u8; 32]).unwrap();
4426
4427 let base_before = held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap();
4428 let chan_before = held_epoch_keys(&cid, &private).unwrap();
4429 assert!(!base_before.is_empty() && !chan_before.is_empty(), "base + channel keys archived");
4430
4431 delete_community_retain_keys(&cid).unwrap();
4432
4433 assert!(!community_exists(c.id()).unwrap());
4435 assert!(community_id_for_channel(&c.channels[0].id.to_hex()).unwrap().is_none());
4436 assert!(community_id_for_channel(&private).unwrap().is_none());
4437 assert!(list_public_invites(&cid).unwrap().is_empty());
4438 assert_eq!(get_edition_head(&cid, &"a".repeat(64)).unwrap(), None);
4439 assert_eq!(held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap(), base_before,
4441 "base epoch keys retained for self-scrub");
4442 assert_eq!(held_epoch_keys(&cid, &private).unwrap(), chan_before,
4443 "channel epoch keys retained for self-scrub");
4444 }
4445
4446 #[test]
4447 fn channel_resolves_to_owning_community() {
4448 let (_tmp, _guard) = init_test_db();
4449 let (_, cid, chan) = saved_v2("HQ");
4450 assert_eq!(community_id_for_channel(&chan).unwrap().as_deref(), Some(cid.as_str()));
4451 assert!(community_id_for_channel(&"ff".repeat(32)).unwrap().is_none());
4452 }
4453
4454 #[test]
4455 fn the_channel_cache_answers_in_bytes_and_hex_alike() {
4456 let (_tmp, _guard) = init_test_db();
4457 let (c, cid, chan) = saved_v2("Bytes");
4458 let ch = c.channels[0].id.0;
4459 assert_eq!(community_for_channel(&ch).unwrap(), Some(c.id().0));
4461 assert_eq!(channel_community_cache().read().unwrap().get(&ch), Some(&c.id().0), "the miss filled the cache");
4462 assert_eq!(community_for_channel(&ch).unwrap(), Some(c.id().0));
4463 assert_eq!(community_id_for_channel(&chan).unwrap().as_deref(), Some(cid.as_str()));
4464 assert_eq!(community_id_for_channel(&chan.to_uppercase()).unwrap(), None);
4466 assert_eq!(community_for_channel(&[0xFF; 32]).unwrap(), None);
4467 assert!(channel_community_cache().read().unwrap().get(&[0xFF; 32]).is_none(), "a miss is never cached");
4468 delete_community_retain_keys(&cid).unwrap();
4470 assert_eq!(community_for_channel(&ch).unwrap(), None);
4471 assert_eq!(community_id_for_channel(&chan).unwrap(), None);
4472 }
4473
4474 #[test]
4475 fn communities_that_ban_nobody_share_one_empty_set() {
4476 let (_tmp, _guard) = init_test_db();
4477 let (a, a_hex, _) = saved_v2("Calm");
4478 let (b, b_hex, _) = saved_v2("Quiet");
4479 let (ea, eb) = (banned_set_of(&a.id().0), banned_set(&b_hex));
4480 assert!(ea.is_empty() && std::sync::Arc::ptr_eq(&ea, &eb), "every empty banlist is the one shared set");
4481
4482 let villain = Keys::generate().public_key();
4483 set_community_banlist(&a_hex, &[villain.to_hex()], 10).unwrap();
4484 assert!(is_author_banned(&a_hex, &villain) && is_author_banned_in(&a.id().0, &villain));
4485 assert!(!is_author_banned_in(&b.id().0, &villain), "a ban stays in its own community");
4486 assert!(!std::sync::Arc::ptr_eq(&banned_set_of(&a.id().0), &empty_ban_set()));
4487
4488 set_community_banlist(&a_hex, &[], 11).unwrap();
4489 assert!(std::sync::Arc::ptr_eq(&banned_set_of(&a.id().0), &empty_ban_set()), "an emptied banlist returns to the shared set");
4490 assert!(!is_author_banned_in(&a.id().0, &villain));
4491 }
4492
4493 #[test]
4494 fn community_exists_reflects_saved() {
4495 let (_tmp, _guard) = init_test_db();
4496 let c = v2_fixture("A", &[]);
4497 assert!(!community_exists(c.id()).unwrap());
4498 save_community_v2(&c).unwrap();
4499 assert!(community_exists(c.id()).unwrap());
4500 }
4501
4502 #[test]
4503 fn a_block_drops_only_that_persons_parked_invites() {
4504 let (_tmp, _guard) = init_test_db();
4505 let (spam, friend) = ("cd".repeat(32), "ef".repeat(32));
4506 save_pending_invite(&spam, &v2_bundle("Spam"), "npub1spammer", 0).unwrap();
4507 save_pending_invite(&friend, &v2_bundle("Friends"), "npub1friend", 0).unwrap();
4508 assert_eq!(delete_pending_invites_from("npub1spammer").unwrap(), 1);
4509 let left: Vec<String> = list_pending_invites().unwrap().into_iter().map(|i| i.community_id).collect();
4510 assert_eq!(left, vec![friend], "the friend's invite stays");
4511 }
4512
4513 #[test]
4514 fn pending_invite_first_wins_and_round_trips() {
4515 let (_tmp, _guard) = init_test_db();
4516 let cid = "ab".repeat(32);
4517 let (first, second) = (v2_bundle("First"), v2_bundle("Second"));
4518 assert!(save_pending_invite(&cid, &first, "npub1inviter", 0).unwrap());
4521 assert!(!save_pending_invite(&cid, &second, "npub1other", 0).unwrap());
4522 assert!(pending_invite_exists(&cid).unwrap());
4523
4524 let listed = list_pending_invites().unwrap();
4525 assert_eq!(listed.len(), 1);
4526 assert_eq!(listed[0].community_id, cid);
4527 assert_eq!(listed[0].bundle_json, first, "original bundle preserved");
4528 assert_eq!(listed[0].inviter_npub, "npub1inviter");
4529
4530 assert_eq!(get_pending_invite(&cid).unwrap(), Some(first.clone()));
4532 assert!(pending_invite_exists(&cid).unwrap(), "get must not delete");
4533 delete_pending_invite(&cid).unwrap();
4534 assert!(!pending_invite_exists(&cid).unwrap());
4535 assert!(get_pending_invite(&cid).unwrap().is_none());
4536 }
4537
4538 #[test]
4539 fn purge_drops_invites_for_held_communities_only() {
4540 let (_tmp, _guard) = init_test_db();
4541 let (_, held_hex, _) = saved_v2("Held");
4544 save_pending_invite(&held_hex, "{\"bundle\":1}", "npub1inviter", 0).unwrap();
4545 let stranger = "ab".repeat(32);
4547 save_pending_invite(&stranger, "{\"bundle\":2}", "npub1inviter", 0).unwrap();
4548
4549 let n = purge_pending_invites_for_held_communities().unwrap();
4550 assert_eq!(n, 1, "only the held community's invite is purged");
4551 assert!(!pending_invite_exists(&held_hex).unwrap(), "held → invite gone");
4552 assert!(pending_invite_exists(&stranger).unwrap(), "unknown community → invite kept");
4553 }
4554
4555 #[test]
4556 fn an_invites_lifetime_runs_from_when_it_was_sent() {
4557 let (_tmp, _guard) = init_test_db();
4558 let lifetime = crate::event_handler::DIRECT_INVITE_LIFETIME_SECS as i64;
4559 let now = now_secs();
4560 let (old, fresh, unknown, deadline) = ("a1".repeat(32), "a2".repeat(32), "a3".repeat(32), "a4".repeat(32));
4561 for cid in [&old, &fresh, &unknown] {
4562 save_pending_invite(cid, "{}", "npub1x", 0).unwrap();
4563 }
4564 save_pending_invite(&deadline, "{}", "npub1x", now + 60).unwrap();
4565 set_pending_invite_sent(&old, now - lifetime - 1).unwrap();
4566 set_pending_invite_sent(&fresh, now - 60).unwrap();
4567 set_pending_invite_sent(&fresh, 1).unwrap();
4568 set_pending_invite_sent(&deadline, now - 60).unwrap();
4569
4570 let listed = list_pending_invites().unwrap();
4571 let get = |cid: &str| listed.iter().find(|i| i.community_id == cid);
4572 assert!(get(&old).is_none(), "sent past its lifetime, so gone though parked just now");
4573 let f = get(&fresh).unwrap();
4574 assert_eq!((f.sent_at, f.ends_at), (now - 60, now - 60 + lifetime), "the first send time stands");
4575 let u = get(&unknown).unwrap();
4576 assert_eq!((u.sent_at, u.ends_at), (0, u.received_at + lifetime));
4577 assert_eq!(get(&deadline).unwrap().ends_at, now + 60, "the sender's earlier deadline wins");
4578 assert_eq!(purge_expired_pending_invites().unwrap(), 1);
4579 }
4580
4581 #[test]
4582 fn an_invites_wraps_are_kept_once_each_up_to_a_cap_and_go_with_it() {
4583 let (_tmp, _guard) = init_test_db();
4584 let cid = "ef".repeat(32);
4585 note_pending_invite_wrap(&cid, &"01".repeat(32)).unwrap();
4586 assert!(pending_invite_wraps(&cid).unwrap().is_empty(), "no parked invite, nothing kept");
4587 save_pending_invite(&cid, "{}", "npub1x", 0).unwrap();
4588 for n in [1u8, 2, 1] {
4589 note_pending_invite_wrap(&cid, &format!("{n:02x}").repeat(32)).unwrap();
4590 }
4591 assert_eq!(pending_invite_wraps(&cid).unwrap(), ["01".repeat(32), "02".repeat(32)]);
4592 for n in 3u8..40 {
4593 note_pending_invite_wrap(&cid, &format!("{n:02x}").repeat(32)).unwrap();
4594 }
4595 assert_eq!(pending_invite_wraps(&cid).unwrap().len(), 16);
4596 delete_pending_invite(&cid).unwrap();
4597 assert!(pending_invite_wraps(&cid).unwrap().is_empty());
4598 }
4599
4600 #[test]
4601 fn decline_drops_pending_invite() {
4602 let (_tmp, _guard) = init_test_db();
4603 let cid = "cd".repeat(32);
4604 save_pending_invite(&cid, "{}", "npub1x", 0).unwrap();
4605 delete_pending_invite(&cid).unwrap();
4606 assert!(!pending_invite_exists(&cid).unwrap());
4607 }
4608
4609 #[test]
4610 fn pending_invites_are_capped_keeping_the_newest() {
4611 let (_tmp, _guard) = init_test_db();
4612 let bundle = v2_bundle("Flood");
4617 for i in 0..150u32 {
4618 let cid = format!("{:064x}", i);
4619 save_pending_invite(&cid, &bundle, "npub1x", 0).unwrap();
4620 }
4621 let all = list_pending_invites().unwrap();
4622 assert_eq!(all.len(), 100, "table capped at MAX_PENDING_INVITES");
4623 for i in 150..400u32 {
4625 let cid = format!("{:064x}", i);
4626 save_pending_invite(&cid, &bundle, "npub1x", 0).unwrap();
4627 }
4628 assert_eq!(list_pending_invites().unwrap().len(), 100, "cap holds under flood");
4629 }
4630
4631 #[test]
4636 fn expired_parked_invites_are_hidden_from_list_and_accept() {
4637 let (_tmp, _guard) = init_test_db();
4638 let now = now_secs();
4639 let live = "aa".repeat(32);
4640 let expired = "bb".repeat(32);
4641 let permanent = "cc".repeat(32);
4642
4643 save_pending_invite(&live, &v2_bundle("Live"), "npub1x", now + 3600).unwrap();
4644 save_pending_invite(&expired, &v2_bundle("Dead"), "npub1x", now - 1).unwrap();
4645 save_pending_invite(&permanent, &v2_bundle("Forever"), "npub1x", 0).unwrap();
4648
4649 let listed: Vec<String> = list_pending_invites().unwrap().into_iter().map(|i| i.community_id).collect();
4650 assert!(listed.contains(&live), "an unexpired invite still lists");
4651 assert!(listed.contains(&permanent), "a no-deadline invite still lists");
4652 assert!(!listed.contains(&expired), "an expired invite is hidden from the list");
4653
4654 assert!(get_pending_invite(&live).unwrap().is_some());
4655 assert!(get_pending_invite(&permanent).unwrap().is_some());
4656 assert!(
4657 get_pending_invite(&expired).unwrap().is_none(),
4658 "an expired invite must not be redeemable"
4659 );
4660
4661 assert!(pending_invite_exists(&expired).unwrap(), "hidden, not yet deleted");
4663 assert_eq!(purge_expired_pending_invites().unwrap(), 1);
4664 assert!(!pending_invite_exists(&expired).unwrap());
4665 assert!(pending_invite_exists(&live).unwrap(), "the sweep spares live invites");
4666 assert!(pending_invite_exists(&permanent).unwrap(), "and no-deadline ones");
4667 }
4668
4669 #[test]
4672 fn expiry_follows_the_senders_deadline_not_receipt_time() {
4673 let (_tmp, _guard) = init_test_db();
4674 let cid = "de".repeat(32);
4675 save_pending_invite(&cid, "{}", "npub1x", now_secs() - 10).unwrap();
4678 assert!(list_pending_invites().unwrap().is_empty(), "receipt time does not extend the deadline");
4679 assert!(get_pending_invite(&cid).unwrap().is_none());
4680 }
4681
4682 #[test]
4685 fn a_legacy_banlist_is_adopted_on_first_read() {
4686 let (_tmp, _guard) = init_test_db();
4687 let (_, cid, _) = saved_v2("Legacy bans");
4688 let banned = "ab".repeat(32);
4689 {
4690 let conn = crate::db::get_write_connection_guard_static().unwrap();
4691 conn.execute("DELETE FROM community_bans WHERE community_id = ?1", params![cid]).unwrap();
4692 conn.execute("UPDATE communities SET banlist = ?1 WHERE community_id = ?2", params![format!("[\"{banned}\"]"), cid]).unwrap();
4693 }
4694 assert_eq!(get_community_banlist(&cid).unwrap(), vec![banned.clone()]);
4695 assert_eq!(get_community_banlist(&cid).unwrap(), vec![banned], "and stays adopted");
4696 }
4697
4698 #[test]
4701 fn a_task_of_a_swapped_out_account_cannot_seal() {
4702 struct Vault;
4703 impl Drop for Vault {
4704 fn drop(&mut self) {
4705 crate::state::ENCRYPTION_KEY.clear(&[]);
4706 crate::state::set_encryption_enabled(false);
4707 }
4708 }
4709 const KA: [u8; 32] = [0x61; 32];
4710 const KB: [u8; 32] = [0x62; 32];
4711 let (_tmp, _guard) = init_test_db();
4712 let _vault = Vault;
4713 let account_a = crate::db::get_current_account().unwrap();
4714 crate::db::set_sql_setting("encryption_enabled".to_string(), "true".to_string()).unwrap();
4715 crate::state::ENCRYPTION_KEY.set(KA, &[]);
4716 crate::state::set_encryption_enabled(true);
4717 let (_, cid, ch) = saved_v2("A");
4718
4719 let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
4720 let late_write = |label: &'static str| {
4721 let (go, wait) = tokio::sync::oneshot::channel::<()>();
4722 let (cid, ch) = (cid.clone(), ch.clone());
4723 let task = {
4724 let _rt = rt.enter();
4725 crate::db::spawn_bound(async move {
4726 let _ = wait.await;
4727 set_community_pins(&cid, &ch, &format!("{{\"{label}\":1}}"), 1)
4728 })
4729 };
4730 (go, task)
4731 };
4732 let (go_plain, plain) = late_write("plain");
4733 let (go_foreign, foreign) = late_write("foreign");
4734
4735 let account_b = make_test_npub(TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
4737 crate::state::ENCRYPTION_KEY.clear(&[]);
4738 crate::state::set_encryption_enabled(false);
4739 crate::db::set_current_account(account_b.clone()).unwrap();
4740 crate::db::init_database(&account_b).unwrap();
4741 go_plain.send(()).unwrap();
4742 assert!(rt.block_on(plain).unwrap().is_err(), "no plaintext into an encrypted store");
4743 crate::state::ENCRYPTION_KEY.set(KB, &[]);
4744 crate::state::set_encryption_enabled(true);
4745 go_foreign.send(()).unwrap();
4746 assert!(rt.block_on(foreign).unwrap().is_err(), "no seal under another account's key");
4747
4748 crate::db::set_current_account(account_a.clone()).unwrap();
4749 crate::db::init_database(&account_a).unwrap();
4750 crate::state::ENCRYPTION_KEY.set(KA, &[]);
4751 assert_eq!(get_community_pins(&cid, &ch).unwrap(), None, "account A's store is untouched");
4752 }
4753
4754 #[test]
4758 fn a_legacy_account_moves_onto_its_own_salt_at_unlock() {
4759 use crate::crypto::{derive_key, Kdf};
4760 use crate::db::at_rest;
4761 struct Vault;
4762 impl Drop for Vault {
4763 fn drop(&mut self) {
4764 crate::state::ENCRYPTION_KEY.clear(&[]);
4765 crate::state::set_encryption_enabled(false);
4766 }
4767 }
4768 let (_tmp, _guard) = init_test_db();
4769 let _vault = Vault;
4770 let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
4771 let pin = "123456";
4772 let legacy = rt.block_on(derive_key(pin, &Kdf::Legacy));
4773 crate::state::ENCRYPTION_KEY.set(legacy, &[]);
4774 crate::state::set_encryption_enabled(true);
4775 crate::db::set_sql_setting("encryption_enabled".to_string(), "true".to_string()).unwrap();
4776 crate::db::set_sql_setting("security_type".to_string(), "pin".to_string()).unwrap();
4777 crate::db::set_sql_setting("last_vacuum".to_string(), "1".to_string()).unwrap();
4778 crate::db::set_pkey(&crate::crypto::encrypt_with_key("nsec1legacyaccount", &legacy).unwrap()).unwrap();
4779 let mut community = v2_fixture("Old", &["wss://r"]);
4780 community.channels.push(private_channel(0x61, 0x62));
4781 save_community_v2(&community).unwrap();
4782 let (cid, ch) = (community.id().to_hex(), community.channels[0].id.to_hex());
4783 set_community_pins(&cid, &ch, r#"{"pins":["old"]}"#, 1).unwrap();
4784 let dm_chat = make_test_npub(900_002);
4785 let dm = crate::types::Message { id: "e1".repeat(32), content: "said long ago".into(), at: 1_600_000_000_000, mine: true, ..Default::default() };
4786 rt.block_on(crate::db::events::save_message(&dm_chat, &dm)).unwrap();
4787 let dm_int = crate::db::id_cache::get_or_create_chat_id(&dm_chat).unwrap();
4788 let read = || {
4789 (
4790 get_community_pins(&cid, &ch).unwrap(),
4791 load_community_v2(community.id()).unwrap().map(|c| format!("{c:?}")),
4792 rt.block_on(crate::db::events::get_message_views(dm_int, 10, 0)).unwrap().into_iter().map(|m| m.content).collect::<Vec<_>>(),
4793 )
4794 };
4795 let before = read();
4796 assert_eq!(before.1, Some(format!("{community:?}")));
4797 assert_eq!(before.2, vec!["said long ago".to_string()]);
4798
4799 assert!(!rt.block_on(at_rest::upgrade_after_unlock(pin, &[0x77; 32])).unwrap(), "a key that proves nothing moves nothing");
4800 assert_eq!(Kdf::of_account().unwrap(), Kdf::Legacy);
4801 crate::db::set_sql_setting("security_type".to_string(), "biometric".to_string()).unwrap();
4802 assert!(!rt.block_on(at_rest::upgrade_after_unlock(pin, &legacy)).unwrap(), "a biometric account stays put");
4803 crate::db::set_sql_setting("security_type".to_string(), "pin".to_string()).unwrap();
4804 assert_eq!(read(), before);
4805
4806 {
4808 let conn = crate::db::get_write_connection_guard_static().unwrap();
4809 conn.execute_batch("CREATE TABLE unaddressable (k TEXT PRIMARY KEY, v TEXT) WITHOUT ROWID;").unwrap();
4810 conn.execute("INSERT INTO unaddressable VALUES ('a', ?1)", [crate::crypto::encrypt_with_key("x", &legacy).unwrap()]).unwrap();
4811 }
4812 assert!(rt.block_on(at_rest::upgrade_after_unlock(pin, &legacy)).is_err());
4813 assert_eq!((Kdf::of_account().unwrap(), read()), (Kdf::Legacy, before.clone()), "nothing moved");
4814 assert_eq!(crate::state::ENCRYPTION_KEY.get(), Some(legacy));
4815 assert!(!rt.block_on(at_rest::upgrade_after_unlock(pin, &legacy)).unwrap(), "backed off");
4816 crate::db::get_write_connection_guard_static().unwrap().execute_batch("DROP TABLE unaddressable;").unwrap();
4817 crate::db::settings::remove_setting("kdf_upgrade_attempt").unwrap();
4818
4819 assert!(rt.block_on(at_rest::upgrade_after_unlock(pin, &legacy)).unwrap());
4820 let kdf = Kdf::of_account().unwrap();
4821 assert!(!kdf.is_legacy(), "the salt is recorded");
4822 let salted = rt.block_on(derive_key(pin, &kdf));
4823 assert_eq!(crate::state::ENCRYPTION_KEY.get(), Some(salted), "the session carries on under the new key");
4824 assert_eq!(read(), before, "everything reads back");
4825 {
4826 let conn = crate::db::get_write_connection_guard_static().unwrap();
4827 let tx = conn.unchecked_transaction().unwrap();
4828 assert_eq!(at_rest::sweep_residue_in_tx(&tx, &legacy, None).unwrap(), 0, "nothing opens under the legacy key");
4829 }
4830 assert_eq!(crate::db::get_sql_setting("last_vacuum".to_string()).unwrap(), None, "a vacuum is due");
4831 assert!(!rt.block_on(at_rest::upgrade_after_unlock(pin, &salted)).unwrap(), "the next unlock has nothing to do");
4832
4833 assert!(crate::crypto::install_unlocked_key(&legacy, &Kdf::Legacy).is_err());
4836 assert_eq!(crate::state::ENCRYPTION_KEY.get(), Some(salted));
4837 let again = Kdf::fresh();
4838 let again_key = rt.block_on(derive_key(pin, &again));
4839 assert!(!at_rest::upgrade_legacy_derivation(&legacy, &again_key, &again, &|_| {}).unwrap());
4840 assert_eq!(Kdf::of_account().unwrap(), kdf);
4841 }
4842
4843 const CRASH_PIN: &str = "424242";
4844
4845 #[test]
4848 #[ignore = "driven by the_upgrade_survives_a_kill_at_any_moment"]
4849 fn upgrade_crash_child() {
4850 use std::io::Write;
4851 let (Ok(root), Ok(npub)) = (std::env::var("VECTOR_CRASH_ROOT"), std::env::var("VECTOR_CRASH_NPUB")) else { return };
4852 crate::db::set_app_data_dir(root.into());
4853 crate::db::set_current_account(npub.clone()).unwrap();
4854 crate::db::init_database(&npub).unwrap();
4855 crate::state::init_encryption_enabled();
4856 let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
4857 let legacy = rt.block_on(crate::crypto::derive_key(CRASH_PIN, &crate::crypto::Kdf::Legacy));
4858 crate::state::ENCRYPTION_KEY.set(legacy, &[]);
4859 let kdf = crate::crypto::Kdf::fresh();
4861 let salted = rt.block_on(crate::crypto::derive_key(CRASH_PIN, &kdf));
4862 println!("CHILD READY");
4863 std::io::stdout().flush().unwrap();
4864 assert!(crate::db::at_rest::upgrade_legacy_derivation(&legacy, &salted, &kdf, &|_| {}).unwrap());
4865 println!("CHILD DONE");
4866 std::io::stdout().flush().unwrap();
4867 }
4868
4869 #[test]
4873 #[ignore = "spawns and kills child processes; run with --ignored"]
4874 fn the_upgrade_survives_a_kill_at_any_moment() {
4875 use crate::crypto::{derive_key, Kdf};
4876 use std::io::BufRead;
4877 struct Vault;
4878 impl Drop for Vault {
4879 fn drop(&mut self) {
4880 crate::state::ENCRYPTION_KEY.clear(&[]);
4881 crate::state::set_encryption_enabled(false);
4882 }
4883 }
4884 let (_tmp, _guard) = init_test_db();
4885 let _vault = Vault;
4886 let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
4887 let legacy = rt.block_on(derive_key(CRASH_PIN, &Kdf::Legacy));
4888
4889 let template = crate::db::get_current_account().unwrap();
4891 crate::state::ENCRYPTION_KEY.set(legacy, &[]);
4892 crate::state::set_encryption_enabled(true);
4893 crate::db::set_sql_setting("encryption_enabled".to_string(), "true".to_string()).unwrap();
4894 crate::db::set_sql_setting("security_type".to_string(), "pin".to_string()).unwrap();
4895 crate::db::set_pkey(&crate::crypto::encrypt_with_key("nsec1crashaccount", &legacy).unwrap()).unwrap();
4896 let (_, cid, ch) = saved_v2("Crash");
4897 set_community_pins(&cid, &ch, r#"{"pins":["kept"]}"#, 1).unwrap();
4898 let chat = crate::db::id_cache::get_or_create_chat_id(&make_test_npub(900_003)).unwrap();
4899 {
4900 let mut conn = crate::db::get_write_connection_guard_static().unwrap();
4901 let tx = conn.transaction().unwrap();
4902 for i in 0..20_000u32 {
4903 tx.execute(
4904 "INSERT INTO events (id, kind, chat_id, content, created_at, received_at) VALUES (?1, 14, ?2, ?3, ?4, ?4)",
4905 rusqlite::params![format!("{i:064x}"), chat, crate::crypto::encrypt_with_key(&format!("message {i}"), &legacy).unwrap(), i],
4906 ).unwrap();
4907 }
4908 tx.commit().unwrap();
4909 }
4910 crate::db::close_database();
4911 let root = crate::db::shared_test_data_dir().to_path_buf();
4912
4913 let copy_of_template = || -> String {
4914 let npub = make_test_npub(TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
4915 std::fs::create_dir_all(root.join(&npub)).unwrap();
4916 for entry in std::fs::read_dir(root.join(&template)).unwrap().flatten() {
4917 std::fs::copy(entry.path(), root.join(&npub).join(entry.file_name())).unwrap();
4918 }
4919 npub
4920 };
4921 let run_child = |npub: &str, after: Option<std::time::Duration>| -> std::time::Duration {
4923 let mut child = std::process::Command::new(std::env::current_exe().unwrap())
4924 .args(["--exact", "db::community::tests::upgrade_crash_child", "--ignored", "--nocapture", "--test-threads=1"])
4925 .env("VECTOR_CRASH_ROOT", &root)
4926 .env("VECTOR_CRASH_NPUB", npub)
4927 .stdout(std::process::Stdio::piped())
4928 .stderr(std::process::Stdio::null())
4929 .spawn()
4930 .unwrap();
4931 let mut lines = std::io::BufReader::new(child.stdout.take().unwrap()).lines();
4932 while let Some(Ok(line)) = lines.next() {
4933 if line.contains("CHILD READY") {
4934 break;
4935 }
4936 }
4937 let ready = std::time::Instant::now();
4938 match after {
4939 Some(delay) => {
4940 std::thread::sleep(delay);
4941 let _ = child.kill();
4942 }
4943 None => {
4944 while let Some(Ok(line)) = lines.next() {
4945 if line.contains("CHILD DONE") {
4946 break;
4947 }
4948 }
4949 }
4950 }
4951 let _ = child.wait();
4952 ready.elapsed()
4953 };
4954 let verify = |npub: &str| -> bool {
4955 crate::db::set_current_account(npub.to_string()).unwrap();
4956 crate::db::init_database(npub).unwrap();
4957 let kdf = Kdf::of_account().unwrap();
4958 let key = rt.block_on(derive_key(CRASH_PIN, &kdf));
4959 crate::state::ENCRYPTION_KEY.set(key, &[]);
4960 let pkey = crate::db::get_pkey().unwrap().unwrap();
4961 assert_eq!(crate::crypto::decrypt_with_key(&pkey, &key).unwrap(), "nsec1crashaccount", "{npub}: the stored key opens");
4962 assert_eq!(get_community_pins(&cid, &ch).unwrap().map(|p| p.0).as_deref(), Some(r#"{"pins":["kept"]}"#));
4963 let conn = crate::db::get_db_connection_guard_static().unwrap();
4964 let mut stmt = conn.prepare("SELECT content FROM events WHERE chat_id = ?1").unwrap();
4965 let unopened = stmt
4966 .query_map([chat], |r| r.get::<_, String>(0)).unwrap()
4967 .flatten()
4968 .filter(|c| crate::crypto::decrypt_with_key(c, &key).is_err())
4969 .count();
4970 assert_eq!(unopened, 0, "{npub}: every message opens under the recorded derivation");
4971 !kdf.is_legacy()
4972 };
4973
4974 let first = copy_of_template();
4976 let whole = run_child(&first, None);
4977 assert!(verify(&first), "an uninterrupted run upgrades");
4978 let mut outcomes = (0, 0);
4979 let mut trace = String::new();
4980 for step in 0..24u32 {
4981 let npub = copy_of_template();
4982 run_child(&npub, Some(whole * step / 21));
4983 let upgraded = verify(&npub);
4984 trace.push(if upgraded { 'U' } else { 'L' });
4985 if upgraded { outcomes.1 += 1 } else { outcomes.0 += 1 }
4986 }
4987 println!("kill outcomes in time order: {trace}");
4988 println!("crash sweep over a {whole:?} transaction: {} left legacy, {} upgraded", outcomes.0, outcomes.1);
4989 assert!(outcomes.0 >= 10, "most kills land inside the transaction and roll it back");
4990 assert!(outcomes.1 > 0, "and the sweep reaches past the commit");
4991 }
4992
4993 #[test]
4997 fn the_key_derivation_moves_with_every_migration() {
4998 use crate::crypto::Kdf;
4999 use crate::db::at_rest;
5000 struct Vault;
5001 impl Drop for Vault {
5002 fn drop(&mut self) {
5003 crate::state::ENCRYPTION_KEY.clear(&[]);
5004 crate::state::set_encryption_enabled(false);
5005 }
5006 }
5007 let (_tmp, _guard) = init_test_db();
5008 let _vault = Vault;
5009 assert_eq!(Kdf::of_account().unwrap(), Kdf::Legacy, "no row reads as the legacy salt");
5010 save_community_v2(&v2_fixture("K", &[])).unwrap();
5011
5012 let (k1, key1) = (Kdf::fresh(), [0x51; 32]);
5013 at_rest::enable(&key1, &k1, "pin", None, None, &|_| {}).unwrap();
5014 assert_eq!(Kdf::of_account().unwrap(), k1);
5015
5016 let (k2, key2) = (Kdf::fresh(), [0x52; 32]);
5017 assert!(at_rest::rekey(&[0x5F; 32], &key2, &k2, "pin", None, &|_| {}).is_err());
5018 assert_eq!(Kdf::of_account().unwrap(), k1, "a refused change keeps the derivation");
5019 at_rest::rekey(&key1, &key2, &k2, "pin", None, &|_| {}).unwrap();
5020 assert_eq!(Kdf::of_account().unwrap(), k2);
5021
5022 at_rest::disable(&key2, &|_| {}).unwrap();
5023 assert_eq!(Kdf::of_account().unwrap(), Kdf::Legacy, "a plaintext store keeps no derivation");
5024
5025 let k3 = Kdf::fresh();
5026 let sealed = crate::crypto::encrypt_with_key("nsec1setup", &[0x53; 32]).unwrap();
5027 crate::db::settings::commit_account_setup(&sealed, true, Some("pin"), None, None, k3.descriptor().as_deref()).unwrap();
5028 assert_eq!(Kdf::of_account().unwrap(), k3, "setup records the salt with the key it sealed");
5029 }
5030
5031 #[test]
5032 fn the_identity_opens_under_the_users_proof_and_nothing_else() {
5033 use crate::crypto::{derive_key, Kdf};
5034 use crate::db::at_rest::{self, open_identity_secrets, CREDENTIAL_INCORRECT};
5035 struct Vault;
5036 impl Drop for Vault {
5037 fn drop(&mut self) {
5038 crate::state::ENCRYPTION_KEY.clear(&[]);
5039 crate::state::set_encryption_enabled(false);
5040 }
5041 }
5042 let (_tmp, _guard) = init_test_db();
5043 let _vault = Vault;
5044 let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
5045 crate::db::set_pkey("nsec1identity").unwrap();
5046 crate::db::set_seed("abandon ability able").unwrap();
5047 let plain = open_identity_secrets(None).unwrap();
5048 assert_eq!((plain.0.as_str(), plain.1.as_deref().map(|s| s.as_str())), ("nsec1identity", Some("abandon ability able")));
5049
5050 let kdf = Kdf::fresh();
5051 let key = rt.block_on(derive_key("424242", &kdf));
5052 at_rest::enable(&key, &kdf, "pin", None, None, &|_| {}).unwrap();
5053 assert!(crate::state::ENCRYPTION_KEY.get().is_some(), "the session holds the key");
5054 assert!(open_identity_secrets(None).is_err(), "a sealed store opens nothing on the session alone");
5055 assert_eq!(rt.block_on(at_rest::prove_credential("000000")).unwrap_err(), CREDENTIAL_INCORRECT);
5056 assert_eq!(open_identity_secrets(Some(&[0x09; 32])).unwrap_err(), CREDENTIAL_INCORRECT);
5057
5058 let proven = rt.block_on(at_rest::prove_credential("424242")).unwrap();
5059 let (nsec, seed) = open_identity_secrets(Some(&proven)).unwrap();
5060 assert_eq!((nsec.as_str(), seed.as_deref().map(|s| s.as_str())), ("nsec1identity", Some("abandon ability able")));
5061
5062 for _ in 0..4 {
5064 assert_eq!(rt.block_on(at_rest::prove_credential("000000")).unwrap_err(), CREDENTIAL_INCORRECT);
5065 }
5066 assert_eq!(rt.block_on(at_rest::prove_credential("000000")).unwrap_err(), CREDENTIAL_INCORRECT);
5067 let locked = rt.block_on(at_rest::prove_credential("424242")).unwrap_err();
5068 assert!(locked.starts_with("CREDENTIAL_LOCKED:"), "{locked}");
5069 crate::db::remove_setting("credential_retry_at").unwrap();
5070 rt.block_on(at_rest::prove_credential("424242")).unwrap();
5071 assert!(crate::db::get_sql_setting("credential_failures".to_string()).unwrap().is_none());
5072
5073 let far = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_secs() + 86_400 * 30;
5075 crate::db::set_sql_setting("credential_retry_at".to_string(), far.to_string()).unwrap();
5076 let locked = rt.block_on(at_rest::prove_credential("424242")).unwrap_err();
5077 let secs: u64 = locked.strip_prefix("CREDENTIAL_LOCKED:").unwrap().parse().unwrap();
5078 assert!(secs <= 15 * 60, "{secs}");
5079 crate::db::remove_setting("credential_retry_at").unwrap();
5080
5081 crate::db::set_seed("abandon ability able").unwrap();
5083 assert_eq!(open_identity_secrets(Some(&proven)).unwrap().1.as_deref().map(|s| s.as_str()), Some("abandon ability able"));
5084 crate::db::set_seed("deadbeef").unwrap();
5085 let (nsec, seed) = open_identity_secrets(Some(&proven)).unwrap();
5086 assert!(nsec.starts_with("nsec1") && seed.is_none());
5087 }
5088
5089 #[test]
5093 fn reads_racing_pin_changes_always_open() {
5094 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
5095 use std::sync::Arc;
5096 struct Vault;
5097 impl Drop for Vault {
5098 fn drop(&mut self) {
5099 crate::state::ENCRYPTION_KEY.clear(&[]);
5100 crate::state::set_encryption_enabled(false);
5101 }
5102 }
5103 let (_tmp, _guard) = init_test_db();
5104 let _vault = Vault;
5105 let keys: Vec<[u8; 32]> = (0u8..31).map(|i| [0x90 + i; 32]).collect();
5106 crate::state::ENCRYPTION_KEY.set(keys[0], &[]);
5107 crate::state::set_encryption_enabled(true);
5108 let (_, cid, ch) = saved_v2("Read");
5109 let pinned = r#"{"pins":["kept"]}"#;
5110 set_community_pins(&cid, &ch, pinned, 1).unwrap();
5111
5112 let stop = Arc::new(AtomicBool::new(false));
5113 let (reads, garbled) = (Arc::new(AtomicU64::new(0)), Arc::new(AtomicU64::new(0)));
5114 let reader = {
5115 let (stop, reads, garbled, cid, ch) = (stop.clone(), reads.clone(), garbled.clone(), cid.clone(), ch.clone());
5116 std::thread::spawn(move || {
5117 while !stop.load(Ordering::SeqCst) {
5118 let got = get_community_pins(&cid, &ch).unwrap().map(|(c, _)| c);
5119 reads.fetch_add(1, Ordering::SeqCst);
5120 if got.as_deref() != Some(pinned) {
5121 garbled.fetch_add(1, Ordering::SeqCst);
5122 }
5123 }
5124 })
5125 };
5126 for pair in keys.windows(2) {
5127 crate::db::at_rest::rekey(&pair[0], &pair[1], &crate::crypto::Kdf::fresh(), "pin", None, &|_| {}).unwrap();
5128 let seen = reads.load(Ordering::SeqCst);
5131 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
5132 while reads.load(Ordering::SeqCst) < seen + 2 {
5133 assert!(std::time::Instant::now() < deadline, "reads stopped completing across a PIN change");
5134 std::thread::yield_now();
5135 }
5136 }
5137 stop.store(true, Ordering::SeqCst);
5138 reader.join().unwrap();
5139 assert!(reads.load(Ordering::SeqCst) > 0);
5140 assert_eq!(garbled.load(Ordering::SeqCst), 0, "no read across a PIN change came back unopened");
5141 std::thread::sleep(std::time::Duration::from_millis(600));
5142 assert!(!crate::state::PREVIOUS_AT_REST_KEY.has_key(), "the replaced key is wiped after its grace");
5143 }
5144
5145 #[test]
5148 fn writes_racing_pin_changes_land_on_the_final_key() {
5149 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
5150 use std::sync::Arc;
5151 struct Vault;
5152 impl Drop for Vault {
5153 fn drop(&mut self) {
5154 crate::state::ENCRYPTION_KEY.clear(&[]);
5155 crate::state::set_encryption_enabled(false);
5156 }
5157 }
5158 let (_tmp, _guard) = init_test_db();
5159 let _vault = Vault;
5160 let keys: Vec<[u8; 32]> = (0u8..21).map(|i| [0x40 + i; 32]).collect();
5161 crate::state::ENCRYPTION_KEY.set(keys[0], &[]);
5162 crate::state::set_encryption_enabled(true);
5163 let (_, cid, ch) = saved_v2("Race");
5164
5165 let stop = Arc::new(AtomicBool::new(false));
5166 let last = Arc::new(AtomicU64::new(0));
5167 let writer = {
5168 let (stop, last, cid, ch) = (stop.clone(), last.clone(), cid.clone(), ch.clone());
5169 std::thread::spawn(move || {
5170 let mut i = 0u64;
5171 while !stop.load(Ordering::SeqCst) {
5172 i += 1;
5173 set_community_pins(&cid, &ch, &format!("{{\"v\":{i}}}"), i as i64).unwrap();
5174 merge_community_ban_marks(&cid, &[(format!("npub{i}"), i)].into_iter().collect()).unwrap();
5175 last.store(i, Ordering::SeqCst);
5176 }
5177 })
5178 };
5179 while last.load(Ordering::SeqCst) == 0 {
5180 std::thread::yield_now();
5181 }
5182 for pair in keys.windows(2) {
5183 crate::db::at_rest::rekey(&pair[0], &pair[1], &crate::crypto::Kdf::fresh(), "pin", None, &|_| {}).unwrap();
5184 }
5185 stop.store(true, Ordering::SeqCst);
5186 writer.join().unwrap();
5187
5188 let n = last.load(Ordering::SeqCst);
5189 assert_eq!(get_community_pins(&cid, &ch).unwrap(), Some((format!("{{\"v\":{n}}}"), n as i64)));
5190 let marks = get_community_ban_marks(&cid).unwrap();
5191 assert_eq!(marks.len() as u64, n, "every merged mark survives the key changes");
5192 }
5193
5194 #[test]
5198 fn a_v2_link_counts_the_members_who_joined_through_it() {
5199 use crate::community::v2::guestbook::{GuestbookEntry, GuestbookEvent};
5200 let (_tmp, _guard) = init_test_db();
5201 let owner = nostr_sdk::prelude::Keys::generate();
5202 let g = crate::community::v2::control::genesis(
5203 &owner,
5204 crate::community::v2::control::CommunityMetadata { name: "Hub".into(), ..Default::default() },
5205 1_000,
5206 )
5207 .unwrap();
5208 let v2 = crate::community::v2::community::CommunityV2::from_genesis(&g, "Hub", None, vec!["wss://r".into()], 1_000);
5209 save_community_v2(&v2).unwrap();
5210 let cid = v2.id().to_hex();
5211
5212 let me = owner.public_key();
5213 let someone_else = nostr_sdk::prelude::Keys::generate().public_key();
5214 let (a, b, c) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
5215 let join = |n: u8, member: PublicKey, by: Option<(String, &str)>| GuestbookEvent {
5216 epoch: None,
5217 observed_at: None,
5218 rumor_id: [n; 32],
5219 entry: GuestbookEntry::Join { member, invited_by: by.map(|(c, l)| (c, l.to_string())), at_ms: n as u64 },
5220 };
5221 let events = vec![
5222 join(1, a, Some((me.to_hex(), "hub"))),
5223 join(2, b, Some((me.to_bech32().unwrap(), "hub"))),
5224 join(3, a, Some((me.to_hex(), "hub"))),
5225 join(4, c, Some((me.to_hex(), ""))),
5226 join(5, c, Some((someone_else.to_hex(), "hub"))),
5227 join(6, b, None),
5228 ];
5229 set_guestbook(&cid, &events, 9).unwrap();
5230
5231 let counts = community_invite_join_counts(&cid, &me).unwrap();
5232 assert_eq!(counts.get("hub"), Some(&2), "a rejoin counts once, either spelling of the creator counts");
5233 assert_eq!(counts.get(""), Some(&1), "an unlabeled link's joins are kept apart");
5234 assert_eq!(counts.len(), 2, "another creator's link and a bare join count for nobody here");
5235 }
5236
5237 #[test]
5238 fn a_group_chat_becomes_a_community_with_a_second_channel_or_an_invite_link() {
5239 let (_tmp, _guard) = init_test_db();
5240 let is = |c: &crate::community::v2::community::CommunityV2| crate::notify::is_community(&c.id().to_hex());
5241
5242 let mut chat = v2_fixture("Friends", &["wss://r"]);
5243 save_community_v2(&chat).unwrap();
5244 assert!(!is(&chat), "one channel, no link: a group chat");
5245 assert_eq!(crate::notify::default_level(Some(&chat.id().to_hex())), crate::notify::NotifyLevel::All);
5246
5247 let mut second = chat.channels[0].clone();
5248 second.id = crate::community::ChannelId([0x42; 32]);
5249 second.name = "random".into();
5250 chat.channels.push(second);
5251 save_community_v2(&chat).unwrap();
5252 assert!(is(&chat), "a second channel makes it a community");
5253 assert_eq!(crate::notify::default_level(Some(&chat.id().to_hex())), crate::notify::NotifyLevel::Mentions);
5254
5255 let open = v2_fixture("Open", &["wss://r"]);
5256 save_community_v2(&open).unwrap();
5257 assert!(!is(&open));
5258 set_community_invite_registry(&open.id().to_hex(), &["loc1".into()]).unwrap();
5259 assert!(is(&open), "an invite link makes it a community");
5260 set_community_invite_registry(&open.id().to_hex(), &[]).unwrap();
5261 assert!(!is(&open), "revoking the last link makes it a group chat again");
5262
5263 assert_eq!(crate::notify::default_level(None), crate::notify::NotifyLevel::All, "a DM rings for everything");
5264 }
5265
5266 #[test]
5267 fn every_encrypting_writer_is_covered_by_the_at_rest_sweep() {
5268 use crate::db::at_rest;
5269 const K: [u8; 32] = [0x31; 32];
5270 const K2: [u8; 32] = [0x32; 32];
5271 const WRONG: [u8; 32] = [0x39; 32];
5272 struct Vault;
5273 impl Drop for Vault {
5274 fn drop(&mut self) {
5275 crate::state::ENCRYPTION_KEY.clear(&[]);
5276 crate::state::set_encryption_enabled(false);
5277 }
5278 }
5279 let (_tmp, _guard) = init_test_db();
5280 let _vault = Vault;
5281 crate::state::ENCRYPTION_KEY.set(K, &[]);
5282 crate::state::set_encryption_enabled(true);
5283
5284 let mut v2 = v2_fixture("HQ", &["wss://r"]);
5285 v2.description = Some("about".into());
5286 let image = |url: &str| crate::community::v2::control::ImageRef {
5287 url: url.into(), key: "0".repeat(64), nonce: "1".repeat(32), hash: "a".repeat(64), extra: Default::default(),
5288 };
5289 v2.icon = Some(image("https://blossom.example/icon"));
5290 v2.banner = Some(image("https://blossom.example/banner"));
5291 v2.meta_custom = Some([("k".to_string(), serde_json::Value::from("v"))].into_iter().collect());
5292 v2.channels[0].voice = Some(true);
5293 v2.channels[0].meta_extra.insert("vnd".into(), serde_json::Value::from(7));
5294 v2.channels.push(private_channel(0x61, 0x62));
5295 save_community_v2(&v2).unwrap();
5296 let cid = v2.id().to_hex();
5297 let ch = v2.channels[0].id.to_hex();
5298 let private = v2.channels[1].id.to_hex();
5299 store_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 0, &v2.community_root).unwrap();
5300 store_epoch_key(&cid, &private, 0, &[0x62; 32]).unwrap();
5301 park_channel_key(&cid, &private, 3, &[0x33; 32], &"ab".repeat(32)).unwrap();
5302 store_message_key("m1", "o1", &nostr_sdk::prelude::Keys::generate(), &["wss://r".into()]).unwrap();
5303 let owner = nostr_sdk::prelude::Keys::generate();
5304 store_wrap_owner("m1", "o1", &owner, &["wss://r".into()]).unwrap();
5305 save_pending_invite(&"de".repeat(32), r#"{"bundle":1}"#, "npub1inviter", now_secs() + 3600).unwrap();
5306 save_public_invite(&"ab".repeat(32), &cid, "https://vectorapp.io/invite#x", None, Some("Label")).unwrap();
5307 set_community_policy(&cid, "p1", r#"{"format":1}"#, "hh", true, 0).unwrap();
5308 merge_community_ban_marks(&cid, &[("npub1banned".to_string(), 5u64)].into_iter().collect()).unwrap();
5309 set_community_roles(&cid, &crate::community::roles::CommunityRoles::default(), 1).unwrap();
5310 set_community_invite_registry(&cid, &["loc1".into()]).unwrap();
5311 replace_invite_link_sets(&cid, &[InviteLinkSetRow { creator_hex: "cd".repeat(32), locators: vec!["l1".into()] }]).unwrap();
5312 set_guestbook(&cid, &[], 9).unwrap();
5313 set_community_pins(&cid, &ch, r#"{"pins":["x"]}"#, 1).unwrap();
5314 record_audit_local(&cid, "e1", 5, r#"{"action":"message_delete"}"#).unwrap();
5315 let control_wrap = br#"{"kind":1059,"content":"a control wrap as a relay served it"}"#.to_vec();
5316 store_control_wraps(&cid, &[0x77; 32], 1, 5, &[([0x11; 32], 5, Some(control_wrap.clone())), ([0x12; 32], 6, None)]).unwrap();
5317 let control_wraps = || control_wrap_page(&cid, &[0x77; 32], None, 10).unwrap();
5318 assert_eq!(control_wraps(), vec![([0x11; 32], 5, control_wrap.clone())]);
5319 let on_disk: Vec<u8> = crate::db::get_db_connection_guard_static().unwrap()
5320 .query_row("SELECT wrap FROM community_control_wraps WHERE wrap IS NOT NULL", [], |r| r.get(0)).unwrap();
5321 assert_ne!(on_disk, control_wrap, "a held Control wrap is sealed on disk");
5322
5323 let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
5325 let dm_chat = make_test_npub(900_000);
5326 let dm = crate::types::Message {
5327 id: "a1".repeat(32),
5328 content: "the message itself".into(),
5329 at: 1_700_000_000_000,
5330 mine: true,
5331 preview_metadata: Some(crate::types::SiteMetadata {
5332 domain: "example.com".into(), og_title: Some("A title".into()), og_description: None,
5333 og_image: None, og_url: Some("https://example.com/a".into()), og_type: None,
5334 title: None, description: None, favicon: None,
5335 }),
5336 attachments: vec![crate::types::Attachment {
5337 id: "b2".repeat(32), key: "c3".repeat(32), nonce: "d4".repeat(16), extension: "jpg".into(),
5338 name: "passport.jpg".into(), url: "https://blossom.example/x.jpg".into(), size: 42,
5339 img_meta: Some(crate::types::ImageMetadata { thumbhash: "thumb".into(), width: 4, height: 3 }),
5340 fallback_urls: vec!["https://mirror.example/x.jpg".into()],
5341 ..Default::default()
5342 }],
5343 ..Default::default()
5344 };
5345 rt.block_on(crate::db::events::save_message(&dm_chat, &dm)).unwrap();
5346 let dm_chat_int = crate::db::id_cache::get_or_create_chat_id(&dm_chat).unwrap();
5347 let (wrap, rumor) = {
5348 use crate::event_ext::FinalizeUnsignedWithId;
5349 use nostr_sdk::prelude::*;
5350 let ephemeral = Keys::generate();
5351 let wrap = EventBuilder::new(Kind::TextNote, "wrap").finalize(&ephemeral).unwrap();
5352 let rumor = EventBuilder::new(Kind::PrivateDirectMessage, "still sending")
5353 .finalize_unsigned_with_id(Keys::generate().public_key());
5354 crate::db::nip17_keys::store_wrap_key(
5355 &wrap.id, &rumor.id.unwrap(), &Keys::generate().public_key(),
5356 crate::db::nip17_keys::WrapRole::Recipient, ephemeral.secret_key(), &[],
5357 ).unwrap();
5358 (wrap, rumor)
5359 };
5360 crate::db::nip17_keys::stash_resend_payload(&wrap.id, "pending-1", &wrap, &rumor).unwrap();
5361 crate::db::chats::hold_wallpaper(&dm_chat, 5, r#"{"url":"https://blossom.example/held-wallpaper"}"#).unwrap();
5363 let kept = crate::db::media_store::StoredMedia {
5365 hash: [0x5b; 32], file: "f".into(), key: "e5".repeat(32), nonce: "f6".repeat(16), blob_sha256: "aa".repeat(32),
5366 pt_len: 9, mime: "image/png".into(), origin: crate::db::media_store::Origin::Received,
5367 };
5368 crate::db::media_store::insert(&kept).unwrap();
5369
5370 let (banned, allowed) = {
5372 use nostr_sdk::prelude::ToBech32;
5373 (nostr_sdk::prelude::Keys::generate().public_key(), nostr_sdk::prelude::Keys::generate().public_key().to_bech32().unwrap())
5374 };
5375 set_community_banlist(&cid, &[banned.to_hex()], 1).unwrap();
5376 for (id, author) in [("c7", { use nostr_sdk::prelude::ToBech32; banned.to_bech32().unwrap() }), ("d8", allowed)] {
5377 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() };
5378 rt.block_on(crate::db::events::save_message(&ch, &msg)).unwrap();
5379 }
5380 let ch_int = crate::db::id_cache::get_or_create_chat_id(&ch).unwrap();
5381
5382 let read = || {
5383 (
5384 get_pending_channel_keys(&cid).unwrap().iter().map(|k| (k.key, k.sender.clone())).collect::<Vec<_>>(),
5385 get_community_ban_marks(&cid).unwrap(),
5386 get_community_pins(&cid, &ch).unwrap(),
5387 load_community_v2(v2.id()).unwrap().map(|c| format!("{c:?}")),
5388 (
5389 held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap(),
5390 held_epoch_keys(&cid, &private).unwrap(),
5391 get_audit_local(&cid).unwrap(),
5392 ),
5393 rt.block_on(crate::db::events::get_message_views(dm_chat_int, 10, 0)).unwrap()
5394 .into_iter().map(|m| (m.content, m.preview_metadata, m.attachments)).collect::<Vec<_>>(),
5395 crate::db::nip17_keys::get_resend_payload_by_pending("pending-1").unwrap().map(|p| p.rumor.content),
5396 (
5397 get_community_banlist(&cid).unwrap(),
5398 rt.block_on(crate::db::events::get_message_views(ch_int, 10, 0)).unwrap().into_iter().map(|m| m.id).collect::<Vec<_>>(),
5399 rt.block_on(crate::db::events::unread_count_for_chat(&ch)).unwrap(),
5400 rt.block_on(crate::db::events::unread_counts()).unwrap().get(&ch).copied(),
5401 ),
5402 wrap_owners("m1").unwrap().into_iter().map(|(k, outer, relays)| (k.public_key(), outer, relays)).collect::<Vec<_>>(),
5403 crate::db::media_store::get(&[0x5b; 32]).unwrap(),
5404 )
5405 };
5406 let before = read();
5407 assert_eq!(before.8, vec![(owner.public_key(), "o1".to_string(), vec!["wss://r".to_string()])]);
5408 assert_eq!(before.9.as_ref(), Some(&kept));
5409 assert_eq!(before.0, vec![([0x33; 32], "ab".repeat(32))]);
5410 assert_eq!(before.2, Some((r#"{"pins":["x"]}"#.to_string(), 1)));
5411 assert_eq!(before.3, Some(format!("{v2:?}")));
5412 assert_eq!(
5413 before.4,
5414 (vec![(Epoch(0), v2.community_root)], vec![(Epoch(0), [0x62; 32])], vec![("e1".to_string(), 5, r#"{"action":"message_delete"}"#.to_string())])
5415 );
5416 assert_eq!(before.5, vec![(String::new(), dm.preview_metadata.clone(), dm.attachments.clone())]);
5418 assert_eq!(before.6.as_deref(), Some("still sending"));
5419 assert_eq!(before.7, (vec![banned.to_hex()], vec!["d8".repeat(32)], 1, Some(1)), "the banned author stays hidden");
5420 let sealed: (String, String, String) = crate::db::get_db_connection_guard_static().unwrap().query_row(
5421 "SELECT a.name || e.preview_metadata || e.content, w.rumor_json, a.key FROM attachments a, events e, nip17_wrap_keys w
5422 WHERE e.id = a.event_id AND w.pending_id = 'pending-1'", [], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
5423 ).unwrap();
5424 for plain in ["passport", "A title", "the message itself"] {
5425 assert!(!sealed.0.contains(plain), "{plain} is sealed on disk");
5426 }
5427 assert!(!sealed.1.contains("still sending") && sealed.2 != "c3".repeat(32), "unconfirmed sends and file keys are sealed");
5428 let held: String = crate::db::get_db_connection_guard_static().unwrap()
5429 .query_row("SELECT payload FROM dm_held_wallpapers", [], |r| r.get(0)).unwrap();
5430 assert!(!held.contains("held-wallpaper"), "a held wallpaper is sealed on disk");
5431
5432 {
5433 let conn = crate::db::get_write_connection_guard_static().unwrap();
5434 let tx = conn.unchecked_transaction().unwrap();
5435 at_rest::rekey_listed_in_tx(&tx, &K, &K2, &|_| {}).unwrap();
5436 assert_eq!(
5437 at_rest::sweep_residue_in_tx(&tx, &K, Some(&K2)).unwrap(),
5438 0,
5439 "the sweep list must name every column these writers encrypt"
5440 );
5441 }
5442
5443 assert!(at_rest::rekey(&WRONG, &K2, &crate::crypto::Kdf::fresh(), "pin", None, &|_| {}).is_err(), "a key the store does not open is refused");
5444 at_rest::rekey(&K, &K2, &crate::crypto::Kdf::fresh(), "pin", None, &|_| {}).unwrap();
5445 crate::state::ENCRYPTION_KEY.set(K2, &[]);
5446 assert_eq!(read(), before, "every value reads back after a PIN change");
5447 assert_eq!(control_wraps(), vec![([0x11; 32], 5, control_wrap.clone())], "a held Control wrap moves with the key");
5448 assert_eq!(control_wrap_counts(&cid, &[0x77; 32]).unwrap().1, 1, "and a refusal, which holds no body, stays as it was");
5449 assert_eq!(
5450 crate::db::chats::take_held_wallpaper(&dm_chat).unwrap().as_deref(),
5451 Some(r#"{"url":"https://blossom.example/held-wallpaper"}"#),
5452 "a held wallpaper moves with the key"
5453 );
5454
5455 let mode = || crate::db::get_sql_setting("security_type".to_string()).unwrap();
5456 at_rest::rekey(&K2, &K2, &crate::crypto::Kdf::of_account().unwrap(), "password", None, &|_| {}).unwrap();
5457 assert_eq!((read(), mode().as_deref()), (before.clone(), Some("password")), "the same key on both sides only switches the mode");
5458
5459 let legacy_chat = crate::db::id_cache::get_or_create_chat_id(&make_test_npub(900_001)).unwrap();
5461 let hexish = "ab".repeat(40);
5462 {
5463 let conn = crate::db::get_write_connection_guard_static().unwrap();
5464 for (id, kind, content) in [("e5", 15, "old caption"), ("f6", 14, hexish.as_str())] {
5465 conn.execute(
5466 "INSERT INTO events (id, kind, chat_id, content, created_at, received_at) VALUES (?1, ?2, ?3, ?4, 1, 1)",
5467 rusqlite::params![id.repeat(32), kind, legacy_chat, content],
5468 ).unwrap();
5469 }
5470 }
5471 let flag = || crate::db::get_sql_setting("community_at_rest_encrypted".to_string()).unwrap();
5472 crate::db::set_sql_setting("community_at_rest_encrypted".to_string(), "1".to_string()).unwrap();
5473 crate::state::ENCRYPTION_KEY.set(WRONG, &[]);
5474 assert!(at_rest::backfill_at_rest().is_err(), "the backfill never wraps under a key it cannot prove");
5475 assert_eq!(flag().as_deref(), Some("1"));
5476 crate::state::ENCRYPTION_KEY.set(K2, &[]);
5477 at_rest::backfill_at_rest().unwrap();
5478 assert_eq!((read(), flag().as_deref()), (before.clone(), Some("8")));
5479 let stored = |id: &str| -> String {
5480 crate::db::get_db_connection_guard_static().unwrap()
5481 .query_row("SELECT content FROM events WHERE id = ?1", [id.repeat(32)], |r| r.get(0)).unwrap()
5482 };
5483 assert!(stored("e5") != "old caption" && stored("f6") != hexish, "the backfill seals legacy plaintext messages");
5484 let legacy = rt.block_on(crate::db::events::get_message_views(legacy_chat, 10, 0)).unwrap();
5485 assert!(legacy.iter().any(|m| m.content == hexish), "and they still read back");
5486
5487 assert!(at_rest::disable(&WRONG, &|_| {}).is_err(), "a wrong key never turns encryption off");
5488 assert_eq!(read(), before);
5489 at_rest::disable(&K2, &|_| {}).unwrap();
5490 crate::state::ENCRYPTION_KEY.clear(&[]);
5491 assert_eq!(read(), before, "every value reads back after Local Encryption is turned off");
5492 }
5493}
5494
5495pub fn set_community_pins(community_id: &str, channel_id: &str, content: &str, version: i64) -> Result<bool, String> {
5507 let _seal = crate::crypto::gate::sealing();
5508 let enc = enc_txt(content)?;
5509 let conn = super::get_write_connection_guard_static()?;
5510 let changed = conn
5511 .execute(
5512 "INSERT INTO community_pins (community_id, channel_id, content, version) VALUES (?1, ?2, ?3, ?4)
5513 ON CONFLICT(community_id, channel_id) DO UPDATE SET
5514 content = excluded.content, version = excluded.version
5515 WHERE excluded.version >= community_pins.version",
5516 params![community_id, channel_id, enc, version],
5517 )
5518 .map_err(|e| format!("set pins: {e}"))?;
5519 Ok(changed > 0)
5520}
5521
5522pub fn set_community_writers(community_id: &str, channel_id: &str, content: &str, version: i64, replace: bool) -> Result<bool, String> {
5524 let _seal = crate::crypto::gate::sealing();
5525 let enc = enc_txt(content)?;
5526 let conn = super::get_write_connection_guard_static()?;
5527 let old: Option<String> = conn
5528 .query_row("SELECT content FROM community_writers WHERE community_id = ?1 AND channel_id = ?2", params![community_id, channel_id], |r| r.get(0))
5529 .optional()
5530 .map_err(|e| format!("get writers: {e}"))?
5531 .map(|c: String| dec_txt(&c));
5532 let changed = conn
5533 .execute(
5534 "INSERT INTO community_writers (community_id, channel_id, content, version) VALUES (?1, ?2, ?3, ?4)
5535 ON CONFLICT(community_id, channel_id) DO UPDATE SET
5536 content = excluded.content, version = excluded.version
5537 WHERE ?5 OR excluded.version >= community_writers.version",
5538 params![community_id, channel_id, enc, version, replace],
5539 )
5540 .map_err(|e| format!("set writers: {e}"))?;
5541 if changed > 0 {
5543 crate::community::v2::realtime::invalidate_held_v2_community(community_id);
5544 if let Some(since) = retraction_since(old.as_deref(), content) {
5545 owe_retraction(&conn, community_id, channel_id, since)?;
5546 }
5547 for (writer, since) in stop_owes(old.as_deref(), content) {
5548 owe_author_retraction_on(&conn, community_id, channel_id, &crate::simd::hex::bytes_to_hex_32(&writer), since, None)?;
5549 }
5550 }
5551 Ok(changed > 0)
5552}
5553
5554pub(crate) fn retraction_since(old: Option<&str>, new: &str) -> Option<u64> {
5558 use crate::community::v2::writers::{Ledger, Spell};
5559 let new = Ledger::parse(new)?;
5560 let old = old.and_then(Ledger::parse);
5561 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)));
5562 let front = new.entries.first().map_or(u64::MAX, |e| e.at);
5563 let dropped = old.iter().flat_map(|o| o.entries.iter()).filter(|e| !matches!(e.spell, Spell::Other) && e.at >= front && !new.entries.contains(e));
5564 added.chain(dropped).map(|e| e.effective()).min()
5565}
5566
5567pub(crate) fn stop_owes(old: Option<&str>, new: &str) -> Vec<([u8; 32], u64)> {
5569 use crate::community::v2::writers::{Ledger, Spell};
5570 let Some(new) = Ledger::parse(new) else { return Vec::new() };
5571 let old = old.and_then(Ledger::parse);
5572 new.entries
5573 .iter()
5574 .filter(|e| !old.as_ref().is_some_and(|o| o.entries.contains(e)))
5575 .filter_map(|e| match e.spell {
5576 Spell::Stop { writer } => Some((writer, e.effective())),
5577 _ => None,
5578 })
5579 .collect()
5580}
5581
5582fn retraction_key(community_id: &str, channel_id: &str) -> String {
5583 format!("writer_retract:{community_id}:{channel_id}")
5584}
5585
5586fn parse_owed(value: &str) -> Option<(u64, u64)> {
5589 let mut parts = value.split(':');
5590 Some((parts.next()?.parse().ok()?, parts.next().and_then(|g| g.parse().ok()).unwrap_or(0)))
5591}
5592
5593fn owe_retraction(conn: &rusqlite::Connection, community_id: &str, channel_id: &str, since: u64) -> Result<(), String> {
5594 let key = retraction_key(community_id, channel_id);
5595 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}"))?;
5596 let (since, generation) = held.as_deref().and_then(parse_owed).map_or((since, 1), |(s, g)| (s.min(since), g + 1));
5597 conn.execute("INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)", params![key, format!("{since}:{generation}")]).map_err(|e| format!("owe retraction: {e}"))?;
5598 Ok(())
5599}
5600
5601pub fn owe_writer_retraction(community_id: &str, channel_id: &str, since_ms: u64) -> Result<(), String> {
5603 let conn = super::get_write_connection_guard_static()?;
5604 owe_retraction(&conn, community_id, channel_id, since_ms)
5605}
5606
5607pub fn owed_retractions(community_id: &str) -> Result<Vec<(String, u64, u64)>, String> {
5609 let prefix = retraction_key(community_id, "");
5610 let conn = super::get_db_connection_guard_static()?;
5611 let mut stmt = conn.prepare("SELECT key, value FROM settings WHERE substr(key, 1, length(?1)) = ?1").map_err(|e| format!("owed retractions: {e}"))?;
5612 let rows = stmt.query_map(params![prefix], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).map_err(|e| format!("owed retractions: {e}"))?;
5613 Ok(rows.flatten().filter_map(|(k, v)| parse_owed(&v).map(|(since, generation)| (k[prefix.len()..].to_string(), since, generation))).collect())
5614}
5615
5616fn legacy_author_retraction_range(community_id: &str) -> (String, String) {
5618 (format!("writer_retract_by:{community_id}:"), format!("writer_retract_by:{community_id};"))
5619}
5620
5621pub fn owe_author_retraction(community_id: &str, channel_id: &str, author: &str, since_ms: u64, until_ms: Option<u64>) -> Result<(), String> {
5624 let _seal = crate::crypto::gate::sealing();
5625 let conn = super::get_write_connection_guard_static()?;
5626 owe_author_retraction_on(&conn, community_id, channel_id, author, since_ms, until_ms)
5627}
5628
5629fn parse_author_owed(value: &str) -> Option<(u64, u64, Option<u64>)> {
5631 let mut parts = value.split(':');
5632 let since = parts.next()?.parse().ok()?;
5633 let generation = parts.next().and_then(|g| g.parse().ok()).unwrap_or(0);
5634 let until = parts.next().and_then(|u| u.parse().ok());
5635 Some((since, generation, until))
5636}
5637
5638struct AuthorOwed {
5640 seq: i64,
5641 channel: String,
5642 author: [u8; 32],
5643 since: u64,
5644 generation: u64,
5645 until: Option<u64>,
5646}
5647
5648fn author_owed_body(author: &[u8; 32], since: u64, generation: u64, until: Option<u64>) -> Vec<u8> {
5651 let mut out = Vec::with_capacity(64);
5652 out.push(1);
5653 out.extend_from_slice(author);
5654 varint(&mut out, since);
5655 varint(&mut out, generation);
5656 out.push(until.is_some() as u8);
5657 if let Some(until) = until {
5658 varint(&mut out, until);
5659 }
5660 out
5661}
5662
5663fn author_owed_from_body(body: &[u8]) -> Option<([u8; 32], u64, u64, Option<u64>)> {
5664 let (&1, rest) = body.split_first()? else { return None };
5665 let (author, mut rest) = rest.split_at_checked(32)?;
5666 let since = take_varint(&mut rest)?;
5667 let generation = take_varint(&mut rest)?;
5668 let (&flags, tail) = rest.split_first()?;
5669 rest = tail;
5670 let until = match flags {
5671 0 => None,
5672 1 => Some(take_varint(&mut rest)?),
5673 _ => return None,
5674 };
5675 rest.is_empty().then_some((author.try_into().ok()?, since, generation, until))
5676}
5677
5678fn held_author_retractions(conn: &rusqlite::Connection, community_id: &str, channel_id: Option<&str>) -> Result<Vec<AuthorOwed>, String> {
5680 let rows: Vec<(i64, String, Vec<u8>)> = {
5681 let mut stmt = conn
5682 .prepare_cached(
5683 "SELECT o.seq, o.channel_id, o.body FROM community_owed_authors o
5684 JOIN community_guestbook_books b ON b.book = o.book
5685 WHERE b.community_id = ?1 AND (?2 IS NULL OR o.channel_id = ?2) ORDER BY o.seq",
5686 )
5687 .map_err(|e| format!("owed retractions: {e}"))?;
5688 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}"))?;
5689 rows.filter_map(|r| r.ok()).collect()
5690 };
5691 Ok(crate::crypto::open_batch(|o| {
5692 rows.into_iter()
5693 .filter_map(|(seq, channel, body)| {
5694 let (author, since, generation, until) = author_owed_from_body(&o.open_blob_or_keep(&body))?;
5695 Some(AuthorOwed { seq, channel, author, since, generation, until })
5696 })
5697 .collect()
5698 }))
5699}
5700
5701fn has_legacy_author_retractions(conn: &rusqlite::Connection, community_id: &str) -> Result<bool, String> {
5702 let (lo, hi) = legacy_author_retraction_range(community_id);
5703 conn.query_row("SELECT 1 FROM settings WHERE key >= ?1 AND key < ?2 LIMIT 1", params![lo, hi], |_| Ok(()))
5704 .optional()
5705 .map(|r| r.is_some())
5706 .map_err(|e| format!("owed retractions: {e}"))
5707}
5708
5709fn move_author_retraction_settings(conn: &rusqlite::Connection, community_id: &str) -> Result<(), String> {
5712 let (lo, hi) = legacy_author_retraction_range(community_id);
5713 let legacy: Vec<(String, String)> = {
5714 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}"))?;
5715 let rows = stmt.query_map(params![lo, hi], |r| Ok((r.get(0)?, r.get(1)?))).map_err(|e| format!("move owed retractions: {e}"))?;
5716 rows.filter_map(|r| r.ok()).collect()
5717 };
5718 if legacy.is_empty() {
5719 return Ok(());
5720 }
5721 let book = guestbook_book(conn, community_id)?;
5722 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}"))?;
5723 crate::crypto::seal_batch(|sealer| {
5724 for (key, value) in &legacy {
5725 let Some((channel, author)) = key[lo.len()..].split_once(':') else { continue };
5726 let (Some(author), Some((since, generation, until))) = (crate::simd::hex::hex_to_bytes_32_checked(author), parse_author_owed(value)) else { continue };
5727 insert.execute(params![book, channel, sealer.seal_blob(&author_owed_body(&author, since, generation, until))?]).map_err(|e| format!("move owed retractions: {e}"))?;
5728 }
5729 Ok::<(), String>(())
5730 })?;
5731 conn.execute("DELETE FROM settings WHERE key >= ?1 AND key < ?2", params![lo, hi]).map_err(|e| format!("move owed retractions: {e}"))?;
5732 Ok(())
5733}
5734
5735fn in_savepoint<T>(conn: &rusqlite::Connection, f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
5737 conn.execute_batch("SAVEPOINT owed_authors").map_err(|e| format!("owed retractions: {e}"))?;
5738 match f() {
5739 Ok(v) => {
5740 conn.execute_batch("RELEASE owed_authors").map_err(|e| format!("owed retractions: {e}"))?;
5741 Ok(v)
5742 }
5743 Err(e) => {
5744 let _ = conn.execute_batch("ROLLBACK TO owed_authors; RELEASE owed_authors");
5745 Err(e)
5746 }
5747 }
5748}
5749
5750fn owe_author_retraction_on(conn: &rusqlite::Connection, community_id: &str, channel_id: &str, author: &str, since_ms: u64, until_ms: Option<u64>) -> Result<(), String> {
5752 let author = crate::simd::hex::hex_to_bytes_32_checked(author).ok_or_else(|| format!("owe retraction: not an author key: {author}"))?;
5753 in_savepoint(conn, || {
5754 move_author_retraction_settings(conn, community_id)?;
5755 let held = held_author_retractions(conn, community_id, Some(channel_id))?.into_iter().find(|o| o.author == author);
5756 let (since, generation, until) = match &held {
5757 Some(o) => (o.since.min(since_ms), o.generation + 1, match (o.until, until_ms) {
5759 (Some(a), Some(b)) => Some(a.max(b)),
5760 (None, Some(b)) if o.since == since_ms => Some(b),
5761 _ => None,
5762 }),
5763 None => (since_ms, 1, until_ms),
5764 };
5765 let body = crate::crypto::seal_batch(|sealer| sealer.seal_blob(&author_owed_body(&author, since, generation, until)))?;
5766 match held {
5767 Some(o) => conn.execute("UPDATE community_owed_authors SET body = ?1 WHERE seq = ?2", params![body, o.seq]),
5768 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]),
5769 }
5770 .map_err(|e| format!("owe retraction: {e}"))?;
5771 Ok(())
5772 })
5773}
5774
5775pub fn owed_author_retractions(community_id: &str) -> Result<Vec<(String, String, u64, Option<u64>, u64)>, String> {
5777 if has_legacy_author_retractions(&*super::get_db_connection_guard_static()?, community_id)? {
5778 let _seal = crate::crypto::gate::sealing();
5779 let conn = super::get_write_connection_guard_static()?;
5780 in_savepoint(&conn, || move_author_retraction_settings(&conn, community_id))?;
5781 }
5782 let mut owed: Vec<_> = held_author_retractions(&*super::get_db_connection_guard_static()?, community_id, None)?
5783 .into_iter()
5784 .map(|o| (o.channel, crate::simd::hex::bytes_to_hex_32(&o.author), o.since, o.until, o.generation))
5785 .collect();
5786 owed.sort_by(|a, b| (&a.0, &a.1).cmp(&(&b.0, &b.1)));
5787 Ok(owed)
5788}
5789
5790pub fn settle_author_retraction(community_id: &str, channel_id: &str, author: &str, since: u64, until: Option<u64>, generation: u64) -> Result<(), String> {
5792 let Some(author) = crate::simd::hex::hex_to_bytes_32_checked(author) else { return Ok(()) };
5793 let _seal = crate::crypto::gate::sealing();
5794 let conn = super::get_write_connection_guard_static()?;
5795 in_savepoint(&conn, || {
5796 move_author_retraction_settings(&conn, community_id)?;
5797 let done = held_author_retractions(&conn, community_id, Some(channel_id))?
5798 .into_iter()
5799 .filter(|o| o.author == author && o.since == since && o.until == until && o.generation == generation);
5800 for o in done {
5801 conn.execute("DELETE FROM community_owed_authors WHERE seq = ?1", params![o.seq]).map_err(|e| format!("settle retraction: {e}"))?;
5802 }
5803 Ok(())
5804 })
5805}
5806
5807pub type DepartureSpans = std::collections::BTreeMap<PublicKey, std::sync::Arc<[crate::community::v2::guestbook::Span]>>;
5810
5811#[derive(Default)]
5813pub struct DeparturesSeen {
5814 pub spans: std::sync::Arc<DepartureSpans>,
5815 rows: Vec<i64>,
5817}
5818
5819type DeparturesSeenCache = Parsed<std::sync::Arc<DeparturesSeen>, 8>;
5820
5821fn departures_seen_cache() -> std::sync::Arc<std::sync::Mutex<DeparturesSeenCache>> {
5822 struct Key;
5823 super::current_session().scoped::<Key, std::sync::Mutex<DeparturesSeenCache>>()
5824}
5825
5826fn legacy_departures_key(community_id: &str) -> String {
5827 format!("departures_seen:{community_id}")
5828}
5829
5830pub fn departures_seen(community_id: &str) -> Result<std::sync::Arc<DeparturesSeen>, String> {
5831 let cache = departures_seen_cache();
5832 let generation = {
5833 let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
5834 if let Some(hit) = held.get(community_id) {
5835 return Ok(hit);
5836 }
5837 held.generation(community_id)
5838 };
5839 let legacy = super::get_db_connection_guard_static()?
5840 .query_row("SELECT 1 FROM settings WHERE key = ?1", params![legacy_departures_key(community_id)], |_| Ok(()))
5841 .optional()
5842 .map_err(|e| format!("load departures: {e}"))?
5843 .is_some();
5844 if legacy {
5845 let _seal = crate::crypto::gate::sealing();
5846 let conn = super::get_write_connection_guard_static()?;
5847 let tx = conn.unchecked_transaction().map_err(|e| format!("move departures tx: {e}"))?;
5848 move_departures_setting(&tx, community_id)?;
5849 tx.commit().map_err(|e| format!("move departures commit: {e}"))?;
5850 }
5851 let seen = std::sync::Arc::new(read_departures(&*super::get_db_connection_guard_static()?, community_id)?);
5852 cache.lock().unwrap_or_else(|e| e.into_inner()).put(community_id, generation, seen.clone());
5853 Ok(seen)
5854}
5855
5856fn read_departures(conn: &rusqlite::Connection, community_id: &str) -> Result<DeparturesSeen, String> {
5857 let rows: Vec<(i64, Vec<u8>)> = {
5858 let mut stmt = conn
5859 .prepare_cached(
5860 "SELECT d.seq, d.body FROM community_departures_seen d
5861 JOIN community_guestbook_books b ON b.book = d.book
5862 WHERE b.community_id = ?1 ORDER BY d.seq",
5863 )
5864 .map_err(|e| format!("load departures: {e}"))?;
5865 let rows = stmt.query_map(params![community_id], |r| Ok((r.get(0)?, r.get(1)?))).map_err(|e| format!("load departures: {e}"))?;
5866 rows.filter_map(|r| r.ok()).collect()
5867 };
5868 let held: std::collections::BTreeMap<PublicKey, (i64, Vec<crate::community::v2::guestbook::Span>)> = crate::crypto::open_batch(|o| {
5869 rows.into_iter().filter_map(|(seq, body)| departure_from_body(&o.open_blob_or_keep(&body)).map(|(member, owed)| (member, (seq, owed)))).collect()
5870 });
5871 let rows = held.values().map(|(seq, _)| *seq).collect();
5872 Ok(DeparturesSeen { spans: std::sync::Arc::new(held.into_iter().map(|(member, (_, owed))| (member, owed.into())).collect()), rows })
5873}
5874
5875fn move_departures_setting(tx: &rusqlite::Connection, community_id: &str) -> Result<(), String> {
5877 let key = legacy_departures_key(community_id);
5878 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 {
5879 return Ok(());
5880 };
5881 let by_hex: std::collections::BTreeMap<String, Vec<crate::community::v2::guestbook::Span>> = serde_json::from_str(&json).unwrap_or_default();
5882 let book = guestbook_book(tx, community_id)?;
5883 let mut stmt = tx.prepare_cached("INSERT INTO community_departures_seen (book, body) VALUES (?1, ?2)").map_err(|e| format!("move departures: {e}"))?;
5884 crate::crypto::seal_batch(|sealer| {
5885 for (member, owed) in by_hex.iter().filter_map(|(k, v)| Some((PublicKey::from_hex(k).ok()?, v))) {
5886 stmt.execute(params![book, sealer.seal_blob(&departure_body(&member, owed))?]).map_err(|e| format!("move departures: {e}"))?;
5887 }
5888 Ok::<(), String>(())
5889 })?;
5890 tx.execute("DELETE FROM settings WHERE key = ?1", params![key]).map_err(|e| format!("move departures: {e}"))?;
5891 Ok(())
5892}
5893
5894pub fn set_departures_seen(community_id: &str, now: std::sync::Arc<DepartureSpans>) -> Result<(), String> {
5896 let _seal = crate::crypto::gate::sealing();
5897 let conn = super::get_write_connection_guard_static()?;
5898 let tx = conn.unchecked_transaction().map_err(|e| format!("store departures tx: {e}"))?;
5899 move_departures_setting(&tx, community_id)?;
5900 let cache = departures_seen_cache();
5901 let cached = cache.lock().unwrap_or_else(|e| e.into_inner()).get(community_id);
5902 let held = match cached {
5903 Some(held) => held,
5904 None => std::sync::Arc::new(read_departures(&tx, community_id)?),
5905 };
5906 let book = guestbook_book(&tx, community_id)?;
5907 let mut rows = Vec::with_capacity(now.len());
5908 {
5909 let mut update = tx.prepare_cached("UPDATE community_departures_seen SET body = ?1 WHERE seq = ?2").map_err(|e| format!("store departures: {e}"))?;
5910 let mut insert = tx.prepare_cached("INSERT INTO community_departures_seen (book, body) VALUES (?1, ?2)").map_err(|e| format!("store departures: {e}"))?;
5911 let mut delete = tx.prepare_cached("DELETE FROM community_departures_seen WHERE seq = ?1").map_err(|e| format!("store departures: {e}"))?;
5912 let mut was = held.spans.iter().zip(held.rows.iter().copied()).peekable();
5914 crate::crypto::seal_batch(|sealer| {
5915 for (member, owed) in now.iter() {
5916 while let Some((_, seq)) = was.next_if(|((m, _), _)| *m < member) {
5917 delete.execute(params![seq]).map_err(|e| format!("store departures: {e}"))?;
5918 }
5919 let seq = match was.next_if(|((m, _), _)| *m == member) {
5920 Some(((_, before), seq)) if before == owed => seq,
5921 Some((_, seq)) => {
5922 update.execute(params![sealer.seal_blob(&departure_body(member, owed))?, seq]).map_err(|e| format!("store departures: {e}"))?;
5923 seq
5924 }
5925 None => {
5926 insert.execute(params![book, sealer.seal_blob(&departure_body(member, owed))?]).map_err(|e| format!("store departures: {e}"))?;
5927 tx.last_insert_rowid()
5928 }
5929 };
5930 rows.push(seq);
5931 }
5932 for (_, seq) in was.by_ref() {
5933 delete.execute(params![seq]).map_err(|e| format!("store departures: {e}"))?;
5934 }
5935 Ok::<(), String>(())
5936 })?;
5937 }
5938 tx.commit().map_err(|e| format!("store departures commit: {e}"))?;
5939 let mut cached = cache.lock().unwrap_or_else(|e| e.into_inner());
5940 let generation = cached.moved(community_id);
5941 cached.put(community_id, generation, std::sync::Arc::new(DeparturesSeen { spans: now, rows }));
5942 Ok(())
5943}
5944
5945fn varint(out: &mut Vec<u8>, mut v: u64) {
5946 while v >= 0x80 {
5947 out.push(v as u8 | 0x80);
5948 v >>= 7;
5949 }
5950 out.push(v as u8);
5951}
5952
5953fn take_varint(rest: &mut &[u8]) -> Option<u64> {
5954 let mut v = 0u64;
5955 for shift in (0..64).step_by(7) {
5956 let (&b, tail) = rest.split_first()?;
5957 *rest = tail;
5958 v |= ((b & 0x7f) as u64).checked_shl(shift)?;
5959 if b & 0x80 == 0 {
5960 return Some(v);
5961 }
5962 }
5963 None
5964}
5965
5966fn departure_body(member: &PublicKey, spans: &[crate::community::v2::guestbook::Span]) -> Vec<u8> {
5969 let mut out = Vec::with_capacity(34 + spans.len() * 13);
5970 out.push(1);
5971 out.extend_from_slice(member.as_bytes());
5972 varint(&mut out, spans.len() as u64);
5973 for &(from, until, kicked) in spans {
5974 out.push(until.is_some() as u8 | (kicked as u8) << 1);
5975 varint(&mut out, from);
5976 if let Some(until) = until {
5977 varint(&mut out, until);
5978 }
5979 }
5980 out
5981}
5982
5983fn departure_from_body(body: &[u8]) -> Option<(PublicKey, Vec<crate::community::v2::guestbook::Span>)> {
5984 let (&1, rest) = body.split_first()? else { return None };
5985 let (member, mut rest) = rest.split_at_checked(32)?;
5986 let member = PublicKey::from_byte_array(member.try_into().ok()?);
5987 let count = take_varint(&mut rest)?;
5988 if count > rest.len() as u64 / 2 {
5990 return None;
5991 }
5992 let mut spans = Vec::with_capacity(count as usize);
5993 for _ in 0..count {
5994 let (&flags, tail) = rest.split_first()?;
5995 rest = tail;
5996 if flags & !0b11 != 0 {
5997 return None;
5998 }
5999 let from = take_varint(&mut rest)?;
6000 let until = if flags & 1 != 0 { Some(take_varint(&mut rest)?) } else { None };
6001 spans.push((from, until, flags & 2 != 0));
6002 }
6003 rest.is_empty().then_some((member, spans))
6004}
6005
6006pub fn settle_retraction(community_id: &str, channel_id: &str, since: u64, generation: u64) -> Result<(), String> {
6008 let conn = super::get_write_connection_guard_static()?;
6009 conn.execute("DELETE FROM settings WHERE key = ?1 AND value = ?2", params![retraction_key(community_id, channel_id), format!("{since}:{generation}")])
6010 .map_err(|e| format!("settle retraction: {e}"))?;
6011 Ok(())
6012}
6013
6014pub fn get_community_writers(community_id: &str, channel_id: &str) -> Result<Option<(String, i64)>, String> {
6015 let conn = super::get_db_connection_guard_static()?;
6016 let row: Option<(String, i64)> = conn
6017 .query_row(
6018 "SELECT content, version FROM community_writers WHERE community_id = ?1 AND channel_id = ?2",
6019 params![community_id, channel_id],
6020 |r| Ok((r.get(0)?, r.get(1)?)),
6021 )
6022 .optional()
6023 .map_err(|e| format!("get writers: {e}"))?;
6024 Ok(row.map(|(content, version)| (dec_txt(&content), version)))
6025}
6026
6027pub const MAX_HELD_WRAPS: usize = 500;
6031pub const MAX_HELD_BYTES: usize = 4 * 1024 * 1024;
6032pub const MAX_HELD_PER_AUTHOR: usize = MAX_HELD_WRAPS / 10;
6033pub const MAX_HELD_COMMUNITY_BYTES: usize = 16 * 1024 * 1024;
6034
6035pub const HELD_HORIZON_MS: u64 = 60 * 60 * 1000;
6038
6039pub fn hold_wrap(community_id: &str, channel_id: &str, wrap_id: &str, wrap: &str, author: &str, at_ms: u64) -> Result<bool, String> {
6043 let now = now_secs().max(0) as u64 * 1000;
6044 if at_ms > now.saturating_add(HELD_HORIZON_MS) {
6045 let held = deferred();
6046 let mut map = held.lock().unwrap_or_else(|e| e.into_inner());
6047 map.insert(wrap_id.to_string(), at_ms);
6048 if map.len() > MAX_DEFERRED {
6050 if let Some(furthest) = map.iter().max_by_key(|(_, at)| **at).map(|(id, _)| id.clone()) {
6051 map.remove(&furthest);
6052 }
6053 }
6054 return Ok(false);
6055 }
6056 let _seal = crate::crypto::gate::sealing();
6057 let enc = enc_txt(wrap)?;
6058 let conn = super::get_write_connection_guard_static()?;
6059 conn.execute(
6060 "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)",
6061 params![wrap_id, community_id, channel_id, enc, at_ms as i64, author, enc.len() as i64],
6062 )
6063 .map_err(|e| format!("hold wrap: {e}"))?;
6064 let ranked: Vec<(String, String, String, usize)> = {
6066 let mut stmt = conn
6067 .prepare("SELECT wrap_id, channel_id, author, bytes FROM community_held_wraps WHERE community_id = ?1 ORDER BY ABS(at_ms - ?2), wrap_id")
6068 .map_err(|e| format!("rank held wraps: {e}"))?;
6069 let rows = stmt
6070 .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)))
6071 .map_err(|e| format!("rank held wraps: {e}"))?;
6072 rows.flatten().collect()
6073 };
6074 let (mut channels, mut authors) = (std::collections::HashMap::<&str, (usize, usize)>::new(), std::collections::HashMap::<(&str, &str), usize>::new());
6075 let mut evicted: Vec<&String> = Vec::new();
6076 let mut kept: Vec<(&String, &str, usize)> = Vec::new();
6077 for (id, ch, who, len) in &ranked {
6078 let c = channels.entry(ch.as_str()).or_default();
6079 let a = authors.entry((ch.as_str(), who.as_str())).or_default();
6080 if c.0 >= MAX_HELD_WRAPS || c.1 + len > MAX_HELD_BYTES || (!who.is_empty() && *a >= MAX_HELD_PER_AUTHOR) {
6081 evicted.push(id);
6082 continue;
6083 }
6084 c.0 += 1;
6085 c.1 += len;
6086 *a += 1;
6087 kept.push((id, ch.as_str(), *len));
6088 }
6089 let mut total: usize = kept.iter().map(|k| k.2).sum();
6092 while total > MAX_HELD_COMMUNITY_BYTES {
6093 let most = channels.values().map(|c| c.1).max().unwrap_or(0);
6094 let Some(i) = kept.iter().rposition(|k| channels.get(k.1).is_some_and(|c| c.1 == most)) else { break };
6095 let (id, ch, len) = kept.remove(i);
6096 if let Some(c) = channels.get_mut(ch) {
6097 c.1 -= len;
6098 }
6099 total -= len;
6100 evicted.push(id);
6101 }
6102 for id in &evicted {
6103 conn.execute("DELETE FROM community_held_wraps WHERE wrap_id = ?1", params![id]).map_err(|e| format!("trim held wraps: {e}"))?;
6104 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}"))?;
6105 }
6106 Ok(!evicted.iter().any(|id| *id == wrap_id))
6107}
6108
6109pub type ControlWrapRow = ([u8; 32], u64, Option<Vec<u8>>);
6113
6114pub fn control_wrap_ids(community_id: &str, view: &[u8; 32]) -> Result<Vec<([u8; 32], u64)>, String> {
6116 let conn = super::get_db_connection_guard_static()?;
6117 let mut stmt = conn
6118 .prepare_cached("SELECT wrap_id, created_at FROM community_control_wraps WHERE community_id = ?1 AND view = ?2")
6119 .map_err(|e| format!("control wrap ids: {e}"))?;
6120 let rows = stmt
6121 .query_map(params![community_id, &view[..]], |r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, i64>(1)?)))
6122 .map_err(|e| format!("control wrap ids: {e}"))?;
6123 let mut out = Vec::new();
6124 for row in rows {
6125 let (id, at) = row.map_err(|e| format!("control wrap ids: {e}"))?;
6126 out.push((id.try_into().map_err(|_| "control wrap ids: a wrap id is not 32 bytes".to_string())?, at.max(0) as u64));
6127 }
6128 Ok(out)
6129}
6130
6131pub fn store_control_wraps(community_id: &str, view: &[u8; 32], rules: u32, now_secs: u64, rows: &[ControlWrapRow]) -> Result<usize, String> {
6134 if rows.is_empty() {
6135 return Ok(0);
6136 }
6137 let _seal = crate::crypto::gate::sealing();
6138 let conn = super::get_write_connection_guard_static()?;
6139 let tx = conn.unchecked_transaction().map_err(|e| format!("store control wraps tx: {e}"))?;
6140 let mut stored = 0usize;
6141 {
6142 let mut stmt = tx
6143 .prepare_cached(
6144 "INSERT OR IGNORE INTO community_control_wraps (community_id, view, wrap_id, created_at, wrap, rules, judged_at)
6145 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
6146 )
6147 .map_err(|e| format!("store control wraps: {e}"))?;
6148 crate::crypto::seal_batch(|sealer| -> Result<(), String> {
6149 for (id, at, body) in rows {
6150 let sealed = body.as_deref().map(|b| sealer.seal_blob(b)).transpose()?;
6151 stored += stmt
6152 .execute(params![community_id, &view[..], &id[..], *at as i64, sealed, rules, now_secs as i64])
6153 .map_err(|e| format!("store control wraps: {e}"))?;
6154 }
6155 Ok(())
6156 })?;
6157 }
6158 tx.commit().map_err(|e| format!("store control wraps commit: {e}"))?;
6159 Ok(stored)
6160}
6161
6162pub 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> {
6164 let rows: Vec<(Vec<u8>, i64, Vec<u8>)> = {
6165 let conn = super::get_db_connection_guard_static()?;
6166 let (at, id) = below.map_or((i64::MAX, vec![0xff; 33]), |(at, id)| (at as i64, id.to_vec()));
6168 let mut stmt = conn
6169 .prepare_cached(
6170 "SELECT wrap_id, created_at, wrap FROM community_control_wraps
6171 WHERE community_id = ?1 AND view = ?2 AND wrap IS NOT NULL AND (created_at, wrap_id) < (?3, ?4)
6172 ORDER BY created_at DESC, wrap_id DESC LIMIT ?5",
6173 )
6174 .map_err(|e| format!("control wrap page: {e}"))?;
6175 let rows = stmt
6176 .query_map(params![community_id, &view[..], at, id, limit as i64], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
6177 .map_err(|e| format!("control wrap page: {e}"))?;
6178 rows.collect::<Result<_, _>>().map_err(|e| format!("control wrap page: {e}"))?
6179 };
6180 crate::crypto::open_batch(|o| {
6181 rows.into_iter()
6182 .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))))
6183 .collect()
6184 })
6185}
6186
6187pub fn control_wrap_bodies(community_id: &str, view: &[u8; 32], ids: &[[u8; 32]]) -> Result<Vec<Vec<u8>>, String> {
6189 let mut sealed: Vec<Vec<u8>> = Vec::with_capacity(ids.len());
6190 {
6191 let conn = super::get_db_connection_guard_static()?;
6192 let mut stmt = conn
6193 .prepare_cached("SELECT wrap FROM community_control_wraps WHERE community_id = ?1 AND view = ?2 AND wrap_id = ?3 AND wrap IS NOT NULL")
6194 .map_err(|e| format!("control wrap bodies: {e}"))?;
6195 for id in ids {
6196 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}"))? {
6197 sealed.push(body);
6198 }
6199 }
6200 }
6201 crate::crypto::open_batch(|o| Ok(sealed.iter().map(|body| o.open_blob_or_keep(body)).collect()))
6202}
6203
6204pub fn control_wrap_counts(community_id: &str, view: &[u8; 32]) -> Result<(usize, usize, usize), String> {
6206 let conn = super::get_db_connection_guard_static()?;
6207 conn.query_row(
6208 "SELECT COUNT(wrap), COUNT(*) - COUNT(wrap), COALESCE(SUM(length(wrap)), 0) FROM community_control_wraps WHERE community_id = ?1 AND view = ?2",
6209 params![community_id, &view[..]],
6210 |r| Ok((r.get::<_, i64>(0)? as usize, r.get::<_, i64>(1)? as usize, r.get::<_, i64>(2)? as usize)),
6211 )
6212 .map_err(|e| format!("control wrap counts: {e}"))
6213}
6214
6215pub fn guestbook_wrap_ids(community_id: &str, plane: &[u8; 32]) -> Result<Vec<([u8; 32], u64)>, String> {
6217 let conn = super::get_db_connection_guard_static()?;
6218 let mut stmt = conn
6219 .prepare_cached("SELECT wrap_id, created_at FROM community_guestbook_wraps WHERE community_id = ?1 AND plane = ?2")
6220 .map_err(|e| format!("guestbook wrap ids: {e}"))?;
6221 let rows = stmt
6222 .query_map(params![community_id, &plane[..]], |r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, i64>(1)?)))
6223 .map_err(|e| format!("guestbook wrap ids: {e}"))?;
6224 let mut out = Vec::new();
6225 for row in rows {
6226 let (id, at) = row.map_err(|e| format!("guestbook wrap ids: {e}"))?;
6227 out.push((id.try_into().map_err(|_| "guestbook wrap ids: a wrap id is not 32 bytes".to_string())?, at.max(0) as u64));
6228 }
6229 Ok(out)
6230}
6231
6232pub fn store_guestbook_wraps(community_id: &str, plane: &[u8; 32], now_secs: u64, rows: &[([u8; 32], u64, u32)]) -> Result<(), String> {
6234 if rows.is_empty() {
6235 return Ok(());
6236 }
6237 let conn = super::get_write_connection_guard_static()?;
6238 let tx = conn.unchecked_transaction().map_err(|e| format!("store guestbook wraps tx: {e}"))?;
6239 {
6240 let mut stmt = tx
6241 .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)")
6242 .map_err(|e| format!("store guestbook wraps: {e}"))?;
6243 for (id, at, rules) in rows {
6244 stmt.execute(params![community_id, &plane[..], &id[..], *at as i64, rules, now_secs as i64]).map_err(|e| format!("store guestbook wraps: {e}"))?;
6245 }
6246 }
6247 tx.commit().map_err(|e| format!("store guestbook wraps commit: {e}"))
6248}
6249
6250pub fn forget_guestbook_wraps(community_id: &str, plane: &[u8; 32], rules: u32, oldest: usize) -> Result<(), String> {
6253 let conn = super::get_write_connection_guard_static()?;
6254 conn.execute(
6255 "DELETE FROM community_guestbook_wraps WHERE community_id = ?1 AND (plane != ?2 OR (rules != 0 AND rules != ?3))",
6256 params![community_id, &plane[..], rules],
6257 )
6258 .map_err(|e| format!("forget guestbook wraps: {e}"))?;
6259 if oldest > 0 {
6260 conn.execute(
6261 "DELETE FROM community_guestbook_wraps WHERE community_id = ?1 AND plane = ?2 AND wrap_id IN (
6262 SELECT wrap_id FROM community_guestbook_wraps WHERE community_id = ?1 AND plane = ?2 AND rules != 0 ORDER BY judged_at LIMIT ?3)",
6263 params![community_id, &plane[..], oldest as i64],
6264 )
6265 .map_err(|e| format!("forget guestbook wraps: {e}"))?;
6266 }
6267 Ok(())
6268}
6269
6270pub fn purge_guestbook_wraps(community_id: &str) -> Result<(), String> {
6272 let conn = super::get_write_connection_guard_static()?;
6273 conn.execute("DELETE FROM community_guestbook_wraps WHERE community_id = ?1", params![community_id]).map_err(|e| format!("purge guestbook wraps: {e}"))?;
6274 conn.execute("DELETE FROM settings WHERE key = 'gbk_reads:' || ?1", params![community_id]).map_err(|e| format!("purge guestbook wraps: {e}"))?;
6275 Ok(())
6276}
6277
6278pub fn purge_control_wraps(community_id: &str) -> Result<(), String> {
6280 let conn = super::get_write_connection_guard_static()?;
6281 conn.execute("DELETE FROM community_control_wraps WHERE community_id = ?1", params![community_id]).map_err(|e| format!("purge control wraps: {e}"))?;
6282 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}"))?;
6283 Ok(())
6284}
6285
6286pub fn drop_control_wrap(community_id: &str, view: &[u8; 32], wrap_id: &[u8; 32]) -> Result<(), String> {
6288 let conn = super::get_write_connection_guard_static()?;
6289 conn.execute(
6290 "DELETE FROM community_control_wraps WHERE community_id = ?1 AND view = ?2 AND wrap_id = ?3",
6291 params![community_id, &view[..], &wrap_id[..]],
6292 )
6293 .map_err(|e| format!("drop control wrap: {e}"))?;
6294 Ok(())
6295}
6296
6297pub fn forget_control_refusals(community_id: &str, view: &[u8; 32], rules: u32, oldest: usize) -> Result<usize, String> {
6300 let conn = super::get_write_connection_guard_static()?;
6301 let other = conn
6302 .execute(
6303 "DELETE FROM community_control_wraps WHERE community_id = ?1 AND view = ?2 AND wrap IS NULL AND rules != ?3",
6304 params![community_id, &view[..], rules],
6305 )
6306 .map_err(|e| format!("forget control refusals: {e}"))?;
6307 let aged = conn
6308 .execute(
6309 "DELETE FROM community_control_wraps WHERE rowid IN (
6310 SELECT rowid FROM community_control_wraps WHERE community_id = ?1 AND view = ?2 AND wrap IS NULL
6311 ORDER BY judged_at, wrap_id LIMIT ?3)",
6312 params![community_id, &view[..], oldest as i64],
6313 )
6314 .map_err(|e| format!("forget control refusals: {e}"))?;
6315 Ok(other + aged)
6316}
6317
6318pub fn record_audit_local(community_id: &str, id: &str, at_ms: u64, entry: &str) -> Result<(), String> {
6321 let _seal = crate::crypto::gate::sealing();
6322 let enc = enc_txt(entry)?;
6323 let conn = super::get_write_connection_guard_static()?;
6324 conn.execute(
6325 "INSERT OR IGNORE INTO community_audit_local (id, community_id, at_ms, entry) VALUES (?1, ?2, ?3, ?4)",
6326 params![id, community_id, at_ms as i64, enc],
6327 )
6328 .map_err(|e| format!("record audit: {e}"))?;
6329 Ok(())
6330}
6331
6332pub fn get_audit_local(community_id: &str) -> Result<Vec<(String, u64, String)>, String> {
6334 let conn = super::get_db_connection_guard_static()?;
6335 let mut stmt = conn
6336 .prepare("SELECT id, at_ms, entry FROM community_audit_local WHERE community_id = ?1 ORDER BY at_ms")
6337 .map_err(|e| format!("read audit: {e}"))?;
6338 let rows = stmt
6339 .query_map(params![community_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.max(0) as u64, r.get::<_, String>(2)?)))
6340 .map_err(|e| format!("read audit: {e}"))?;
6341 Ok(rows.flatten().map(|(id, at, entry)| (id, at, dec_txt(&entry))).collect())
6342}
6343
6344pub fn held_wrap_channels(community_id: &str) -> Result<Vec<String>, String> {
6346 let conn = super::get_db_connection_guard_static()?;
6347 let mut stmt = conn.prepare("SELECT DISTINCT channel_id FROM community_held_wraps WHERE community_id = ?1").map_err(|e| format!("held channels: {e}"))?;
6348 let rows = stmt.query_map(params![community_id], |r| r.get(0)).map_err(|e| format!("held channels: {e}"))?;
6349 Ok(rows.flatten().collect())
6350}
6351
6352pub fn held_wrap_ids_in(community_id: &str, channel_id: &str) -> Result<Vec<String>, String> {
6354 let conn = super::get_db_connection_guard_static()?;
6355 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}"))?;
6356 let rows = stmt.query_map(params![community_id, channel_id], |r| r.get(0)).map_err(|e| format!("held ids: {e}"))?;
6357 Ok(rows.flatten().collect())
6358}
6359
6360pub fn held_wraps_in(community_id: &str, channel_id: &str) -> Result<Vec<(String, String)>, String> {
6362 let conn = super::get_db_connection_guard_static()?;
6363 let mut stmt = conn
6364 .prepare("SELECT wrap_id, wrap FROM community_held_wraps WHERE community_id = ?1 AND channel_id = ?2 ORDER BY at_ms")
6365 .map_err(|e| format!("held wraps: {e}"))?;
6366 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}"))?;
6367 Ok(rows.flatten().map(|(id, wrap)| (id, dec_txt(&wrap))).collect())
6368}
6369
6370pub fn held_wraps(community_id: &str) -> Result<Vec<(String, String, String)>, String> {
6372 let conn = super::get_db_connection_guard_static()?;
6373 let mut stmt = conn
6374 .prepare("SELECT wrap_id, channel_id, wrap FROM community_held_wraps WHERE community_id = ?1 ORDER BY at_ms")
6375 .map_err(|e| format!("held wraps: {e}"))?;
6376 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}"))?;
6377 Ok(rows.flatten().map(|(id, ch, wrap)| (id, ch, dec_txt(&wrap))).collect())
6378}
6379
6380pub fn holds_wraps(community_id: &str) -> bool {
6382 super::get_db_connection_guard_static()
6383 .ok()
6384 .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())
6385 .is_some()
6386}
6387
6388pub fn holds_wraps_at(community_id: &str, channel_id: &str, author: &str, address: &[u8; 32]) -> bool {
6391 let wraps: Vec<String> = {
6392 let Ok(conn) = super::get_db_connection_guard_static() else { return false };
6393 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 };
6394 let Ok(rows) = stmt.query_map(params![community_id, channel_id, author], |r| r.get::<_, String>(0)) else { return false };
6395 rows.flatten().collect()
6396 };
6397 wraps.iter().any(|w| crate::event_json::event(&dec_txt(w)).is_ok_and(|e| e.pubkey.to_bytes() == *address))
6398}
6399
6400struct DeferredWraps;
6401
6402pub const MAX_DEFERRED: usize = 4096;
6403
6404fn deferred() -> std::sync::Arc<std::sync::Mutex<std::collections::HashMap<String, u64>>> {
6406 super::current_session().scoped::<DeferredWraps, _>()
6407}
6408
6409pub fn held_wrap_ids(wrap_ids: &[String]) -> std::collections::HashSet<String> {
6411 let now = now_secs().max(0) as u64 * 1000;
6412 let waiting: std::collections::HashSet<String> = {
6413 let held = deferred();
6414 let mut map = held.lock().unwrap_or_else(|e| e.into_inner());
6415 map.retain(|_, at| *at > now.saturating_add(HELD_HORIZON_MS));
6416 wrap_ids.iter().filter(|id| map.contains_key(*id)).cloned().collect()
6417 };
6418 let mut out = held_wrap_rows(wrap_ids);
6419 out.extend(waiting);
6420 out
6421}
6422
6423fn held_wrap_rows(wrap_ids: &[String]) -> std::collections::HashSet<String> {
6424 let Ok(conn) = super::get_db_connection_guard_static() else { return Default::default() };
6425 let Ok(json) = serde_json::to_string(wrap_ids) else { return Default::default() };
6426 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() };
6427 stmt.query_map(params![json], |r| r.get::<_, String>(0)).map(|rows| rows.flatten().collect()).unwrap_or_default()
6428}
6429
6430pub fn release_held_wrap(wrap_id: &str) -> Result<(), String> {
6432 let conn = super::get_write_connection_guard_static()?;
6433 conn.execute("DELETE FROM community_held_wraps WHERE wrap_id = ?1", params![wrap_id]).map_err(|e| format!("release held wrap: {e}"))?;
6434 Ok(())
6435}
6436
6437pub fn get_community_pin_versions(community_id: &str) -> Result<std::collections::HashMap<String, i64>, String> {
6441 let conn = super::get_db_connection_guard_static()?;
6442 let mut stmt = conn
6443 .prepare("SELECT channel_id, version FROM community_pins WHERE community_id = ?1")
6444 .map_err(|e| format!("get pin versions: {e}"))?;
6445 let rows = stmt
6446 .query_map(params![community_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))
6447 .map_err(|e| format!("get pin versions: {e}"))?;
6448 rows.collect::<Result<_, _>>().map_err(|e| format!("get pin versions: {e}"))
6449}
6450
6451pub fn get_community_pins(community_id: &str, channel_id: &str) -> Result<Option<(String, i64)>, String> {
6452 let conn = super::get_db_connection_guard_static()?;
6453 let row: Option<(String, i64)> = conn
6454 .query_row(
6455 "SELECT content, version FROM community_pins WHERE community_id = ?1 AND channel_id = ?2",
6456 params![community_id, channel_id],
6457 |r| Ok((r.get(0)?, r.get(1)?)),
6458 )
6459 .optional()
6460 .map_err(|e| format!("get pins: {e}"))?;
6461 Ok(row.map(|(content, version)| (dec_txt(&content), version)))
6462}