use nostr_sdk::prelude::{Keys, PublicKey, SecretKey};
use nostr_sdk::prelude::ToBech32;
use rusqlite::{params, OptionalExtension};
use crate::community::{ChannelId, CommunityId, Epoch};
fn now_secs() -> i64 {
crate::clock::now_secs() as i64
}
fn to_32(bytes: &[u8]) -> Result<[u8; 32], String> {
bytes
.try_into()
.map_err(|_| format!("expected 32-byte key, got {} bytes", bytes.len()))
}
fn enc_key(k: &[u8; 32]) -> Result<Vec<u8>, String> { crate::crypto::maybe_encrypt_blob(k) }
fn dec_key(stored: &[u8]) -> Result<[u8; 32], String> { to_32(&crate::crypto::maybe_decrypt_blob(stored)) }
fn enc_txt(s: &str) -> Result<String, String> { crate::crypto::maybe_encrypt_text(s) }
fn dec_txt(s: &str) -> String { crate::crypto::maybe_decrypt_text(s) }
fn enc_txt_opt(s: &Option<String>) -> Result<Option<String>, String> {
s.as_deref().map(enc_txt).transpose()
}
pub(crate) fn hex_id_to_32(hex: &str) -> Result<[u8; 32], String> {
crate::simd::hex::hex_to_bytes_32_checked(hex)
.ok_or_else(|| format!("corrupt or wrong-length 64-char hex id ({} chars)", hex.len()))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingChannelKey {
pub id: i64,
pub channel_id: String,
pub epoch: u64,
pub key: [u8; 32],
pub sender: String,
pub received_at: i64,
}
const MAX_PARKED_PER_CHANNEL: usize = 4;
const MAX_PARKED_PER_COMMUNITY: usize = 64;
pub fn park_channel_key(
community_id: &str,
channel_id: &str,
epoch: u64,
key: &[u8; 32],
sender: &str,
) -> Result<(), String> {
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
let tx = conn.unchecked_transaction().map_err(|e| format!("park channel key tx: {e}"))?;
let enc = enc_key(key)?;
let enc_sender = enc_txt(sender)?;
tx.execute(
"INSERT INTO pending_channel_keys
(community_id, channel_id, epoch, channel_key, sender, received_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![community_id, channel_id, epoch as i64, &enc[..], enc_sender, now_secs()],
)
.map_err(|e| format!("park channel key: {e}"))?;
tx.execute(
"DELETE FROM pending_channel_keys WHERE id IN (
SELECT id FROM pending_channel_keys
WHERE community_id = ?1 AND channel_id = ?2
ORDER BY id DESC LIMIT -1 OFFSET ?3)",
params![community_id, channel_id, MAX_PARKED_PER_CHANNEL as i64],
)
.map_err(|e| format!("trim parked channel keys: {e}"))?;
tx.execute(
"DELETE FROM pending_channel_keys WHERE id IN (
SELECT id FROM pending_channel_keys
WHERE community_id = ?1
ORDER BY id DESC LIMIT -1 OFFSET ?2)",
params![community_id, MAX_PARKED_PER_COMMUNITY as i64],
)
.map_err(|e| format!("trim parked community keys: {e}"))?;
tx.commit().map_err(|e| format!("park channel key commit: {e}"))?;
Ok(())
}
pub fn get_pending_channel_keys(community_id: &str) -> Result<Vec<PendingChannelKey>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare("SELECT id, channel_id, epoch, channel_key, sender, received_at FROM pending_channel_keys WHERE community_id = ?1 ORDER BY id DESC")
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![community_id], |row| {
Ok((
row.get::<_, i64>(0)?,
row.get::<_, String>(1)?,
row.get::<_, i64>(2)?,
row.get::<_, Vec<u8>>(3)?,
row.get::<_, String>(4)?,
row.get::<_, i64>(5)?,
))
})
.map_err(|e| e.to_string())?;
let mut out = Vec::new();
for row in rows {
let (id, channel_id, epoch, blob, sender, received_at) = row.map_err(|e| e.to_string())?;
let Ok(key) = dec_key(&blob) else { continue };
out.push(PendingChannelKey { id, channel_id, epoch: epoch as u64, key, sender: dec_txt(&sender), received_at });
}
Ok(out)
}
pub fn seat_channel_key(
community_id: &str,
channel_id: &str,
epoch: u64,
key: &[u8; 32],
) -> Result<(), String> {
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
let tx = conn.unchecked_transaction().map_err(|e| format!("seat channel key tx: {e}"))?;
let placeholder: Vec<u8> = tx
.query_row(
"SELECT server_root_key FROM communities WHERE community_id = ?1",
params![community_id],
|r| r.get(0),
)
.map_err(|e| format!("seat channel key root: {e}"))?;
let current: Vec<u8> = tx
.query_row(
"SELECT channel_key FROM community_channels WHERE community_id = ?1 AND channel_id = ?2",
params![community_id, channel_id],
|r| r.get(0),
)
.map_err(|e| format!("seat channel key read: {e}"))?;
if dec_key(¤t)? != dec_key(&placeholder)? {
return Err("channel already holds a key — seating would downgrade it".to_string());
}
store_epoch_key_tx(&tx, community_id, channel_id, epoch, key)?;
let enc = enc_key(key)?;
tx.execute(
"UPDATE community_channels SET epoch = ?1, channel_key = ?2
WHERE community_id = ?3 AND channel_id = ?4",
params![epoch as i64, &enc[..], community_id, channel_id],
)
.map_err(|e| format!("seat channel key: {e}"))?;
tx.commit().map_err(|e| format!("seat channel key commit: {e}"))?;
crate::community::v2::realtime::invalidate_held_v2_community(community_id);
Ok(())
}
pub fn drop_pending_channel_key(id: i64) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
conn.execute("DELETE FROM pending_channel_keys WHERE id = ?1", params![id])
.map_err(|e| format!("drop pending channel key: {e}"))?;
Ok(())
}
pub fn drop_pending_channel_keys_for(community_id: &str, channel_id: &str) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
conn.execute(
"DELETE FROM pending_channel_keys WHERE community_id = ?1 AND channel_id = ?2",
params![community_id, channel_id],
)
.map_err(|e| format!("drop pending channel keys: {e}"))?;
Ok(())
}
pub fn store_epoch_key(community_id: &str, scope_id: &str, epoch: u64, key: &[u8; 32]) -> Result<(), String> {
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
store_epoch_key_tx(&conn, community_id, scope_id, epoch, key)
}
#[cfg(test)]
pub fn delete_epoch_key(community_id: &str, scope_id: &str, epoch: u64) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
conn.execute(
"DELETE FROM community_epoch_keys WHERE community_id = ?1 AND scope_id = ?2 AND epoch = ?3",
params![community_id, scope_id, epoch as i64],
)
.map_err(|e| format!("delete epoch key: {e}"))?;
Ok(())
}
fn store_epoch_key_tx<C: std::ops::Deref<Target = rusqlite::Connection>>(
conn: &C,
community_id: &str,
scope_id: &str,
epoch: u64,
key: &[u8; 32],
) -> Result<(), String> {
let enc = enc_key(key)?;
conn.execute(
"INSERT OR REPLACE INTO community_epoch_keys
(community_id, scope_id, epoch, key, created_at)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![community_id, scope_id, epoch as i64, &enc[..], now_secs()],
)
.map_err(|e| format!("store epoch key: {e}"))?;
Ok(())
}
pub fn advance_channel_epoch(
community_id: &str,
channel_id: &str,
new_epoch: u64,
new_key: &[u8; 32],
) -> Result<bool, String> {
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
let tx = conn.unchecked_transaction().map_err(|e| format!("advance channel epoch tx: {e}"))?;
store_epoch_key_tx(&tx, community_id, channel_id, new_epoch, new_key)?;
let cur: Option<i64> = tx
.query_row(
"SELECT epoch FROM community_channels WHERE community_id = ?1 AND channel_id = ?2",
params![community_id, channel_id],
|r| r.get(0),
)
.optional()
.map_err(|e| format!("read channel head: {e}"))?;
let advanced = matches!(cur, Some(c) if new_epoch > c as u64);
if advanced {
let enc = enc_key(new_key)?;
tx.execute(
"UPDATE community_channels SET epoch = ?1, channel_key = ?2
WHERE community_id = ?3 AND channel_id = ?4",
params![new_epoch as i64, &enc[..], community_id, channel_id],
)
.map_err(|e| format!("advance channel head: {e}"))?;
}
tx.commit().map_err(|e| format!("advance channel epoch commit: {e}"))?;
if advanced {
crate::community::v2::realtime::invalidate_held_v2_community(community_id);
}
Ok(advanced)
}
pub fn get_server_root_epoch(community_id: &str) -> Result<Option<u64>, String> {
let conn = super::get_db_connection_guard_static()?;
conn.query_row(
"SELECT server_root_epoch FROM communities WHERE community_id = ?1",
params![community_id],
|r| r.get::<_, i64>(0),
)
.optional()
.map(|v| v.map(|e| e as u64))
.map_err(|e| format!("get server root epoch: {e}"))
}
pub fn advance_server_root_epoch(community_id: &str, new_epoch: u64, new_root: &[u8; 32]) -> Result<bool, String> {
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
let tx = conn.unchecked_transaction().map_err(|e| format!("advance server root tx: {e}"))?;
store_epoch_key_tx(&tx, community_id, crate::community::SERVER_ROOT_SCOPE_HEX, new_epoch, new_root)?;
let cur: Option<i64> = tx
.query_row(
"SELECT server_root_epoch FROM communities WHERE community_id = ?1",
params![community_id],
|r| r.get(0),
)
.optional()
.map_err(|e| format!("read server-root epoch: {e}"))?;
let advanced = matches!(cur, Some(c) if new_epoch > c as u64);
if advanced {
let enc = enc_key(new_root)?;
tx.execute(
"UPDATE communities SET server_root_epoch = ?1, server_root_key = ?2 WHERE community_id = ?3",
params![new_epoch as i64, &enc[..], community_id],
)
.map_err(|e| format!("advance server-root head: {e}"))?;
}
tx.commit().map_err(|e| format!("advance server root commit: {e}"))?;
if advanced {
crate::community::v2::realtime::invalidate_held_v2_community(community_id);
}
Ok(advanced)
}
pub fn converge_server_root_epoch(community_id: &str, epoch: u64, new_root: &[u8; 32]) -> Result<bool, String> {
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
let tx = conn.unchecked_transaction().map_err(|e| format!("converge server root tx: {e}"))?;
store_epoch_key_tx(&tx, community_id, crate::community::SERVER_ROOT_SCOPE_HEX, epoch, new_root)?;
let enc = enc_key(new_root)?;
let switched = tx
.execute(
"UPDATE communities SET server_root_key = ?1 WHERE community_id = ?2 AND server_root_epoch = ?3",
params![&enc[..], community_id, epoch as i64],
)
.map_err(|e| format!("converge server-root head: {e}"))?
> 0;
tx.commit().map_err(|e| format!("converge server root commit: {e}"))?;
if switched {
crate::community::v2::realtime::invalidate_held_v2_community(community_id);
}
Ok(switched)
}
pub fn held_epoch_keys(community_id: &str, scope_id: &str) -> Result<Vec<(Epoch, [u8; 32])>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare("SELECT epoch, key FROM community_epoch_keys WHERE community_id = ?1 AND scope_id = ?2")
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![community_id, scope_id], |r| {
Ok((r.get::<_, i64>(0)?, r.get::<_, Vec<u8>>(1)?))
})
.map_err(|e| e.to_string())?;
let mut out: Vec<(Epoch, [u8; 32])> = Vec::new();
for row in rows {
let (epoch, key_blob) = row.map_err(|e| e.to_string())?;
out.push((Epoch(epoch as u64), dec_key(&key_blob)?));
}
out.sort_by_key(|(e, _)| e.0);
Ok(out)
}
pub fn store_history_view(community_id: &str, channel_id: &str, epoch: u64, view: &crate::community::v2::rekey::HistoryView) -> Result<(), String> {
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
let tx = conn.unchecked_transaction().map_err(|e| format!("store history view tx: {e}"))?;
store_epoch_key_tx(&tx, community_id, &format!("hist:{channel_id}"), epoch, &view.conv_key)?;
store_epoch_key_tx(&tx, community_id, &format!("hista:{channel_id}"), epoch, &view.address)?;
tx.commit().map_err(|e| format!("store history view commit: {e}"))
}
pub fn history_views(community_id: &str, channel_id: &str) -> Result<Vec<(Epoch, crate::community::v2::rekey::HistoryView)>, String> {
let addresses: std::collections::HashMap<u64, [u8; 32]> =
held_epoch_keys(community_id, &format!("hista:{channel_id}"))?.into_iter().map(|(e, a)| (e.0, a)).collect();
Ok(held_epoch_keys(community_id, &format!("hist:{channel_id}"))?
.into_iter()
.filter_map(|(e, conv_key)| addresses.get(&e.0).map(|address| (e, crate::community::v2::rekey::HistoryView { address: *address, conv_key })))
.collect())
}
pub fn held_epoch_key(community_id: &str, scope_id: &str, epoch: u64) -> Result<Option<[u8; 32]>, String> {
let conn = super::get_db_connection_guard_static()?;
let blob: Option<Vec<u8>> = conn
.query_row(
"SELECT key FROM community_epoch_keys WHERE community_id = ?1 AND scope_id = ?2 AND epoch = ?3",
params![community_id, scope_id, epoch as i64],
|r| r.get(0),
)
.optional()
.map_err(|e| format!("held epoch key: {e}"))?;
blob.map(|b| dec_key(&b)).transpose()
}
pub fn store_message_key(
message_id: &str,
outer_event_id: &str,
ephemeral: &Keys,
relays: &[String],
) -> Result<(), String> {
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
let relays_json = serde_json::to_string(relays).map_err(|e| e.to_string())?;
let sk_bytes = to_32(ephemeral.secret_key().as_secret_bytes())?;
let enc_secret = enc_key(&sk_bytes)?;
let enc_relays = enc_txt(&relays_json)?;
conn.execute(
"INSERT OR REPLACE INTO community_message_keys
(outer_event_id, message_id, ephemeral_secret, relays, created_at)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![
outer_event_id,
message_id,
&enc_secret[..],
enc_relays,
now_secs(),
],
)
.map_err(|e| format!("store message key: {e}"))?;
Ok(())
}
pub fn get_message_key(message_id: &str) -> Result<Option<(Keys, String, Vec<String>)>, String> {
let conn = super::get_db_connection_guard_static()?;
let row = conn
.query_row(
"SELECT ephemeral_secret, outer_event_id, relays
FROM community_message_keys WHERE message_id = ?1",
params![message_id],
|r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)),
)
.optional()
.map_err(|e| format!("get message key: {e}"))?;
let (secret_blob, outer_event_id, relays_json) = match row {
Some(t) => t,
None => return Ok(None),
};
let secret = SecretKey::from_slice(&dec_key(&secret_blob)?).map_err(|e| format!("ephemeral secret: {e}"))?;
let relays: Vec<String> = serde_json::from_str(&dec_txt(&relays_json)).map_err(|e| e.to_string())?;
Ok(Some((Keys::new(secret), outer_event_id, relays)))
}
pub fn has_message_key(message_id: &str) -> Result<bool, String> {
let conn = super::get_db_connection_guard_static()?;
conn.prepare_cached("SELECT EXISTS(SELECT 1 FROM community_message_keys WHERE message_id = ?1)")
.and_then(|mut stmt| stmt.query_row(params![message_id], |r| r.get(0)))
.map_err(|e| format!("has message key: {e}"))
}
pub fn delete_message_key(message_id: &str) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
conn.execute(
"DELETE FROM community_message_keys WHERE message_id = ?1",
params![message_id],
)
.map_err(|e| format!("remove message key: {e}"))?;
Ok(())
}
pub fn take_message_key(message_id: &str) -> Result<Option<(Keys, String, Vec<String>)>, String> {
let r = get_message_key(message_id)?;
if r.is_some() {
delete_message_key(message_id)?;
}
Ok(r)
}
pub fn store_wrap_owner(message_id: &str, outer_event_id: &str, owner: &Keys, relays: &[String]) -> Result<(), String> {
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
let relays_json = serde_json::to_string(relays).map_err(|e| e.to_string())?;
let enc_secret = enc_key(&to_32(owner.secret_key().as_secret_bytes())?)?;
let enc_relays = enc_txt(&relays_json)?;
conn.execute(
"INSERT OR REPLACE INTO community_wrap_owners (outer_event_id, message_id, owner_secret, relays, created_at)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![outer_event_id, message_id, &enc_secret[..], enc_relays, now_secs()],
)
.map_err(|e| format!("store wrap owner: {e}"))?;
Ok(())
}
pub fn wrap_owners(message_id: &str) -> Result<Vec<(Keys, String, Vec<String>)>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare_cached("SELECT owner_secret, outer_event_id, relays FROM community_wrap_owners WHERE message_id = ?1")
.map_err(|e| format!("wrap owners: {e}"))?;
let rows = stmt
.query_map(params![message_id], |r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)))
.map_err(|e| format!("wrap owners: {e}"))?;
let mut out = Vec::new();
for row in rows {
let (secret_blob, outer_event_id, relays_json) = row.map_err(|e| format!("wrap owners: {e}"))?;
let secret = SecretKey::from_slice(&dec_key(&secret_blob)?).map_err(|e| format!("wrap owner secret: {e}"))?;
let relays: Vec<String> = serde_json::from_str(&dec_txt(&relays_json)).map_err(|e| e.to_string())?;
out.push((Keys::new(secret), outer_event_id, relays));
}
Ok(out)
}
pub fn has_wrap_owner(message_id: &str) -> Result<bool, String> {
let conn = super::get_db_connection_guard_static()?;
conn.prepare_cached("SELECT EXISTS(SELECT 1 FROM community_wrap_owners WHERE message_id = ?1)")
.and_then(|mut stmt| stmt.query_row(params![message_id], |r| r.get(0)))
.map_err(|e| format!("has wrap owner: {e}"))
}
pub fn forget_wrap_owners(message_id: &str) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
conn.execute("DELETE FROM community_wrap_owners WHERE message_id = ?1", params![message_id])
.map_err(|e| format!("forget wrap owners: {e}"))?;
Ok(())
}
pub fn queue_wrap_scrubs(community_id: &str, message_ids: &[String]) -> Result<(), String> {
let mut conn = super::get_write_connection_guard_static()?;
let tx = conn.transaction().map_err(|e| format!("queue wrap scrubs: {e}"))?;
for id in message_ids {
tx.execute(
"INSERT OR IGNORE INTO community_wrap_scrubs (message_id, community_id, queued_at) VALUES (?1, ?2, ?3)",
params![id, community_id, now_secs()],
)
.map_err(|e| format!("queue wrap scrubs: {e}"))?;
}
tx.commit().map_err(|e| format!("queue wrap scrubs: {e}"))
}
pub fn next_wrap_scrub() -> Result<Option<(String, String)>, String> {
let conn = super::get_db_connection_guard_static()?;
conn.query_row(
"SELECT message_id, community_id FROM community_wrap_scrubs ORDER BY queued_at, rowid LIMIT 1",
[],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()
.map_err(|e| format!("next wrap scrub: {e}"))
}
pub fn settle_wrap_scrub(message_id: &str, retry: bool) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
let sql = if retry {
"UPDATE community_wrap_scrubs SET queued_at = ?2 WHERE message_id = ?1"
} else {
"DELETE FROM community_wrap_scrubs WHERE message_id = ?1"
};
let n = if retry { conn.execute(sql, params![message_id, now_secs()]) } else { conn.execute(sql, params![message_id]) };
n.map(|_| ()).map_err(|e| format!("settle wrap scrub: {e}"))
}
pub fn forget_channel_chat(community_id: &str, channel_id: &str) -> Result<bool, String> {
let held = {
let conn = super::get_write_connection_guard_static()?;
let files = conn
.execute(
"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)",
params![channel_id],
)
.map_err(|e| format!("forget channel attachments: {e}"))?;
let wraps = conn
.execute("DELETE FROM community_held_wraps WHERE community_id = ?1 AND channel_id = ?2", params![community_id, channel_id])
.map_err(|e| format!("forget channel held wraps: {e}"))?;
let chat: bool = conn
.query_row("SELECT EXISTS(SELECT 1 FROM chats WHERE chat_identifier = ?1)", params![channel_id], |r| r.get(0))
.map_err(|e| format!("forget channel chat: {e}"))?;
files + wraps > 0 || chat
};
if held {
super::chats::delete_chat(channel_id)?;
}
Ok(held)
}
pub fn channel_events(channel_id: &str) -> Result<Vec<(String, bool)>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare(
"SELECT e.id, EXISTS(SELECT 1 FROM attachments a WHERE a.event_id = e.id)
FROM events e JOIN chats c ON c.id = e.chat_id WHERE c.chat_identifier = ?1",
)
.map_err(|e| format!("channel events: {e}"))?;
let rows = stmt
.query_map(params![channel_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, bool>(1)?)))
.map_err(|e| format!("channel events: {e}"))?;
rows.collect::<Result<_, _>>().map_err(|e| format!("channel events: {e}"))
}
struct ChannelCommunityCache;
type ChannelCommunityMap = std::sync::RwLock<std::collections::HashMap<[u8; 32], [u8; 32]>>;
fn channel_community_cache() -> std::sync::Arc<ChannelCommunityMap> {
crate::db::current_session().scoped::<ChannelCommunityCache, ChannelCommunityMap>()
}
pub fn clear_channel_community_cache() {
*channel_community_cache().write().unwrap_or_else(|e| e.into_inner()) = Default::default();
crate::notify::invalidate_communities();
}
fn forget_community_channels(community_id: &str) {
if let Some(cid) = crate::community::id32_from_hex(community_id) {
channel_community_cache().write().unwrap_or_else(|e| e.into_inner()).retain(|_, c| *c != cid);
}
crate::notify::invalidate_communities();
}
fn query_community_for_channel(channel_id: &str) -> Result<Option<String>, String> {
let conn = super::get_db_connection_guard_static()?;
conn.prepare_cached("SELECT community_id FROM community_channels WHERE channel_id = ?1")
.and_then(|mut stmt| stmt.query_row(params![channel_id], |r| r.get::<_, String>(0)))
.optional()
.map_err(|e| format!("community_id_for_channel: {e}"))
}
pub fn channel_is_private(channel_id: &str) -> Result<Option<bool>, String> {
let conn = super::get_db_connection_guard_static()?;
conn.prepare_cached("SELECT private FROM community_channels WHERE channel_id = ?1")
.and_then(|mut stmt| stmt.query_row(params![channel_id], |r| r.get::<_, i64>(0)))
.optional()
.map(|p| p.map(|p| p != 0))
.map_err(|e| format!("channel_is_private: {e}"))
}
pub fn community_for_channel(channel: &[u8; 32]) -> Result<Option<[u8; 32]>, String> {
let cache = channel_community_cache();
if let Some(cid) = cache.read().unwrap_or_else(|e| e.into_inner()).get(channel) {
return Ok(Some(*cid));
}
let Some(cid_hex) = query_community_for_channel(&crate::simd::hex::bytes_to_hex_32(channel))? else {
return Ok(None);
};
let Some(cid) = crate::community::id32_from_hex(&cid_hex) else {
return Ok(None);
};
cache.write().unwrap_or_else(|e| e.into_inner()).insert(*channel, cid);
Ok(Some(cid))
}
pub fn community_id_for_channel(channel_id: &str) -> Result<Option<String>, String> {
let channel = crate::community::id32_from_hex(channel_id);
if let Some(ch) = channel {
if let Some(cid) = channel_community_cache().read().unwrap_or_else(|e| e.into_inner()).get(&ch) {
return Ok(Some(crate::simd::hex::bytes_to_hex_32(cid)));
}
}
let cid = query_community_for_channel(channel_id)?;
if let (Some(ch), Some(c)) = (channel, cid.as_deref().and_then(crate::community::id32_from_hex)) {
channel_community_cache().write().unwrap_or_else(|e| e.into_inner()).insert(ch, c);
}
Ok(cid)
}
pub fn community_exists(id: &CommunityId) -> Result<bool, String> {
let conn = super::get_db_connection_guard_static()?;
let found: Option<i64> = conn
.query_row(
"SELECT 1 FROM communities WHERE community_id = ?1",
params![id.to_hex()],
|r| r.get(0),
)
.optional()
.map_err(|e| format!("community_exists: {e}"))?;
Ok(found.is_some())
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct PendingCommunityInvite {
pub community_id: String,
pub bundle_json: String,
pub inviter_npub: String,
pub received_at: i64,
pub expires_at: i64,
pub sent_at: i64,
pub ends_at: i64,
}
pub fn save_pending_invite(
community_id: &str,
bundle_json: &str,
inviter_npub: &str,
expires_at: i64,
) -> Result<bool, String> {
let _seal = crate::crypto::gate::sealing();
const MAX_PENDING_INVITES: usize = 100;
let conn = super::get_write_connection_guard_static()?;
let enc_bundle = enc_txt(bundle_json)?;
let enc_inviter = enc_txt(inviter_npub)?;
let changed = conn
.execute(
"INSERT OR IGNORE INTO pending_community_invites
(community_id, bundle_json, inviter_npub, received_at, expires_at)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![community_id, enc_bundle, enc_inviter, now_secs(), expires_at],
)
.map_err(|e| format!("save pending invite: {e}"))?;
if changed > 0 {
let _ = conn.execute(
"DELETE FROM pending_community_invites
WHERE community_id IN (
SELECT community_id FROM pending_community_invites
ORDER BY received_at DESC, community_id DESC
LIMIT -1 OFFSET ?1
)",
params![MAX_PENDING_INVITES],
);
}
Ok(changed > 0)
}
pub fn note_pending_invite_wrap(community_id: &str, wrap_hex: &str) -> Result<(), String> {
const MAX_WRAPS: usize = 16;
let conn = super::get_write_connection_guard_static()?;
let held: Option<String> = conn
.query_row("SELECT wrap_ids FROM pending_community_invites WHERE community_id = ?1", params![community_id], |r| r.get(0))
.optional()
.map_err(|e| format!("read invite wraps: {e}"))?;
let Some(held) = held else { return Ok(()) };
let mut ids: Vec<&str> = held.split_whitespace().collect();
if ids.contains(&wrap_hex) || ids.len() >= MAX_WRAPS {
return Ok(());
}
ids.push(wrap_hex);
conn.execute("UPDATE pending_community_invites SET wrap_ids = ?2 WHERE community_id = ?1", params![community_id, ids.join(" ")])
.map_err(|e| format!("note invite wrap: {e}"))?;
Ok(())
}
pub fn set_pending_invite_sent(community_id: &str, sent_at: i64) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
conn.execute("UPDATE pending_community_invites SET sent_at = ?2 WHERE community_id = ?1 AND sent_at = 0", params![community_id, sent_at])
.map_err(|e| format!("set invite send time: {e}"))?;
Ok(())
}
const INVITE_LIFETIME_FROM: &str = "CASE WHEN sent_at > 0 THEN sent_at ELSE received_at END";
pub fn pending_invite_wraps(community_id: &str) -> Result<Vec<String>, String> {
let conn = super::get_db_connection_guard_static()?;
let held: Option<String> = conn
.query_row("SELECT wrap_ids FROM pending_community_invites WHERE community_id = ?1", params![community_id], |r| r.get(0))
.optional()
.map_err(|e| format!("read invite wraps: {e}"))?;
Ok(held.map(|s| s.split_whitespace().map(String::from).collect()).unwrap_or_default())
}
pub fn purge_pending_invites_for_held_communities() -> Result<usize, String> {
let conn = super::get_write_connection_guard_static()?;
let n = conn
.execute(
"DELETE FROM pending_community_invites
WHERE community_id IN (SELECT community_id FROM communities)",
[],
)
.map_err(|e| format!("purge held pending invites: {e}"))?;
Ok(n)
}
pub fn purge_expired_pending_invites() -> Result<usize, String> {
let conn = super::get_write_connection_guard_static()?;
let now = now_secs();
let n = conn
.execute(
&format!(
"DELETE FROM pending_community_invites
WHERE (expires_at != 0 AND expires_at <= ?1)
OR {INVITE_LIFETIME_FROM} <= ?2"
),
params![now, now - crate::event_handler::DIRECT_INVITE_LIFETIME_SECS as i64],
)
.map_err(|e| format!("purge expired pending invites: {e}"))?;
Ok(n)
}
pub fn list_pending_invites() -> Result<Vec<PendingCommunityInvite>, String> {
let now = now_secs();
let raw: Vec<(String, String, String, i64, i64, i64)> = {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare(&format!(
"SELECT community_id, bundle_json, inviter_npub, received_at, expires_at, sent_at
FROM pending_community_invites
WHERE (expires_at = 0 OR expires_at > ?1)
AND {INVITE_LIFETIME_FROM} > ?2
ORDER BY received_at DESC"
))
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![now, now - crate::event_handler::DIRECT_INVITE_LIFETIME_SECS as i64], |r| {
Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?))
})
.map_err(|e| e.to_string())?;
rows.collect::<Result<_, _>>().map_err(|e| e.to_string())?
};
Ok(raw
.into_iter()
.map(|(community_id, bundle, inviter, received_at, expires_at, sent_at)| {
let from = if sent_at > 0 { sent_at } else { received_at };
let lifetime_end = from + crate::event_handler::DIRECT_INVITE_LIFETIME_SECS as i64;
PendingCommunityInvite {
community_id,
bundle_json: dec_txt(&bundle),
inviter_npub: dec_txt(&inviter),
received_at,
expires_at,
sent_at,
ends_at: if expires_at != 0 { expires_at.min(lifetime_end) } else { lifetime_end },
}
})
.collect())
}
pub fn get_pending_invite(community_id: &str) -> Result<Option<String>, String> {
let conn = super::get_db_connection_guard_static()?;
let raw: Option<String> = conn
.query_row(
"SELECT bundle_json FROM pending_community_invites
WHERE community_id = ?1 AND (expires_at = 0 OR expires_at > ?2)",
params![community_id, now_secs()],
|r| r.get::<_, String>(0),
)
.optional()
.map_err(|e| format!("get pending invite: {e}"))?;
Ok(raw.map(|s| dec_txt(&s)))
}
pub fn delete_pending_invite(community_id: &str) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
conn.execute(
"DELETE FROM pending_community_invites WHERE community_id = ?1",
params![community_id],
)
.map_err(|e| format!("delete pending invite: {e}"))?;
Ok(())
}
pub fn delete_pending_invites_from(inviter_npub: &str) -> Result<usize, String> {
let mut dropped = 0;
for invite in list_pending_invites()? {
if invite.inviter_npub == inviter_npub {
delete_pending_invite(&invite.community_id)?;
dropped += 1;
}
}
Ok(dropped)
}
pub fn pending_invite_received_at(community_id: &str) -> Result<Option<i64>, String> {
let conn = super::get_db_connection_guard_static()?;
conn.query_row(
"SELECT received_at FROM pending_community_invites WHERE community_id = ?1",
params![community_id],
|r| r.get(0),
)
.optional()
.map_err(|e| format!("pending_invite_received_at: {e}"))
}
pub fn pending_invite_exists(community_id: &str) -> Result<bool, String> {
let conn = super::get_db_connection_guard_static()?;
let found: Option<i64> = conn
.query_row(
"SELECT 1 FROM pending_community_invites WHERE community_id = ?1",
params![community_id],
|r| r.get(0),
)
.optional()
.map_err(|e| format!("pending_invite_exists: {e}"))?;
Ok(found.is_some())
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct PublicInviteRecord {
pub token: String,
pub community_id: String,
pub url: String,
pub expires_at: Option<i64>,
pub created_at: i64,
pub label: Option<String>,
#[serde(default)]
pub join_count: u64,
}
pub fn save_public_invite(
token: &str,
community_id: &str,
url: &str,
expires_at: Option<i64>,
label: Option<&str>,
) -> Result<(), String> {
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
let enc_token = enc_txt(token)?;
let enc_url = enc_txt(url)?;
let enc_label = label.map(enc_txt).transpose()?;
conn.execute(
"INSERT OR REPLACE INTO community_public_invites
(token, community_id, url, expires_at, created_at, label)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![enc_token, community_id, enc_url, expires_at, now_secs(), enc_label],
)
.map_err(|e| format!("save public invite: {e}"))?;
Ok(())
}
pub fn adopt_public_invite(token: &str, community_id: &str, url: &str, expires_at: Option<i64>, label: Option<&str>, created_at: i64) -> Result<(), String> {
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
let enc_label = label.map(enc_txt).transpose()?;
conn.execute(
"INSERT INTO community_public_invites
(token, community_id, url, expires_at, created_at, label)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![enc_txt(token)?, community_id, enc_txt(url)?, expires_at, created_at, enc_label],
)
.map_err(|e| format!("adopt public invite: {e}"))?;
Ok(())
}
pub fn list_public_invites(community_id: &str) -> Result<Vec<PublicInviteRecord>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare(
"SELECT token, community_id, url, expires_at, created_at, label
FROM community_public_invites WHERE community_id = ?1 ORDER BY created_at DESC",
)
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![community_id], |r| {
Ok(PublicInviteRecord {
token: dec_txt(&r.get::<_, String>(0)?),
community_id: r.get(1)?,
url: dec_txt(&r.get::<_, String>(2)?),
expires_at: r.get(3)?,
created_at: r.get(4)?,
label: r.get::<_, Option<String>>(5)?.map(|s| dec_txt(&s)),
join_count: 0,
})
})
.map_err(|e| e.to_string())?;
let mut out = Vec::new();
for row in rows {
out.push(row.map_err(|e| e.to_string())?);
}
if let Some(me) = crate::state::my_public_key() {
if let Ok(counts) = community_invite_join_counts(community_id, &me) {
let unlabeled = out.iter().filter(|r| r.label.as_deref().is_none_or(str::is_empty)).count();
for rec in &mut out {
match rec.label.as_deref() {
Some(l) if !l.is_empty() => rec.join_count = counts.get(l).copied().unwrap_or(0),
_ if unlabeled == 1 => rec.join_count = counts.get("").copied().unwrap_or(0),
_ => {}
}
}
}
}
Ok(out)
}
pub fn delete_public_invite(token: &str) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
let rows: Vec<(i64, String)> = {
let mut stmt = conn
.prepare("SELECT rowid, token FROM community_public_invites")
.map_err(|e| e.to_string())?;
let mapped = stmt
.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)))
.map_err(|e| e.to_string())?;
mapped.filter_map(|r| r.ok()).collect()
};
for (rowid, stored) in rows {
if dec_txt(&stored) == token {
conn.execute("DELETE FROM community_public_invites WHERE rowid = ?1", params![rowid])
.map_err(|e| format!("delete public invite: {e}"))?;
}
}
Ok(())
}
pub fn list_all_public_invites() -> Result<Vec<PublicInviteRecord>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare(
"SELECT token, community_id, url, expires_at, created_at, label
FROM community_public_invites ORDER BY created_at DESC",
)
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map([], |r| {
Ok(PublicInviteRecord {
token: dec_txt(&r.get::<_, String>(0)?),
community_id: r.get(1)?,
url: dec_txt(&r.get::<_, String>(2)?),
expires_at: r.get(3)?,
created_at: r.get(4)?,
label: r.get::<_, Option<String>>(5)?.map(|s| dec_txt(&s)),
join_count: 0,
})
})
.map_err(|e| e.to_string())?;
let mut out = Vec::new();
for row in rows {
out.push(row.map_err(|e| e.to_string())?);
}
Ok(out)
}
pub fn delete_community(community_id: &str) -> Result<(), String> {
let out = delete_community_inner(community_id, false);
crate::community::v2::realtime::invalidate_held_v2_community(community_id);
out
}
pub fn delete_community_retain_keys(community_id: &str) -> Result<(), String> {
let out = delete_community_inner(community_id, true);
crate::community::v2::realtime::invalidate_held_v2_community(community_id);
out
}
fn delete_community_inner(community_id: &str, retain_keys: bool) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
let tx = conn.unchecked_transaction().map_err(|e| format!("delete community tx: {e}"))?;
for sql in [
Some("DELETE FROM communities WHERE community_id = ?1"),
Some("DELETE FROM community_channels WHERE community_id = ?1"),
(!retain_keys).then_some("DELETE FROM community_epoch_keys WHERE community_id = ?1"),
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:%')"),
Some("DELETE FROM community_public_invites WHERE community_id = ?1"),
Some("DELETE FROM community_invite_link_sets WHERE community_id = ?1"),
Some("DELETE FROM pending_community_invites WHERE community_id = ?1"),
Some("DELETE FROM pending_channel_keys WHERE community_id = ?1"),
Some("DELETE FROM community_edition_heads WHERE community_id = ?1"),
Some("DELETE FROM community_bans WHERE community_id = ?1"),
Some("DELETE FROM community_writers WHERE community_id = ?1"),
Some("DELETE FROM community_held_wraps WHERE community_id = ?1"),
Some("DELETE FROM community_control_wraps WHERE community_id = ?1"),
Some("DELETE FROM settings WHERE key LIKE 'ctl_reads:' || ?1 || '%'"),
Some("DELETE FROM settings WHERE key LIKE 'pln_reads:' || ?1 || '%'"),
Some("DELETE FROM community_guestbook_wraps WHERE community_id = ?1"),
Some("DELETE FROM settings WHERE key = 'gbk_reads:' || ?1"),
Some("DELETE FROM settings WHERE key = 'gb_reads:' || ?1"),
Some("DELETE FROM community_audit_local WHERE community_id = ?1"),
Some("DELETE FROM settings WHERE key LIKE 'writer_postable:' || ?1 || ':%'"),
Some("DELETE FROM settings WHERE key LIKE 'writer_cert:' || ?1 || ':%'"),
Some("DELETE FROM settings WHERE key LIKE 'writer_retract:' || ?1 || ':%'"),
Some("DELETE FROM settings WHERE key LIKE 'writer_retract_by:' || ?1 || ':%'"),
Some("DELETE FROM community_owed_authors WHERE book IN (SELECT book FROM community_guestbook_books WHERE community_id = ?1)"),
Some("DELETE FROM settings WHERE key = 'departures_seen:' || ?1"),
Some("DELETE FROM community_departures_seen WHERE book IN (SELECT book FROM community_guestbook_books WHERE community_id = ?1)"),
]
.into_iter()
.flatten()
{
tx.execute(sql, params![community_id])
.map_err(|e| format!("delete community: {e}"))?;
}
tx.commit().map_err(|e| format!("delete community commit: {e}"))?;
roster_cache().lock().unwrap_or_else(|e| e.into_inner()).moved(community_id);
departures_seen_cache().lock().unwrap_or_else(|e| e.into_inner()).moved(community_id);
if let Some(cid) = crate::community::id32_from_hex(community_id) {
banlist_cache().write().unwrap_or_else(|e| e.into_inner()).remove(&cid);
}
forget_community_channels(community_id);
Ok(())
}
pub fn community_member_activity(community_id: &str) -> Result<Vec<(String, u64)>, String> {
community_member_activity_capped(community_id, true)
}
pub fn community_member_activity_capped(community_id: &str, capped: bool) -> Result<Vec<(String, u64)>, String> {
member_activity(community_id, capped, false)
}
pub fn community_member_activity_strict(community_id: &str) -> Result<Vec<(String, u64)>, String> {
member_activity(community_id, false, true)
}
fn activity_sql(placeholders: &str) -> String {
let sys = crate::stored_event::event_kind::APPLICATION_SPECIFIC;
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")
}
fn flagged_sql(placeholders: &str, strict: bool) -> String {
let sys = crate::stored_event::event_kind::APPLICATION_SPECIFIC;
let read = |sign: &str| format!("SELECT npub FROM events WHERE chat_id IN ({placeholders}) AND kind != {sys} AND npub IS NOT NULL AND {sign}");
if strict { format!("{} UNION {}", read(HELD_POST), read(WRITER_POST)) } else { format!("SELECT DISTINCT npub FROM ({})", read(HELD_POST)) }
}
pub(crate) const HELD_POST: &str = "instr(tags, '[\"unauthorized\"]') > 0";
pub(crate) const WRITER_POST: &str = "instr(tags, '[\"writer\"]') > 0";
fn member_activity(community_id: &str, capped: bool, strict: bool) -> Result<Vec<(String, u64)>, String> {
let grant_stamp = if strict { 0 } else { now_secs() as u64 };
const COMMUNITY_MEMBER_CAP: usize = 500;
use std::collections::HashMap;
if !community_held(&CommunityId(hex_id_to_32(community_id)?))? {
return Ok(Vec::new());
}
let chat_ints = community_chat_row_ids(community_id)?;
let sys = crate::stored_event::event_kind::APPLICATION_SPECIFIC;
let mut active: HashMap<String, u64> = HashMap::new();
let mut left: HashMap<String, u64> = HashMap::new();
if !chat_ints.is_empty() {
let conn = super::get_db_connection_guard_static()?;
let placeholders = chat_ints.iter().map(|_| "?").collect::<Vec<_>>().join(",");
{
let mut stmt = conn.prepare(&activity_sql(&placeholders)).map_err(|e| e.to_string())?;
let rows = stmt
.query_map(rusqlite::params_from_iter(chat_ints.iter()), |r| {
Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.max(0) as u64))
})
.map_err(|e| e.to_string())?;
for row in rows {
let (npub, at) = row.map_err(|e| e.to_string())?;
let newest = active.entry(npub).or_insert(at);
*newest = (*newest).max(at);
}
}
{
let excluded = if strict { format!("({HELD_POST} OR {WRITER_POST})") } else { HELD_POST.to_string() };
let mut stmt = conn.prepare(&flagged_sql(&placeholders, strict)).map_err(|e| e.to_string())?;
let binds = chat_ints.iter().chain(chat_ints.iter().filter(|_| strict));
let flagged: Vec<String> = stmt.query_map(rusqlite::params_from_iter(binds), |r| r.get(0)).map_err(|e| e.to_string())?.flatten().collect();
let sql = format!("SELECT MAX(created_at) FROM events WHERE chat_id IN ({placeholders}) AND kind != {sys} AND npub = ? AND NOT {excluded}");
for npub in flagged {
let mut args: Vec<rusqlite::types::Value> = chat_ints.iter().map(|i| rusqlite::types::Value::Integer(*i)).collect();
args.push(npub.clone().into());
let newest: Option<i64> = conn.query_row(&sql, rusqlite::params_from_iter(args), |r| r.get(0)).map_err(|e| e.to_string())?;
match newest {
Some(at) => active.insert(npub, at.max(0) as u64),
None => active.remove(&npub),
};
}
}
{
let sql = format!(
"SELECT npub, created_at, tags FROM events \
WHERE chat_id IN ({placeholders}) AND kind = {sys} AND npub IS NOT NULL AND npub != ''"
);
let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
let rows = stmt
.query_map(rusqlite::params_from_iter(chat_ints.iter()), |r| {
Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.max(0) as u64, r.get::<_, String>(2)?))
})
.map_err(|e| e.to_string())?
.collect::<Result<Vec<_>, _>>()
.map_err(|e| e.to_string())?;
drop(stmt);
drop(conn);
for (npub, at, tags_json) in rows {
let etype = serde_json::from_str::<Vec<Vec<String>>>(&tags_json)
.ok()
.and_then(|tags| {
tags.into_iter()
.find(|t| t.first().map(|s| s == "event-type").unwrap_or(false))
.and_then(|t| t.into_iter().nth(1))
});
match etype.as_deref() {
Some("1") => {
let e = active.entry(npub).or_insert(0);
if at > *e { *e = at; }
}
Some("0") => {
let e = left.entry(npub).or_insert(0);
if at > *e { *e = at; }
}
_ => {}
}
}
}
}
let banned: std::collections::HashSet<String> = banned_set(community_id)
.iter()
.filter_map(|b| PublicKey::from_slice(b).ok())
.filter_map(|pk| pk.to_bech32().ok())
.collect();
let mut out: Vec<(String, u64)> = active
.into_iter()
.filter(|(npub, at)| !banned.contains(npub) && left.get(npub).is_none_or(|l| at >= l))
.collect();
{
let mut present: std::collections::HashSet<String> = out.iter().map(|(n, _)| n.clone()).collect();
let mut reassert = |npub: String| {
if !banned.contains(&npub) && present.insert(npub.clone()) {
out.push((npub, grant_stamp));
}
};
if let Ok(roles) = get_community_roles(community_id) {
for g in &roles.grants {
if g.role_ids.is_empty() {
continue; }
if let Some(b32) = PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()) {
reassert(b32);
}
}
}
}
out.sort_by_key(|m| std::cmp::Reverse(m.1));
if capped {
out.truncate(COMMUNITY_MEMBER_CAP);
}
Ok(out)
}
pub fn community_invite_join_counts(
community_id: &str,
inviter: &PublicKey,
) -> Result<std::collections::HashMap<String, u64>, String> {
use std::collections::{HashMap, HashSet};
hex_id_to_32(community_id)?;
let (hex, npub) = (inviter.to_hex(), inviter.to_bech32().unwrap_or_default());
let (events, _) = get_guestbook(community_id)?;
let mut per_label: HashMap<String, HashSet<PublicKey>> = HashMap::new();
for e in &events {
let crate::community::v2::guestbook::GuestbookEntry::Join { member, invited_by: Some((by, label)), .. } = &e.entry else {
continue;
};
if by.eq_ignore_ascii_case(&hex) || *by == npub {
per_label.entry(label.clone()).or_default().insert(*member);
}
}
Ok(per_label.into_iter().map(|(k, v)| (k, v.len() as u64)).collect())
}
#[derive(Debug, Clone)]
pub struct AuthorFootprint {
pub npub: String,
pub messages: u64,
pub first_secs: u64,
pub last_secs: u64,
}
pub fn community_chat_row_ids(community_id: &str) -> Result<Vec<i64>, String> {
let channel_ids = community_channel_ids(community_id)?;
Ok(channel_ids.iter().filter_map(|c| super::id_cache::get_chat_id_by_identifier(c).ok()).collect())
}
pub fn community_channel_ids(community_id: &str) -> Result<Vec<String>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare("SELECT channel_id FROM community_channels WHERE community_id = ?1")
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![community_id], |r| r.get::<_, String>(0))
.map_err(|e| e.to_string())?;
rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
}
#[derive(Debug, Clone)]
pub struct StoredPolicy {
pub policy_id: String,
pub bytes: String,
pub hash: String,
pub enabled: bool,
pub updated_at: u64,
}
pub fn get_community_policies(community_id: &str) -> Result<Vec<StoredPolicy>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare(
"SELECT policy_id, bytes, hash, enabled, updated_at FROM community_policies \
WHERE community_id = ?1 ORDER BY policy_id",
)
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![community_id], |r| {
Ok(StoredPolicy {
policy_id: r.get::<_, String>(0)?,
bytes: dec_txt(&r.get::<_, String>(1)?),
hash: r.get::<_, String>(2)?,
enabled: r.get::<_, i64>(3)? != 0,
updated_at: r.get::<_, i64>(4)?.max(0) as u64,
})
})
.map_err(|e| e.to_string())?;
rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
}
pub fn set_community_policy(
community_id: &str,
policy_id: &str,
bytes: &str,
hash: &str,
enabled: bool,
updated_at: u64,
) -> Result<(), String> {
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
conn.execute(
"INSERT INTO community_policies (community_id, policy_id, bytes, hash, enabled, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
ON CONFLICT(community_id, policy_id) DO UPDATE SET bytes=?3, hash=?4, enabled=?5, updated_at=?6",
params![community_id, policy_id, enc_txt(bytes)?, hash, enabled as i64, updated_at as i64],
)
.map_err(|e| format!("save policy: {e}"))?;
Ok(())
}
pub fn delete_community_policy(community_id: &str, policy_id: &str) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
conn.execute(
"DELETE FROM community_policies WHERE community_id = ?1 AND policy_id = ?2",
params![community_id, policy_id],
)
.map_err(|e| format!("delete policy: {e}"))?;
Ok(())
}
#[derive(Debug, Clone)]
pub struct PolicyMessage {
pub id: String,
pub npub: String,
pub channel_id: String,
pub at_ms: u64,
pub text: String,
pub mentions: u32,
}
pub fn community_policy_messages(community_id: &str, limit: usize) -> Result<Vec<PolicyMessage>, String> {
let channel_ids: Vec<String> = {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare("SELECT channel_id FROM community_channels WHERE community_id = ?1")
.map_err(|e| e.to_string())?;
let rows = stmt.query_map(params![community_id], |r| r.get::<_, String>(0)).map_err(|e| e.to_string())?;
rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())?
};
if channel_ids.is_empty() || limit == 0 {
return Ok(Vec::new());
}
let mut chat_to_channel: std::collections::HashMap<i64, String> = std::collections::HashMap::new();
for c in &channel_ids {
if let Ok(row) = super::id_cache::get_chat_id_by_identifier(c) {
chat_to_channel.insert(row, c.clone());
}
}
if chat_to_channel.is_empty() {
return Ok(Vec::new());
}
let text = crate::stored_event::event_kind::PRIVATE_DIRECT_MESSAGE;
let chat_ints: Vec<i64> = chat_to_channel.keys().copied().collect();
let rows: Vec<(String, String, i64, i64, String)> = {
let conn = super::get_db_connection_guard_static()?;
let placeholders = chat_ints.iter().map(|_| "?").collect::<Vec<_>>().join(",");
let sql = format!(
"SELECT id, npub, chat_id, created_at, content FROM events \
WHERE chat_id IN ({placeholders}) AND kind = {text} \
AND npub IS NOT NULL AND npub != '' \
ORDER BY created_at DESC LIMIT {limit}"
);
let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
let mapped = stmt
.query_map(rusqlite::params_from_iter(chat_ints.iter()), |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, String>(1)?,
r.get::<_, i64>(2)?,
r.get::<_, i64>(3)?,
r.get::<_, String>(4)?,
))
})
.map_err(|e| e.to_string())?;
mapped.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())?
};
let mut out: Vec<PolicyMessage> = crate::crypto::open_batch(|at_rest| rows
.into_iter()
.filter_map(|(id, npub, chat_id, created_at, content)| {
let channel_id = chat_to_channel.get(&chat_id)?.clone();
let content = at_rest.open_or_keep(content);
let mentions = crate::community::policy::matchers::count_mentions(&content);
Some(PolicyMessage {
id,
npub,
channel_id,
at_ms: (created_at.max(0) as u64).saturating_mul(1000),
text: content,
mentions,
})
})
.collect());
out.reverse(); Ok(out)
}
pub fn community_author_footprints(community_id: &str) -> Result<Vec<AuthorFootprint>, String> {
let chat_ints = community_chat_row_ids(community_id)?;
if chat_ints.is_empty() {
return Ok(Vec::new());
}
let text = crate::stored_event::event_kind::PRIVATE_DIRECT_MESSAGE;
let file = crate::stored_event::event_kind::FILE_ATTACHMENT;
let conn = super::get_db_connection_guard_static()?;
let placeholders = chat_ints.iter().map(|_| "?").collect::<Vec<_>>().join(",");
let sql = format!(
"SELECT npub, COUNT(*), MIN(created_at), MAX(created_at) FROM events \
WHERE chat_id IN ({placeholders}) AND kind IN ({text}, {file}) \
AND npub IS NOT NULL AND npub != '' \
GROUP BY npub"
);
let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
let rows = stmt
.query_map(rusqlite::params_from_iter(chat_ints.iter()), |r| {
Ok(AuthorFootprint {
npub: r.get::<_, String>(0)?,
messages: r.get::<_, i64>(1)?.max(0) as u64,
first_secs: r.get::<_, i64>(2)?.max(0) as u64,
last_secs: r.get::<_, i64>(3)?.max(0) as u64,
})
})
.map_err(|e| e.to_string())?;
rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
}
pub fn community_recent_texts(community_id: &str, limit: usize) -> Result<Vec<(String, u64, String)>, String> {
let chat_ints = community_chat_row_ids(community_id)?;
if chat_ints.is_empty() || limit == 0 {
return Ok(Vec::new());
}
let text = crate::stored_event::event_kind::PRIVATE_DIRECT_MESSAGE;
let rows: Vec<(String, u64, String)> = {
let conn = super::get_db_connection_guard_static()?;
let placeholders = chat_ints.iter().map(|_| "?").collect::<Vec<_>>().join(",");
let sql = format!(
"SELECT npub, created_at, content FROM events \
WHERE chat_id IN ({placeholders}) AND kind = {text} \
AND npub IS NOT NULL AND npub != '' \
ORDER BY created_at DESC LIMIT {limit}"
);
let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
let mapped = stmt
.query_map(rusqlite::params_from_iter(chat_ints.iter()), |r| {
Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.max(0) as u64, r.get::<_, String>(2)?))
})
.map_err(|e| e.to_string())?;
mapped.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())?
};
Ok(crate::crypto::open_batch(|at_rest| {
rows.into_iter().map(|(npub, at, content)| (npub, at, at_rest.open_or_keep(content))).collect()
}))
}
type BanSet = std::sync::Arc<std::collections::HashSet<[u8; 32]>>;
struct BanlistCache;
type BanlistMap = std::sync::RwLock<std::collections::HashMap<[u8; 32], BanSet>>;
fn banlist_cache() -> std::sync::Arc<BanlistMap> {
crate::db::current_session().scoped::<BanlistCache, BanlistMap>()
}
fn empty_ban_set() -> BanSet {
static EMPTY: std::sync::LazyLock<BanSet> = std::sync::LazyLock::new(Default::default);
std::sync::Arc::clone(&EMPTY)
}
fn ban_set_from_hexes(hexes: &[String]) -> BanSet {
let set: std::collections::HashSet<[u8; 32]> =
hexes.iter().filter_map(|h| crate::simd::hex::hex_to_bytes_32_checked(h)).collect();
if set.is_empty() { empty_ban_set() } else { std::sync::Arc::new(set) }
}
pub fn clear_banlist_cache() {
*banlist_cache().write().unwrap_or_else(|e| e.into_inner()) = Default::default();
}
pub fn banned_set_of(community: &[u8; 32]) -> BanSet {
let cache = banlist_cache();
if let Some(set) = cache.read().unwrap_or_else(|e| e.into_inner()).get(community) {
return std::sync::Arc::clone(set);
}
let set = ban_set_from_hexes(&get_community_banlist(&crate::simd::hex::bytes_to_hex_32(community)).unwrap_or_default());
cache.write().unwrap_or_else(|e| e.into_inner()).insert(*community, std::sync::Arc::clone(&set));
set
}
pub fn banned_set(community_id: &str) -> BanSet {
match crate::community::id32_from_hex(community_id) {
Some(cid) => banned_set_of(&cid),
None => ban_set_from_hexes(&get_community_banlist(community_id).unwrap_or_default()),
}
}
pub fn is_author_banned(community_id: &str, author: &PublicKey) -> bool {
let set = banned_set(community_id);
!set.is_empty() && set.contains(author.as_bytes())
}
pub fn is_author_banned_in(community: &[u8; 32], author: &PublicKey) -> bool {
let set = banned_set_of(community);
!set.is_empty() && set.contains(author.as_bytes())
}
fn forget_console_verdict(community_id: &str) {
crate::VectorCore::invalidate_raid_report(community_id);
}
pub fn set_community_banlist(community_id: &str, banned_hex: &[String], at: i64) -> Result<bool, String> {
let before: std::collections::BTreeSet<String> = get_community_banlist(community_id).unwrap_or_default().into_iter().collect();
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
let current_at: Option<i64> = conn
.query_row("SELECT banlist_at FROM communities WHERE community_id = ?1", params![community_id], |r| r.get(0))
.optional()
.map_err(|e| format!("read banlist_at: {e}"))?
.flatten();
if current_at.is_some_and(|have| have > at) {
crate::log_warn!(
"[Banlist] refused a stale edition (v{at} behind held v{}) — un-banning is the fail-open direction",
current_at.unwrap_or(0)
);
return Ok(false);
}
let tx = conn.unchecked_transaction().map_err(|e| format!("banlist tx: {e}"))?;
tx.execute("DELETE FROM community_bans WHERE community_id = ?1", params![community_id])
.map_err(|e| format!("clear banlist: {e}"))?;
{
let mut ins = tx
.prepare("INSERT INTO community_bans (community_id, npub) VALUES (?1, ?2)")
.map_err(|e| format!("prepare banlist insert: {e}"))?;
let joinable: std::collections::BTreeSet<String> = banned_hex
.iter()
.map(|hex| {
PublicKey::from_hex(hex)
.ok()
.and_then(|pk| pk.to_bech32().ok())
.unwrap_or_else(|| hex.clone())
})
.collect();
crate::crypto::seal_batch(|seal| {
for npub in &joinable {
ins.execute(params![community_id, seal.seal(npub)?])
.map_err(|e| format!("insert ban: {e}"))?;
}
Ok::<_, String>(())
})?;
}
tx.execute(
"UPDATE communities SET banlist_at = ?1 WHERE community_id = ?2",
params![at, community_id],
)
.map_err(|e| format!("set banlist_at: {e}"))?;
tx.commit().map_err(|e| format!("commit banlist: {e}"))?;
forget_console_verdict(community_id);
if let Some(cid) = crate::community::id32_from_hex(community_id) {
banlist_cache().write().unwrap_or_else(|e| e.into_inner()).insert(cid, ban_set_from_hexes(banned_hex));
}
Ok(before != banned_hex.iter().cloned().collect())
}
pub fn get_community_ban_marks(community_id: &str) -> Result<std::collections::BTreeMap<String, u64>, String> {
let conn = super::get_db_connection_guard_static()?;
let json: Option<String> = conn
.query_row(
"SELECT banlist_marks FROM communities WHERE community_id = ?1",
params![community_id],
|r| r.get(0),
)
.optional()
.map_err(|e| format!("get ban marks: {e}"))?;
Ok(json.and_then(|j| serde_json::from_str(&dec_txt(&j)).ok()).unwrap_or_default())
}
pub fn merge_community_ban_marks(community_id: &str, marks: &std::collections::BTreeMap<String, u64>) -> Result<bool, String> {
let _seal = crate::crypto::gate::sealing();
if marks.is_empty() {
return Ok(false);
}
let mut stored = get_community_ban_marks(community_id)?;
let mut changed = false;
for (npub, at) in marks {
let slot = stored.entry(npub.clone()).or_insert(0);
if *at > *slot {
*slot = *at;
changed = true;
}
}
if !changed {
return Ok(false);
}
let json = enc_txt(&serde_json::to_string(&stored).map_err(|e| e.to_string())?)?;
let conn = super::get_write_connection_guard_static()?;
conn.execute(
"UPDATE communities SET banlist_marks = ?1 WHERE community_id = ?2",
params![json, community_id],
)
.map_err(|e| format!("set ban marks: {e}"))?;
Ok(true)
}
pub fn get_community_banlist_at(community_id: &str) -> Result<i64, String> {
let conn = super::get_db_connection_guard_static()?;
let at: Option<i64> = conn
.query_row(
"SELECT banlist_at FROM communities WHERE community_id = ?1",
params![community_id],
|r| r.get(0),
)
.optional()
.map_err(|e| format!("get banlist_at: {e}"))?;
Ok(at.unwrap_or(0))
}
pub fn set_community_roles(
community_id: &str,
roles: &crate::community::roles::CommunityRoles,
at: i64,
) -> Result<(), String> {
let _seal = crate::crypto::gate::sealing();
forget_console_verdict(community_id);
let json = enc_txt(&serde_json::to_string(roles).map_err(|e| e.to_string())?)?;
let conn = super::get_write_connection_guard_static()?;
conn.execute(
"UPDATE communities SET roles = ?1, roles_at = ?2 WHERE community_id = ?3",
params![json, at, community_id],
)
.map_err(|e| format!("set roles: {e}"))?;
roster_cache().lock().unwrap_or_else(|e| e.into_inner()).moved(community_id);
drop(conn);
bump_membership_generation();
Ok(())
}
type RosterCache = Parsed<std::sync::Arc<crate::community::roles::CommunityRoles>, 16>;
fn roster_cache() -> std::sync::Arc<std::sync::Mutex<RosterCache>> {
struct Key;
super::current_session().scoped::<Key, std::sync::Mutex<RosterCache>>()
}
pub fn get_community_roles(
community_id: &str,
) -> Result<crate::community::roles::CommunityRoles, String> {
get_community_roles_shared(community_id).map(std::sync::Arc::unwrap_or_clone)
}
pub fn get_community_roles_shared(community_id: &str) -> Result<std::sync::Arc<crate::community::roles::CommunityRoles>, String> {
let cache = roster_cache();
let generation = {
let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
if let Some(hit) = held.get(community_id) {
return Ok(hit);
}
held.generation(community_id)
};
let json = {
let conn = super::get_db_connection_guard_static()?;
stored_roles(&conn, community_id).map_err(|e| format!("get roles: {e}"))?
};
let roles = std::sync::Arc::new(parse_roles(json, dec_txt));
cache.lock().unwrap_or_else(|e| e.into_inner()).put(community_id, generation, roles.clone());
Ok(roles)
}
fn stored_roles(conn: &rusqlite::Connection, community_id: &str) -> rusqlite::Result<Option<String>> {
conn.query_row("SELECT roles FROM communities WHERE community_id = ?1", params![community_id], |r| r.get(0))
.optional()
}
fn parse_roles(json: Option<String>, open: impl FnOnce(&str) -> String) -> crate::community::roles::CommunityRoles {
json.and_then(|j| serde_json::from_str(&open(&j)).ok()).unwrap_or_default()
}
pub fn get_community_roles_at(community_id: &str) -> Result<i64, String> {
let conn = super::get_db_connection_guard_static()?;
let at: Option<i64> = conn
.query_row(
"SELECT roles_at FROM communities WHERE community_id = ?1",
params![community_id],
|r| r.get(0),
)
.optional()
.map_err(|e| format!("get roles_at: {e}"))?;
Ok(at.unwrap_or(0))
}
pub fn set_edition_head(community_id: &str, entity_id: &str, version: u64, self_hash: &[u8; 32]) -> Result<(), String> {
set_edition_head_inner(community_id, entity_id, version, self_hash, None, None, None)
}
pub fn set_edition_head_with_id(community_id: &str, entity_id: &str, version: u64, self_hash: &[u8; 32], inner_id: &[u8; 32]) -> Result<(), String> {
set_edition_head_inner(community_id, entity_id, version, self_hash, Some(inner_id), None, None)
}
pub fn delete_edition_head(community_id: &str, entity_id: &str) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
conn.execute(
"DELETE FROM community_edition_heads WHERE community_id = ?1 AND entity_id = ?2",
params![community_id, entity_id],
)
.map_err(|e| format!("delete edition head: {e}"))?;
Ok(())
}
pub 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> {
set_edition_head_inner(community_id, entity_id, version, self_hash, Some(inner_id), Some(author), Some(epoch))
}
#[allow(clippy::too_many_arguments)]
pub 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> {
set_family_head_on(&*super::get_write_connection_guard_static()?, community_id, entity_id, version, self_hash, inner_id, author, epoch, family)
}
#[allow(clippy::too_many_arguments)]
fn 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> {
conn.execute(
"INSERT INTO community_edition_heads (community_id, entity_id, version, self_hash, inner_id, epoch, author, family)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
ON CONFLICT(community_id, entity_id) DO UPDATE SET
version = excluded.version,
self_hash = excluded.self_hash,
inner_id = excluded.inner_id,
epoch = excluded.epoch,
author = excluded.author,
family = excluded.family
WHERE NOT (community_edition_heads.family IS 'a' AND excluded.family IS NOT 'a')
AND (excluded.epoch > community_edition_heads.epoch
OR (excluded.epoch = community_edition_heads.epoch AND excluded.version > community_edition_heads.version)
OR (excluded.family = 'a' AND community_edition_heads.family IS NOT NULL AND community_edition_heads.family IS NOT 'a'))",
params![community_id, entity_id, version as i64, self_hash.as_slice(), inner_id.as_slice(), epoch as i64, author.as_slice(), family],
)
.map_err(|e| format!("set edition head: {e}"))?;
Ok(())
}
type HeldFloorRow = (u64, u64, Vec<u8>, Option<Vec<u8>>, Option<Vec<u8>>, Option<String>);
pub struct FloorWrites<'c> {
conn: &'c rusqlite::Connection,
community_id: &'c str,
held: std::collections::HashMap<String, HeldFloorRow>,
touched: std::collections::HashSet<String>,
}
impl FloorWrites<'_> {
#[allow(clippy::too_many_arguments)]
fn already(&self, entity_id: &str, version: u64, self_hash: &[u8; 32], inner_id: &[u8; 32], author: &[u8; 32], epoch: u64, family: &str) -> bool {
!self.touched.contains(entity_id)
&& self.held.get(entity_id).is_some_and(|(e, v, h, i, a, f)| {
*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)
})
}
#[allow(clippy::too_many_arguments)]
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> {
if self.already(entity_id, version, self_hash, inner_id, author, epoch, family) {
return Ok(());
}
self.touched.insert(entity_id.to_string());
set_family_head_on(self.conn, self.community_id, entity_id, version, self_hash, inner_id, author, epoch, family)
}
#[allow(clippy::too_many_arguments)]
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> {
if self.already(entity_id, version, self_hash, inner_id, author, epoch, family) {
return Ok(());
}
self.touched.insert(entity_id.to_string());
converge_family_head_on(self.conn, self.community_id, entity_id, version, self_hash, inner_id, author, epoch, Some(family))
}
#[allow(clippy::too_many_arguments)]
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> {
if self.already(entity_id, version, self_hash, inner_id, author, epoch, family) {
return Ok(());
}
self.touched.insert(entity_id.to_string());
rebase_edition_head_on(self.conn, self.community_id, entity_id, version, self_hash, inner_id, author, epoch, family)
}
}
pub fn write_folded_heads(community_id: &str, write: impl FnOnce(&mut FloorWrites<'_>) -> Result<(), String>) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
let tx = conn.unchecked_transaction().map_err(|e| format!("floor writes tx: {e}"))?;
let held = {
let mut stmt = tx
.prepare_cached("SELECT entity_id, epoch, version, self_hash, inner_id, author, family FROM community_edition_heads WHERE community_id = ?1")
.map_err(|e| format!("floor writes: {e}"))?;
let rows = stmt
.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)?))))
.map_err(|e| format!("floor writes: {e}"))?;
rows.collect::<Result<_, _>>().map_err(|e| format!("floor writes: {e}"))?
};
let mut writes = FloorWrites { conn: &tx, community_id, held, touched: Default::default() };
write(&mut writes)?;
tx.commit().map_err(|e| format!("floor writes commit: {e}"))
}
pub const FLOOR_AUTHORITY: &str = "a";
pub const FLOOR_CONTROL: &str = "c";
pub fn edition_head_families(community_id: &str) -> Result<std::collections::HashMap<String, String>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare("SELECT entity_id, family FROM community_edition_heads WHERE community_id = ?1 AND family IS NOT NULL")
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![community_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))
.map_err(|e| e.to_string())?;
rows.collect::<Result<_, _>>().map_err(|e| e.to_string())
}
fn 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> {
let conn = super::get_write_connection_guard_static()?;
conn.execute(
"INSERT INTO community_edition_heads (community_id, entity_id, version, self_hash, inner_id, epoch, author)
VALUES (?1, ?2, ?3, ?4, ?5, COALESCE(?6, (SELECT server_root_epoch FROM communities WHERE community_id = ?1), 0), ?7)
ON CONFLICT(community_id, entity_id) DO UPDATE SET
version = excluded.version,
self_hash = excluded.self_hash,
inner_id = excluded.inner_id,
epoch = excluded.epoch,
author = excluded.author
WHERE excluded.epoch > community_edition_heads.epoch
OR (excluded.epoch = community_edition_heads.epoch AND excluded.version > community_edition_heads.version)",
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())],
)
.map_err(|e| format!("set edition head: {e}"))?;
Ok(())
}
pub 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> {
converge_family_head_at_epoch(community_id, entity_id, version, self_hash, inner_id, author, epoch, None)
}
#[allow(clippy::too_many_arguments)]
pub 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> {
converge_family_head_on(&*super::get_write_connection_guard_static()?, community_id, entity_id, version, self_hash, inner_id, author, epoch, family)
}
#[allow(clippy::too_many_arguments)]
fn 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> {
conn.execute(
"UPDATE community_edition_heads
SET self_hash = ?4, inner_id = ?5, author = ?7
WHERE community_id = ?1 AND entity_id = ?2
AND version = ?3
AND epoch = ?6
AND (?8 IS NULL OR family IS NULL OR family = ?8)
AND (self_hash IS NOT ?4 OR inner_id IS NOT ?5 OR author IS NOT ?7)",
params![community_id, entity_id, version as i64, self_hash.as_slice(), inner_id.as_slice(), epoch as i64, author.as_slice(), family],
)
.map_err(|e| format!("converge edition head: {e}"))?;
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub 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> {
rebase_edition_head_on(&*super::get_write_connection_guard_static()?, community_id, entity_id, version, self_hash, inner_id, author, epoch, family)
}
#[allow(clippy::too_many_arguments)]
fn 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> {
conn.execute(
"UPDATE community_edition_heads
SET version = ?3, self_hash = ?4, inner_id = ?5, author = ?7, family = COALESCE(family, ?8)
WHERE community_id = ?1 AND entity_id = ?2 AND epoch = ?6 AND (family IS NULL OR family = ?8)",
params![community_id, entity_id, version as i64, self_hash.as_slice(), inner_id.as_slice(), epoch as i64, author.as_slice(), family],
)
.map_err(|e| format!("rebase edition head: {e}"))?;
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub 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> {
let conn = super::get_write_connection_guard_static()?;
conn.execute(
"UPDATE community_edition_heads SET self_hash = ?6, inner_id = ?7, author = ?8
WHERE community_id = ?1 AND entity_id = ?2 AND epoch = ?3 AND version = ?4 AND self_hash = ?5",
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()],
)
.map_err(|e| format!("heal edition head: {e}"))?;
Ok(())
}
pub fn get_edition_head_inner_id(community_id: &str, entity_id: &str) -> Result<Option<[u8; 32]>, String> {
let conn = super::get_db_connection_guard_static()?;
let row: Option<Option<Vec<u8>>> = conn
.query_row(
"SELECT inner_id FROM community_edition_heads WHERE community_id = ?1 AND entity_id = ?2",
params![community_id, entity_id],
|r| r.get(0),
)
.optional()
.map_err(|e| format!("get edition head inner_id: {e}"))?;
match row.flatten() {
Some(blob) if blob.len() == 32 => {
let mut h = [0u8; 32];
h.copy_from_slice(&blob);
Ok(Some(h))
}
_ => Ok(None),
}
}
pub fn get_edition_head(community_id: &str, entity_id: &str) -> Result<Option<(u64, [u8; 32])>, String> {
let conn = super::get_db_connection_guard_static()?;
let row: Option<(i64, Vec<u8>)> = conn
.query_row(
"SELECT version, self_hash FROM community_edition_heads WHERE community_id = ?1 AND entity_id = ?2",
params![community_id, entity_id],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()
.map_err(|e| format!("get edition head: {e}"))?;
match row {
Some((v, hash)) if hash.len() == 32 => {
let mut h = [0u8; 32];
h.copy_from_slice(&hash);
Ok(Some((v as u64, h)))
}
_ => Ok(None),
}
}
pub fn edition_head_entity_ids(community_id: &str) -> Result<std::collections::HashSet<String>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare("SELECT entity_id FROM community_edition_heads WHERE community_id = ?1")
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![community_id], |r| r.get::<_, String>(0))
.map_err(|e| e.to_string())?;
let mut out = std::collections::HashSet::new();
for row in rows {
out.insert(row.map_err(|e| e.to_string())?);
}
Ok(out)
}
type EditionHeadFull = (u64, u64, [u8; 32], Option<[u8; 32]>, Option<[u8; 32]>, Option<FloorFamily>);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FloorFamily {
Authority,
Control,
Other,
}
impl FloorFamily {
pub fn of(family: &str) -> Self {
match family {
FLOOR_AUTHORITY => FloorFamily::Authority,
FLOOR_CONTROL => FloorFamily::Control,
_ => FloorFamily::Other,
}
}
}
type EditionHead = (u64, u64, [u8; 32]);
pub fn get_all_edition_heads_full(community_id: &str) -> Result<std::collections::HashMap<String, EditionHeadFull>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare("SELECT entity_id, epoch, version, self_hash, inner_id, author, family FROM community_edition_heads WHERE community_id = ?1")
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![community_id], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, i64>(1)?,
r.get::<_, i64>(2)?,
r.get::<_, Vec<u8>>(3)?,
r.get::<_, Option<Vec<u8>>>(4)?,
r.get::<_, Option<Vec<u8>>>(5)?,
r.get::<_, Option<String>>(6)?,
))
})
.map_err(|e| e.to_string())?;
let blob32 = |b: Option<Vec<u8>>| {
b.and_then(|b| {
(b.len() == 32).then(|| {
let mut i = [0u8; 32];
i.copy_from_slice(&b);
i
})
})
};
let mut out = std::collections::HashMap::new();
for row in rows {
let (entity, epoch, version, hash, inner, author, family) = row.map_err(|e| e.to_string())?;
if hash.len() == 32 {
let mut h = [0u8; 32];
h.copy_from_slice(&hash);
out.insert(entity, (epoch as u64, version as u64, h, blob32(inner), blob32(author), family.as_deref().map(FloorFamily::of)));
}
}
Ok(out)
}
pub fn get_all_edition_heads_epoched(community_id: &str) -> Result<std::collections::HashMap<String, EditionHead>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare("SELECT entity_id, epoch, version, self_hash FROM community_edition_heads WHERE community_id = ?1")
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![community_id], |r| {
Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?, r.get::<_, i64>(2)?, r.get::<_, Vec<u8>>(3)?))
})
.map_err(|e| e.to_string())?;
let mut out = std::collections::HashMap::new();
for row in rows {
let (entity, epoch, version, hash) = row.map_err(|e| e.to_string())?;
if hash.len() == 32 {
let mut h = [0u8; 32];
h.copy_from_slice(&hash);
out.insert(entity, (epoch as u64, version as u64, h));
}
}
Ok(out)
}
pub fn get_community_banlist(community_id: &str) -> Result<Vec<String>, String> {
let _seal = crate::crypto::gate::sealing();
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare("SELECT npub FROM community_bans WHERE community_id = ?1")
.map_err(|e| format!("prepare get banlist: {e}"))?;
let rows = stmt
.query_map(params![community_id], |r| r.get::<_, String>(0))
.map_err(|e| format!("get banlist: {e}"))?;
let mut out: Vec<String> = crate::crypto::open_batch(|at_rest| {
rows.flatten()
.map(|b| at_rest.open_or_keep(b))
.map(|b| PublicKey::parse(&b).map(|pk| pk.to_hex()).unwrap_or(b))
.collect()
});
if !out.is_empty() {
return Ok(out);
}
drop(stmt);
let legacy: Option<String> = conn
.query_row(
"SELECT banlist FROM communities WHERE community_id = ?1 AND banlist IS NOT NULL AND banlist != ''",
params![community_id],
|r| r.get(0),
)
.optional()
.map_err(|e| format!("read legacy banlist: {e}"))?
.flatten();
let Some(blob) = legacy else { return Ok(out) };
let decoded = dec_txt(&blob);
let Ok(list) = serde_json::from_str::<Vec<String>>(&decoded) else { return Ok(out) };
if list.is_empty() {
return Ok(out);
}
let tx = conn.unchecked_transaction().map_err(|e| format!("adopt tx: {e}"))?;
{
let mut ins = tx
.prepare("INSERT INTO community_bans (community_id, npub) VALUES (?1, ?2)")
.map_err(|e| format!("prepare adopt: {e}"))?;
let joinable: std::collections::BTreeSet<String> = list
.iter()
.map(|hex| {
PublicKey::from_hex(hex)
.ok()
.and_then(|pk| pk.to_bech32().ok())
.unwrap_or_else(|| hex.clone())
})
.collect();
crate::crypto::seal_batch(|seal| {
for npub in &joinable {
ins.execute(params![community_id, seal.seal(npub)?]).map_err(|e| format!("adopt ban: {e}"))?;
}
Ok::<_, String>(())
})?;
}
tx.execute("UPDATE communities SET banlist = '[]' WHERE community_id = ?1", params![community_id])
.map_err(|e| format!("retire legacy banlist: {e}"))?;
tx.commit().map_err(|e| format!("commit adopt: {e}"))?;
crate::log_info!("[Banlist] adopted {} legacy ban(s) into community_bans", list.len());
out = list;
Ok(out)
}
pub fn set_community_invite_registry(community_id: &str, link_locators: &[String]) -> Result<(), String> {
let _seal = crate::crypto::gate::sealing();
let json = enc_txt(&serde_json::to_string(link_locators).map_err(|e| e.to_string())?)?;
let conn = super::get_write_connection_guard_static()?;
conn.execute(
"UPDATE communities SET invite_registry = ?1 WHERE community_id = ?2",
params![json, community_id],
)
.map_err(|e| format!("set invite registry: {e}"))?;
crate::notify::invalidate_communities();
Ok(())
}
pub fn community_ids_beyond_group_chat() -> Result<std::collections::HashSet<[u8; 32]>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare(
"SELECT c.community_id, c.invite_registry,
(SELECT COUNT(*) FROM community_channels ch WHERE ch.community_id = c.community_id)
FROM communities c",
)
.map_err(|e| format!("prepare community kinds: {e}"))?;
let rows = stmt
.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, i64>(2)?)))
.map_err(|e| format!("query community kinds: {e}"))?
.collect::<Result<Vec<_>, _>>()
.map_err(|e| format!("read community kinds: {e}"))?;
drop(stmt);
drop(conn);
let mut out = std::collections::HashSet::new();
for (id, registry, channels) in rows {
let links: Vec<String> = serde_json::from_str(&dec_txt(®istry)).unwrap_or_default();
if channels > 1 || !links.is_empty() {
out.extend(crate::community::id32_from_hex(&id));
}
}
Ok(out)
}
pub fn get_community_invite_registry(community_id: &str) -> Result<Vec<String>, String> {
let conn = super::get_db_connection_guard_static()?;
let json: Option<String> = conn
.query_row(
"SELECT invite_registry FROM communities WHERE community_id = ?1",
params![community_id],
|r| r.get(0),
)
.optional()
.map_err(|e| format!("get invite registry: {e}"))?;
Ok(json.and_then(|j| serde_json::from_str(&dec_txt(&j)).ok()).unwrap_or_default())
}
pub struct InviteLinkSetRow {
pub creator_hex: String,
pub locators: Vec<String>,
}
pub fn invite_link_set_creators(community_id: &str) -> Result<Vec<String>, String> {
let conn = super::get_write_connection_guard_static()?;
let mut stmt = conn
.prepare("SELECT creator FROM community_invite_link_sets WHERE community_id = ?1")
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![community_id], |r| r.get::<_, String>(0))
.map_err(|e| e.to_string())?
.filter_map(|r| r.ok())
.map(|stored| dec_txt(&stored))
.collect();
Ok(rows)
}
pub fn replace_invite_link_sets(community_id: &str, sets: &[InviteLinkSetRow]) -> Result<(), String> {
let _seal = crate::crypto::gate::sealing();
let mut conn = super::get_write_connection_guard_static()?;
let tx = conn.transaction().map_err(|e| format!("invite-link-sets tx: {e}"))?;
tx.execute("DELETE FROM community_invite_link_sets WHERE community_id = ?1", params![community_id])
.map_err(|e| format!("clear invite-link-sets: {e}"))?;
for s in sets {
if s.locators.is_empty() {
continue; }
let enc_creator = enc_txt(&s.creator_hex)?;
let enc_locators = enc_txt(&serde_json::to_string(&s.locators).map_err(|e| e.to_string())?)?;
tx.execute(
"INSERT INTO community_invite_link_sets (community_id, creator, locators) VALUES (?1, ?2, ?3)",
params![community_id, enc_creator, enc_locators],
)
.map_err(|e| format!("insert invite-link-set: {e}"))?;
}
tx.commit().map_err(|e| format!("commit invite-link-sets: {e}"))?;
Ok(())
}
pub fn get_invite_link_sets(community_id: &str) -> Result<Vec<InviteLinkSetRow>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare("SELECT creator, locators FROM community_invite_link_sets WHERE community_id = ?1")
.map_err(|e| format!("prepare invite-link-sets: {e}"))?;
let rows = stmt
.query_map(params![community_id], |r| {
let creator_hex: String = r.get(0)?;
let json: String = r.get(1)?;
Ok((creator_hex, json))
})
.map_err(|e| format!("query invite-link-sets: {e}"))?;
let mut out = Vec::new();
for row in rows {
let (creator_hex, json) = row.map_err(|e| format!("row invite-link-sets: {e}"))?;
let locators: Vec<String> = serde_json::from_str(&dec_txt(&json)).unwrap_or_default();
out.push(InviteLinkSetRow { creator_hex: dec_txt(&creator_hex), locators });
}
Ok(out)
}
pub fn set_community_dissolved(community_id: &str) -> Result<bool, String> {
let conn = super::get_write_connection_guard_static()?;
let changed = conn
.execute(
"UPDATE communities SET dissolved = 1 WHERE community_id = ?1 AND dissolved = 0",
params![community_id],
)
.map_err(|e| format!("set dissolved: {e}"))?;
crate::community::v2::realtime::invalidate_held_v2_community(community_id);
Ok(changed > 0)
}
pub fn get_community_dissolved(community_id: &str) -> Result<bool, String> {
let conn = super::get_db_connection_guard_static()?;
let v: Option<i64> = conn
.query_row(
"SELECT dissolved FROM communities WHERE community_id = ?1",
params![community_id],
|r| r.get(0),
)
.optional()
.map_err(|e| format!("get dissolved: {e}"))?;
Ok(v.unwrap_or(0) != 0)
}
pub fn list_community_ids() -> Result<Vec<CommunityId>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare("SELECT community_id FROM communities ORDER BY created_at")
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map([], |r| r.get::<_, String>(0))
.map_err(|e| e.to_string())?;
let mut ids = Vec::new();
for row in rows {
ids.push(CommunityId(hex_id_to_32(&row.map_err(|e| e.to_string())?)?));
}
Ok(ids)
}
pub fn held_channel_ids() -> Result<std::collections::HashSet<String>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare("SELECT ch.channel_id FROM community_channels ch JOIN communities c ON c.community_id = ch.community_id")
.map_err(|e| e.to_string())?;
let rows = stmt.query_map([], |r| r.get::<_, String>(0)).map_err(|e| e.to_string())?;
rows.collect::<Result<_, _>>().map_err(|e| e.to_string())
}
pub fn held_community_relays() -> Result<std::collections::HashSet<String>, String> {
let sealed: Vec<String> = {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn.prepare("SELECT relays FROM communities").map_err(|e| e.to_string())?;
let rows = stmt.query_map([], |r| r.get::<_, String>(0)).map_err(|e| e.to_string())?;
rows.collect::<Result<_, _>>().map_err(|e| e.to_string())?
};
Ok(crate::crypto::open_batch(|o| {
sealed
.into_iter()
.filter_map(|s| serde_json::from_str::<Vec<String>>(&o.open_or_keep(s)).ok())
.flatten()
.collect()
}))
}
pub fn community_image(community_id: &str, banner: bool) -> Result<Option<crate::community::CommunityImage>, String> {
let sql = if banner {
"SELECT banner FROM communities WHERE community_id = ?1"
} else {
"SELECT icon FROM communities WHERE community_id = ?1"
};
let sealed: Option<String> = {
let conn = super::get_db_connection_guard_static()?;
conn.query_row(sql, params![community_id], |r| r.get::<_, Option<String>>(0))
.optional()
.map_err(|e| e.to_string())?
.flatten()
};
let Some(sealed) = sealed else { return Ok(None) };
let json = crate::crypto::open_batch(|o| o.open_or_keep(sealed));
serde_json::from_str(&json).map(Some).map_err(|e| format!("community image json: {e}"))
}
pub fn community_held(id: &CommunityId) -> Result<bool, String> {
let conn = super::get_db_connection_guard_static()?;
conn.query_row("SELECT 1 FROM communities WHERE community_id = ?1", params![id.to_hex()], |_| Ok(()))
.optional()
.map(|row| row.is_some())
.map_err(|e| e.to_string())
}
#[derive(serde::Serialize, serde::Deserialize, Default)]
struct CommunityMetaStash {
#[serde(default, skip_serializing_if = "Option::is_none")]
custom: Option<serde_json::Map<String, serde_json::Value>>,
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
extra: serde_json::Map<String, serde_json::Value>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
categories: Vec<CategoryStash>,
}
#[derive(serde::Serialize, serde::Deserialize)]
struct CategoryStash {
id: String,
name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
position: Option<String>,
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
extra: serde_json::Map<String, serde_json::Value>,
}
#[derive(serde::Serialize, serde::Deserialize, Default)]
struct ChannelMetaStash {
#[serde(default, skip_serializing_if = "Option::is_none")]
voice: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
custom: Option<serde_json::Map<String, serde_json::Value>>,
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
extra: serde_json::Map<String, serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
sealed: Option<crate::community::v2::community::SealedMeta>,
}
pub fn save_community_v2(c: &crate::community::v2::community::CommunityV2) -> Result<(), String> {
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
let id_hex = crate::simd::hex::bytes_to_hex_32(&c.identity.community_id.0);
let relays_json = serde_json::to_string(&c.relays).map_err(|e| e.to_string())?;
let created = (c.created_at_ms / 1000) as i64;
let enc_root = enc_key(&c.community_root)?;
let enc_name = enc_txt(&c.name)?;
let enc_relays = enc_txt(&relays_json)?;
let enc_desc = enc_txt_opt(&c.description)?;
let enc_owner_pk = enc_txt(&crate::simd::hex::bytes_to_hex_32(&c.identity.owner_xonly))?;
let enc_owner_salt = enc_txt(&crate::simd::hex::bytes_to_hex_32(&c.identity.owner_salt))?;
let icon_json = c.icon.as_ref().map(|i| serde_json::to_string(i).map_err(|e| e.to_string())).transpose()?;
let banner_json = c.banner.as_ref().map(|b| serde_json::to_string(b).map_err(|e| e.to_string())).transpose()?;
let enc_icon = enc_txt_opt(&icon_json)?;
let enc_banner = enc_txt_opt(&banner_json)?;
let categories: Vec<CategoryStash> = c
.categories
.iter()
.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() })
.collect();
let stash_json = (c.meta_custom.is_some() || !c.meta_extra.is_empty() || !categories.is_empty())
.then(|| serde_json::to_string(&CommunityMetaStash { custom: c.meta_custom.clone(), extra: c.meta_extra.clone(), categories }).map_err(|e| e.to_string()))
.transpose()?;
let enc_stash = enc_txt_opt(&stash_json)?;
let enc_control_pk = enc_txt_opt(&c.control_pk.map(|p| p.to_hex()))?;
let enc_control_root = c.control_root.as_ref().map(enc_key).transpose()?;
let tx = conn.unchecked_transaction().map_err(|e| format!("save v2 community tx: {e}"))?;
tx.execute(
"INSERT INTO communities
(community_id, server_root_key, name, relays, created_at, description,
server_root_epoch, dissolved, protocol, owner_pubkey, owner_salt, icon, banner, meta_extra,
control_pk, control_root)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 2, ?9, ?10, ?11, ?12, ?13, ?14, ?15)
ON CONFLICT(community_id) DO UPDATE SET
server_root_key=?2, name=?3, relays=?4, description=?6,
server_root_epoch=?7, dissolved=?8, protocol=2, owner_pubkey=?9, owner_salt=?10,
icon=?11, banner=?12, meta_extra=?13, control_pk=?14, control_root=?15",
params![
id_hex, enc_root, enc_name, enc_relays, created, enc_desc,
c.root_epoch.0 as i64, c.dissolved as i64, enc_owner_pk, enc_owner_salt,
enc_icon, enc_banner, enc_stash, enc_control_pk, enc_control_root,
],
)
.map_err(|e| format!("save v2 community: {e}"))?;
for ch in &c.channels {
let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
let owner_of: Option<String> = tx
.query_row("SELECT community_id FROM community_channels WHERE channel_id=?1", params![ch_hex], |r| r.get(0))
.optional()
.map_err(|e| format!("channel ownership check: {e}"))?;
if let Some(existing) = owner_of.filter(|existing| *existing != id_hex) {
crate::log_warn!(
"[v2:{}] channel {} not saved: its row belongs to community {} (unflipped migration, or a hijack attempt)",
&id_hex[..8],
&ch_hex[..8],
&existing[..8.min(existing.len())]
);
continue;
}
let stored_key = ch.key.unwrap_or(c.community_root);
let enc_ch_key = enc_key(&stored_key)?;
let enc_ch_name = enc_txt(&ch.name)?;
let ch_stash_json = (ch.voice.is_some() || ch.meta_custom.is_some() || !ch.meta_extra.is_empty() || ch.sealed.is_some())
.then(|| {
serde_json::to_string(&ChannelMetaStash { voice: ch.voice, custom: ch.meta_custom.clone(), extra: ch.meta_extra.clone(), sealed: ch.sealed.clone() })
.map_err(|e| e.to_string())
})
.transpose()?;
let enc_ch_stash = enc_txt_opt(&ch_stash_json)?;
tx.execute(
"INSERT INTO community_channels
(channel_id, community_id, channel_key, epoch, name, created_at, private, meta_extra)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
ON CONFLICT(channel_id) DO UPDATE SET
channel_key=?3, epoch=?4, name=?5, private=?7, meta_extra=?8",
params![ch_hex, id_hex, enc_ch_key, ch.epoch.0 as i64, enc_ch_name, created, ch.private as i64, enc_ch_stash],
)
.map_err(|e| format!("save v2 channel: {e}"))?;
}
let keep: Vec<String> = c.channels.iter().map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0)).collect();
if keep.is_empty() {
tx.execute("DELETE FROM community_channels WHERE community_id=?1", params![id_hex])
.map_err(|e| format!("prune v2 channels: {e}"))?;
} else {
let placeholders = std::iter::repeat_n("?", keep.len()).collect::<Vec<_>>().join(",");
let sql = format!("DELETE FROM community_channels WHERE community_id=? AND channel_id NOT IN ({placeholders})");
let mut binds: Vec<String> = Vec::with_capacity(keep.len() + 1);
binds.push(id_hex.clone());
binds.extend(keep);
tx.execute(&sql, rusqlite::params_from_iter(binds.iter()))
.map_err(|e| format!("prune v2 channels: {e}"))?;
}
tx.commit().map_err(|e| format!("commit v2 community: {e}"))?;
crate::community::v2::realtime::invalidate_held_v2_community(&id_hex);
forget_community_channels(&id_hex);
Ok(())
}
pub fn load_community_v2(id: &CommunityId) -> Result<Option<crate::community::v2::community::CommunityV2>, String> {
use crate::community::v2::community::{ChannelV2, CommunityV2};
use crate::community::v2::control::CommunityIdentity;
let conn = super::get_db_connection_guard_static()?;
let id_hex = id.to_hex();
let row = conn
.query_row(
"SELECT server_root_key, name, relays, created_at, description,
server_root_epoch, dissolved, owner_pubkey, owner_salt,
icon, banner, meta_extra, control_pk, control_root
FROM communities WHERE community_id = ?1",
params![id_hex],
|r| {
Ok((
r.get::<_, Vec<u8>>(0)?,
r.get::<_, String>(1)?,
r.get::<_, String>(2)?,
r.get::<_, i64>(3)?,
r.get::<_, Option<String>>(4)?,
r.get::<_, i64>(5)?,
r.get::<_, i64>(6)?,
r.get::<_, Option<String>>(7)?,
r.get::<_, Option<String>>(8)?,
r.get::<_, Option<String>>(9)?,
r.get::<_, Option<String>>(10)?,
r.get::<_, Option<String>>(11)?,
r.get::<_, Option<String>>(12)?,
r.get::<_, Option<Vec<u8>>>(13)?,
))
},
)
.optional()
.map_err(|e| e.to_string())?;
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
else {
return Ok(None);
};
let (Some(owner_pk_e), Some(owner_salt_e)) = (owner_pk_e, owner_salt_e) else {
return Err("v2 community row is missing its owner commitment".to_string());
};
let dk = |o: &mut crate::crypto::AtRestOpener, b: &[u8]| to_32(&o.open_blob_or_keep(b));
let dt = |o: &mut crate::crypto::AtRestOpener, s: &str| o.open_or_keep(s.to_string());
crate::crypto::open_batch(|o| {
let community_root = dk(o, &root_blob)?;
let owner_xonly = parse_hex32(&dt(o, &owner_pk_e))?;
let owner_salt = parse_hex32(&dt(o, &owner_salt_e))?;
let identity = CommunityIdentity { community_id: *id, owner_xonly, owner_salt };
let relays: Vec<String> = serde_json::from_str(&dt(o, &relays_e)).unwrap_or_default();
let mut channels = Vec::new();
{
let mut stmt = conn
.prepare(
"SELECT channel_id, channel_key, epoch, name, private, meta_extra
FROM community_channels WHERE community_id = ?1 ORDER BY created_at",
)
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![id_hex], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, Vec<u8>>(1)?,
r.get::<_, i64>(2)?,
r.get::<_, String>(3)?,
r.get::<_, i64>(4)?,
r.get::<_, Option<String>>(5)?,
))
})
.map_err(|e| e.to_string())?;
for row in rows {
let (ch_hex, key_blob, epoch, name_e, private, ch_stash_e) = row.map_err(|e| e.to_string())?;
let private = private != 0;
let key = dk(o, &key_blob)?;
let ch_stash: ChannelMetaStash = ch_stash_e
.map(|s| dt(o, &s))
.and_then(|j| serde_json::from_str(&j).ok())
.unwrap_or_default();
channels.push(ChannelV2 {
id: ChannelId(hex_id_to_32(&ch_hex)?),
name: dt(o, &name_e),
private,
key: (private && key != community_root).then_some(key),
epoch: Epoch(epoch as u64),
voice: ch_stash.voice,
meta_custom: ch_stash.custom,
meta_extra: ch_stash.extra,
writers: None,
sealed: ch_stash.sealed,
});
}
}
{
let mut stmt = conn
.prepare("SELECT channel_id, content FROM community_writers WHERE community_id = ?1")
.map_err(|e| e.to_string())?;
let rows = stmt
.query_map(params![id_hex], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))
.map_err(|e| e.to_string())?;
for row in rows {
let (ch_hex, content) = row.map_err(|e| e.to_string())?;
let Some(ch) = channels.iter_mut().find(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0) == ch_hex) else { continue };
ch.writers = crate::community::v2::writers::Ledger::parse(&dt(o, &content)).filter(|l| l.channel == ch.id.0);
}
}
channels.shrink_to_fit();
let icon = icon_e
.map(|s| dt(o, &s))
.and_then(|j| serde_json::from_str::<crate::community::v2::control::ImageRef>(&j).ok());
let banner = banner_e
.map(|s| dt(o, &s))
.and_then(|j| serde_json::from_str::<crate::community::v2::control::ImageRef>(&j).ok());
let stash: CommunityMetaStash = stash_e
.map(|s| dt(o, &s))
.and_then(|j| serde_json::from_str(&j).ok())
.unwrap_or_default();
let control_pk = control_pk_e
.as_deref()
.and_then(|e| nostr_sdk::prelude::PublicKey::from_hex(&dt(o, e)).ok());
let control_root = match (control_pk, control_root_b) {
(Some(pk), Some(blob)) => dk(o, &blob).ok().filter(|cr| {
crate::community::v2::derive::control_signer_group_key(cr, id, Epoch(root_epoch as u64)).pk() == pk
}),
_ => None,
};
Ok(Some(CommunityV2 {
identity,
community_root,
root_epoch: Epoch(root_epoch as u64),
control_pk,
control_root,
name: dt(o, &name_e),
description: desc_e.map(|d| dt(o, &d)),
icon,
banner,
meta_custom: stash.custom,
meta_extra: stash.extra,
relays,
channels,
categories: stash
.categories
.into_iter()
.filter_map(|k| {
let id = crate::simd::hex::hex_to_bytes_32_checked(&k.id)?;
Some(crate::community::v2::community::CategoryV2 { id, name: k.name, position: k.position, extra: k.extra })
})
.collect(),
dissolved: dissolved != 0,
created_at_ms: (created as u64).saturating_mul(1000),
}))
})
}
fn parse_hex32(hex: &str) -> Result<[u8; 32], String> {
if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err("stored value is not 32-byte hex".to_string());
}
Ok(crate::simd::hex::hex_to_bytes_32(hex))
}
struct Parsed<T, const CAP: usize> {
generations: std::collections::HashMap<String, u64>,
slots: Vec<(String, u64, T)>,
}
impl<T, const CAP: usize> Default for Parsed<T, CAP> {
fn default() -> Self {
Parsed { generations: Default::default(), slots: Vec::new() }
}
}
impl<T: Clone, const CAP: usize> Parsed<T, CAP> {
fn generation(&self, community_id: &str) -> u64 {
self.generations.get(community_id).copied().unwrap_or(0)
}
fn get(&mut self, community_id: &str) -> Option<T> {
let generation = self.generation(community_id);
let i = self.slots.iter().position(|(id, g, _)| id == community_id && *g == generation)?;
let slot = self.slots.remove(i);
let held = slot.2.clone();
self.slots.push(slot);
Some(held)
}
fn put(&mut self, community_id: &str, generation: u64, held: T) {
if generation != self.generation(community_id) {
return;
}
self.slots.retain(|(id, ..)| id != community_id);
if self.slots.len() >= CAP {
self.slots.remove(0);
}
self.slots.push((community_id.to_string(), generation, held));
}
fn moved(&mut self, community_id: &str) -> u64 {
let generation = self.generation(community_id) + 1;
self.generations.insert(community_id.to_string(), generation);
self.slots.retain(|(id, ..)| id != community_id);
generation
}
}
#[derive(Clone, Default)]
pub struct Guestbook {
events: Vec<crate::community::v2::guestbook::GuestbookEvent>,
by_id: std::collections::HashMap<[u8; 32], u32>,
}
impl Guestbook {
fn new(given: Vec<crate::community::v2::guestbook::GuestbookEvent>) -> Self {
let mut book = Guestbook { events: Vec::with_capacity(given.len()), by_id: std::collections::HashMap::with_capacity(given.len()) };
for ev in given {
if !book.by_id.contains_key(&ev.rumor_id) {
book.by_id.insert(ev.rumor_id, book.events.len() as u32);
book.events.push(ev);
}
}
book
}
pub fn get(&self, rumor_id: &[u8; 32]) -> Option<&crate::community::v2::guestbook::GuestbookEvent> {
self.by_id.get(rumor_id).map(|&i| &self.events[i as usize])
}
pub fn into_events(self) -> Vec<crate::community::v2::guestbook::GuestbookEvent> {
self.events
}
fn upsert(&mut self, ev: &crate::community::v2::guestbook::GuestbookEvent) {
match self.by_id.get(&ev.rumor_id) {
Some(&i) => self.events[i as usize] = ev.clone(),
None => {
self.by_id.insert(ev.rumor_id, self.events.len() as u32);
self.events.push(ev.clone());
}
}
}
}
impl std::ops::Deref for Guestbook {
type Target = [crate::community::v2::guestbook::GuestbookEvent];
fn deref(&self) -> &Self::Target {
&self.events
}
}
type GuestbookShared = (std::sync::Arc<Guestbook>, u64);
type GuestbookCache = Parsed<GuestbookShared, 8>;
fn guestbook_cache() -> std::sync::Arc<std::sync::Mutex<GuestbookCache>> {
struct Key;
super::current_session().scoped::<Key, std::sync::Mutex<GuestbookCache>>()
}
pub fn get_guestbook_shared(community_id: &str) -> Result<GuestbookShared, String> {
let cache = guestbook_cache();
let generation = {
let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
if let Some(hit) = held.get(community_id) {
return Ok(hit);
}
held.generation(community_id)
};
let (events, cursor) = read_guestbook(community_id)?;
let shared = (std::sync::Arc::new(Guestbook::new(events)), cursor);
cache.lock().unwrap_or_else(|e| e.into_inner()).put(community_id, generation, shared.clone());
Ok(shared)
}
pub fn get_guestbook(community_id: &str) -> Result<(Vec<crate::community::v2::guestbook::GuestbookEvent>, u64), String> {
let (events, cursor) = get_guestbook_shared(community_id)?;
Ok((std::sync::Arc::unwrap_or_clone(events).into_events(), cursor))
}
fn read_guestbook(community_id: &str) -> Result<(Vec<crate::community::v2::guestbook::GuestbookEvent>, u64), String> {
let legacy = {
let conn = super::get_db_connection_guard_static()?;
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)?)))
.optional()
.map_err(|e| format!("load guestbook: {e}"))?
};
let Some((blob, cursor)) = legacy else {
return Ok((Vec::new(), 0));
};
if !blob.is_empty() {
move_guestbook_blob(community_id, &blob)?;
}
let rows: Vec<([u8; 32], Vec<u8>)> = {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare_cached(
"SELECT e.rumor_id, e.body FROM community_guestbook_events e
JOIN community_guestbook_books b ON b.book = e.book
WHERE b.community_id = ?1 ORDER BY e.seq",
)
.map_err(|e| format!("load guestbook events: {e}"))?;
let rows = stmt
.query_map(params![community_id], |r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, Vec<u8>>(1)?)))
.map_err(|e| format!("load guestbook events: {e}"))?;
rows.filter_map(|r| r.ok()).filter_map(|(id, body)| Some((id.try_into().ok()?, body))).collect()
};
let events = crate::crypto::open_batch(|o| {
rows.into_iter().filter_map(|(id, body)| crate::community::v2::guestbook::event_from_body(id, &o.open_blob_or_keep(&body))).collect()
});
Ok((events, cursor.max(0) as u64))
}
fn move_guestbook_blob(community_id: &str, blob: &str) -> Result<(), String> {
let Ok(events) = serde_json::from_str::<Vec<crate::community::v2::guestbook::GuestbookEvent>>(&dec_txt(blob)) else {
return Ok(());
};
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
let tx = conn.unchecked_transaction().map_err(|e| format!("move guestbook tx: {e}"))?;
let still: Option<String> = tx
.query_row("SELECT events FROM community_guestbook WHERE community_id = ?1", params![community_id], |r| r.get(0))
.optional()
.map_err(|e| format!("move guestbook: {e}"))?;
if still.as_deref() != Some(blob) {
return Ok(());
}
insert_guestbook_events(&tx, community_id, &events, false)?;
tx.execute("UPDATE community_guestbook SET events = '' WHERE community_id = ?1", params![community_id])
.map_err(|e| format!("move guestbook: {e}"))?;
tx.commit().map_err(|e| format!("move guestbook commit: {e}"))
}
fn guestbook_book(tx: &rusqlite::Connection, community_id: &str) -> Result<i64, String> {
tx.prepare_cached("INSERT OR IGNORE INTO community_guestbook_books (community_id) VALUES (?1)")
.and_then(|mut s| s.execute(params![community_id]))
.map_err(|e| format!("guestbook book: {e}"))?;
tx.prepare_cached("SELECT book FROM community_guestbook_books WHERE community_id = ?1")
.and_then(|mut s| s.query_row(params![community_id], |r| r.get(0)))
.map_err(|e| format!("guestbook book: {e}"))
}
fn insert_guestbook_events(tx: &rusqlite::Connection, community_id: &str, events: &[crate::community::v2::guestbook::GuestbookEvent], restamp: bool) -> Result<(), String> {
let book = guestbook_book(tx, community_id)?;
let sql = if restamp {
"INSERT INTO community_guestbook_events (book, rumor_id, body) VALUES (?1, ?2, ?3)
ON CONFLICT (book, rumor_id) DO UPDATE SET body = excluded.body"
} else {
"INSERT OR IGNORE INTO community_guestbook_events (book, rumor_id, body) VALUES (?1, ?2, ?3)"
};
let mut stmt = tx.prepare_cached(sql).map_err(|e| format!("store guestbook event: {e}"))?;
crate::crypto::seal_batch(|sealer| {
for ev in events {
let body = sealer.seal_blob(&crate::community::v2::guestbook::event_body(ev))?;
stmt.execute(params![book, &ev.rumor_id[..], body]).map_err(|e| format!("store guestbook event: {e}"))?;
}
Ok(())
})
}
struct StandingCache;
type StandingMap = std::sync::RwLock<std::collections::HashMap<String, (u64, Option<std::sync::Arc<Vec<crate::community::v2::guestbook::GuestbookEvent>>>)>>;
fn standing_cache() -> std::sync::Arc<StandingMap> {
crate::db::current_session().scoped::<StandingCache, StandingMap>()
}
pub fn get_guestbook_standing(community_id: &str) -> Result<std::sync::Arc<Vec<crate::community::v2::guestbook::GuestbookEvent>>, String> {
let generation = match standing_cache().read().unwrap_or_else(|e| e.into_inner()).get(community_id) {
Some((_, Some(held))) => return Ok(held.clone()),
Some((generation, None)) => *generation,
None => 0,
};
let (events, _) = get_guestbook(community_id)?;
use crate::community::v2::guestbook::GuestbookEntry;
let standing: std::sync::Arc<Vec<_>> = std::sync::Arc::new(
events.into_iter().filter(|e| matches!(e.entry, GuestbookEntry::Timeout { .. } | GuestbookEntry::Nickname { .. })).collect(),
);
let map = standing_cache();
let mut cache = map.write().unwrap_or_else(|e| e.into_inner());
let entry = cache.entry(community_id.to_string()).or_insert((0, None));
if entry.0 == generation {
entry.1 = Some(standing.clone());
}
Ok(standing)
}
struct MembershipGeneration;
pub fn membership_generation() -> u64 {
super::current_session().scoped::<MembershipGeneration, std::sync::atomic::AtomicU64>().load(std::sync::atomic::Ordering::Acquire)
}
pub fn bump_membership_generation() {
super::current_session().scoped::<MembershipGeneration, std::sync::atomic::AtomicU64>().fetch_add(1, std::sync::atomic::Ordering::AcqRel);
}
pub fn set_guestbook(
community_id: &str,
events: &[crate::community::v2::guestbook::GuestbookEvent],
cursor_secs: u64,
) -> Result<(), String> {
let _seal = crate::crypto::gate::sealing();
forget_console_verdict(community_id);
let conn = super::get_write_connection_guard_static()?;
let tx = conn.unchecked_transaction().map_err(|e| format!("save guestbook tx: {e}"))?;
let book = guestbook_book(&tx, community_id)?;
tx.execute("DELETE FROM community_guestbook_events WHERE book = ?1", params![book])
.map_err(|e| format!("save guestbook: {e}"))?;
tx.execute("DELETE FROM community_guestbook_wraps WHERE community_id = ?1", params![community_id])
.map_err(|e| format!("save guestbook: {e}"))?;
insert_guestbook_events(&tx, community_id, events, false)?;
upsert_guestbook_cursor(&tx, community_id, cursor_secs)?;
tx.commit().map_err(|e| format!("save guestbook commit: {e}"))?;
{
let cache = guestbook_cache();
let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
let generation = held.moved(community_id);
held.put(community_id, generation, (std::sync::Arc::new(Guestbook::new(events.to_vec())), cursor_secs));
}
drop(conn);
guestbook_moved_on(community_id);
Ok(())
}
pub fn store_guestbook_events(
community_id: &str,
events: &[crate::community::v2::guestbook::GuestbookEvent],
cursor_secs: u64,
) -> Result<(), String> {
let _seal = crate::crypto::gate::sealing();
forget_console_verdict(community_id);
let conn = super::get_write_connection_guard_static()?;
let tx = conn.unchecked_transaction().map_err(|e| format!("store guestbook tx: {e}"))?;
insert_guestbook_events(&tx, community_id, events, true)?;
upsert_guestbook_cursor(&tx, community_id, cursor_secs)?;
tx.commit().map_err(|e| format!("store guestbook commit: {e}"))?;
guestbook_written(
community_id,
|held| {
for ev in events {
held.upsert(ev);
}
},
cursor_secs,
);
drop(conn);
guestbook_moved_on(community_id);
Ok(())
}
fn upsert_guestbook_cursor(tx: &rusqlite::Connection, community_id: &str, cursor_secs: u64) -> Result<(), String> {
tx.prepare_cached(
"INSERT INTO community_guestbook (community_id, events, cursor_secs) VALUES (?1, '', ?2)
ON CONFLICT(community_id) DO UPDATE SET cursor_secs = ?2",
)
.and_then(|mut s| s.execute(params![community_id, cursor_secs as i64]))
.map(|_| ())
.map_err(|e| format!("save guestbook cursor: {e}"))
}
fn guestbook_written(community_id: &str, apply: impl FnOnce(&mut Guestbook), cursor_secs: u64) {
let cache = guestbook_cache();
let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
let before = held.get(community_id);
let generation = held.moved(community_id);
if let Some((events, _)) = before {
let mut events = std::sync::Arc::unwrap_or_clone(events);
apply(&mut events);
held.put(community_id, generation, (std::sync::Arc::new(events), cursor_secs));
}
}
fn guestbook_moved_on(community_id: &str) {
let map = standing_cache();
let mut cache = map.write().unwrap_or_else(|e| e.into_inner());
let entry = cache.entry(community_id.to_string()).or_insert((0, None));
*entry = (entry.0 + 1, None);
drop(cache);
bump_membership_generation();
}
#[cfg(test)]
mod tests {
use super::*;
static TEST_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
fn make_test_npub(n: u32) -> String {
const BECH32: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
let mut payload = vec![b'q'; 58];
let mut x = n as u64;
let mut i = 58;
while x > 0 && i > 0 {
i -= 1;
payload[i] = BECH32[(x as usize) % 32];
x /= 32;
}
format!("npub1{}", std::str::from_utf8(&payload).unwrap())
}
fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
crate::db::close_database();
crate::db::clear_id_caches();
let tmp = tempfile::tempdir().unwrap();
let n = TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let account = make_test_npub(n);
std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
crate::db::set_current_account(account.clone()).unwrap();
crate::db::init_database(&account).unwrap();
(tmp, guard)
}
#[test]
fn a_channel_holds_its_newest_dated_wraps_up_to_the_cap() {
let (_tmp, _guard) = init_test_db();
let (cid, ch) = ("c".repeat(64), "d".repeat(64));
for i in 0..MAX_HELD_WRAPS + 2 {
hold_wrap(&cid, &ch, &format!("{i:064x}"), &format!("wrap {i}"), "", 1_000 + i as u64).unwrap();
}
hold_wrap(&cid, &"e".repeat(64), &"f".repeat(64), "another channel's", "", 1).unwrap();
let held = held_wraps(&cid).unwrap();
assert_eq!(held.len(), MAX_HELD_WRAPS + 1, "each channel caps on its own");
assert!(!held.iter().any(|(id, ..)| *id == format!("{:064x}", 0) || *id == format!("{:064x}", 1)), "the oldest-dated go first");
assert!(held.iter().any(|(_, _, wrap)| wrap == "wrap 501"), "opened as it was held");
hold_wrap(&cid, &ch, &format!("{:064x}", 501), "again", "", 1).unwrap();
assert_eq!(held_wraps(&cid).unwrap().iter().filter(|(id, ..)| *id == format!("{:064x}", 501)).count(), 1, "once");
release_held_wrap(&format!("{:064x}", 501)).unwrap();
assert!(held_wrap_ids(&[format!("{:064x}", 501), format!("{:064x}", 500)]) == std::collections::HashSet::from([format!("{:064x}", 500)]));
}
fn v2_fixture(name: &str, relays: &[&str]) -> crate::community::v2::community::CommunityV2 {
let owner = Keys::generate();
let g = crate::community::v2::control::genesis(
&owner,
crate::community::v2::control::CommunityMetadata { name: name.into(), ..Default::default() },
1_000,
)
.unwrap();
let relays = relays.iter().map(|r| r.to_string()).collect();
crate::community::v2::community::CommunityV2::from_genesis(&g, name, None, relays, 1_000)
}
fn v2_bundle(name: &str) -> String {
let bundle = crate::community::v2::service::bundle_of(
&v2_fixture(name, &["wss://r"]),
crate::community::v2::service::BundleAudience::Link,
None,
None,
None,
);
serde_json::to_string(&bundle).unwrap()
}
fn saved_v2(name: &str) -> (crate::community::v2::community::CommunityV2, String, String) {
let c = v2_fixture(name, &["wss://r"]);
save_community_v2(&c).unwrap();
let (cid, ch) = (c.id().to_hex(), c.channels[0].id.to_hex());
(c, cid, ch)
}
fn private_channel(id: u8, key: u8) -> crate::community::v2::community::ChannelV2 {
crate::community::v2::community::ChannelV2 {
id: ChannelId([id; 32]),
name: "staff".into(),
private: true,
key: Some([key; 32]),
epoch: Epoch(0),
voice: None,
meta_custom: None,
meta_extra: Default::default(),
writers: None,
sealed: None,
}
}
fn archived_v2() -> (crate::community::v2::community::CommunityV2, String, String) {
let mut c = v2_fixture("HQ", &["r1"]);
c.channels.push(private_channel(0x61, 0x62));
save_community_v2(&c).unwrap();
let (cid, private) = (c.id().to_hex(), c.channels[1].id.to_hex());
store_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 0, &c.community_root).unwrap();
store_epoch_key(&cid, &private, 0, &[0x62; 32]).unwrap();
(c, cid, private)
}
fn encrypted_community_with_messages(n: usize) -> String {
crate::state::ENCRYPTION_KEY.set([0x55u8; 32], &[]);
crate::state::set_encryption_enabled(true);
let (_, cid, ch) = saved_v2("HQ");
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
for i in 0..n {
let msg = crate::types::Message {
id: format!("{i:064x}"),
content: format!("message number {i}, a few words long"),
at: 1_700_000_000_000 + i as u64 * 1000,
npub: Some(make_test_npub(i as u32 % 7)),
..Default::default()
};
rt.block_on(crate::db::events::save_message(&ch, &msg)).unwrap();
}
cid
}
#[test]
fn the_policy_window_and_recent_texts_open_sealed_rows() {
let (_tmp, _guard) = init_test_db();
struct Vault;
impl Drop for Vault {
fn drop(&mut self) {
crate::state::set_encryption_enabled(false);
crate::state::ENCRYPTION_KEY.clear(&[]);
}
}
let _vault = Vault;
let cid = encrypted_community_with_messages(5);
let stored: String = crate::db::get_db_connection_guard_static()
.unwrap()
.query_row("SELECT content FROM events WHERE content != '' LIMIT 1", [], |r| r.get(0))
.unwrap();
assert!(crate::crypto::looks_encrypted(&stored), "the rows read back are sealed on disk");
let window = community_policy_messages(&cid, 100).unwrap();
assert_eq!(window.len(), 5);
assert_eq!(window[0].text, "message number 0, a few words long");
let recent = community_recent_texts(&cid, 100).unwrap();
assert_eq!(recent[0].2, "message number 4, a few words long");
}
#[test]
fn an_authority_floor_takes_a_squatted_coordinate_and_keeps_it() {
let (_tmp, _guard) = init_test_db();
let (cid, entity) = ("f".repeat(64), "a".repeat(64));
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();
let held = || (get_edition_head(&cid, &entity).unwrap().unwrap(), edition_head_families(&cid).unwrap().get(&entity).cloned());
head(50, 0xC0, FLOOR_CONTROL);
head(1, 0xA1, FLOOR_AUTHORITY);
assert_eq!(held(), ((1, [0xA1; 32]), Some("a".into())), "an authority head replaces a control row at any version");
head(99, 0xC1, FLOOR_CONTROL);
assert_eq!(held().0, (1, [0xA1; 32]), "a control head never takes it back");
converge_family_head_at_epoch(&cid, &entity, 1, &[0xC2; 32], &[0xC2; 32], &[0xC2; 32], 0, Some(FLOOR_CONTROL)).unwrap();
assert_eq!(held().0, (1, [0xA1; 32]), "nor converges it");
rebase_edition_head_at_epoch(&cid, &entity, 0, &[0xC3; 32], &[0xC3; 32], &[0xC3; 32], 0, FLOOR_CONTROL).unwrap();
assert_eq!(held().0, (1, [0xA1; 32]), "nor moves it down");
head(1, 0xA0, FLOOR_AUTHORITY);
assert_eq!(held().0, (1, [0xA1; 32]), "within the family the version still only advances");
head(2, 0xA2, FLOOR_AUTHORITY);
assert_eq!(held().0, (2, [0xA2; 32]));
}
#[test]
fn edition_head_round_trips_and_upserts() {
let (_tmp, _guard) = init_test_db();
let cid = "f".repeat(64);
let entity = "a".repeat(64);
assert_eq!(get_edition_head(&cid, &entity).unwrap(), None);
let h1 = [0x11u8; 32];
set_edition_head(&cid, &entity, 1, &h1).unwrap();
assert_eq!(get_edition_head(&cid, &entity).unwrap(), Some((1, h1)));
let h2 = [0x22u8; 32];
set_edition_head(&cid, &entity, 2, &h2).unwrap();
assert_eq!(get_edition_head(&cid, &entity).unwrap(), Some((2, h2)));
set_edition_head(&cid, &entity, 1, &[0xEEu8; 32]).unwrap();
assert_eq!(get_edition_head(&cid, &entity).unwrap(), Some((2, h2)), "rollback to v1 ignored");
set_edition_head(&cid, &entity, 2, &[0xEEu8; 32]).unwrap();
assert_eq!(get_edition_head(&cid, &entity).unwrap(), Some((2, h2)), "equal version is a no-op too");
let other = "b".repeat(64);
assert_eq!(get_edition_head(&cid, &other).unwrap(), None);
}
#[test]
fn a_floor_written_before_families_still_advances() {
let (_tmp, _guard) = init_test_db();
let (cid, entity) = ("c".repeat(64), "e".repeat(64));
set_edition_head(&cid, &entity, 1, &[0x11; 32]).unwrap();
assert_eq!(get_all_edition_heads_full(&cid).unwrap()[&entity].5, None, "a familyless row");
set_family_head_at_epoch(&cid, &entity, 2, &[0x22; 32], &[0x02; 32], &[0xA1; 32], 0, FLOOR_CONTROL).unwrap();
let f = get_all_edition_heads_full(&cid).unwrap()[&entity];
assert_eq!((f.1, f.2, f.5), (2, [0x22; 32], Some(FloorFamily::of(FLOOR_CONTROL))), "it advances, and takes the family");
set_family_head_at_epoch(&cid, "a".repeat(64).as_str(), 1, &[0x33; 32], &[0x03; 32], &[0xA1; 32], 0, FLOOR_AUTHORITY).unwrap();
set_family_head_at_epoch(&cid, "a".repeat(64).as_str(), 2, &[0x44; 32], &[0x04; 32], &[0xA1; 32], 0, FLOOR_CONTROL).unwrap();
assert_eq!(get_all_edition_heads_full(&cid).unwrap()[&"a".repeat(64)].1, 1);
}
#[test]
fn a_floor_keeps_the_author_of_the_head_it_holds() {
let (_tmp, _guard) = init_test_db();
let cid = "c".repeat(64);
let entity = "e".repeat(64);
let author = |b: u8| [b; 32];
let held = |cid: &str| {
let f = get_all_edition_heads_full(cid).unwrap()[&entity];
(f.0, f.1, f.2, f.3, f.4)
};
set_edition_head_at_epoch(&cid, &entity, 1, &[0x11; 32], &[0x01; 32], &author(0xA1), 0).unwrap();
set_edition_head_at_epoch(&cid, &entity, 2, &[0x22; 32], &[0x02; 32], &author(0xB2), 0).unwrap();
assert_eq!(held(&cid), (0, 2, [0x22; 32], Some([0x02; 32]), Some(author(0xB2))), "an advance records its own author");
converge_edition_head_at_epoch(&cid, &entity, 2, &[0x33; 32], &[0xFF; 32], &author(0xC3), 0).unwrap();
assert_eq!(held(&cid), (0, 2, [0x33; 32], Some([0xFF; 32]), Some(author(0xC3))), "a higher id can win on authority");
converge_edition_head_at_epoch(&cid, &entity, 3, &[0x44; 32], &[0x00; 32], &author(0xD4), 0).unwrap();
converge_edition_head_at_epoch(&cid, &entity, 2, &[0x55; 32], &[0x00; 32], &author(0xE5), 1).unwrap();
assert_eq!(held(&cid).2, [0x33; 32], "another version or epoch is never converged onto");
set_edition_head_at_epoch(&cid, &entity, 1, &[0x66; 32], &[0x06; 32], &author(0xF6), 1).unwrap();
assert_eq!(held(&cid), (1, 1, [0x66; 32], Some([0x06; 32]), Some(author(0xF6))));
}
#[test]
fn guestbook_round_trips_events_and_cursor() {
let (_tmp, _guard) = init_test_db();
let member = nostr_sdk::prelude::Keys::generate();
let ev = crate::community::v2::guestbook::GuestbookEvent { epoch: None, observed_at: None,
rumor_id: [7u8; 32],
entry: crate::community::v2::guestbook::GuestbookEntry::Join {
member: member.public_key(),
invited_by: Some(("creator".into(), "label".into())),
at_ms: 1_000,
},
};
let cid = "d".repeat(64);
assert_eq!(get_guestbook(&cid).unwrap(), (Vec::new(), 0), "absent reads as empty at cursor 0");
set_guestbook(&cid, std::slice::from_ref(&ev), 42).unwrap();
let (events, cursor) = read_guestbook(&cid).unwrap();
assert_eq!(events, vec![ev.clone()], "events round-trip through the encrypted blob");
assert_eq!(cursor, 42);
assert_eq!(get_guestbook(&cid).unwrap(), (vec![ev], 42), "and the cached read agrees");
}
fn gb(b: u8, epoch: Option<u64>) -> crate::community::v2::guestbook::GuestbookEvent {
crate::community::v2::guestbook::GuestbookEvent {
rumor_id: [b; 32],
entry: crate::community::v2::guestbook::GuestbookEntry::Join { member: nostr_sdk::prelude::Keys::generate().public_key(), invited_by: None, at_ms: b as u64 * 1000 },
epoch,
observed_at: Some(1_790_000_000 + b as u64),
}
}
#[test]
fn a_guestbook_blob_moves_into_rows_in_order_and_once() {
let (_tmp, _guard) = init_test_db();
let cid = "f".repeat(64);
let events: Vec<_> = [9u8, 3, 7, 1].iter().map(|&b| gb(b, Some(2))).collect();
{
let _seal = crate::crypto::gate::sealing();
let conn = crate::db::get_write_connection_guard_static().unwrap();
conn.execute(
"INSERT INTO community_guestbook (community_id, events, cursor_secs) VALUES (?1, ?2, 55)",
params![cid, enc_txt(&serde_json::to_string(&events).unwrap()).unwrap()],
)
.unwrap();
}
assert_eq!(read_guestbook(&cid).unwrap(), (events.clone(), 55), "arrival order kept");
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();
assert!(blob.is_empty(), "the blob is moved out, not kept beside the rows");
assert_eq!(read_guestbook(&cid).unwrap(), (events, 55), "and reads the same from rows");
}
#[test]
fn a_guestbook_blob_that_does_not_read_is_left_as_it_is() {
let (_tmp, _guard) = init_test_db();
let cid = "c".repeat(64);
{
let conn = crate::db::get_write_connection_guard_static().unwrap();
conn.execute("INSERT INTO community_guestbook (community_id, events, cursor_secs) VALUES (?1, 'not json', 3)", params![cid]).unwrap();
}
assert_eq!(read_guestbook(&cid).unwrap(), (Vec::new(), 3));
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();
assert_eq!(blob, "not json", "nothing it couldn't read is thrown away");
}
#[test]
fn stored_guestbook_events_dedup_restamp_in_place_and_match_the_cache() {
let (_tmp, _guard) = init_test_db();
let cid = "b".repeat(64);
let (a, b, c) = (gb(1, None), gb(2, Some(1)), gb(3, Some(1)));
store_guestbook_events(&cid, &[a.clone(), b.clone()], 10).unwrap();
assert_eq!(get_guestbook(&cid).unwrap().0, vec![a.clone(), b.clone()]);
let a2 = crate::community::v2::guestbook::GuestbookEvent { epoch: Some(4), ..a.clone() };
store_guestbook_events(&cid, &[b.clone(), a2.clone(), c.clone()], 20).unwrap();
let want = (vec![a2, b, c], 20);
assert_eq!(get_guestbook(&cid).unwrap(), want, "the cached copy");
assert_eq!(read_guestbook(&cid).unwrap(), want, "the rows");
let rows: i64 = crate::db::get_db_connection_guard_static().unwrap().query_row("SELECT COUNT(*) FROM community_guestbook_events", [], |r| r.get(0)).unwrap();
assert_eq!(rows, 3);
set_guestbook(&cid, &[want.0[2].clone()], 30).unwrap();
assert_eq!(read_guestbook(&cid).unwrap(), (vec![want.0[2].clone()], 30));
assert_eq!(get_guestbook(&cid).unwrap(), (vec![want.0[2].clone()], 30));
}
#[test]
fn owed_departures_write_only_the_members_that_changed() {
let (_tmp, _guard) = init_test_db();
let cid = "e".repeat(64);
let mut keys: Vec<PublicKey> = (0..3).map(|_| Keys::generate().public_key()).collect();
keys.sort();
let (a, b, c) = (keys[0], keys[1], keys[2]);
let rows = || -> Vec<(i64, Vec<u8>)> {
let conn = crate::db::get_db_connection_guard_static().unwrap();
let mut stmt = conn.prepare("SELECT seq, body FROM community_departures_seen ORDER BY seq").unwrap();
stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?))).unwrap().map(|r| r.unwrap()).collect()
};
let stored = || {
departures_seen_cache().lock().unwrap().moved(&cid);
(*departures_seen(&cid).unwrap().spans).clone()
};
let first: DepartureSpans = [(a, vec![(5, Some(9), false)].into()), (b, vec![(1, None, true)].into())].into_iter().collect();
set_departures_seen(&cid, std::sync::Arc::new(first.clone())).unwrap();
assert_eq!(stored(), first);
let before = rows();
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();
set_departures_seen(&cid, std::sync::Arc::new(second.clone())).unwrap();
let after = rows();
assert_eq!(after.len(), 3);
assert_eq!(after[0], before[0], "an unchanged member's row is left alone");
assert_eq!(after[1].0, before[1].0, "a changed member keeps its row");
assert_ne!(after[1].1, before[1].1);
assert_eq!(stored(), second);
let third: DepartureSpans = [(c, vec![(7, None, false)].into())].into_iter().collect();
set_departures_seen(&cid, std::sync::Arc::new(third.clone())).unwrap();
assert_eq!(rows().iter().map(|r| r.0).collect::<Vec<_>>(), vec![after[2].0], "a member with no spans left goes");
assert_eq!(stored(), third);
let fourth: DepartureSpans = [(a, vec![(5, Some(9), false)].into())].into_iter().collect();
set_departures_seen(&cid, std::sync::Arc::new(fourth.clone())).unwrap();
assert_eq!(rows().len(), 1, "and one after every member written");
assert_eq!(stored(), fourth);
delete_community(&cid).unwrap();
assert!(departures_seen(&cid).unwrap().spans.is_empty());
assert!(rows().is_empty());
}
#[test]
fn owed_departures_kept_in_settings_move_into_sealed_rows() {
let (_tmp, _guard) = init_test_db();
crate::state::ENCRYPTION_KEY.set([0x37u8; 32], &[]);
crate::state::set_encryption_enabled(true);
let cid = "f".repeat(64);
let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
let json = format!(r#"{{"{}":[[5,9,false]],"{}":[[1,null,true],[12,20,false]]}}"#, a.to_hex(), b.to_hex());
super::super::settings::set_sql_setting(format!("departures_seen:{cid}"), json).unwrap();
let want: DepartureSpans = [(a, vec![(5, Some(9), false)].into()), (b, vec![(1, None, true), (12, Some(20), false)].into())].into_iter().collect();
assert_eq!(*departures_seen(&cid).unwrap().spans, want);
assert_eq!(super::super::settings::get_sql_setting(format!("departures_seen:{cid}")).unwrap(), None);
let bodies: Vec<Vec<u8>> = {
let conn = crate::db::get_db_connection_guard_static().unwrap();
let mut stmt = conn.prepare("SELECT body FROM community_departures_seen").unwrap();
stmt.query_map([], |r| r.get(0)).unwrap().map(|r| r.unwrap()).collect()
};
assert_eq!(bodies.len(), 2);
for body in &bodies {
assert!(!body.windows(32).any(|w| w == a.as_bytes() || w == b.as_bytes()), "who left is never stored in the clear");
}
departures_seen_cache().lock().unwrap().moved(&cid);
assert_eq!(*departures_seen(&cid).unwrap().spans, want, "read back from the sealed rows");
crate::state::set_encryption_enabled(false);
}
#[test]
fn a_folds_floor_writes_skip_only_what_is_already_stored() {
let (_tmp, _guard) = init_test_db();
let cid = "c".repeat(64);
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));
let (h4, h5, a) = ([4u8; 32], [5u8; 32], [9u8; 32]);
set_family_head_at_epoch(&cid, "e1", 5, &h5, &[7; 32], &a, 2, FLOOR_CONTROL).unwrap();
set_family_head_at_epoch(&cid, "e2", 3, &h5, &[8; 32], &a, 2, FLOOR_AUTHORITY).unwrap();
write_folded_heads(&cid, |w| {
w.rebase("e1", 4, &h4, &[6; 32], &a, 2, FLOOR_CONTROL)?;
w.set("e1", 5, &h5, &[7; 32], &a, 2, FLOOR_CONTROL)?;
w.converge("e2", 3, &h5, &[1; 32], &a, 2, FLOOR_AUTHORITY)
})
.unwrap();
assert_eq!(row("e1"), Some((2, 5, h5, Some([7; 32]), Some(a))));
assert_eq!(row("e2"), Some((2, 3, h5, Some([1; 32]), Some(a))));
let failed = write_folded_heads(&cid, |w| {
w.set("e3", 1, &h4, &[2; 32], &a, 2, FLOOR_CONTROL)?;
Err("cut short".into())
});
assert!(failed.is_err());
assert_eq!(row("e3"), None);
}
#[test]
fn a_member_list_reads_posts_through_indexes_not_a_scan() {
let (_tmp, _guard) = init_test_db();
let conn = crate::db::get_db_connection_guard_static().unwrap();
let plan = |sql: &str| -> String {
let mut stmt = conn.prepare(&format!("EXPLAIN QUERY PLAN {sql}")).unwrap();
let binds = vec![1i64; stmt.parameter_count()];
stmt.query_map(rusqlite::params_from_iter(binds), |r| r.get::<_, String>(3)).unwrap().map(|r| r.unwrap()).collect::<Vec<_>>().join(" | ") + " "
};
let held = plan(&flagged_sql("?, ?", false));
assert!(held.contains("USING INDEX idx_events_unauthorized ") && !held.contains("writer"), "{held}");
let strict = plan(&flagged_sql("?, ?", true));
assert!(strict.contains("USING INDEX idx_events_unauthorized ") && strict.contains("USING INDEX idx_events_writer_post "), "{strict}");
let activity = plan(&activity_sql("?, ?"));
assert!(activity.contains("idx_events_chat_kind_npub") && !activity.contains("TEMP B-TREE"), "{activity}");
}
#[test]
fn an_owed_author_take_back_widens_narrows_and_settles_as_it_did_in_settings() {
let (_tmp, _guard) = init_test_db();
let (cid, chan) = ("a".repeat(64), "c".repeat(64));
let author = Keys::generate().public_key().to_hex();
let owed = || owed_author_retractions(&cid).unwrap();
owe_author_retraction(&cid, &chan, &author, 10, None).unwrap();
assert_eq!(owed(), vec![(chan.clone(), author.clone(), 10, None, 1)]);
owe_author_retraction(&cid, &chan, &author, 10, Some(20)).unwrap();
assert_eq!(owed(), vec![(chan.clone(), author.clone(), 10, Some(20), 2)], "the same span closing narrows its own owe");
owe_author_retraction(&cid, &chan, &author, 15, Some(30)).unwrap();
assert_eq!(owed(), vec![(chan.clone(), author.clone(), 10, Some(30), 3)]);
owe_author_retraction(&cid, &chan, &author, 5, None).unwrap();
assert_eq!(owed(), vec![(chan.clone(), author.clone(), 5, None, 4)], "any other range widens it");
settle_author_retraction(&cid, &chan, &author, 5, None, 3).unwrap();
assert_eq!(owed().len(), 1, "more was owed since it was read");
settle_author_retraction(&cid, &chan, &author, 5, None, 4).unwrap();
assert!(owed().is_empty());
let other = Keys::generate().public_key().to_hex();
owe_author_retraction(&cid, &chan, &author, 1, None).unwrap();
owe_author_retraction(&cid, &"d".repeat(64), &other, 2, Some(3)).unwrap();
assert_eq!(owed().len(), 2, "one row per author and Channel");
delete_community(&cid).unwrap();
assert!(owed().is_empty());
}
#[test]
fn owed_author_take_backs_kept_in_settings_move_into_sealed_rows() {
let (_tmp, _guard) = init_test_db();
crate::state::ENCRYPTION_KEY.set([0x41u8; 32], &[]);
crate::state::set_encryption_enabled(true);
let (cid, elsewhere, chan) = ("a".repeat(64), "b".repeat(64), "c".repeat(64));
let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
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();
legacy(&cid, &a, "7:3:");
legacy(&cid, &b, "4:1:9");
legacy(&elsewhere, &a, "1:1:");
let mut want = vec![(chan.clone(), a.to_hex(), 7, None, 3), (chan.clone(), b.to_hex(), 4, Some(9), 1)];
want.sort();
assert_eq!(owed_author_retractions(&cid).unwrap(), want);
let conn = crate::db::get_db_connection_guard_static().unwrap();
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();
assert_eq!(left, vec![format!("writer_retract_by:{elsewhere}:{chan}:{}", a.to_hex())], "another community's rows wait for their own read");
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();
drop(conn);
assert_eq!(bodies.len(), 2);
for body in &bodies {
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");
}
legacy(&elsewhere, &b, "2:5:");
owe_author_retraction(&elsewhere, &chan, &b.to_hex(), 1, None).unwrap();
settle_author_retraction(&elsewhere, &chan, &a.to_hex(), 1, None, 1).unwrap();
assert_eq!(owed_author_retractions(&elsewhere).unwrap(), vec![(chan.clone(), b.to_hex(), 1, None, 6)]);
let conn = crate::db::get_db_connection_guard_static().unwrap();
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();
assert!(bodies.iter().all(|body| !body.windows(32).any(|w| w == a.as_bytes() || w == b.as_bytes())), "nor once owed again");
drop(conn);
crate::state::set_encryption_enabled(false);
}
#[test]
fn an_owed_author_body_round_trips_and_refuses_what_it_did_not_write() {
let author = [7u8; 32];
for (since, generation, until) in [(0, 0, None), (1, 2, Some(3)), (u64::MAX, u64::MAX, Some(u64::MAX))] {
let body = author_owed_body(&author, since, generation, until);
assert_ne!(body.len(), 32);
assert_eq!(author_owed_from_body(&body), Some((author, since, generation, until)));
let mut longer = body.clone();
longer.push(0);
assert_eq!(author_owed_from_body(&longer), None, "no trailing bytes");
assert_eq!(author_owed_from_body(&body[..body.len() - 1]), None, "no cut body");
}
let mut flags = author_owed_body(&author, 1, 1, None);
*flags.last_mut().unwrap() = 2;
assert_eq!(author_owed_from_body(&flags), None, "unknown flags");
let mut format = author_owed_body(&author, 1, 1, None);
format[0] = 2;
assert_eq!(author_owed_from_body(&format), None);
}
#[test]
fn an_owed_departure_body_round_trips_and_refuses_what_it_did_not_write() {
let member = Keys::generate().public_key();
for spans in [vec![], vec![(0, None, false)], vec![(1, Some(2), true), (u64::MAX, Some(u64::MAX), false), (300, None, true)]] {
let body = departure_body(&member, &spans);
assert_ne!(body.len(), 32);
assert_eq!(departure_from_body(&body), Some((member, spans.clone())));
let mut longer = body.clone();
longer.push(0);
assert_eq!(departure_from_body(&longer), None, "no trailing bytes");
assert_eq!(departure_from_body(&body[..body.len() - 1]), None, "no cut body");
}
let mut forged = departure_body(&member, &[(1, None, false)]);
forged[33] = 0x7f;
assert_eq!(departure_from_body(&forged), None, "a count beyond the body");
let mut flags = departure_body(&member, &[(1, None, false)]);
flags[34] = 0b100;
assert_eq!(departure_from_body(&flags), None, "unknown flags");
let mut format = departure_body(&member, &[]);
format[0] = 2;
assert_eq!(departure_from_body(&format), None);
}
#[test]
fn guestbook_rows_are_sealed_at_rest() {
let (_tmp, _guard) = init_test_db();
crate::state::ENCRYPTION_KEY.set([0x31u8; 32], &[]);
crate::state::set_encryption_enabled(true);
let cid = "d".repeat(64);
let ev = gb(5, Some(1));
store_guestbook_events(&cid, std::slice::from_ref(&ev), 1).unwrap();
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();
assert_ne!(body, crate::community::v2::guestbook::event_body(&ev), "not stored in the clear");
assert_eq!(read_guestbook(&cid).unwrap().0, vec![ev]);
crate::state::set_encryption_enabled(false);
crate::state::ENCRYPTION_KEY.clear(&[]);
}
#[test]
fn a_guestbook_read_overlapping_a_write_is_never_served_after_it() {
let (_tmp, _guard) = init_test_db();
let ev = |b: u8| crate::community::v2::guestbook::GuestbookEvent {
epoch: None,
observed_at: None,
rumor_id: [b; 32],
entry: crate::community::v2::guestbook::GuestbookEntry::Leave { member: nostr_sdk::prelude::Keys::generate().public_key(), at_ms: b as u64 },
};
let cid = "e".repeat(64);
let (one, two) = (ev(1), ev(2));
set_guestbook(&cid, std::slice::from_ref(&one), 1).unwrap();
assert_eq!(get_guestbook(&cid).unwrap().0, vec![one.clone()]);
let began_under = guestbook_cache().lock().unwrap().generation(&cid);
set_guestbook(&cid, &[one.clone(), two.clone()], 2).unwrap();
guestbook_cache().lock().unwrap().put(&cid, began_under, (std::sync::Arc::new(Guestbook::new(vec![one.clone()])), 1));
assert_eq!(get_guestbook(&cid).unwrap(), (vec![one, two], 2), "the write stands over the late read");
}
#[test]
fn v2_images_round_trip_and_read_as_community_images() {
let (_tmp, _guard) = init_test_db();
let owner = nostr_sdk::prelude::Keys::generate();
let g = crate::community::v2::control::genesis(
&owner,
crate::community::v2::control::CommunityMetadata { name: "Icons".into(), ..Default::default() },
1_000,
)
.unwrap();
let mut c = crate::community::v2::community::CommunityV2::from_genesis(&g, "Icons", None, vec!["wss://r".into()], 1_000);
let mut extra = serde_json::Map::new();
extra.insert("ext".into(), serde_json::Value::String("webp".into()));
c.icon = Some(crate::community::v2::control::ImageRef {
url: "https://blossom.example/abc".into(),
key: "0".repeat(64),
nonce: "1".repeat(32),
hash: "a".repeat(64),
extra,
});
c.meta_custom = Some({
let mut m = serde_json::Map::new();
m.insert("k".into(), serde_json::Value::from("v"));
m
});
c.channels[0].voice = Some(true);
c.channels[0].meta_extra.insert("vnd".into(), serde_json::Value::from(7));
save_community_v2(&c).unwrap();
let re = load_community_v2(c.id()).unwrap().unwrap();
assert_eq!(re.icon, c.icon);
assert_eq!(re.banner, None);
assert_eq!(re.meta_custom, c.meta_custom);
assert_eq!(re.channels[0].voice, Some(true));
assert_eq!(re.channels[0].meta_extra.get("vnd"), Some(&serde_json::Value::from(7)));
let cid = crate::simd::hex::bytes_to_hex_32(&c.id().0);
let img = community_image(&cid, false).unwrap().expect("the v2 icon reads as a CommunityImage");
assert_eq!(img.url, "https://blossom.example/abc");
assert_eq!(img.ext, "webp");
assert_eq!(img.hash, "a".repeat(64));
assert_eq!(community_image(&cid, true).unwrap(), None);
assert_eq!(community_image(&"cd".repeat(32), false).unwrap(), None);
}
#[test]
fn column_reads_and_the_owner_check_serve_a_v2_community() {
use crate::community::roles::{CommunityRoles, MemberGrant, Permissions, Role, RoleScope};
use crate::community::moderation::is_owner_or_admin;
let (_tmp, _guard) = init_test_db();
let owner = nostr_sdk::prelude::Keys::generate();
let g = crate::community::v2::control::genesis(
&owner,
crate::community::v2::control::CommunityMetadata { name: "Two".into(), ..Default::default() },
1_000,
)
.unwrap();
let v2 = crate::community::v2::community::CommunityV2::from_genesis(&g, "Two", None, vec!["wss://two".into()], 1_000);
save_community_v2(&v2).unwrap();
let mut other = v2_fixture("One", &["wss://one"]);
other.channels.push(private_channel(0x71, 0x72));
save_community_v2(&other).unwrap();
crate::db::get_write_connection_guard_static()
.unwrap()
.execute(
"INSERT INTO community_channels (channel_id, community_id, channel_key, epoch, name, created_at)
VALUES (?1, ?2, x'00', 0, 'c', 1)",
params!["ee".repeat(32), "ff".repeat(32)],
)
.unwrap();
let channels = held_channel_ids().unwrap();
assert!(!channels.contains(&"ee".repeat(32)), "a channel whose community is gone is not held");
assert!(channels.contains(&crate::simd::hex::bytes_to_hex_32(&v2.channels[0].id.0)));
assert!(other.channels.iter().all(|ch| channels.contains(&ch.id.to_hex())));
assert_eq!(channels.len(), other.channels.len() + v2.channels.len());
let relays = held_community_relays().unwrap();
assert!(relays.contains("wss://two") && relays.contains("wss://one"));
let cid = crate::simd::hex::bytes_to_hex_32(&v2.id().0);
let (admin, social, stranger) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
let role = |id: &str, perms: u64| Role {
role_id: id.repeat(32), name: id.into(), position: 1, permissions: Permissions(perms),
scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
};
let roles = CommunityRoles {
roles: vec![role("aa", Permissions::ADMIN_ALL), role("bb", 0)],
grants: vec![
MemberGrant { member: admin.to_hex(), role_ids: vec!["aa".repeat(32)] },
MemberGrant { member: social.to_hex(), role_ids: vec!["bb".repeat(32)] },
],
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
};
set_community_roles(&cid, &roles, 1).unwrap();
assert!(is_owner_or_admin(&cid, &owner.public_key().to_hex()), "a v2 owner proves itself from the id");
assert!(is_owner_or_admin(&cid, &admin.to_hex()));
assert!(!is_owner_or_admin(&cid, &social.to_hex()), "a role without management is not admin");
assert!(!is_owner_or_admin(&cid, &stranger.to_hex()));
assert!(!is_owner_or_admin(&"cd".repeat(32), &owner.public_key().to_hex()));
}
#[test]
fn epoch_key_archive_retains_every_epoch() {
let (_tmp, _guard) = init_test_db();
let cid = "f".repeat(64);
let scope = "a".repeat(64);
store_epoch_key(&cid, &scope, 0, &[0xA0u8; 32]).unwrap();
store_epoch_key(&cid, &scope, 1, &[0xA1u8; 32]).unwrap();
store_epoch_key(&cid, &scope, 2, &[0xA2u8; 32]).unwrap();
let held = held_epoch_keys(&cid, &scope).unwrap();
assert_eq!(held.len(), 3, "all three epoch keys retained");
assert_eq!(held[0], (Epoch(0), [0xA0u8; 32]));
assert_eq!(held[1], (Epoch(1), [0xA1u8; 32]));
assert_eq!(held[2], (Epoch(2), [0xA2u8; 32]));
assert_eq!(held_epoch_key(&cid, &scope, 1).unwrap(), Some([0xA1u8; 32]));
assert_eq!(held_epoch_key(&cid, &scope, 9).unwrap(), None, "unheld epoch is None");
store_epoch_key(&cid, &scope, 1, &[0xBBu8; 32]).unwrap();
assert_eq!(held_epoch_key(&cid, &scope, 1).unwrap(), Some([0xBBu8; 32]));
assert_eq!(held_epoch_keys(&cid, &scope).unwrap().len(), 3, "replace didn't add a row");
assert!(held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap().is_empty());
assert_eq!(
held_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 1).unwrap(),
None,
"epoch 1 under a different scope is not the channel's key"
);
}
#[test]
fn at_rest_encryption_wraps_keys_and_metadata_on_disk() {
let (_tmp, _guard) = init_test_db();
crate::state::ENCRYPTION_KEY.set([0x55u8; 32], &[]);
crate::state::set_encryption_enabled(true);
let mut c = v2_fixture("Secret HQ", &["wss://relay.example"]);
c.community_root = [0x42u8; 32];
c.description = Some("top secret".into());
c.channels.push(private_channel(0x61, 0x62));
save_community_v2(&c).unwrap();
let cid = c.id().to_hex();
store_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 0, &c.community_root).unwrap();
set_community_banlist(&cid, &["deadbeef".repeat(8)], 1).unwrap();
{
let conn = crate::db::get_db_connection_guard_static().unwrap();
let (root_len, control_root_len, name, relays, description): (i64, i64, String, String, String) = conn
.query_row(
"SELECT length(server_root_key), length(control_root), name, relays, description
FROM communities WHERE community_id = ?1",
params![cid],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
)
.unwrap();
assert_eq!(root_len, 60, "server_root_key must be ciphertext, not a raw 32-byte key");
assert_eq!(control_root_len, 60, "control_root must be ciphertext, not a raw 32-byte key");
for (column, stored, plain) in [
("name", &name, "Secret HQ"),
("relays", &relays, r#"["wss://relay.example"]"#),
("description", &description, "top secret"),
] {
assert_ne!(stored, plain, "{column} must not be plaintext on disk");
assert!(crate::crypto::looks_encrypted(stored), "{column} column is ciphertext");
}
let (owner_pk, owner_salt, control_pk): (String, String, String) = conn
.query_row(
"SELECT owner_pubkey, owner_salt, control_pk FROM communities WHERE community_id = ?1",
params![cid],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.unwrap();
for (column, stored, plain) in [
("owner_pubkey", &owner_pk, crate::simd::hex::bytes_to_hex_32(&c.identity.owner_xonly)),
("owner_salt", &owner_salt, crate::simd::hex::bytes_to_hex_32(&c.identity.owner_salt)),
("control_pk", &control_pk, c.control_pk.unwrap().to_hex()),
] {
assert_ne!(*stored, plain, "{column} must not be plaintext on disk");
assert!(crate::crypto::looks_encrypted(stored), "{column} column is ciphertext");
}
let mut stmt = conn
.prepare("SELECT length(channel_key), name FROM community_channels WHERE community_id = ?1")
.unwrap();
let channels: Vec<(i64, String)> =
stmt.query_map(params![cid], |r| Ok((r.get(0)?, r.get(1)?))).unwrap().map(Result::unwrap).collect();
assert_eq!(channels.len(), 2);
for (key_len, name) in &channels {
assert_eq!(*key_len, 60, "channel_key must be ciphertext, Public placeholder and Private key alike");
assert!(crate::crypto::looks_encrypted(name) && name != "general" && name != "staff", "channel name is ciphertext");
}
let banned_npub: String = conn
.query_row("SELECT npub FROM community_bans WHERE community_id = ?1 LIMIT 1", params![cid], |r| r.get(0))
.unwrap();
assert!(crate::crypto::looks_encrypted(&banned_npub), "who is banned is sealed on disk, got {banned_npub}");
let opened = crate::crypto::maybe_decrypt_text(&banned_npub);
assert!(opened.starts_with("npub1"), "and opens to the form `events.npub` uses");
let key_len: i64 = conn
.query_row(
"SELECT length(key) FROM community_epoch_keys WHERE community_id = ?1 LIMIT 1",
params![cid],
|r| r.get(0),
)
.unwrap();
assert_eq!(key_len, 60, "epoch-archive key must be ciphertext");
}
let loaded = load_community_v2(c.id()).unwrap().unwrap();
assert_eq!(loaded.name, "Secret HQ");
assert_eq!(loaded.description.as_deref(), Some("top secret"));
assert_eq!(loaded.community_root, [0x42u8; 32]);
assert_eq!(loaded.control_root, c.control_root);
assert_eq!(loaded.control_pk, c.control_pk);
assert_eq!(loaded.identity.owner_xonly, c.identity.owner_xonly);
assert_eq!(loaded.identity.owner_salt, c.identity.owner_salt);
assert_eq!(loaded.relays, vec!["wss://relay.example".to_string()]);
assert_eq!(loaded.channels[0].name, "general");
assert_eq!(loaded.channels[1].key, Some([0x62u8; 32]));
assert_eq!(held_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 0).unwrap(), Some([0x42u8; 32]));
assert_eq!(get_community_banlist(&cid).unwrap(), vec!["deadbeef".repeat(8)]);
crate::state::set_encryption_enabled(false);
crate::state::ENCRYPTION_KEY.clear(&[]);
}
#[test]
fn an_encrypted_v2_community_loads_back_whole() {
let (_tmp, _guard) = init_test_db();
struct Vault;
impl Drop for Vault {
fn drop(&mut self) {
crate::state::set_encryption_enabled(false);
crate::state::ENCRYPTION_KEY.clear(&[]);
}
}
let _vault = Vault;
crate::state::ENCRYPTION_KEY.set([0x55u8; 32], &[]);
crate::state::set_encryption_enabled(true);
let owner = nostr_sdk::prelude::Keys::generate();
let g = crate::community::v2::control::genesis(
&owner,
crate::community::v2::control::CommunityMetadata { name: "Sealed".into(), ..Default::default() },
1_000,
)
.unwrap();
let mut v2 = crate::community::v2::community::CommunityV2::from_genesis(&g, "Sealed", Some("about".into()), vec!["wss://r".into()], 1_000);
let mut private = v2.channels[0].clone();
private.id = ChannelId([0x61; 32]);
private.name = "staff".into();
private.private = true;
private.key = Some([0x62; 32]);
v2.channels.push(private);
save_community_v2(&v2).unwrap();
let name: String = crate::db::get_db_connection_guard_static()
.unwrap()
.query_row("SELECT name FROM communities WHERE community_id = ?1", params![v2.id().to_hex()], |r| r.get(0))
.unwrap();
assert!(crate::crypto::looks_encrypted(&name), "sealed on disk");
let loaded = load_community_v2(v2.id()).unwrap().unwrap();
assert_eq!(format!("{loaded:?}"), format!("{v2:?}"), "every field opens back to what was saved");
}
#[test]
fn at_rest_decrypt_tolerates_a_pre_migration_plaintext_row() {
let (_tmp, _guard) = init_test_db();
crate::state::set_encryption_enabled(false);
let mut c = v2_fixture("Legacy HQ", &[]);
c.community_root = [0x42u8; 32];
c.channels.push(private_channel(0x61, 0x62));
save_community_v2(&c).unwrap();
crate::state::ENCRYPTION_KEY.set([0x55u8; 32], &[]);
crate::state::set_encryption_enabled(true);
let loaded = load_community_v2(c.id()).unwrap().unwrap();
assert_eq!(loaded.name, "Legacy HQ", "plaintext name reads through");
assert_eq!(loaded.community_root, [0x42u8; 32], "raw 32-byte key reads through");
assert_eq!(loaded.control_root, c.control_root, "raw 32-byte control root reads through");
assert_eq!(loaded.channels[1].key, Some([0x62u8; 32]), "raw 32-byte channel key reads through");
crate::state::set_encryption_enabled(false);
crate::state::ENCRYPTION_KEY.clear(&[]);
}
#[test]
fn large_epoch_round_trips_losslessly() {
let (_tmp, _guard) = init_test_db();
let mut c = v2_fixture("HQ", &[]);
c.root_epoch = Epoch(u64::MAX - 3);
c.channels[0].epoch = Epoch(u64::MAX - 7);
save_community_v2(&c).unwrap();
let loaded = load_community_v2(c.id()).unwrap().unwrap();
assert_eq!(loaded.root_epoch, Epoch(u64::MAX - 3));
assert_eq!(loaded.channels[0].epoch, Epoch(u64::MAX - 7));
}
#[test]
fn malformed_channel_id_row_errors_not_corrupts() {
let (_tmp, _guard) = init_test_db();
let (c, cid, _) = saved_v2("HQ");
{
let conn = crate::db::get_write_connection_guard_static().unwrap();
conn.execute(
"INSERT OR REPLACE INTO community_channels
(channel_id, community_id, channel_key, epoch, name, created_at)
VALUES (?1, ?2, ?3, 0, 'bad', 0)",
rusqlite::params!["zz_not_hex", cid, &[0u8; 32][..]],
)
.unwrap();
}
assert!(load_community_v2(c.id()).is_err(), "malformed id must error, not corrupt");
}
#[test]
fn message_key_store_take_round_trip() {
let (_tmp, _guard) = init_test_db();
let eph = Keys::generate();
let relays = vec!["wss://r.one".to_string()];
store_message_key("inner_msg_id", "outer_evid", &eph, &relays).unwrap();
let (loaded, outer, r) = take_message_key("inner_msg_id").unwrap().expect("present");
assert_eq!(
loaded.secret_key().as_secret_bytes(),
eph.secret_key().as_secret_bytes()
);
assert_eq!(outer, "outer_evid");
assert_eq!(r, relays);
assert!(take_message_key("inner_msg_id").unwrap().is_none());
}
#[test]
fn missing_community_is_none() {
let (_tmp, _guard) = init_test_db();
let absent = CommunityId([0x33u8; 32]);
assert!(load_community_v2(&absent).unwrap().is_none());
}
#[test]
fn list_ids_reflects_saved() {
let (_tmp, _guard) = init_test_db();
let (a, _, _) = saved_v2("A");
let (b, _, _) = saved_v2("B");
let ids = list_community_ids().unwrap();
assert_eq!(ids.len(), 2);
assert!(ids.contains(a.id()) && ids.contains(b.id()));
}
#[test]
fn delete_community_clears_all_local_state() {
let (_tmp, _guard) = init_test_db();
let (c, cid, private) = archived_v2();
save_public_invite(&"ab".repeat(32), &cid, "url", None, None).unwrap();
save_pending_invite(&"cd".repeat(32), "{}", "npub1x", 0).unwrap();
set_edition_head(&cid, &"a".repeat(64), 3, &[0x11u8; 32]).unwrap();
assert!(!held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap().is_empty());
assert!(!held_epoch_keys(&cid, &private).unwrap().is_empty());
delete_community(&cid).unwrap();
assert!(!community_exists(c.id()).unwrap());
assert!(community_id_for_channel(&c.channels[0].id.to_hex()).unwrap().is_none());
assert!(community_id_for_channel(&private).unwrap().is_none());
assert!(list_public_invites(&cid).unwrap().is_empty());
assert_eq!(get_edition_head(&cid, &"a".repeat(64)).unwrap(), None, "edition heads cleared on delete");
assert!(held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap().is_empty(), "epoch keys cleared on delete");
assert!(held_epoch_keys(&cid, &private).unwrap().is_empty(), "channel epoch keys cleared on delete");
}
#[test]
fn delete_community_retain_keys_drops_state_but_keeps_epoch_keys() {
let (_tmp, _guard) = init_test_db();
let (c, cid, private) = archived_v2();
save_public_invite(&"ab".repeat(32), &cid, "url", None, None).unwrap();
set_edition_head(&cid, &"a".repeat(64), 3, &[0x11u8; 32]).unwrap();
let base_before = held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap();
let chan_before = held_epoch_keys(&cid, &private).unwrap();
assert!(!base_before.is_empty() && !chan_before.is_empty(), "base + channel keys archived");
delete_community_retain_keys(&cid).unwrap();
assert!(!community_exists(c.id()).unwrap());
assert!(community_id_for_channel(&c.channels[0].id.to_hex()).unwrap().is_none());
assert!(community_id_for_channel(&private).unwrap().is_none());
assert!(list_public_invites(&cid).unwrap().is_empty());
assert_eq!(get_edition_head(&cid, &"a".repeat(64)).unwrap(), None);
assert_eq!(held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap(), base_before,
"base epoch keys retained for self-scrub");
assert_eq!(held_epoch_keys(&cid, &private).unwrap(), chan_before,
"channel epoch keys retained for self-scrub");
}
#[test]
fn channel_resolves_to_owning_community() {
let (_tmp, _guard) = init_test_db();
let (_, cid, chan) = saved_v2("HQ");
assert_eq!(community_id_for_channel(&chan).unwrap().as_deref(), Some(cid.as_str()));
assert!(community_id_for_channel(&"ff".repeat(32)).unwrap().is_none());
}
#[test]
fn the_channel_cache_answers_in_bytes_and_hex_alike() {
let (_tmp, _guard) = init_test_db();
let (c, cid, chan) = saved_v2("Bytes");
let ch = c.channels[0].id.0;
assert_eq!(community_for_channel(&ch).unwrap(), Some(c.id().0));
assert_eq!(channel_community_cache().read().unwrap().get(&ch), Some(&c.id().0), "the miss filled the cache");
assert_eq!(community_for_channel(&ch).unwrap(), Some(c.id().0));
assert_eq!(community_id_for_channel(&chan).unwrap().as_deref(), Some(cid.as_str()));
assert_eq!(community_id_for_channel(&chan.to_uppercase()).unwrap(), None);
assert_eq!(community_for_channel(&[0xFF; 32]).unwrap(), None);
assert!(channel_community_cache().read().unwrap().get(&[0xFF; 32]).is_none(), "a miss is never cached");
delete_community_retain_keys(&cid).unwrap();
assert_eq!(community_for_channel(&ch).unwrap(), None);
assert_eq!(community_id_for_channel(&chan).unwrap(), None);
}
#[test]
fn communities_that_ban_nobody_share_one_empty_set() {
let (_tmp, _guard) = init_test_db();
let (a, a_hex, _) = saved_v2("Calm");
let (b, b_hex, _) = saved_v2("Quiet");
let (ea, eb) = (banned_set_of(&a.id().0), banned_set(&b_hex));
assert!(ea.is_empty() && std::sync::Arc::ptr_eq(&ea, &eb), "every empty banlist is the one shared set");
let villain = Keys::generate().public_key();
set_community_banlist(&a_hex, &[villain.to_hex()], 10).unwrap();
assert!(is_author_banned(&a_hex, &villain) && is_author_banned_in(&a.id().0, &villain));
assert!(!is_author_banned_in(&b.id().0, &villain), "a ban stays in its own community");
assert!(!std::sync::Arc::ptr_eq(&banned_set_of(&a.id().0), &empty_ban_set()));
set_community_banlist(&a_hex, &[], 11).unwrap();
assert!(std::sync::Arc::ptr_eq(&banned_set_of(&a.id().0), &empty_ban_set()), "an emptied banlist returns to the shared set");
assert!(!is_author_banned_in(&a.id().0, &villain));
}
#[test]
fn community_exists_reflects_saved() {
let (_tmp, _guard) = init_test_db();
let c = v2_fixture("A", &[]);
assert!(!community_exists(c.id()).unwrap());
save_community_v2(&c).unwrap();
assert!(community_exists(c.id()).unwrap());
}
#[test]
fn a_block_drops_only_that_persons_parked_invites() {
let (_tmp, _guard) = init_test_db();
let (spam, friend) = ("cd".repeat(32), "ef".repeat(32));
save_pending_invite(&spam, &v2_bundle("Spam"), "npub1spammer", 0).unwrap();
save_pending_invite(&friend, &v2_bundle("Friends"), "npub1friend", 0).unwrap();
assert_eq!(delete_pending_invites_from("npub1spammer").unwrap(), 1);
let left: Vec<String> = list_pending_invites().unwrap().into_iter().map(|i| i.community_id).collect();
assert_eq!(left, vec![friend], "the friend's invite stays");
}
#[test]
fn pending_invite_first_wins_and_round_trips() {
let (_tmp, _guard) = init_test_db();
let cid = "ab".repeat(32);
let (first, second) = (v2_bundle("First"), v2_bundle("Second"));
assert!(save_pending_invite(&cid, &first, "npub1inviter", 0).unwrap());
assert!(!save_pending_invite(&cid, &second, "npub1other", 0).unwrap());
assert!(pending_invite_exists(&cid).unwrap());
let listed = list_pending_invites().unwrap();
assert_eq!(listed.len(), 1);
assert_eq!(listed[0].community_id, cid);
assert_eq!(listed[0].bundle_json, first, "original bundle preserved");
assert_eq!(listed[0].inviter_npub, "npub1inviter");
assert_eq!(get_pending_invite(&cid).unwrap(), Some(first.clone()));
assert!(pending_invite_exists(&cid).unwrap(), "get must not delete");
delete_pending_invite(&cid).unwrap();
assert!(!pending_invite_exists(&cid).unwrap());
assert!(get_pending_invite(&cid).unwrap().is_none());
}
#[test]
fn purge_drops_invites_for_held_communities_only() {
let (_tmp, _guard) = init_test_db();
let (_, held_hex, _) = saved_v2("Held");
save_pending_invite(&held_hex, "{\"bundle\":1}", "npub1inviter", 0).unwrap();
let stranger = "ab".repeat(32);
save_pending_invite(&stranger, "{\"bundle\":2}", "npub1inviter", 0).unwrap();
let n = purge_pending_invites_for_held_communities().unwrap();
assert_eq!(n, 1, "only the held community's invite is purged");
assert!(!pending_invite_exists(&held_hex).unwrap(), "held → invite gone");
assert!(pending_invite_exists(&stranger).unwrap(), "unknown community → invite kept");
}
#[test]
fn an_invites_lifetime_runs_from_when_it_was_sent() {
let (_tmp, _guard) = init_test_db();
let lifetime = crate::event_handler::DIRECT_INVITE_LIFETIME_SECS as i64;
let now = now_secs();
let (old, fresh, unknown, deadline) = ("a1".repeat(32), "a2".repeat(32), "a3".repeat(32), "a4".repeat(32));
for cid in [&old, &fresh, &unknown] {
save_pending_invite(cid, "{}", "npub1x", 0).unwrap();
}
save_pending_invite(&deadline, "{}", "npub1x", now + 60).unwrap();
set_pending_invite_sent(&old, now - lifetime - 1).unwrap();
set_pending_invite_sent(&fresh, now - 60).unwrap();
set_pending_invite_sent(&fresh, 1).unwrap();
set_pending_invite_sent(&deadline, now - 60).unwrap();
let listed = list_pending_invites().unwrap();
let get = |cid: &str| listed.iter().find(|i| i.community_id == cid);
assert!(get(&old).is_none(), "sent past its lifetime, so gone though parked just now");
let f = get(&fresh).unwrap();
assert_eq!((f.sent_at, f.ends_at), (now - 60, now - 60 + lifetime), "the first send time stands");
let u = get(&unknown).unwrap();
assert_eq!((u.sent_at, u.ends_at), (0, u.received_at + lifetime));
assert_eq!(get(&deadline).unwrap().ends_at, now + 60, "the sender's earlier deadline wins");
assert_eq!(purge_expired_pending_invites().unwrap(), 1);
}
#[test]
fn an_invites_wraps_are_kept_once_each_up_to_a_cap_and_go_with_it() {
let (_tmp, _guard) = init_test_db();
let cid = "ef".repeat(32);
note_pending_invite_wrap(&cid, &"01".repeat(32)).unwrap();
assert!(pending_invite_wraps(&cid).unwrap().is_empty(), "no parked invite, nothing kept");
save_pending_invite(&cid, "{}", "npub1x", 0).unwrap();
for n in [1u8, 2, 1] {
note_pending_invite_wrap(&cid, &format!("{n:02x}").repeat(32)).unwrap();
}
assert_eq!(pending_invite_wraps(&cid).unwrap(), ["01".repeat(32), "02".repeat(32)]);
for n in 3u8..40 {
note_pending_invite_wrap(&cid, &format!("{n:02x}").repeat(32)).unwrap();
}
assert_eq!(pending_invite_wraps(&cid).unwrap().len(), 16);
delete_pending_invite(&cid).unwrap();
assert!(pending_invite_wraps(&cid).unwrap().is_empty());
}
#[test]
fn decline_drops_pending_invite() {
let (_tmp, _guard) = init_test_db();
let cid = "cd".repeat(32);
save_pending_invite(&cid, "{}", "npub1x", 0).unwrap();
delete_pending_invite(&cid).unwrap();
assert!(!pending_invite_exists(&cid).unwrap());
}
#[test]
fn pending_invites_are_capped_keeping_the_newest() {
let (_tmp, _guard) = init_test_db();
let bundle = v2_bundle("Flood");
for i in 0..150u32 {
let cid = format!("{:064x}", i);
save_pending_invite(&cid, &bundle, "npub1x", 0).unwrap();
}
let all = list_pending_invites().unwrap();
assert_eq!(all.len(), 100, "table capped at MAX_PENDING_INVITES");
for i in 150..400u32 {
let cid = format!("{:064x}", i);
save_pending_invite(&cid, &bundle, "npub1x", 0).unwrap();
}
assert_eq!(list_pending_invites().unwrap().len(), 100, "cap holds under flood");
}
#[test]
fn expired_parked_invites_are_hidden_from_list_and_accept() {
let (_tmp, _guard) = init_test_db();
let now = now_secs();
let live = "aa".repeat(32);
let expired = "bb".repeat(32);
let permanent = "cc".repeat(32);
save_pending_invite(&live, &v2_bundle("Live"), "npub1x", now + 3600).unwrap();
save_pending_invite(&expired, &v2_bundle("Dead"), "npub1x", now - 1).unwrap();
save_pending_invite(&permanent, &v2_bundle("Forever"), "npub1x", 0).unwrap();
let listed: Vec<String> = list_pending_invites().unwrap().into_iter().map(|i| i.community_id).collect();
assert!(listed.contains(&live), "an unexpired invite still lists");
assert!(listed.contains(&permanent), "a no-deadline invite still lists");
assert!(!listed.contains(&expired), "an expired invite is hidden from the list");
assert!(get_pending_invite(&live).unwrap().is_some());
assert!(get_pending_invite(&permanent).unwrap().is_some());
assert!(
get_pending_invite(&expired).unwrap().is_none(),
"an expired invite must not be redeemable"
);
assert!(pending_invite_exists(&expired).unwrap(), "hidden, not yet deleted");
assert_eq!(purge_expired_pending_invites().unwrap(), 1);
assert!(!pending_invite_exists(&expired).unwrap());
assert!(pending_invite_exists(&live).unwrap(), "the sweep spares live invites");
assert!(pending_invite_exists(&permanent).unwrap(), "and no-deadline ones");
}
#[test]
fn expiry_follows_the_senders_deadline_not_receipt_time() {
let (_tmp, _guard) = init_test_db();
let cid = "de".repeat(32);
save_pending_invite(&cid, "{}", "npub1x", now_secs() - 10).unwrap();
assert!(list_pending_invites().unwrap().is_empty(), "receipt time does not extend the deadline");
assert!(get_pending_invite(&cid).unwrap().is_none());
}
#[test]
fn a_legacy_banlist_is_adopted_on_first_read() {
let (_tmp, _guard) = init_test_db();
let (_, cid, _) = saved_v2("Legacy bans");
let banned = "ab".repeat(32);
{
let conn = crate::db::get_write_connection_guard_static().unwrap();
conn.execute("DELETE FROM community_bans WHERE community_id = ?1", params![cid]).unwrap();
conn.execute("UPDATE communities SET banlist = ?1 WHERE community_id = ?2", params![format!("[\"{banned}\"]"), cid]).unwrap();
}
assert_eq!(get_community_banlist(&cid).unwrap(), vec![banned.clone()]);
assert_eq!(get_community_banlist(&cid).unwrap(), vec![banned], "and stays adopted");
}
#[test]
fn a_task_of_a_swapped_out_account_cannot_seal() {
struct Vault;
impl Drop for Vault {
fn drop(&mut self) {
crate::state::ENCRYPTION_KEY.clear(&[]);
crate::state::set_encryption_enabled(false);
}
}
const KA: [u8; 32] = [0x61; 32];
const KB: [u8; 32] = [0x62; 32];
let (_tmp, _guard) = init_test_db();
let _vault = Vault;
let account_a = crate::db::get_current_account().unwrap();
crate::db::set_sql_setting("encryption_enabled".to_string(), "true".to_string()).unwrap();
crate::state::ENCRYPTION_KEY.set(KA, &[]);
crate::state::set_encryption_enabled(true);
let (_, cid, ch) = saved_v2("A");
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
let late_write = |label: &'static str| {
let (go, wait) = tokio::sync::oneshot::channel::<()>();
let (cid, ch) = (cid.clone(), ch.clone());
let task = {
let _rt = rt.enter();
crate::db::spawn_bound(async move {
let _ = wait.await;
set_community_pins(&cid, &ch, &format!("{{\"{label}\":1}}"), 1)
})
};
(go, task)
};
let (go_plain, plain) = late_write("plain");
let (go_foreign, foreign) = late_write("foreign");
let account_b = make_test_npub(TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
crate::state::ENCRYPTION_KEY.clear(&[]);
crate::state::set_encryption_enabled(false);
crate::db::set_current_account(account_b.clone()).unwrap();
crate::db::init_database(&account_b).unwrap();
go_plain.send(()).unwrap();
assert!(rt.block_on(plain).unwrap().is_err(), "no plaintext into an encrypted store");
crate::state::ENCRYPTION_KEY.set(KB, &[]);
crate::state::set_encryption_enabled(true);
go_foreign.send(()).unwrap();
assert!(rt.block_on(foreign).unwrap().is_err(), "no seal under another account's key");
crate::db::set_current_account(account_a.clone()).unwrap();
crate::db::init_database(&account_a).unwrap();
crate::state::ENCRYPTION_KEY.set(KA, &[]);
assert_eq!(get_community_pins(&cid, &ch).unwrap(), None, "account A's store is untouched");
}
#[test]
fn a_legacy_account_moves_onto_its_own_salt_at_unlock() {
use crate::crypto::{derive_key, Kdf};
use crate::db::at_rest;
struct Vault;
impl Drop for Vault {
fn drop(&mut self) {
crate::state::ENCRYPTION_KEY.clear(&[]);
crate::state::set_encryption_enabled(false);
}
}
let (_tmp, _guard) = init_test_db();
let _vault = Vault;
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
let pin = "123456";
let legacy = rt.block_on(derive_key(pin, &Kdf::Legacy));
crate::state::ENCRYPTION_KEY.set(legacy, &[]);
crate::state::set_encryption_enabled(true);
crate::db::set_sql_setting("encryption_enabled".to_string(), "true".to_string()).unwrap();
crate::db::set_sql_setting("security_type".to_string(), "pin".to_string()).unwrap();
crate::db::set_sql_setting("last_vacuum".to_string(), "1".to_string()).unwrap();
crate::db::set_pkey(&crate::crypto::encrypt_with_key("nsec1legacyaccount", &legacy).unwrap()).unwrap();
let mut community = v2_fixture("Old", &["wss://r"]);
community.channels.push(private_channel(0x61, 0x62));
save_community_v2(&community).unwrap();
let (cid, ch) = (community.id().to_hex(), community.channels[0].id.to_hex());
set_community_pins(&cid, &ch, r#"{"pins":["old"]}"#, 1).unwrap();
let dm_chat = make_test_npub(900_002);
let dm = crate::types::Message { id: "e1".repeat(32), content: "said long ago".into(), at: 1_600_000_000_000, mine: true, ..Default::default() };
rt.block_on(crate::db::events::save_message(&dm_chat, &dm)).unwrap();
let dm_int = crate::db::id_cache::get_or_create_chat_id(&dm_chat).unwrap();
let read = || {
(
get_community_pins(&cid, &ch).unwrap(),
load_community_v2(community.id()).unwrap().map(|c| format!("{c:?}")),
rt.block_on(crate::db::events::get_message_views(dm_int, 10, 0)).unwrap().into_iter().map(|m| m.content).collect::<Vec<_>>(),
)
};
let before = read();
assert_eq!(before.1, Some(format!("{community:?}")));
assert_eq!(before.2, vec!["said long ago".to_string()]);
assert!(!rt.block_on(at_rest::upgrade_after_unlock(pin, &[0x77; 32])).unwrap(), "a key that proves nothing moves nothing");
assert_eq!(Kdf::of_account().unwrap(), Kdf::Legacy);
crate::db::set_sql_setting("security_type".to_string(), "biometric".to_string()).unwrap();
assert!(!rt.block_on(at_rest::upgrade_after_unlock(pin, &legacy)).unwrap(), "a biometric account stays put");
crate::db::set_sql_setting("security_type".to_string(), "pin".to_string()).unwrap();
assert_eq!(read(), before);
{
let conn = crate::db::get_write_connection_guard_static().unwrap();
conn.execute_batch("CREATE TABLE unaddressable (k TEXT PRIMARY KEY, v TEXT) WITHOUT ROWID;").unwrap();
conn.execute("INSERT INTO unaddressable VALUES ('a', ?1)", [crate::crypto::encrypt_with_key("x", &legacy).unwrap()]).unwrap();
}
assert!(rt.block_on(at_rest::upgrade_after_unlock(pin, &legacy)).is_err());
assert_eq!((Kdf::of_account().unwrap(), read()), (Kdf::Legacy, before.clone()), "nothing moved");
assert_eq!(crate::state::ENCRYPTION_KEY.get(), Some(legacy));
assert!(!rt.block_on(at_rest::upgrade_after_unlock(pin, &legacy)).unwrap(), "backed off");
crate::db::get_write_connection_guard_static().unwrap().execute_batch("DROP TABLE unaddressable;").unwrap();
crate::db::settings::remove_setting("kdf_upgrade_attempt").unwrap();
assert!(rt.block_on(at_rest::upgrade_after_unlock(pin, &legacy)).unwrap());
let kdf = Kdf::of_account().unwrap();
assert!(!kdf.is_legacy(), "the salt is recorded");
let salted = rt.block_on(derive_key(pin, &kdf));
assert_eq!(crate::state::ENCRYPTION_KEY.get(), Some(salted), "the session carries on under the new key");
assert_eq!(read(), before, "everything reads back");
{
let conn = crate::db::get_write_connection_guard_static().unwrap();
let tx = conn.unchecked_transaction().unwrap();
assert_eq!(at_rest::sweep_residue_in_tx(&tx, &legacy, None).unwrap(), 0, "nothing opens under the legacy key");
}
assert_eq!(crate::db::get_sql_setting("last_vacuum".to_string()).unwrap(), None, "a vacuum is due");
assert!(!rt.block_on(at_rest::upgrade_after_unlock(pin, &salted)).unwrap(), "the next unlock has nothing to do");
assert!(crate::crypto::install_unlocked_key(&legacy, &Kdf::Legacy).is_err());
assert_eq!(crate::state::ENCRYPTION_KEY.get(), Some(salted));
let again = Kdf::fresh();
let again_key = rt.block_on(derive_key(pin, &again));
assert!(!at_rest::upgrade_legacy_derivation(&legacy, &again_key, &again, &|_| {}).unwrap());
assert_eq!(Kdf::of_account().unwrap(), kdf);
}
const CRASH_PIN: &str = "424242";
#[test]
#[ignore = "driven by the_upgrade_survives_a_kill_at_any_moment"]
fn upgrade_crash_child() {
use std::io::Write;
let (Ok(root), Ok(npub)) = (std::env::var("VECTOR_CRASH_ROOT"), std::env::var("VECTOR_CRASH_NPUB")) else { return };
crate::db::set_app_data_dir(root.into());
crate::db::set_current_account(npub.clone()).unwrap();
crate::db::init_database(&npub).unwrap();
crate::state::init_encryption_enabled();
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
let legacy = rt.block_on(crate::crypto::derive_key(CRASH_PIN, &crate::crypto::Kdf::Legacy));
crate::state::ENCRYPTION_KEY.set(legacy, &[]);
let kdf = crate::crypto::Kdf::fresh();
let salted = rt.block_on(crate::crypto::derive_key(CRASH_PIN, &kdf));
println!("CHILD READY");
std::io::stdout().flush().unwrap();
assert!(crate::db::at_rest::upgrade_legacy_derivation(&legacy, &salted, &kdf, &|_| {}).unwrap());
println!("CHILD DONE");
std::io::stdout().flush().unwrap();
}
#[test]
#[ignore = "spawns and kills child processes; run with --ignored"]
fn the_upgrade_survives_a_kill_at_any_moment() {
use crate::crypto::{derive_key, Kdf};
use std::io::BufRead;
struct Vault;
impl Drop for Vault {
fn drop(&mut self) {
crate::state::ENCRYPTION_KEY.clear(&[]);
crate::state::set_encryption_enabled(false);
}
}
let (_tmp, _guard) = init_test_db();
let _vault = Vault;
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
let legacy = rt.block_on(derive_key(CRASH_PIN, &Kdf::Legacy));
let template = crate::db::get_current_account().unwrap();
crate::state::ENCRYPTION_KEY.set(legacy, &[]);
crate::state::set_encryption_enabled(true);
crate::db::set_sql_setting("encryption_enabled".to_string(), "true".to_string()).unwrap();
crate::db::set_sql_setting("security_type".to_string(), "pin".to_string()).unwrap();
crate::db::set_pkey(&crate::crypto::encrypt_with_key("nsec1crashaccount", &legacy).unwrap()).unwrap();
let (_, cid, ch) = saved_v2("Crash");
set_community_pins(&cid, &ch, r#"{"pins":["kept"]}"#, 1).unwrap();
let chat = crate::db::id_cache::get_or_create_chat_id(&make_test_npub(900_003)).unwrap();
{
let mut conn = crate::db::get_write_connection_guard_static().unwrap();
let tx = conn.transaction().unwrap();
for i in 0..20_000u32 {
tx.execute(
"INSERT INTO events (id, kind, chat_id, content, created_at, received_at) VALUES (?1, 14, ?2, ?3, ?4, ?4)",
rusqlite::params![format!("{i:064x}"), chat, crate::crypto::encrypt_with_key(&format!("message {i}"), &legacy).unwrap(), i],
).unwrap();
}
tx.commit().unwrap();
}
crate::db::close_database();
let root = crate::db::shared_test_data_dir().to_path_buf();
let copy_of_template = || -> String {
let npub = make_test_npub(TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
std::fs::create_dir_all(root.join(&npub)).unwrap();
for entry in std::fs::read_dir(root.join(&template)).unwrap().flatten() {
std::fs::copy(entry.path(), root.join(&npub).join(entry.file_name())).unwrap();
}
npub
};
let run_child = |npub: &str, after: Option<std::time::Duration>| -> std::time::Duration {
let mut child = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "db::community::tests::upgrade_crash_child", "--ignored", "--nocapture", "--test-threads=1"])
.env("VECTOR_CRASH_ROOT", &root)
.env("VECTOR_CRASH_NPUB", npub)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.spawn()
.unwrap();
let mut lines = std::io::BufReader::new(child.stdout.take().unwrap()).lines();
while let Some(Ok(line)) = lines.next() {
if line.contains("CHILD READY") {
break;
}
}
let ready = std::time::Instant::now();
match after {
Some(delay) => {
std::thread::sleep(delay);
let _ = child.kill();
}
None => {
while let Some(Ok(line)) = lines.next() {
if line.contains("CHILD DONE") {
break;
}
}
}
}
let _ = child.wait();
ready.elapsed()
};
let verify = |npub: &str| -> bool {
crate::db::set_current_account(npub.to_string()).unwrap();
crate::db::init_database(npub).unwrap();
let kdf = Kdf::of_account().unwrap();
let key = rt.block_on(derive_key(CRASH_PIN, &kdf));
crate::state::ENCRYPTION_KEY.set(key, &[]);
let pkey = crate::db::get_pkey().unwrap().unwrap();
assert_eq!(crate::crypto::decrypt_with_key(&pkey, &key).unwrap(), "nsec1crashaccount", "{npub}: the stored key opens");
assert_eq!(get_community_pins(&cid, &ch).unwrap().map(|p| p.0).as_deref(), Some(r#"{"pins":["kept"]}"#));
let conn = crate::db::get_db_connection_guard_static().unwrap();
let mut stmt = conn.prepare("SELECT content FROM events WHERE chat_id = ?1").unwrap();
let unopened = stmt
.query_map([chat], |r| r.get::<_, String>(0)).unwrap()
.flatten()
.filter(|c| crate::crypto::decrypt_with_key(c, &key).is_err())
.count();
assert_eq!(unopened, 0, "{npub}: every message opens under the recorded derivation");
!kdf.is_legacy()
};
let first = copy_of_template();
let whole = run_child(&first, None);
assert!(verify(&first), "an uninterrupted run upgrades");
let mut outcomes = (0, 0);
let mut trace = String::new();
for step in 0..24u32 {
let npub = copy_of_template();
run_child(&npub, Some(whole * step / 21));
let upgraded = verify(&npub);
trace.push(if upgraded { 'U' } else { 'L' });
if upgraded { outcomes.1 += 1 } else { outcomes.0 += 1 }
}
println!("kill outcomes in time order: {trace}");
println!("crash sweep over a {whole:?} transaction: {} left legacy, {} upgraded", outcomes.0, outcomes.1);
assert!(outcomes.0 >= 10, "most kills land inside the transaction and roll it back");
assert!(outcomes.1 > 0, "and the sweep reaches past the commit");
}
#[test]
fn the_key_derivation_moves_with_every_migration() {
use crate::crypto::Kdf;
use crate::db::at_rest;
struct Vault;
impl Drop for Vault {
fn drop(&mut self) {
crate::state::ENCRYPTION_KEY.clear(&[]);
crate::state::set_encryption_enabled(false);
}
}
let (_tmp, _guard) = init_test_db();
let _vault = Vault;
assert_eq!(Kdf::of_account().unwrap(), Kdf::Legacy, "no row reads as the legacy salt");
save_community_v2(&v2_fixture("K", &[])).unwrap();
let (k1, key1) = (Kdf::fresh(), [0x51; 32]);
at_rest::enable(&key1, &k1, "pin", None, None, &|_| {}).unwrap();
assert_eq!(Kdf::of_account().unwrap(), k1);
let (k2, key2) = (Kdf::fresh(), [0x52; 32]);
assert!(at_rest::rekey(&[0x5F; 32], &key2, &k2, "pin", None, &|_| {}).is_err());
assert_eq!(Kdf::of_account().unwrap(), k1, "a refused change keeps the derivation");
at_rest::rekey(&key1, &key2, &k2, "pin", None, &|_| {}).unwrap();
assert_eq!(Kdf::of_account().unwrap(), k2);
at_rest::disable(&key2, &|_| {}).unwrap();
assert_eq!(Kdf::of_account().unwrap(), Kdf::Legacy, "a plaintext store keeps no derivation");
let k3 = Kdf::fresh();
let sealed = crate::crypto::encrypt_with_key("nsec1setup", &[0x53; 32]).unwrap();
crate::db::settings::commit_account_setup(&sealed, true, Some("pin"), None, None, k3.descriptor().as_deref()).unwrap();
assert_eq!(Kdf::of_account().unwrap(), k3, "setup records the salt with the key it sealed");
}
#[test]
fn the_identity_opens_under_the_users_proof_and_nothing_else() {
use crate::crypto::{derive_key, Kdf};
use crate::db::at_rest::{self, open_identity_secrets, CREDENTIAL_INCORRECT};
struct Vault;
impl Drop for Vault {
fn drop(&mut self) {
crate::state::ENCRYPTION_KEY.clear(&[]);
crate::state::set_encryption_enabled(false);
}
}
let (_tmp, _guard) = init_test_db();
let _vault = Vault;
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
crate::db::set_pkey("nsec1identity").unwrap();
crate::db::set_seed("abandon ability able").unwrap();
let plain = open_identity_secrets(None).unwrap();
assert_eq!((plain.0.as_str(), plain.1.as_deref().map(|s| s.as_str())), ("nsec1identity", Some("abandon ability able")));
let kdf = Kdf::fresh();
let key = rt.block_on(derive_key("424242", &kdf));
at_rest::enable(&key, &kdf, "pin", None, None, &|_| {}).unwrap();
assert!(crate::state::ENCRYPTION_KEY.get().is_some(), "the session holds the key");
assert!(open_identity_secrets(None).is_err(), "a sealed store opens nothing on the session alone");
assert_eq!(rt.block_on(at_rest::prove_credential("000000")).unwrap_err(), CREDENTIAL_INCORRECT);
assert_eq!(open_identity_secrets(Some(&[0x09; 32])).unwrap_err(), CREDENTIAL_INCORRECT);
let proven = rt.block_on(at_rest::prove_credential("424242")).unwrap();
let (nsec, seed) = open_identity_secrets(Some(&proven)).unwrap();
assert_eq!((nsec.as_str(), seed.as_deref().map(|s| s.as_str())), ("nsec1identity", Some("abandon ability able")));
for _ in 0..4 {
assert_eq!(rt.block_on(at_rest::prove_credential("000000")).unwrap_err(), CREDENTIAL_INCORRECT);
}
assert_eq!(rt.block_on(at_rest::prove_credential("000000")).unwrap_err(), CREDENTIAL_INCORRECT);
let locked = rt.block_on(at_rest::prove_credential("424242")).unwrap_err();
assert!(locked.starts_with("CREDENTIAL_LOCKED:"), "{locked}");
crate::db::remove_setting("credential_retry_at").unwrap();
rt.block_on(at_rest::prove_credential("424242")).unwrap();
assert!(crate::db::get_sql_setting("credential_failures".to_string()).unwrap().is_none());
let far = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_secs() + 86_400 * 30;
crate::db::set_sql_setting("credential_retry_at".to_string(), far.to_string()).unwrap();
let locked = rt.block_on(at_rest::prove_credential("424242")).unwrap_err();
let secs: u64 = locked.strip_prefix("CREDENTIAL_LOCKED:").unwrap().parse().unwrap();
assert!(secs <= 15 * 60, "{secs}");
crate::db::remove_setting("credential_retry_at").unwrap();
crate::db::set_seed("abandon ability able").unwrap();
assert_eq!(open_identity_secrets(Some(&proven)).unwrap().1.as_deref().map(|s| s.as_str()), Some("abandon ability able"));
crate::db::set_seed("deadbeef").unwrap();
let (nsec, seed) = open_identity_secrets(Some(&proven)).unwrap();
assert!(nsec.starts_with("nsec1") && seed.is_none());
}
#[test]
fn reads_racing_pin_changes_always_open() {
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
struct Vault;
impl Drop for Vault {
fn drop(&mut self) {
crate::state::ENCRYPTION_KEY.clear(&[]);
crate::state::set_encryption_enabled(false);
}
}
let (_tmp, _guard) = init_test_db();
let _vault = Vault;
let keys: Vec<[u8; 32]> = (0u8..31).map(|i| [0x90 + i; 32]).collect();
crate::state::ENCRYPTION_KEY.set(keys[0], &[]);
crate::state::set_encryption_enabled(true);
let (_, cid, ch) = saved_v2("Read");
let pinned = r#"{"pins":["kept"]}"#;
set_community_pins(&cid, &ch, pinned, 1).unwrap();
let stop = Arc::new(AtomicBool::new(false));
let (reads, garbled) = (Arc::new(AtomicU64::new(0)), Arc::new(AtomicU64::new(0)));
let reader = {
let (stop, reads, garbled, cid, ch) = (stop.clone(), reads.clone(), garbled.clone(), cid.clone(), ch.clone());
std::thread::spawn(move || {
while !stop.load(Ordering::SeqCst) {
let got = get_community_pins(&cid, &ch).unwrap().map(|(c, _)| c);
reads.fetch_add(1, Ordering::SeqCst);
if got.as_deref() != Some(pinned) {
garbled.fetch_add(1, Ordering::SeqCst);
}
}
})
};
for pair in keys.windows(2) {
crate::db::at_rest::rekey(&pair[0], &pair[1], &crate::crypto::Kdf::fresh(), "pin", None, &|_| {}).unwrap();
let seen = reads.load(Ordering::SeqCst);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
while reads.load(Ordering::SeqCst) < seen + 2 {
assert!(std::time::Instant::now() < deadline, "reads stopped completing across a PIN change");
std::thread::yield_now();
}
}
stop.store(true, Ordering::SeqCst);
reader.join().unwrap();
assert!(reads.load(Ordering::SeqCst) > 0);
assert_eq!(garbled.load(Ordering::SeqCst), 0, "no read across a PIN change came back unopened");
std::thread::sleep(std::time::Duration::from_millis(600));
assert!(!crate::state::PREVIOUS_AT_REST_KEY.has_key(), "the replaced key is wiped after its grace");
}
#[test]
fn writes_racing_pin_changes_land_on_the_final_key() {
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
struct Vault;
impl Drop for Vault {
fn drop(&mut self) {
crate::state::ENCRYPTION_KEY.clear(&[]);
crate::state::set_encryption_enabled(false);
}
}
let (_tmp, _guard) = init_test_db();
let _vault = Vault;
let keys: Vec<[u8; 32]> = (0u8..21).map(|i| [0x40 + i; 32]).collect();
crate::state::ENCRYPTION_KEY.set(keys[0], &[]);
crate::state::set_encryption_enabled(true);
let (_, cid, ch) = saved_v2("Race");
let stop = Arc::new(AtomicBool::new(false));
let last = Arc::new(AtomicU64::new(0));
let writer = {
let (stop, last, cid, ch) = (stop.clone(), last.clone(), cid.clone(), ch.clone());
std::thread::spawn(move || {
let mut i = 0u64;
while !stop.load(Ordering::SeqCst) {
i += 1;
set_community_pins(&cid, &ch, &format!("{{\"v\":{i}}}"), i as i64).unwrap();
merge_community_ban_marks(&cid, &[(format!("npub{i}"), i)].into_iter().collect()).unwrap();
last.store(i, Ordering::SeqCst);
}
})
};
while last.load(Ordering::SeqCst) == 0 {
std::thread::yield_now();
}
for pair in keys.windows(2) {
crate::db::at_rest::rekey(&pair[0], &pair[1], &crate::crypto::Kdf::fresh(), "pin", None, &|_| {}).unwrap();
}
stop.store(true, Ordering::SeqCst);
writer.join().unwrap();
let n = last.load(Ordering::SeqCst);
assert_eq!(get_community_pins(&cid, &ch).unwrap(), Some((format!("{{\"v\":{n}}}"), n as i64)));
let marks = get_community_ban_marks(&cid).unwrap();
assert_eq!(marks.len() as u64, n, "every merged mark survives the key changes");
}
#[test]
fn a_v2_link_counts_the_members_who_joined_through_it() {
use crate::community::v2::guestbook::{GuestbookEntry, GuestbookEvent};
let (_tmp, _guard) = init_test_db();
let owner = nostr_sdk::prelude::Keys::generate();
let g = crate::community::v2::control::genesis(
&owner,
crate::community::v2::control::CommunityMetadata { name: "Hub".into(), ..Default::default() },
1_000,
)
.unwrap();
let v2 = crate::community::v2::community::CommunityV2::from_genesis(&g, "Hub", None, vec!["wss://r".into()], 1_000);
save_community_v2(&v2).unwrap();
let cid = v2.id().to_hex();
let me = owner.public_key();
let someone_else = nostr_sdk::prelude::Keys::generate().public_key();
let (a, b, c) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
let join = |n: u8, member: PublicKey, by: Option<(String, &str)>| GuestbookEvent {
epoch: None,
observed_at: None,
rumor_id: [n; 32],
entry: GuestbookEntry::Join { member, invited_by: by.map(|(c, l)| (c, l.to_string())), at_ms: n as u64 },
};
let events = vec![
join(1, a, Some((me.to_hex(), "hub"))),
join(2, b, Some((me.to_bech32().unwrap(), "hub"))),
join(3, a, Some((me.to_hex(), "hub"))),
join(4, c, Some((me.to_hex(), ""))),
join(5, c, Some((someone_else.to_hex(), "hub"))),
join(6, b, None),
];
set_guestbook(&cid, &events, 9).unwrap();
let counts = community_invite_join_counts(&cid, &me).unwrap();
assert_eq!(counts.get("hub"), Some(&2), "a rejoin counts once, either spelling of the creator counts");
assert_eq!(counts.get(""), Some(&1), "an unlabeled link's joins are kept apart");
assert_eq!(counts.len(), 2, "another creator's link and a bare join count for nobody here");
}
#[test]
fn a_group_chat_becomes_a_community_with_a_second_channel_or_an_invite_link() {
let (_tmp, _guard) = init_test_db();
let is = |c: &crate::community::v2::community::CommunityV2| crate::notify::is_community(&c.id().to_hex());
let mut chat = v2_fixture("Friends", &["wss://r"]);
save_community_v2(&chat).unwrap();
assert!(!is(&chat), "one channel, no link: a group chat");
assert_eq!(crate::notify::default_level(Some(&chat.id().to_hex())), crate::notify::NotifyLevel::All);
let mut second = chat.channels[0].clone();
second.id = crate::community::ChannelId([0x42; 32]);
second.name = "random".into();
chat.channels.push(second);
save_community_v2(&chat).unwrap();
assert!(is(&chat), "a second channel makes it a community");
assert_eq!(crate::notify::default_level(Some(&chat.id().to_hex())), crate::notify::NotifyLevel::Mentions);
let open = v2_fixture("Open", &["wss://r"]);
save_community_v2(&open).unwrap();
assert!(!is(&open));
set_community_invite_registry(&open.id().to_hex(), &["loc1".into()]).unwrap();
assert!(is(&open), "an invite link makes it a community");
set_community_invite_registry(&open.id().to_hex(), &[]).unwrap();
assert!(!is(&open), "revoking the last link makes it a group chat again");
assert_eq!(crate::notify::default_level(None), crate::notify::NotifyLevel::All, "a DM rings for everything");
}
#[test]
fn every_encrypting_writer_is_covered_by_the_at_rest_sweep() {
use crate::db::at_rest;
const K: [u8; 32] = [0x31; 32];
const K2: [u8; 32] = [0x32; 32];
const WRONG: [u8; 32] = [0x39; 32];
struct Vault;
impl Drop for Vault {
fn drop(&mut self) {
crate::state::ENCRYPTION_KEY.clear(&[]);
crate::state::set_encryption_enabled(false);
}
}
let (_tmp, _guard) = init_test_db();
let _vault = Vault;
crate::state::ENCRYPTION_KEY.set(K, &[]);
crate::state::set_encryption_enabled(true);
let mut v2 = v2_fixture("HQ", &["wss://r"]);
v2.description = Some("about".into());
let image = |url: &str| crate::community::v2::control::ImageRef {
url: url.into(), key: "0".repeat(64), nonce: "1".repeat(32), hash: "a".repeat(64), extra: Default::default(),
};
v2.icon = Some(image("https://blossom.example/icon"));
v2.banner = Some(image("https://blossom.example/banner"));
v2.meta_custom = Some([("k".to_string(), serde_json::Value::from("v"))].into_iter().collect());
v2.channels[0].voice = Some(true);
v2.channels[0].meta_extra.insert("vnd".into(), serde_json::Value::from(7));
v2.channels.push(private_channel(0x61, 0x62));
save_community_v2(&v2).unwrap();
let cid = v2.id().to_hex();
let ch = v2.channels[0].id.to_hex();
let private = v2.channels[1].id.to_hex();
store_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 0, &v2.community_root).unwrap();
store_epoch_key(&cid, &private, 0, &[0x62; 32]).unwrap();
park_channel_key(&cid, &private, 3, &[0x33; 32], &"ab".repeat(32)).unwrap();
store_message_key("m1", "o1", &nostr_sdk::prelude::Keys::generate(), &["wss://r".into()]).unwrap();
let owner = nostr_sdk::prelude::Keys::generate();
store_wrap_owner("m1", "o1", &owner, &["wss://r".into()]).unwrap();
save_pending_invite(&"de".repeat(32), r#"{"bundle":1}"#, "npub1inviter", now_secs() + 3600).unwrap();
save_public_invite(&"ab".repeat(32), &cid, "https://vectorapp.io/invite#x", None, Some("Label")).unwrap();
set_community_policy(&cid, "p1", r#"{"format":1}"#, "hh", true, 0).unwrap();
merge_community_ban_marks(&cid, &[("npub1banned".to_string(), 5u64)].into_iter().collect()).unwrap();
set_community_roles(&cid, &crate::community::roles::CommunityRoles::default(), 1).unwrap();
set_community_invite_registry(&cid, &["loc1".into()]).unwrap();
replace_invite_link_sets(&cid, &[InviteLinkSetRow { creator_hex: "cd".repeat(32), locators: vec!["l1".into()] }]).unwrap();
set_guestbook(&cid, &[], 9).unwrap();
set_community_pins(&cid, &ch, r#"{"pins":["x"]}"#, 1).unwrap();
record_audit_local(&cid, "e1", 5, r#"{"action":"message_delete"}"#).unwrap();
let control_wrap = br#"{"kind":1059,"content":"a control wrap as a relay served it"}"#.to_vec();
store_control_wraps(&cid, &[0x77; 32], 1, 5, &[([0x11; 32], 5, Some(control_wrap.clone())), ([0x12; 32], 6, None)]).unwrap();
let control_wraps = || control_wrap_page(&cid, &[0x77; 32], None, 10).unwrap();
assert_eq!(control_wraps(), vec![([0x11; 32], 5, control_wrap.clone())]);
let on_disk: Vec<u8> = crate::db::get_db_connection_guard_static().unwrap()
.query_row("SELECT wrap FROM community_control_wraps WHERE wrap IS NOT NULL", [], |r| r.get(0)).unwrap();
assert_ne!(on_disk, control_wrap, "a held Control wrap is sealed on disk");
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
let dm_chat = make_test_npub(900_000);
let dm = crate::types::Message {
id: "a1".repeat(32),
content: "the message itself".into(),
at: 1_700_000_000_000,
mine: true,
preview_metadata: Some(crate::types::SiteMetadata {
domain: "example.com".into(), og_title: Some("A title".into()), og_description: None,
og_image: None, og_url: Some("https://example.com/a".into()), og_type: None,
title: None, description: None, favicon: None,
}),
attachments: vec![crate::types::Attachment {
id: "b2".repeat(32), key: "c3".repeat(32), nonce: "d4".repeat(16), extension: "jpg".into(),
name: "passport.jpg".into(), url: "https://blossom.example/x.jpg".into(), size: 42,
img_meta: Some(crate::types::ImageMetadata { thumbhash: "thumb".into(), width: 4, height: 3 }),
fallback_urls: vec!["https://mirror.example/x.jpg".into()],
..Default::default()
}],
..Default::default()
};
rt.block_on(crate::db::events::save_message(&dm_chat, &dm)).unwrap();
let dm_chat_int = crate::db::id_cache::get_or_create_chat_id(&dm_chat).unwrap();
let (wrap, rumor) = {
use crate::event_ext::FinalizeUnsignedWithId;
use nostr_sdk::prelude::*;
let ephemeral = Keys::generate();
let wrap = EventBuilder::new(Kind::TextNote, "wrap").finalize(&ephemeral).unwrap();
let rumor = EventBuilder::new(Kind::PrivateDirectMessage, "still sending")
.finalize_unsigned_with_id(Keys::generate().public_key());
crate::db::nip17_keys::store_wrap_key(
&wrap.id, &rumor.id.unwrap(), &Keys::generate().public_key(),
crate::db::nip17_keys::WrapRole::Recipient, ephemeral.secret_key(), &[],
).unwrap();
(wrap, rumor)
};
crate::db::nip17_keys::stash_resend_payload(&wrap.id, "pending-1", &wrap, &rumor).unwrap();
crate::db::chats::hold_wallpaper(&dm_chat, 5, r#"{"url":"https://blossom.example/held-wallpaper"}"#).unwrap();
let kept = crate::db::media_store::StoredMedia {
hash: [0x5b; 32], file: "f".into(), key: "e5".repeat(32), nonce: "f6".repeat(16), blob_sha256: "aa".repeat(32),
pt_len: 9, mime: "image/png".into(), origin: crate::db::media_store::Origin::Received,
};
crate::db::media_store::insert(&kept).unwrap();
let (banned, allowed) = {
use nostr_sdk::prelude::ToBech32;
(nostr_sdk::prelude::Keys::generate().public_key(), nostr_sdk::prelude::Keys::generate().public_key().to_bech32().unwrap())
};
set_community_banlist(&cid, &[banned.to_hex()], 1).unwrap();
for (id, author) in [("c7", { use nostr_sdk::prelude::ToBech32; banned.to_bech32().unwrap() }), ("d8", allowed)] {
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() };
rt.block_on(crate::db::events::save_message(&ch, &msg)).unwrap();
}
let ch_int = crate::db::id_cache::get_or_create_chat_id(&ch).unwrap();
let read = || {
(
get_pending_channel_keys(&cid).unwrap().iter().map(|k| (k.key, k.sender.clone())).collect::<Vec<_>>(),
get_community_ban_marks(&cid).unwrap(),
get_community_pins(&cid, &ch).unwrap(),
load_community_v2(v2.id()).unwrap().map(|c| format!("{c:?}")),
(
held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap(),
held_epoch_keys(&cid, &private).unwrap(),
get_audit_local(&cid).unwrap(),
),
rt.block_on(crate::db::events::get_message_views(dm_chat_int, 10, 0)).unwrap()
.into_iter().map(|m| (m.content, m.preview_metadata, m.attachments)).collect::<Vec<_>>(),
crate::db::nip17_keys::get_resend_payload_by_pending("pending-1").unwrap().map(|p| p.rumor.content),
(
get_community_banlist(&cid).unwrap(),
rt.block_on(crate::db::events::get_message_views(ch_int, 10, 0)).unwrap().into_iter().map(|m| m.id).collect::<Vec<_>>(),
rt.block_on(crate::db::events::unread_count_for_chat(&ch)).unwrap(),
rt.block_on(crate::db::events::unread_counts()).unwrap().get(&ch).copied(),
),
wrap_owners("m1").unwrap().into_iter().map(|(k, outer, relays)| (k.public_key(), outer, relays)).collect::<Vec<_>>(),
crate::db::media_store::get(&[0x5b; 32]).unwrap(),
)
};
let before = read();
assert_eq!(before.8, vec![(owner.public_key(), "o1".to_string(), vec!["wss://r".to_string()])]);
assert_eq!(before.9.as_ref(), Some(&kept));
assert_eq!(before.0, vec![([0x33; 32], "ab".repeat(32))]);
assert_eq!(before.2, Some((r#"{"pins":["x"]}"#.to_string(), 1)));
assert_eq!(before.3, Some(format!("{v2:?}")));
assert_eq!(
before.4,
(vec![(Epoch(0), v2.community_root)], vec![(Epoch(0), [0x62; 32])], vec![("e1".to_string(), 5, r#"{"action":"message_delete"}"#.to_string())])
);
assert_eq!(before.5, vec![(String::new(), dm.preview_metadata.clone(), dm.attachments.clone())]);
assert_eq!(before.6.as_deref(), Some("still sending"));
assert_eq!(before.7, (vec![banned.to_hex()], vec!["d8".repeat(32)], 1, Some(1)), "the banned author stays hidden");
let sealed: (String, String, String) = crate::db::get_db_connection_guard_static().unwrap().query_row(
"SELECT a.name || e.preview_metadata || e.content, w.rumor_json, a.key FROM attachments a, events e, nip17_wrap_keys w
WHERE e.id = a.event_id AND w.pending_id = 'pending-1'", [], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
).unwrap();
for plain in ["passport", "A title", "the message itself"] {
assert!(!sealed.0.contains(plain), "{plain} is sealed on disk");
}
assert!(!sealed.1.contains("still sending") && sealed.2 != "c3".repeat(32), "unconfirmed sends and file keys are sealed");
let held: String = crate::db::get_db_connection_guard_static().unwrap()
.query_row("SELECT payload FROM dm_held_wallpapers", [], |r| r.get(0)).unwrap();
assert!(!held.contains("held-wallpaper"), "a held wallpaper is sealed on disk");
{
let conn = crate::db::get_write_connection_guard_static().unwrap();
let tx = conn.unchecked_transaction().unwrap();
at_rest::rekey_listed_in_tx(&tx, &K, &K2, &|_| {}).unwrap();
assert_eq!(
at_rest::sweep_residue_in_tx(&tx, &K, Some(&K2)).unwrap(),
0,
"the sweep list must name every column these writers encrypt"
);
}
assert!(at_rest::rekey(&WRONG, &K2, &crate::crypto::Kdf::fresh(), "pin", None, &|_| {}).is_err(), "a key the store does not open is refused");
at_rest::rekey(&K, &K2, &crate::crypto::Kdf::fresh(), "pin", None, &|_| {}).unwrap();
crate::state::ENCRYPTION_KEY.set(K2, &[]);
assert_eq!(read(), before, "every value reads back after a PIN change");
assert_eq!(control_wraps(), vec![([0x11; 32], 5, control_wrap.clone())], "a held Control wrap moves with the key");
assert_eq!(control_wrap_counts(&cid, &[0x77; 32]).unwrap().1, 1, "and a refusal, which holds no body, stays as it was");
assert_eq!(
crate::db::chats::take_held_wallpaper(&dm_chat).unwrap().as_deref(),
Some(r#"{"url":"https://blossom.example/held-wallpaper"}"#),
"a held wallpaper moves with the key"
);
let mode = || crate::db::get_sql_setting("security_type".to_string()).unwrap();
at_rest::rekey(&K2, &K2, &crate::crypto::Kdf::of_account().unwrap(), "password", None, &|_| {}).unwrap();
assert_eq!((read(), mode().as_deref()), (before.clone(), Some("password")), "the same key on both sides only switches the mode");
let legacy_chat = crate::db::id_cache::get_or_create_chat_id(&make_test_npub(900_001)).unwrap();
let hexish = "ab".repeat(40);
{
let conn = crate::db::get_write_connection_guard_static().unwrap();
for (id, kind, content) in [("e5", 15, "old caption"), ("f6", 14, hexish.as_str())] {
conn.execute(
"INSERT INTO events (id, kind, chat_id, content, created_at, received_at) VALUES (?1, ?2, ?3, ?4, 1, 1)",
rusqlite::params![id.repeat(32), kind, legacy_chat, content],
).unwrap();
}
}
let flag = || crate::db::get_sql_setting("community_at_rest_encrypted".to_string()).unwrap();
crate::db::set_sql_setting("community_at_rest_encrypted".to_string(), "1".to_string()).unwrap();
crate::state::ENCRYPTION_KEY.set(WRONG, &[]);
assert!(at_rest::backfill_at_rest().is_err(), "the backfill never wraps under a key it cannot prove");
assert_eq!(flag().as_deref(), Some("1"));
crate::state::ENCRYPTION_KEY.set(K2, &[]);
at_rest::backfill_at_rest().unwrap();
assert_eq!((read(), flag().as_deref()), (before.clone(), Some("8")));
let stored = |id: &str| -> String {
crate::db::get_db_connection_guard_static().unwrap()
.query_row("SELECT content FROM events WHERE id = ?1", [id.repeat(32)], |r| r.get(0)).unwrap()
};
assert!(stored("e5") != "old caption" && stored("f6") != hexish, "the backfill seals legacy plaintext messages");
let legacy = rt.block_on(crate::db::events::get_message_views(legacy_chat, 10, 0)).unwrap();
assert!(legacy.iter().any(|m| m.content == hexish), "and they still read back");
assert!(at_rest::disable(&WRONG, &|_| {}).is_err(), "a wrong key never turns encryption off");
assert_eq!(read(), before);
at_rest::disable(&K2, &|_| {}).unwrap();
crate::state::ENCRYPTION_KEY.clear(&[]);
assert_eq!(read(), before, "every value reads back after Local Encryption is turned off");
}
}
pub fn set_community_pins(community_id: &str, channel_id: &str, content: &str, version: i64) -> Result<bool, String> {
let _seal = crate::crypto::gate::sealing();
let enc = enc_txt(content)?;
let conn = super::get_write_connection_guard_static()?;
let changed = conn
.execute(
"INSERT INTO community_pins (community_id, channel_id, content, version) VALUES (?1, ?2, ?3, ?4)
ON CONFLICT(community_id, channel_id) DO UPDATE SET
content = excluded.content, version = excluded.version
WHERE excluded.version >= community_pins.version",
params![community_id, channel_id, enc, version],
)
.map_err(|e| format!("set pins: {e}"))?;
Ok(changed > 0)
}
pub fn set_community_writers(community_id: &str, channel_id: &str, content: &str, version: i64, replace: bool) -> Result<bool, String> {
let _seal = crate::crypto::gate::sealing();
let enc = enc_txt(content)?;
let conn = super::get_write_connection_guard_static()?;
let old: Option<String> = conn
.query_row("SELECT content FROM community_writers WHERE community_id = ?1 AND channel_id = ?2", params![community_id, channel_id], |r| r.get(0))
.optional()
.map_err(|e| format!("get writers: {e}"))?
.map(|c: String| dec_txt(&c));
let changed = conn
.execute(
"INSERT INTO community_writers (community_id, channel_id, content, version) VALUES (?1, ?2, ?3, ?4)
ON CONFLICT(community_id, channel_id) DO UPDATE SET
content = excluded.content, version = excluded.version
WHERE ?5 OR excluded.version >= community_writers.version",
params![community_id, channel_id, enc, version, replace],
)
.map_err(|e| format!("set writers: {e}"))?;
if changed > 0 {
crate::community::v2::realtime::invalidate_held_v2_community(community_id);
if let Some(since) = retraction_since(old.as_deref(), content) {
owe_retraction(&conn, community_id, channel_id, since)?;
}
for (writer, since) in stop_owes(old.as_deref(), content) {
owe_author_retraction_on(&conn, community_id, channel_id, &crate::simd::hex::bytes_to_hex_32(&writer), since, None)?;
}
}
Ok(changed > 0)
}
pub(crate) fn retraction_since(old: Option<&str>, new: &str) -> Option<u64> {
use crate::community::v2::writers::{Ledger, Spell};
let new = Ledger::parse(new)?;
let old = old.and_then(Ledger::parse);
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)));
let front = new.entries.first().map_or(u64::MAX, |e| e.at);
let dropped = old.iter().flat_map(|o| o.entries.iter()).filter(|e| !matches!(e.spell, Spell::Other) && e.at >= front && !new.entries.contains(e));
added.chain(dropped).map(|e| e.effective()).min()
}
pub(crate) fn stop_owes(old: Option<&str>, new: &str) -> Vec<([u8; 32], u64)> {
use crate::community::v2::writers::{Ledger, Spell};
let Some(new) = Ledger::parse(new) else { return Vec::new() };
let old = old.and_then(Ledger::parse);
new.entries
.iter()
.filter(|e| !old.as_ref().is_some_and(|o| o.entries.contains(e)))
.filter_map(|e| match e.spell {
Spell::Stop { writer } => Some((writer, e.effective())),
_ => None,
})
.collect()
}
fn retraction_key(community_id: &str, channel_id: &str) -> String {
format!("writer_retract:{community_id}:{channel_id}")
}
fn parse_owed(value: &str) -> Option<(u64, u64)> {
let mut parts = value.split(':');
Some((parts.next()?.parse().ok()?, parts.next().and_then(|g| g.parse().ok()).unwrap_or(0)))
}
fn owe_retraction(conn: &rusqlite::Connection, community_id: &str, channel_id: &str, since: u64) -> Result<(), String> {
let key = retraction_key(community_id, channel_id);
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}"))?;
let (since, generation) = held.as_deref().and_then(parse_owed).map_or((since, 1), |(s, g)| (s.min(since), g + 1));
conn.execute("INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)", params![key, format!("{since}:{generation}")]).map_err(|e| format!("owe retraction: {e}"))?;
Ok(())
}
pub fn owe_writer_retraction(community_id: &str, channel_id: &str, since_ms: u64) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
owe_retraction(&conn, community_id, channel_id, since_ms)
}
pub fn owed_retractions(community_id: &str) -> Result<Vec<(String, u64, u64)>, String> {
let prefix = retraction_key(community_id, "");
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn.prepare("SELECT key, value FROM settings WHERE substr(key, 1, length(?1)) = ?1").map_err(|e| format!("owed retractions: {e}"))?;
let rows = stmt.query_map(params![prefix], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).map_err(|e| format!("owed retractions: {e}"))?;
Ok(rows.flatten().filter_map(|(k, v)| parse_owed(&v).map(|(since, generation)| (k[prefix.len()..].to_string(), since, generation))).collect())
}
fn legacy_author_retraction_range(community_id: &str) -> (String, String) {
(format!("writer_retract_by:{community_id}:"), format!("writer_retract_by:{community_id};"))
}
pub fn owe_author_retraction(community_id: &str, channel_id: &str, author: &str, since_ms: u64, until_ms: Option<u64>) -> Result<(), String> {
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
owe_author_retraction_on(&conn, community_id, channel_id, author, since_ms, until_ms)
}
fn parse_author_owed(value: &str) -> Option<(u64, u64, Option<u64>)> {
let mut parts = value.split(':');
let since = parts.next()?.parse().ok()?;
let generation = parts.next().and_then(|g| g.parse().ok()).unwrap_or(0);
let until = parts.next().and_then(|u| u.parse().ok());
Some((since, generation, until))
}
struct AuthorOwed {
seq: i64,
channel: String,
author: [u8; 32],
since: u64,
generation: u64,
until: Option<u64>,
}
fn author_owed_body(author: &[u8; 32], since: u64, generation: u64, until: Option<u64>) -> Vec<u8> {
let mut out = Vec::with_capacity(64);
out.push(1);
out.extend_from_slice(author);
varint(&mut out, since);
varint(&mut out, generation);
out.push(until.is_some() as u8);
if let Some(until) = until {
varint(&mut out, until);
}
out
}
fn author_owed_from_body(body: &[u8]) -> Option<([u8; 32], u64, u64, Option<u64>)> {
let (&1, rest) = body.split_first()? else { return None };
let (author, mut rest) = rest.split_at_checked(32)?;
let since = take_varint(&mut rest)?;
let generation = take_varint(&mut rest)?;
let (&flags, tail) = rest.split_first()?;
rest = tail;
let until = match flags {
0 => None,
1 => Some(take_varint(&mut rest)?),
_ => return None,
};
rest.is_empty().then_some((author.try_into().ok()?, since, generation, until))
}
fn held_author_retractions(conn: &rusqlite::Connection, community_id: &str, channel_id: Option<&str>) -> Result<Vec<AuthorOwed>, String> {
let rows: Vec<(i64, String, Vec<u8>)> = {
let mut stmt = conn
.prepare_cached(
"SELECT o.seq, o.channel_id, o.body FROM community_owed_authors o
JOIN community_guestbook_books b ON b.book = o.book
WHERE b.community_id = ?1 AND (?2 IS NULL OR o.channel_id = ?2) ORDER BY o.seq",
)
.map_err(|e| format!("owed retractions: {e}"))?;
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}"))?;
rows.filter_map(|r| r.ok()).collect()
};
Ok(crate::crypto::open_batch(|o| {
rows.into_iter()
.filter_map(|(seq, channel, body)| {
let (author, since, generation, until) = author_owed_from_body(&o.open_blob_or_keep(&body))?;
Some(AuthorOwed { seq, channel, author, since, generation, until })
})
.collect()
}))
}
fn has_legacy_author_retractions(conn: &rusqlite::Connection, community_id: &str) -> Result<bool, String> {
let (lo, hi) = legacy_author_retraction_range(community_id);
conn.query_row("SELECT 1 FROM settings WHERE key >= ?1 AND key < ?2 LIMIT 1", params![lo, hi], |_| Ok(()))
.optional()
.map(|r| r.is_some())
.map_err(|e| format!("owed retractions: {e}"))
}
fn move_author_retraction_settings(conn: &rusqlite::Connection, community_id: &str) -> Result<(), String> {
let (lo, hi) = legacy_author_retraction_range(community_id);
let legacy: Vec<(String, String)> = {
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}"))?;
let rows = stmt.query_map(params![lo, hi], |r| Ok((r.get(0)?, r.get(1)?))).map_err(|e| format!("move owed retractions: {e}"))?;
rows.filter_map(|r| r.ok()).collect()
};
if legacy.is_empty() {
return Ok(());
}
let book = guestbook_book(conn, community_id)?;
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}"))?;
crate::crypto::seal_batch(|sealer| {
for (key, value) in &legacy {
let Some((channel, author)) = key[lo.len()..].split_once(':') else { continue };
let (Some(author), Some((since, generation, until))) = (crate::simd::hex::hex_to_bytes_32_checked(author), parse_author_owed(value)) else { continue };
insert.execute(params![book, channel, sealer.seal_blob(&author_owed_body(&author, since, generation, until))?]).map_err(|e| format!("move owed retractions: {e}"))?;
}
Ok::<(), String>(())
})?;
conn.execute("DELETE FROM settings WHERE key >= ?1 AND key < ?2", params![lo, hi]).map_err(|e| format!("move owed retractions: {e}"))?;
Ok(())
}
fn in_savepoint<T>(conn: &rusqlite::Connection, f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
conn.execute_batch("SAVEPOINT owed_authors").map_err(|e| format!("owed retractions: {e}"))?;
match f() {
Ok(v) => {
conn.execute_batch("RELEASE owed_authors").map_err(|e| format!("owed retractions: {e}"))?;
Ok(v)
}
Err(e) => {
let _ = conn.execute_batch("ROLLBACK TO owed_authors; RELEASE owed_authors");
Err(e)
}
}
}
fn owe_author_retraction_on(conn: &rusqlite::Connection, community_id: &str, channel_id: &str, author: &str, since_ms: u64, until_ms: Option<u64>) -> Result<(), String> {
let author = crate::simd::hex::hex_to_bytes_32_checked(author).ok_or_else(|| format!("owe retraction: not an author key: {author}"))?;
in_savepoint(conn, || {
move_author_retraction_settings(conn, community_id)?;
let held = held_author_retractions(conn, community_id, Some(channel_id))?.into_iter().find(|o| o.author == author);
let (since, generation, until) = match &held {
Some(o) => (o.since.min(since_ms), o.generation + 1, match (o.until, until_ms) {
(Some(a), Some(b)) => Some(a.max(b)),
(None, Some(b)) if o.since == since_ms => Some(b),
_ => None,
}),
None => (since_ms, 1, until_ms),
};
let body = crate::crypto::seal_batch(|sealer| sealer.seal_blob(&author_owed_body(&author, since, generation, until)))?;
match held {
Some(o) => conn.execute("UPDATE community_owed_authors SET body = ?1 WHERE seq = ?2", params![body, o.seq]),
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]),
}
.map_err(|e| format!("owe retraction: {e}"))?;
Ok(())
})
}
pub fn owed_author_retractions(community_id: &str) -> Result<Vec<(String, String, u64, Option<u64>, u64)>, String> {
if has_legacy_author_retractions(&*super::get_db_connection_guard_static()?, community_id)? {
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
in_savepoint(&conn, || move_author_retraction_settings(&conn, community_id))?;
}
let mut owed: Vec<_> = held_author_retractions(&*super::get_db_connection_guard_static()?, community_id, None)?
.into_iter()
.map(|o| (o.channel, crate::simd::hex::bytes_to_hex_32(&o.author), o.since, o.until, o.generation))
.collect();
owed.sort_by(|a, b| (&a.0, &a.1).cmp(&(&b.0, &b.1)));
Ok(owed)
}
pub fn settle_author_retraction(community_id: &str, channel_id: &str, author: &str, since: u64, until: Option<u64>, generation: u64) -> Result<(), String> {
let Some(author) = crate::simd::hex::hex_to_bytes_32_checked(author) else { return Ok(()) };
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
in_savepoint(&conn, || {
move_author_retraction_settings(&conn, community_id)?;
let done = held_author_retractions(&conn, community_id, Some(channel_id))?
.into_iter()
.filter(|o| o.author == author && o.since == since && o.until == until && o.generation == generation);
for o in done {
conn.execute("DELETE FROM community_owed_authors WHERE seq = ?1", params![o.seq]).map_err(|e| format!("settle retraction: {e}"))?;
}
Ok(())
})
}
pub type DepartureSpans = std::collections::BTreeMap<PublicKey, std::sync::Arc<[crate::community::v2::guestbook::Span]>>;
#[derive(Default)]
pub struct DeparturesSeen {
pub spans: std::sync::Arc<DepartureSpans>,
rows: Vec<i64>,
}
type DeparturesSeenCache = Parsed<std::sync::Arc<DeparturesSeen>, 8>;
fn departures_seen_cache() -> std::sync::Arc<std::sync::Mutex<DeparturesSeenCache>> {
struct Key;
super::current_session().scoped::<Key, std::sync::Mutex<DeparturesSeenCache>>()
}
fn legacy_departures_key(community_id: &str) -> String {
format!("departures_seen:{community_id}")
}
pub fn departures_seen(community_id: &str) -> Result<std::sync::Arc<DeparturesSeen>, String> {
let cache = departures_seen_cache();
let generation = {
let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
if let Some(hit) = held.get(community_id) {
return Ok(hit);
}
held.generation(community_id)
};
let legacy = super::get_db_connection_guard_static()?
.query_row("SELECT 1 FROM settings WHERE key = ?1", params![legacy_departures_key(community_id)], |_| Ok(()))
.optional()
.map_err(|e| format!("load departures: {e}"))?
.is_some();
if legacy {
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
let tx = conn.unchecked_transaction().map_err(|e| format!("move departures tx: {e}"))?;
move_departures_setting(&tx, community_id)?;
tx.commit().map_err(|e| format!("move departures commit: {e}"))?;
}
let seen = std::sync::Arc::new(read_departures(&*super::get_db_connection_guard_static()?, community_id)?);
cache.lock().unwrap_or_else(|e| e.into_inner()).put(community_id, generation, seen.clone());
Ok(seen)
}
fn read_departures(conn: &rusqlite::Connection, community_id: &str) -> Result<DeparturesSeen, String> {
let rows: Vec<(i64, Vec<u8>)> = {
let mut stmt = conn
.prepare_cached(
"SELECT d.seq, d.body FROM community_departures_seen d
JOIN community_guestbook_books b ON b.book = d.book
WHERE b.community_id = ?1 ORDER BY d.seq",
)
.map_err(|e| format!("load departures: {e}"))?;
let rows = stmt.query_map(params![community_id], |r| Ok((r.get(0)?, r.get(1)?))).map_err(|e| format!("load departures: {e}"))?;
rows.filter_map(|r| r.ok()).collect()
};
let held: std::collections::BTreeMap<PublicKey, (i64, Vec<crate::community::v2::guestbook::Span>)> = crate::crypto::open_batch(|o| {
rows.into_iter().filter_map(|(seq, body)| departure_from_body(&o.open_blob_or_keep(&body)).map(|(member, owed)| (member, (seq, owed)))).collect()
});
let rows = held.values().map(|(seq, _)| *seq).collect();
Ok(DeparturesSeen { spans: std::sync::Arc::new(held.into_iter().map(|(member, (_, owed))| (member, owed.into())).collect()), rows })
}
fn move_departures_setting(tx: &rusqlite::Connection, community_id: &str) -> Result<(), String> {
let key = legacy_departures_key(community_id);
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 {
return Ok(());
};
let by_hex: std::collections::BTreeMap<String, Vec<crate::community::v2::guestbook::Span>> = serde_json::from_str(&json).unwrap_or_default();
let book = guestbook_book(tx, community_id)?;
let mut stmt = tx.prepare_cached("INSERT INTO community_departures_seen (book, body) VALUES (?1, ?2)").map_err(|e| format!("move departures: {e}"))?;
crate::crypto::seal_batch(|sealer| {
for (member, owed) in by_hex.iter().filter_map(|(k, v)| Some((PublicKey::from_hex(k).ok()?, v))) {
stmt.execute(params![book, sealer.seal_blob(&departure_body(&member, owed))?]).map_err(|e| format!("move departures: {e}"))?;
}
Ok::<(), String>(())
})?;
tx.execute("DELETE FROM settings WHERE key = ?1", params![key]).map_err(|e| format!("move departures: {e}"))?;
Ok(())
}
pub fn set_departures_seen(community_id: &str, now: std::sync::Arc<DepartureSpans>) -> Result<(), String> {
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
let tx = conn.unchecked_transaction().map_err(|e| format!("store departures tx: {e}"))?;
move_departures_setting(&tx, community_id)?;
let cache = departures_seen_cache();
let cached = cache.lock().unwrap_or_else(|e| e.into_inner()).get(community_id);
let held = match cached {
Some(held) => held,
None => std::sync::Arc::new(read_departures(&tx, community_id)?),
};
let book = guestbook_book(&tx, community_id)?;
let mut rows = Vec::with_capacity(now.len());
{
let mut update = tx.prepare_cached("UPDATE community_departures_seen SET body = ?1 WHERE seq = ?2").map_err(|e| format!("store departures: {e}"))?;
let mut insert = tx.prepare_cached("INSERT INTO community_departures_seen (book, body) VALUES (?1, ?2)").map_err(|e| format!("store departures: {e}"))?;
let mut delete = tx.prepare_cached("DELETE FROM community_departures_seen WHERE seq = ?1").map_err(|e| format!("store departures: {e}"))?;
let mut was = held.spans.iter().zip(held.rows.iter().copied()).peekable();
crate::crypto::seal_batch(|sealer| {
for (member, owed) in now.iter() {
while let Some((_, seq)) = was.next_if(|((m, _), _)| *m < member) {
delete.execute(params![seq]).map_err(|e| format!("store departures: {e}"))?;
}
let seq = match was.next_if(|((m, _), _)| *m == member) {
Some(((_, before), seq)) if before == owed => seq,
Some((_, seq)) => {
update.execute(params![sealer.seal_blob(&departure_body(member, owed))?, seq]).map_err(|e| format!("store departures: {e}"))?;
seq
}
None => {
insert.execute(params![book, sealer.seal_blob(&departure_body(member, owed))?]).map_err(|e| format!("store departures: {e}"))?;
tx.last_insert_rowid()
}
};
rows.push(seq);
}
for (_, seq) in was.by_ref() {
delete.execute(params![seq]).map_err(|e| format!("store departures: {e}"))?;
}
Ok::<(), String>(())
})?;
}
tx.commit().map_err(|e| format!("store departures commit: {e}"))?;
let mut cached = cache.lock().unwrap_or_else(|e| e.into_inner());
let generation = cached.moved(community_id);
cached.put(community_id, generation, std::sync::Arc::new(DeparturesSeen { spans: now, rows }));
Ok(())
}
fn varint(out: &mut Vec<u8>, mut v: u64) {
while v >= 0x80 {
out.push(v as u8 | 0x80);
v >>= 7;
}
out.push(v as u8);
}
fn take_varint(rest: &mut &[u8]) -> Option<u64> {
let mut v = 0u64;
for shift in (0..64).step_by(7) {
let (&b, tail) = rest.split_first()?;
*rest = tail;
v |= ((b & 0x7f) as u64).checked_shl(shift)?;
if b & 0x80 == 0 {
return Some(v);
}
}
None
}
fn departure_body(member: &PublicKey, spans: &[crate::community::v2::guestbook::Span]) -> Vec<u8> {
let mut out = Vec::with_capacity(34 + spans.len() * 13);
out.push(1);
out.extend_from_slice(member.as_bytes());
varint(&mut out, spans.len() as u64);
for &(from, until, kicked) in spans {
out.push(until.is_some() as u8 | (kicked as u8) << 1);
varint(&mut out, from);
if let Some(until) = until {
varint(&mut out, until);
}
}
out
}
fn departure_from_body(body: &[u8]) -> Option<(PublicKey, Vec<crate::community::v2::guestbook::Span>)> {
let (&1, rest) = body.split_first()? else { return None };
let (member, mut rest) = rest.split_at_checked(32)?;
let member = PublicKey::from_byte_array(member.try_into().ok()?);
let count = take_varint(&mut rest)?;
if count > rest.len() as u64 / 2 {
return None;
}
let mut spans = Vec::with_capacity(count as usize);
for _ in 0..count {
let (&flags, tail) = rest.split_first()?;
rest = tail;
if flags & !0b11 != 0 {
return None;
}
let from = take_varint(&mut rest)?;
let until = if flags & 1 != 0 { Some(take_varint(&mut rest)?) } else { None };
spans.push((from, until, flags & 2 != 0));
}
rest.is_empty().then_some((member, spans))
}
pub fn settle_retraction(community_id: &str, channel_id: &str, since: u64, generation: u64) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
conn.execute("DELETE FROM settings WHERE key = ?1 AND value = ?2", params![retraction_key(community_id, channel_id), format!("{since}:{generation}")])
.map_err(|e| format!("settle retraction: {e}"))?;
Ok(())
}
pub fn get_community_writers(community_id: &str, channel_id: &str) -> Result<Option<(String, i64)>, String> {
let conn = super::get_db_connection_guard_static()?;
let row: Option<(String, i64)> = conn
.query_row(
"SELECT content, version FROM community_writers WHERE community_id = ?1 AND channel_id = ?2",
params![community_id, channel_id],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()
.map_err(|e| format!("get writers: {e}"))?;
Ok(row.map(|(content, version)| (dec_txt(&content), version)))
}
pub const MAX_HELD_WRAPS: usize = 500;
pub const MAX_HELD_BYTES: usize = 4 * 1024 * 1024;
pub const MAX_HELD_PER_AUTHOR: usize = MAX_HELD_WRAPS / 10;
pub const MAX_HELD_COMMUNITY_BYTES: usize = 16 * 1024 * 1024;
pub const HELD_HORIZON_MS: u64 = 60 * 60 * 1000;
pub fn hold_wrap(community_id: &str, channel_id: &str, wrap_id: &str, wrap: &str, author: &str, at_ms: u64) -> Result<bool, String> {
let now = now_secs().max(0) as u64 * 1000;
if at_ms > now.saturating_add(HELD_HORIZON_MS) {
let held = deferred();
let mut map = held.lock().unwrap_or_else(|e| e.into_inner());
map.insert(wrap_id.to_string(), at_ms);
if map.len() > MAX_DEFERRED {
if let Some(furthest) = map.iter().max_by_key(|(_, at)| **at).map(|(id, _)| id.clone()) {
map.remove(&furthest);
}
}
return Ok(false);
}
let _seal = crate::crypto::gate::sealing();
let enc = enc_txt(wrap)?;
let conn = super::get_write_connection_guard_static()?;
conn.execute(
"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)",
params![wrap_id, community_id, channel_id, enc, at_ms as i64, author, enc.len() as i64],
)
.map_err(|e| format!("hold wrap: {e}"))?;
let ranked: Vec<(String, String, String, usize)> = {
let mut stmt = conn
.prepare("SELECT wrap_id, channel_id, author, bytes FROM community_held_wraps WHERE community_id = ?1 ORDER BY ABS(at_ms - ?2), wrap_id")
.map_err(|e| format!("rank held wraps: {e}"))?;
let rows = stmt
.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)))
.map_err(|e| format!("rank held wraps: {e}"))?;
rows.flatten().collect()
};
let (mut channels, mut authors) = (std::collections::HashMap::<&str, (usize, usize)>::new(), std::collections::HashMap::<(&str, &str), usize>::new());
let mut evicted: Vec<&String> = Vec::new();
let mut kept: Vec<(&String, &str, usize)> = Vec::new();
for (id, ch, who, len) in &ranked {
let c = channels.entry(ch.as_str()).or_default();
let a = authors.entry((ch.as_str(), who.as_str())).or_default();
if c.0 >= MAX_HELD_WRAPS || c.1 + len > MAX_HELD_BYTES || (!who.is_empty() && *a >= MAX_HELD_PER_AUTHOR) {
evicted.push(id);
continue;
}
c.0 += 1;
c.1 += len;
*a += 1;
kept.push((id, ch.as_str(), *len));
}
let mut total: usize = kept.iter().map(|k| k.2).sum();
while total > MAX_HELD_COMMUNITY_BYTES {
let most = channels.values().map(|c| c.1).max().unwrap_or(0);
let Some(i) = kept.iter().rposition(|k| channels.get(k.1).is_some_and(|c| c.1 == most)) else { break };
let (id, ch, len) = kept.remove(i);
if let Some(c) = channels.get_mut(ch) {
c.1 -= len;
}
total -= len;
evicted.push(id);
}
for id in &evicted {
conn.execute("DELETE FROM community_held_wraps WHERE wrap_id = ?1", params![id]).map_err(|e| format!("trim held wraps: {e}"))?;
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}"))?;
}
Ok(!evicted.iter().any(|id| *id == wrap_id))
}
pub type ControlWrapRow = ([u8; 32], u64, Option<Vec<u8>>);
pub fn control_wrap_ids(community_id: &str, view: &[u8; 32]) -> Result<Vec<([u8; 32], u64)>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare_cached("SELECT wrap_id, created_at FROM community_control_wraps WHERE community_id = ?1 AND view = ?2")
.map_err(|e| format!("control wrap ids: {e}"))?;
let rows = stmt
.query_map(params![community_id, &view[..]], |r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, i64>(1)?)))
.map_err(|e| format!("control wrap ids: {e}"))?;
let mut out = Vec::new();
for row in rows {
let (id, at) = row.map_err(|e| format!("control wrap ids: {e}"))?;
out.push((id.try_into().map_err(|_| "control wrap ids: a wrap id is not 32 bytes".to_string())?, at.max(0) as u64));
}
Ok(out)
}
pub fn store_control_wraps(community_id: &str, view: &[u8; 32], rules: u32, now_secs: u64, rows: &[ControlWrapRow]) -> Result<usize, String> {
if rows.is_empty() {
return Ok(0);
}
let _seal = crate::crypto::gate::sealing();
let conn = super::get_write_connection_guard_static()?;
let tx = conn.unchecked_transaction().map_err(|e| format!("store control wraps tx: {e}"))?;
let mut stored = 0usize;
{
let mut stmt = tx
.prepare_cached(
"INSERT OR IGNORE INTO community_control_wraps (community_id, view, wrap_id, created_at, wrap, rules, judged_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
)
.map_err(|e| format!("store control wraps: {e}"))?;
crate::crypto::seal_batch(|sealer| -> Result<(), String> {
for (id, at, body) in rows {
let sealed = body.as_deref().map(|b| sealer.seal_blob(b)).transpose()?;
stored += stmt
.execute(params![community_id, &view[..], &id[..], *at as i64, sealed, rules, now_secs as i64])
.map_err(|e| format!("store control wraps: {e}"))?;
}
Ok(())
})?;
}
tx.commit().map_err(|e| format!("store control wraps commit: {e}"))?;
Ok(stored)
}
pub 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> {
let rows: Vec<(Vec<u8>, i64, Vec<u8>)> = {
let conn = super::get_db_connection_guard_static()?;
let (at, id) = below.map_or((i64::MAX, vec![0xff; 33]), |(at, id)| (at as i64, id.to_vec()));
let mut stmt = conn
.prepare_cached(
"SELECT wrap_id, created_at, wrap FROM community_control_wraps
WHERE community_id = ?1 AND view = ?2 AND wrap IS NOT NULL AND (created_at, wrap_id) < (?3, ?4)
ORDER BY created_at DESC, wrap_id DESC LIMIT ?5",
)
.map_err(|e| format!("control wrap page: {e}"))?;
let rows = stmt
.query_map(params![community_id, &view[..], at, id, limit as i64], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
.map_err(|e| format!("control wrap page: {e}"))?;
rows.collect::<Result<_, _>>().map_err(|e| format!("control wrap page: {e}"))?
};
crate::crypto::open_batch(|o| {
rows.into_iter()
.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))))
.collect()
})
}
pub fn control_wrap_bodies(community_id: &str, view: &[u8; 32], ids: &[[u8; 32]]) -> Result<Vec<Vec<u8>>, String> {
let mut sealed: Vec<Vec<u8>> = Vec::with_capacity(ids.len());
{
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare_cached("SELECT wrap FROM community_control_wraps WHERE community_id = ?1 AND view = ?2 AND wrap_id = ?3 AND wrap IS NOT NULL")
.map_err(|e| format!("control wrap bodies: {e}"))?;
for id in ids {
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}"))? {
sealed.push(body);
}
}
}
crate::crypto::open_batch(|o| Ok(sealed.iter().map(|body| o.open_blob_or_keep(body)).collect()))
}
pub fn control_wrap_counts(community_id: &str, view: &[u8; 32]) -> Result<(usize, usize, usize), String> {
let conn = super::get_db_connection_guard_static()?;
conn.query_row(
"SELECT COUNT(wrap), COUNT(*) - COUNT(wrap), COALESCE(SUM(length(wrap)), 0) FROM community_control_wraps WHERE community_id = ?1 AND view = ?2",
params![community_id, &view[..]],
|r| Ok((r.get::<_, i64>(0)? as usize, r.get::<_, i64>(1)? as usize, r.get::<_, i64>(2)? as usize)),
)
.map_err(|e| format!("control wrap counts: {e}"))
}
pub fn guestbook_wrap_ids(community_id: &str, plane: &[u8; 32]) -> Result<Vec<([u8; 32], u64)>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare_cached("SELECT wrap_id, created_at FROM community_guestbook_wraps WHERE community_id = ?1 AND plane = ?2")
.map_err(|e| format!("guestbook wrap ids: {e}"))?;
let rows = stmt
.query_map(params![community_id, &plane[..]], |r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, i64>(1)?)))
.map_err(|e| format!("guestbook wrap ids: {e}"))?;
let mut out = Vec::new();
for row in rows {
let (id, at) = row.map_err(|e| format!("guestbook wrap ids: {e}"))?;
out.push((id.try_into().map_err(|_| "guestbook wrap ids: a wrap id is not 32 bytes".to_string())?, at.max(0) as u64));
}
Ok(out)
}
pub fn store_guestbook_wraps(community_id: &str, plane: &[u8; 32], now_secs: u64, rows: &[([u8; 32], u64, u32)]) -> Result<(), String> {
if rows.is_empty() {
return Ok(());
}
let conn = super::get_write_connection_guard_static()?;
let tx = conn.unchecked_transaction().map_err(|e| format!("store guestbook wraps tx: {e}"))?;
{
let mut stmt = tx
.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)")
.map_err(|e| format!("store guestbook wraps: {e}"))?;
for (id, at, rules) in rows {
stmt.execute(params![community_id, &plane[..], &id[..], *at as i64, rules, now_secs as i64]).map_err(|e| format!("store guestbook wraps: {e}"))?;
}
}
tx.commit().map_err(|e| format!("store guestbook wraps commit: {e}"))
}
pub fn forget_guestbook_wraps(community_id: &str, plane: &[u8; 32], rules: u32, oldest: usize) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
conn.execute(
"DELETE FROM community_guestbook_wraps WHERE community_id = ?1 AND (plane != ?2 OR (rules != 0 AND rules != ?3))",
params![community_id, &plane[..], rules],
)
.map_err(|e| format!("forget guestbook wraps: {e}"))?;
if oldest > 0 {
conn.execute(
"DELETE FROM community_guestbook_wraps WHERE community_id = ?1 AND plane = ?2 AND wrap_id IN (
SELECT wrap_id FROM community_guestbook_wraps WHERE community_id = ?1 AND plane = ?2 AND rules != 0 ORDER BY judged_at LIMIT ?3)",
params![community_id, &plane[..], oldest as i64],
)
.map_err(|e| format!("forget guestbook wraps: {e}"))?;
}
Ok(())
}
pub fn purge_guestbook_wraps(community_id: &str) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
conn.execute("DELETE FROM community_guestbook_wraps WHERE community_id = ?1", params![community_id]).map_err(|e| format!("purge guestbook wraps: {e}"))?;
conn.execute("DELETE FROM settings WHERE key = 'gbk_reads:' || ?1", params![community_id]).map_err(|e| format!("purge guestbook wraps: {e}"))?;
Ok(())
}
pub fn purge_control_wraps(community_id: &str) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
conn.execute("DELETE FROM community_control_wraps WHERE community_id = ?1", params![community_id]).map_err(|e| format!("purge control wraps: {e}"))?;
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}"))?;
Ok(())
}
pub fn drop_control_wrap(community_id: &str, view: &[u8; 32], wrap_id: &[u8; 32]) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
conn.execute(
"DELETE FROM community_control_wraps WHERE community_id = ?1 AND view = ?2 AND wrap_id = ?3",
params![community_id, &view[..], &wrap_id[..]],
)
.map_err(|e| format!("drop control wrap: {e}"))?;
Ok(())
}
pub fn forget_control_refusals(community_id: &str, view: &[u8; 32], rules: u32, oldest: usize) -> Result<usize, String> {
let conn = super::get_write_connection_guard_static()?;
let other = conn
.execute(
"DELETE FROM community_control_wraps WHERE community_id = ?1 AND view = ?2 AND wrap IS NULL AND rules != ?3",
params![community_id, &view[..], rules],
)
.map_err(|e| format!("forget control refusals: {e}"))?;
let aged = conn
.execute(
"DELETE FROM community_control_wraps WHERE rowid IN (
SELECT rowid FROM community_control_wraps WHERE community_id = ?1 AND view = ?2 AND wrap IS NULL
ORDER BY judged_at, wrap_id LIMIT ?3)",
params![community_id, &view[..], oldest as i64],
)
.map_err(|e| format!("forget control refusals: {e}"))?;
Ok(other + aged)
}
pub fn record_audit_local(community_id: &str, id: &str, at_ms: u64, entry: &str) -> Result<(), String> {
let _seal = crate::crypto::gate::sealing();
let enc = enc_txt(entry)?;
let conn = super::get_write_connection_guard_static()?;
conn.execute(
"INSERT OR IGNORE INTO community_audit_local (id, community_id, at_ms, entry) VALUES (?1, ?2, ?3, ?4)",
params![id, community_id, at_ms as i64, enc],
)
.map_err(|e| format!("record audit: {e}"))?;
Ok(())
}
pub fn get_audit_local(community_id: &str) -> Result<Vec<(String, u64, String)>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare("SELECT id, at_ms, entry FROM community_audit_local WHERE community_id = ?1 ORDER BY at_ms")
.map_err(|e| format!("read audit: {e}"))?;
let rows = stmt
.query_map(params![community_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.max(0) as u64, r.get::<_, String>(2)?)))
.map_err(|e| format!("read audit: {e}"))?;
Ok(rows.flatten().map(|(id, at, entry)| (id, at, dec_txt(&entry))).collect())
}
pub fn held_wrap_channels(community_id: &str) -> Result<Vec<String>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn.prepare("SELECT DISTINCT channel_id FROM community_held_wraps WHERE community_id = ?1").map_err(|e| format!("held channels: {e}"))?;
let rows = stmt.query_map(params![community_id], |r| r.get(0)).map_err(|e| format!("held channels: {e}"))?;
Ok(rows.flatten().collect())
}
pub fn held_wrap_ids_in(community_id: &str, channel_id: &str) -> Result<Vec<String>, String> {
let conn = super::get_db_connection_guard_static()?;
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}"))?;
let rows = stmt.query_map(params![community_id, channel_id], |r| r.get(0)).map_err(|e| format!("held ids: {e}"))?;
Ok(rows.flatten().collect())
}
pub fn held_wraps_in(community_id: &str, channel_id: &str) -> Result<Vec<(String, String)>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare("SELECT wrap_id, wrap FROM community_held_wraps WHERE community_id = ?1 AND channel_id = ?2 ORDER BY at_ms")
.map_err(|e| format!("held wraps: {e}"))?;
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}"))?;
Ok(rows.flatten().map(|(id, wrap)| (id, dec_txt(&wrap))).collect())
}
pub fn held_wraps(community_id: &str) -> Result<Vec<(String, String, String)>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare("SELECT wrap_id, channel_id, wrap FROM community_held_wraps WHERE community_id = ?1 ORDER BY at_ms")
.map_err(|e| format!("held wraps: {e}"))?;
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}"))?;
Ok(rows.flatten().map(|(id, ch, wrap)| (id, ch, dec_txt(&wrap))).collect())
}
pub fn holds_wraps(community_id: &str) -> bool {
super::get_db_connection_guard_static()
.ok()
.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())
.is_some()
}
pub fn holds_wraps_at(community_id: &str, channel_id: &str, author: &str, address: &[u8; 32]) -> bool {
let wraps: Vec<String> = {
let Ok(conn) = super::get_db_connection_guard_static() else { return false };
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 };
let Ok(rows) = stmt.query_map(params![community_id, channel_id, author], |r| r.get::<_, String>(0)) else { return false };
rows.flatten().collect()
};
wraps.iter().any(|w| crate::event_json::event(&dec_txt(w)).is_ok_and(|e| e.pubkey.to_bytes() == *address))
}
struct DeferredWraps;
pub const MAX_DEFERRED: usize = 4096;
fn deferred() -> std::sync::Arc<std::sync::Mutex<std::collections::HashMap<String, u64>>> {
super::current_session().scoped::<DeferredWraps, _>()
}
pub fn held_wrap_ids(wrap_ids: &[String]) -> std::collections::HashSet<String> {
let now = now_secs().max(0) as u64 * 1000;
let waiting: std::collections::HashSet<String> = {
let held = deferred();
let mut map = held.lock().unwrap_or_else(|e| e.into_inner());
map.retain(|_, at| *at > now.saturating_add(HELD_HORIZON_MS));
wrap_ids.iter().filter(|id| map.contains_key(*id)).cloned().collect()
};
let mut out = held_wrap_rows(wrap_ids);
out.extend(waiting);
out
}
fn held_wrap_rows(wrap_ids: &[String]) -> std::collections::HashSet<String> {
let Ok(conn) = super::get_db_connection_guard_static() else { return Default::default() };
let Ok(json) = serde_json::to_string(wrap_ids) else { return Default::default() };
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() };
stmt.query_map(params![json], |r| r.get::<_, String>(0)).map(|rows| rows.flatten().collect()).unwrap_or_default()
}
pub fn release_held_wrap(wrap_id: &str) -> Result<(), String> {
let conn = super::get_write_connection_guard_static()?;
conn.execute("DELETE FROM community_held_wraps WHERE wrap_id = ?1", params![wrap_id]).map_err(|e| format!("release held wrap: {e}"))?;
Ok(())
}
pub fn get_community_pin_versions(community_id: &str) -> Result<std::collections::HashMap<String, i64>, String> {
let conn = super::get_db_connection_guard_static()?;
let mut stmt = conn
.prepare("SELECT channel_id, version FROM community_pins WHERE community_id = ?1")
.map_err(|e| format!("get pin versions: {e}"))?;
let rows = stmt
.query_map(params![community_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))
.map_err(|e| format!("get pin versions: {e}"))?;
rows.collect::<Result<_, _>>().map_err(|e| format!("get pin versions: {e}"))
}
pub fn get_community_pins(community_id: &str, channel_id: &str) -> Result<Option<(String, i64)>, String> {
let conn = super::get_db_connection_guard_static()?;
let row: Option<(String, i64)> = conn
.query_row(
"SELECT content, version FROM community_pins WHERE community_id = ?1 AND channel_id = ?2",
params![community_id, channel_id],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()
.map_err(|e| format!("get pins: {e}"))?;
Ok(row.map(|(content, version)| (dec_txt(&content), version)))
}