use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::{Arc, LazyLock, Mutex as StdMutex};
use nostr_sdk::prelude::{Client, Event, Filter, Kind, PublicKey, RelayStatus, RelayUrl, SubscriptionId, Timestamp};
use tokio::sync::mpsc::UnboundedSender;
use tokio::sync::Mutex;
use super::community::CommunityV2;
use super::stream;
use super::{derive, inbound};
use crate::community::{CommunityId, Epoch};
use crate::event_handler::InboundEventHandler;
use crate::ClientRelayExt;
static V2_SUB_ID: LazyLock<Mutex<Option<SubscriptionId>>> = LazyLock::new(|| Mutex::new(None));
static V2_POOLWIDE_SUB_ID: LazyLock<Mutex<Option<SubscriptionId>>> = LazyLock::new(|| Mutex::new(None));
static V2_SUB_FP: LazyLock<Mutex<Option<u64>>> = LazyLock::new(|| Mutex::new(None));
static V2_SUB_READY_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX);
#[inline]
fn mark_subscription_ready() {
V2_SUB_READY_GEN.store(
crate::db::current_session_id(),
std::sync::atomic::Ordering::Release,
);
}
pub fn subscription_ready() -> bool {
V2_SUB_READY_GEN.load(std::sync::atomic::Ordering::Acquire)
== crate::db::current_session_id()
}
#[derive(Default)]
struct SeenWraps {
cur: HashSet<u64>,
prev: HashSet<u64>,
}
const SEEN_WRAPS_GEN: usize = 2048;
impl SeenWraps {
fn first_sight(&mut self, id: &[u8; 32]) -> bool {
let key = u64::from_le_bytes([id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7]]);
if self.cur.contains(&key) || self.prev.contains(&key) {
return false;
}
if self.cur.len() >= SEEN_WRAPS_GEN {
std::mem::swap(&mut self.cur, &mut self.prev);
self.cur.clear();
}
self.cur.insert(key);
true
}
fn forget(&mut self, id: &[u8; 32]) {
let key = u64::from_le_bytes([id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7]]);
self.cur.remove(&key);
self.prev.remove(&key);
}
}
struct SeenWrapsKey;
fn seen_wraps() -> Arc<StdMutex<SeenWraps>> {
crate::db::current_session().scoped::<SeenWrapsKey, StdMutex<SeenWraps>>()
}
static V2_FOLLOW_TX: LazyLock<StdMutex<Option<UnboundedSender<CommunityId>>>> = LazyLock::new(|| StdMutex::new(None));
static V2_FOLLOW_PENDING: LazyLock<StdMutex<HashSet<[u8; 32]>>> = LazyLock::new(|| StdMutex::new(HashSet::new()));
static V2_FOLLOW_URGENT: LazyLock<StdMutex<HashSet<[u8; 32]>>> = LazyLock::new(|| StdMutex::new(HashSet::new()));
type FollowLocks = std::collections::HashMap<[u8; 32], Arc<Mutex<()>>>;
static V2_FOLLOW_LOCKS: LazyLock<StdMutex<FollowLocks>> =
LazyLock::new(|| StdMutex::new(std::collections::HashMap::new()));
fn refreshed(handler: &dyn InboundEventHandler, community_id: &str) {
handler.on_community_refreshed(community_id);
super::changes::notify(handler, community_id);
}
fn self_removed(handler: &dyn InboundEventHandler, community_id: &str) {
super::changes::forget(community_id);
handler.on_community_self_removed(community_id);
}
fn dissolved(handler: &dyn InboundEventHandler, community_id: &str) {
super::changes::forget(community_id);
handler.on_community_dissolved(community_id);
}
struct LiveAuthorityMoves;
fn live_authority_moves() -> Arc<StdMutex<HashSet<[u8; 32]>>> {
crate::db::current_session().scoped::<LiveAuthorityMoves, _>()
}
fn note_live_authority_move(id: &CommunityId) {
live_authority_moves().lock().unwrap_or_else(|e| e.into_inner()).insert(id.0);
}
fn take_live_authority_move(id: &CommunityId) -> bool {
live_authority_moves().lock().unwrap_or_else(|e| e.into_inner()).remove(&id.0)
}
pub(crate) fn follow_pending(id: &CommunityId) -> bool {
V2_FOLLOW_PENDING.lock().unwrap_or_else(|e| e.into_inner()).contains(&id.0)
}
struct LinkGeneration;
pub(crate) fn note_resubscribe() {
crate::db::current_session().scoped::<LinkGeneration, std::sync::atomic::AtomicU64>().fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
pub(crate) fn link_generation() -> u64 {
crate::db::current_session().scoped::<LinkGeneration, std::sync::atomic::AtomicU64>().load(std::sync::atomic::Ordering::SeqCst)
}
pub(crate) fn follow_lock(id: &CommunityId) -> Arc<Mutex<()>> {
let mut locks = V2_FOLLOW_LOCKS.lock().unwrap();
if let Some(lock) = locks.get(&id.0) {
return Arc::clone(lock);
}
locks.retain(|_, lock| Arc::strong_count(lock) > 1);
Arc::clone(locks.entry(id.0).or_default())
}
pub async fn subscribed_author_set() -> Vec<String> {
let Some(client) = crate::state::nostr_client() else {
return Vec::new();
};
let ids = [V2_SUB_ID.lock().await.clone(), V2_POOLWIDE_SUB_ID.lock().await.clone()];
let mut authors: std::collections::BTreeSet<[u8; 32]> = std::collections::BTreeSet::new();
for id in ids.into_iter().flatten() {
for filters in client.subscription(&id).await.into_values() {
for f in filters {
authors.extend(f.authors.into_iter().flatten().map(|pk| pk.to_bytes()));
}
}
}
authors.iter().map(crate::simd::hex::bytes_to_hex_32).collect()
}
#[cfg(debug_assertions)]
pub async fn debug_run_follow_stages(id: &CommunityId, session: &std::sync::Arc<crate::db::Session>) -> (String, String, String) {
let lock = follow_lock(id);
let _guard = lock.lock().await;
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let Ok(Some(c)) = crate::db::community::load_community_v2(id) else {
return ("community gone".into(), "-".into(), "-".into());
};
let rekeys = match super::service::follow_rekeys(&transport, &c, session).await {
Ok(f) => format!(
"Ok(updated={} self_removed={} dissolved={})",
f.updated.as_ref().map(|u| format!("root_e{}", u.root_epoch.0)).unwrap_or_else(|| "no".into()),
f.self_removed, f.dissolved
),
Err(e) => format!("ERR: {e}"),
};
let Ok(Some(c)) = crate::db::community::load_community_v2(id) else {
return (rekeys, "community gone".into(), "-".into());
};
let control = match super::service::follow_control(&transport, &c).await {
Ok(v) => format!("Ok(changed={} authority={})", v.updated.is_some(), v.authority_changed),
Err(e) => format!("ERR: {e}"),
};
let Ok(Some(c)) = crate::db::community::load_community_v2(id) else {
return (rekeys, control, "community gone".into());
};
let guestbook = match super::service::sync_guestbook(&transport, &c).await {
Ok(fresh) => format!("Ok(fresh={})", fresh.len()),
Err(e) => format!("ERR: {e}"),
};
(rekeys, control, guestbook)
}
pub fn is_live_subscription(id: &SubscriptionId) -> bool {
if V2_RETIRED_SUBS.lock().unwrap_or_else(|e| e.into_inner()).contains(id) {
return true;
}
match (V2_SUB_ID.try_lock(), V2_POOLWIDE_SUB_ID.try_lock()) {
(Ok(targeted), Ok(poolwide)) => targeted.as_ref() == Some(id) || poolwide.as_ref() == Some(id),
_ => true,
}
}
const SWAP_REPLAY_DELAY_MS: u64 = 2_000;
const SWAP_REPLAY_BACK_MS: u64 = 15_000;
const WRITER_TAIL_MS: u64 = 5 * 60 * 1000;
fn just_left_writer(ch: &super::community::ChannelV2) -> Option<PublicKey> {
let now = crate::clock::now_ms();
let ledger = ch.writers.as_ref()?;
let (live, _) = ledger.current_writer()?;
let began = ledger.writer_start(live)?;
if now.saturating_sub(began) > WRITER_TAIL_MS {
return None;
}
let (_, pk, _) = ledger.writers().filter(|(e, _, _)| *e < live).max_by_key(|(e, _, _)| e.0)?;
PublicKey::from_slice(&pk).ok()
}
static V2_RETIRED_SUBS: LazyLock<StdMutex<std::collections::VecDeque<SubscriptionId>>> = LazyLock::new(|| StdMutex::new(std::collections::VecDeque::new()));
static V2_LIVE_SUBS: LazyLock<StdMutex<Vec<SubscriptionId>>> = LazyLock::new(|| StdMutex::new(Vec::new()));
fn note_live_subscription(id: &SubscriptionId) {
let mut live = V2_LIVE_SUBS.lock().unwrap_or_else(|e| e.into_inner());
if !live.contains(id) {
live.push(id.clone());
}
}
const RETIRED_SUBS_KEPT: usize = 8;
fn retire_subscription(id: SubscriptionId) {
V2_LIVE_SUBS.lock().unwrap_or_else(|e| e.into_inner()).retain(|l| *l != id);
let mut retired = V2_RETIRED_SUBS.lock().unwrap_or_else(|e| e.into_inner());
if retired.len() >= RETIRED_SUBS_KEPT {
retired.pop_front();
}
retired.push_back(id);
}
pub fn routes_live(id: &SubscriptionId) -> bool {
V2_LIVE_SUBS.lock().unwrap_or_else(|e| e.into_inner()).contains(id) || V2_RETIRED_SUBS.lock().unwrap_or_else(|e| e.into_inner()).contains(id)
}
pub async fn subscription_id() -> Option<SubscriptionId> {
V2_SUB_ID.lock().await.clone()
}
pub async fn poolwide_subscription_id() -> Option<SubscriptionId> {
V2_POOLWIDE_SUB_ID.lock().await.clone()
}
pub async fn clear() {
*V2_SUB_ID.lock().await = None;
*V2_POOLWIDE_SUB_ID.lock().await = None;
*V2_SUB_FP.lock().await = None;
V2_RETIRED_SUBS.lock().unwrap_or_else(|e| e.into_inner()).clear();
V2_LIVE_SUBS.lock().unwrap_or_else(|e| e.into_inner()).clear();
*seen_wraps().lock().unwrap_or_else(|e| e.into_inner()) = SeenWraps::default();
*V2_FOLLOW_TX.lock().unwrap() = None;
*V2_FOLLOW_PENDING.lock().unwrap() = HashSet::new();
*V2_FOLLOW_URGENT.lock().unwrap() = HashSet::new();
*V2_FOLLOW_LOCKS.lock().unwrap() = FollowLocks::new();
super::streamauth::clear();
}
pub fn plane_authors(communities: &[CommunityV2]) -> Vec<PublicKey> {
let mut out: Vec<PublicKey> = communities.iter().flat_map(community_addresses).collect();
out.sort_unstable_by_key(|p| p.to_bytes());
out.dedup();
out
}
pub(crate) async fn settle_owed_retractions<T: crate::community::transport::Transport + ?Sized>(id: &crate::community::CommunityId, transport: &T, handler: &dyn InboundEventHandler) {
let Ok(Some(community)) = crate::db::community::load_community_v2(id) else { return };
let cid = crate::simd::hex::bytes_to_hex_32(&id.0);
for (chan, author, since, until, generation) in crate::db::community::owed_author_retractions(&cid).unwrap_or_default() {
let (Some(ch), Ok(pk)) = (community.channels.iter().find(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0) == chan), nostr_sdk::prelude::PublicKey::from_hex(&author)) else {
let _ = crate::db::community::settle_author_retraction(&cid, &chan, &author, since, until, generation);
continue;
};
if super::service::retract_by(transport, &community, ch, &pk, since, until, handler).await.is_err() {
return;
}
let _ = crate::db::community::settle_author_retraction(&cid, &chan, &author, since, until, generation);
}
for (chan, since, generation) in crate::db::community::owed_retractions(&cid).unwrap_or_default() {
let Some(ch) = community.channels.iter().find(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0) == chan) else {
let _ = crate::db::community::settle_retraction(&cid, &chan, since, generation);
continue;
};
if super::service::retract_since(transport, &community, ch, since, handler).await.is_err() {
break;
}
let _ = crate::db::community::settle_retraction(&cid, &chan, since, generation);
let (after, channel) = (community.clone(), ch.id);
crate::db::spawn_bound(async move {
let Some(me) = crate::state::my_public_key() else { return };
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let since = since.saturating_sub(60_000) / 1000;
let settled = |wraps: &[nostr_sdk::prelude::EventId]| {
let hex: Vec<String> = wraps.iter().map(|w| w.to_hex()).collect();
let settled = crate::db::events::community_wraps_settled(&hex);
wraps.iter().zip(&hex).filter(|(_, h)| settled.contains(*h)).map(|(w, _)| *w).collect()
};
if let Ok(page) = super::service::fetch_channel_history(&transport, &after, &channel, 200, 3, Some(since), None, crate::community::transport::Evidence::Quorum, |_, _| true, settled).await {
crate::VectorCore::v2_ingest_chat_page(&crate::simd::hex::bytes_to_hex_32(&channel.0), me, crate::db::current_session(), page).await;
}
});
}
}
const MOVED_TAIL_SECS: u64 = 8;
pub(crate) fn reread_tails(id: CommunityId, left: Vec<(crate::community::ChannelId, Epoch)>) {
if left.is_empty() || crate::state::nostr_client().is_none() {
return;
}
let moved_at = crate::clock::now_secs();
crate::db::spawn_bound(async move {
crate::rt::time::sleep(std::time::Duration::from_secs(MOVED_TAIL_SECS)).await;
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let since = Some(moved_at.saturating_sub(60));
let settled = |wraps: &[nostr_sdk::prelude::EventId]| {
let hex: Vec<String> = wraps.iter().map(|w| w.to_hex()).collect();
let settled = crate::db::events::community_wraps_settled(&hex);
wraps.iter().zip(&hex).filter(|(_, h)| settled.contains(*h)).map(|(w, _)| *w).collect()
};
for (channel, from) in left {
if !crate::db::current_session().is_live() {
return;
}
let (Some(me), Ok(Some(community))) = (crate::state::my_public_key(), crate::db::community::load_community_v2(&id)) else { return };
let read = super::service::fetch_channel_history_since_epoch(&transport, &community, &channel, 200, 2, since, None, crate::community::transport::Evidence::Quorum, |_, _, _| true, settled, Some((from, since)), &[]).await;
if let Ok((page, ..)) = read {
crate::VectorCore::v2_ingest_chat_page(&crate::simd::hex::bytes_to_hex_32(&channel.0), me, crate::db::current_session(), page).await;
}
}
});
}
fn reread_moved_channels(before: &CommunityV2) {
let Ok(Some(after)) = crate::db::community::load_community_v2(before.id()) else { return };
let moved: Vec<String> = after
.channels
.iter()
.filter(|ch| !(ch.private && ch.key.is_none()))
.filter(|ch| {
before.channel(&ch.id).is_none_or(|was| {
let held: HashSet<PublicKey> = was.published_history().into_iter().map(|(_, g)| g.pk()).collect();
before.channel_secret(was).1 != after.channel_secret(ch).1 || ch.published_history().iter().any(|(_, g)| !held.contains(&g.pk()))
})
})
.map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0))
.collect();
if moved.is_empty() {
return;
}
let id = *after.id();
let readable = |ch: &super::community::ChannelV2| !(ch.private && ch.key.is_none());
let left = after
.channels
.iter()
.filter(|ch| readable(ch))
.filter_map(|ch| before.channel(&ch.id).filter(|was| readable(was)).map(|was| (ch.id, before.channel_secret(was).1, after.channel_secret(ch).1)))
.filter(|(_, left, now)| left != now)
.map(|(channel, left, _)| (channel, left))
.collect();
reread_tails(id, left);
crate::db::spawn_bound(async move {
for channel in moved {
if !crate::db::current_session().is_live() {
return;
}
crate::VectorCore::v2_backfill_channel(&id, &channel, 50, 8, None, None, crate::community::transport::Evidence::Fast, 12).await;
}
});
}
fn community_addresses(c: &CommunityV2) -> Vec<PublicKey> {
let mut out = vec![
derive::guestbook_group_key(&c.community_root, c.id(), c.root_epoch).pk(),
control_author(c),
super::derive::dissolved_group_key(c.id()).pk(),
];
for ch in &c.channels {
if ch.private && ch.key.is_none() {
continue;
}
let (secret, epoch) = c.channel_secret(ch);
if !ch.locked() {
out.push(derive::channel_group_key(&secret, &ch.id, epoch).pk());
}
if let Some(pk) = ch.writers.as_ref().and_then(|l| l.current_writer()).and_then(|(_, pk)| PublicKey::from_slice(&pk).ok()) {
out.push(pk);
}
out.extend(just_left_writer(ch));
}
out.extend(rekey_authors(c));
out
}
struct SubPlan {
authors: Vec<PublicKey>,
per_relay: BTreeMap<RelayUrl, Vec<PublicKey>>,
}
fn sort_dedup(pks: &mut Vec<PublicKey>) {
pks.sort_unstable_by_key(|p| p.to_bytes());
pks.dedup();
}
fn listen_relays(c: &CommunityV2) -> Vec<String> {
let mut out = c.relays.clone();
out.extend(super::service::retired_relays(&crate::simd::hex::bytes_to_hex_32(&c.id().0)));
out
}
fn subscription_plan(communities: &[CommunityV2]) -> SubPlan {
let mut authors = Vec::new();
let mut per_relay: BTreeMap<RelayUrl, Vec<PublicKey>> = BTreeMap::new();
let mut unplaced = Vec::new();
for c in communities {
let addresses = community_addresses(c);
let mut placed = false;
for r in &listen_relays(c) {
let Ok(url) = RelayUrl::parse(r) else { continue };
per_relay.entry(url).or_default().extend_from_slice(&addresses);
placed = true;
}
if !placed {
unplaced.extend_from_slice(&addresses);
}
authors.extend(addresses);
}
if !unplaced.is_empty() {
for share in per_relay.values_mut() {
share.extend_from_slice(&unplaced);
}
}
per_relay.values_mut().for_each(sort_dedup);
sort_dedup(&mut authors);
SubPlan { authors, per_relay }
}
fn plan_fingerprint(plan: &SubPlan) -> u64 {
use std::hash::{BuildHasher, Hash, Hasher};
static KEYS: LazyLock<std::collections::hash_map::RandomState> = LazyLock::new(Default::default);
let mut h = KEYS.build_hasher();
plan.authors.len().hash(&mut h);
for pk in &plan.authors {
h.write(pk.as_bytes());
}
for (url, share) in &plan.per_relay {
url.as_str().hash(&mut h);
share.len().hash(&mut h);
for pk in share {
h.write(pk.as_bytes());
}
}
h.finish()
}
fn live_filter(authors: impl IntoIterator<Item = PublicKey>, since: Timestamp) -> Filter {
Filter::new()
.kinds([Kind::Custom(stream::KIND_WRAP), Kind::Custom(stream::KIND_WRAP_EPHEMERAL)])
.authors(authors)
.since(since)
.limit(0)
}
fn live_since() -> Timestamp {
Timestamp::from_secs(crate::clock::timestamp().as_secs().saturating_sub(crate::community::REALTIME_FRESH_WINDOW_MS / 1000))
}
pub(crate) fn control_author(c: &CommunityV2) -> PublicKey {
super::control::ControlPlane::of(c).pk()
}
pub(crate) fn rekey_authors(c: &CommunityV2) -> Vec<PublicKey> {
let mut out = vec![derive::base_rekey_group_key(&c.community_root, c.id(), Epoch(c.root_epoch.0.saturating_add(1))).pk()];
for ch in &c.channels {
if ch.private {
out.push(derive::channel_rekey_group_key(&c.community_root, &ch.id, Epoch(ch.epoch.0.saturating_add(1))).pk());
}
}
out
}
pub fn load_held_v2() -> Vec<CommunityV2> {
let ids = crate::db::community::list_community_ids().unwrap_or_default();
ids.iter()
.filter(|id| crate::db::community::community_held(id).unwrap_or(false))
.filter(|id| !crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&id.0)).unwrap_or(false))
.filter_map(|id| crate::db::community::load_community_v2(id).ok().flatten())
.collect()
}
pub fn load_dissolved_v2() -> Vec<CommunityV2> {
let ids = crate::db::community::list_community_ids().unwrap_or_default();
ids.iter()
.filter(|id| crate::db::community::community_held(id).unwrap_or(false))
.filter(|id| crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&id.0)).unwrap_or(false))
.filter_map(|id| crate::db::community::load_community_v2(id).ok().flatten())
.collect()
}
async fn stamp_dissolved_chats(id: &CommunityId) {
if let Ok(Some(c)) = crate::db::community::load_community_v2(id) {
crate::register_v2_chats_inner(&c).await;
}
}
#[derive(Default)]
struct HeldV2Cache {
generation: u64,
written: HashMap<[u8; 32], u64>,
whole: Option<u64>,
snapshot: Option<(web_time::Instant, u64, Arc<HeldV2>)>,
}
fn held_v2_cache() -> Arc<std::sync::Mutex<HeldV2Cache>> {
struct Key;
crate::db::current_session().scoped::<Key, std::sync::Mutex<HeldV2Cache>>()
}
pub struct HeldV2 {
communities: Box<[CommunityV2]>,
routes: std::sync::OnceLock<HashMap<[u8; 32], usize>>,
}
impl HeldV2 {
pub fn communities(&self) -> &[CommunityV2] {
&self.communities
}
pub fn route(&self, author: &PublicKey) -> Option<&CommunityV2> {
let routes = self.routes.get_or_init(|| {
let mut map = HashMap::new();
for (i, c) in self.communities.iter().enumerate() {
for pk in community_addresses(c) {
map.entry(pk.to_bytes()).or_insert(i);
}
}
map
});
routes.get(&author.to_bytes()).map(|&i| &self.communities[i])
}
}
#[cfg(feature = "bench")]
impl HeldV2 {
pub fn for_bench(communities: Vec<CommunityV2>) -> Self {
HeldV2 { communities: communities.into_boxed_slice(), routes: std::sync::OnceLock::new() }
}
}
#[cfg(feature = "bench")]
pub fn bench_cache_age_secs() -> u64 {
held_v2_cache().lock().unwrap().snapshot.as_ref().map_or(u64::MAX, |(at, ..)| at.elapsed().as_secs())
}
#[cfg(feature = "bench")]
pub fn bench_addresses(c: &CommunityV2) -> usize {
community_addresses(c).len()
}
fn load_held_one(id: &CommunityId) -> Result<Option<CommunityV2>, String> {
if crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&id.0))? {
return Ok(None);
}
crate::db::community::load_community_v2(id)
}
pub fn load_held_v2_cached() -> Arc<HeldV2> {
let cache = held_v2_cache();
let load = {
let held = cache.lock().unwrap_or_else(|e| e.into_inner());
match &held.snapshot {
Some((at, loaded_under, snapshot)) if *loaded_under == held.generation && held.written.is_empty() && at.elapsed() < HELD_TTL => return Arc::clone(snapshot),
Some((at, _, snapshot)) if held.whole.is_none() && at.elapsed() < HELD_TTL => HeldLoad {
generation: held.generation,
written: held.written.clone(),
whole: None,
previous: Some((*at, Arc::clone(snapshot))),
unread: Vec::new(),
},
_ => HeldLoad { generation: held.generation, written: HashMap::new(), whole: held.whole, previous: None, unread: Vec::new() },
}
};
let mut load = load;
let communities: Vec<CommunityV2> = match &load.previous {
Some((_, previous)) => match crate::db::community::list_community_ids() {
Ok(ids) => ids
.iter()
.filter_map(|id| {
let kept = previous.communities.iter().find(|c| c.id() == id);
match kept {
Some(kept) if !load.written.contains_key(&id.0) => Some(kept.clone()),
_ => load_held_one(id).unwrap_or_else(|_| {
load.unread.push(id.0);
kept.cloned()
}),
}
})
.collect(),
Err(_) => return Arc::clone(previous),
},
None => load_held_v2(),
};
let fresh = Arc::new(HeldV2 { communities: communities.into_boxed_slice(), routes: std::sync::OnceLock::new() });
load.settle(&mut cache.lock().unwrap_or_else(|e| e.into_inner()), Arc::clone(&fresh), web_time::Instant::now());
fresh
}
const HELD_TTL: std::time::Duration = std::time::Duration::from_secs(30);
struct HeldLoad {
generation: u64,
written: HashMap<[u8; 32], u64>,
whole: Option<u64>,
previous: Option<(web_time::Instant, Arc<HeldV2>)>,
unread: Vec<[u8; 32]>,
}
impl HeldLoad {
fn settle(self, held: &mut HeldV2Cache, fresh: Arc<HeldV2>, now: web_time::Instant) {
for (id, at) in &self.written {
if held.written.get(id) == Some(at) && !self.unread.contains(id) {
held.written.remove(id);
}
}
if self.previous.is_none() {
held.written.retain(|_, at| *at > self.generation);
if held.whole == self.whole {
held.whole = None;
}
}
if held.snapshot.as_ref().is_none_or(|(_, under, _)| *under <= self.generation) {
let read_whole_at = self.previous.map_or(now, |(at, _)| at);
held.snapshot = Some((read_whole_at, self.generation, fresh));
}
}
}
pub fn invalidate_held_v2_cache() {
let cache = held_v2_cache();
let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
held.generation += 1;
held.whole = Some(held.generation);
}
pub fn invalidate_held_v2_community(community_id: &str) {
let Some(id) = crate::community::id32_from_hex(community_id) else {
return invalidate_held_v2_cache();
};
let cache = held_v2_cache();
let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
held.generation += 1;
let at = held.generation;
held.written.insert(id, at);
}
pub async fn force_refresh_subscription(client: &Client) {
crate::log_info!("[v2-sub] force re-assert begin");
{
let mut sub_guard = V2_SUB_ID.lock().await;
if let Some(old) = sub_guard.take() {
crate::live_subs::forget(&old);
let _ = client.unsubscribe(&old).await;
retire_subscription(old);
}
let mut pw = V2_POOLWIDE_SUB_ID.lock().await;
if let Some(old) = pw.take() {
crate::live_subs::forget(&old);
let _ = client.unsubscribe(&old).await;
retire_subscription(old);
}
*V2_SUB_FP.lock().await = None;
}
refresh_subscription(client).await;
}
pub async fn refresh_subscription(client: &Client) {
{
let communities = load_held_v2();
let mut relays: Vec<String> = communities.iter().flat_map(listen_relays).collect();
relays.sort();
relays.dedup();
if !relays.is_empty() {
for r in &relays {
let _ = client.add_managed_relay(r.as_str()).capabilities(crate::community_relay_capabilities()).await;
}
client.connect().await;
let wanted: Vec<RelayUrl> = relays.iter().filter_map(|r| RelayUrl::parse(r).ok()).collect();
let wait_t = web_time::Instant::now();
let polls = crate::relay_connect_timeout(std::time::Duration::from_secs(6)).as_millis() / 250;
for _ in 0..polls {
let pool = client.relays().all().await;
if wanted.iter().any(|u| pool.get(u).map(|r| r.status() == RelayStatus::Connected).unwrap_or(false)) {
break;
}
crate::rt::time::sleep(std::time::Duration::from_millis(250)).await;
}
{
let pool = client.relays().all().await;
let up: Vec<String> = wanted.iter()
.filter(|u| pool.get(u).map(|r| r.status() == RelayStatus::Connected).unwrap_or(false))
.map(|u| u.to_string()).collect();
crate::log_info!("[v2-sub] connect-wait {:?}: {}/{} wanted relays up: {:?}", wait_t.elapsed(), up.len(), wanted.len(), up);
}
for c in &communities {
super::streamauth::register_community(c);
}
}
}
let mut sub_guard = V2_SUB_ID.lock().await;
let mut fp_guard = V2_SUB_FP.lock().await;
let communities = load_held_v2();
let plan = subscription_plan(&communities);
let mut relays: Vec<String> = communities.iter().flat_map(listen_relays).collect();
relays.sort();
relays.dedup();
let fingerprint = plan_fingerprint(&plan);
if sub_guard.is_some() && *fp_guard == Some(fingerprint) && (plan.authors.is_empty() || V2_POOLWIDE_SUB_ID.lock().await.is_some()) {
mark_subscription_ready(); return; }
let old_targeted = sub_guard.take();
*fp_guard = Some(fingerprint);
if plan.authors.is_empty() {
if let Some(old) = old_targeted {
crate::live_subs::forget(&old);
let _ = client.unsubscribe(&old).await;
retire_subscription(old);
}
if let Some(old_pw) = V2_POOLWIDE_SUB_ID.lock().await.take() {
crate::live_subs::forget(&old_pw);
let _ = client.unsubscribe(&old_pw).await;
retire_subscription(old_pw);
}
mark_subscription_ready();
return;
}
let since = live_since();
let SubPlan { authors, per_relay } = plan;
let mut retired: Vec<SubscriptionId> = old_targeted.into_iter().collect();
{
let mut pw = V2_POOLWIDE_SUB_ID.lock().await;
retired.extend(pw.take());
let filter = live_filter(authors, since);
match client.subscribe(filter.clone()).await {
Ok(out) => {
crate::live_subs::keep_output(&out, vec![filter]);
crate::log_info!(
"[v2-sub] poolwide {}: ok {:?} failed {:?}",
*out,
out.success.keys().map(|r| r.to_string()).collect::<Vec<_>>(),
out.failed.iter().map(|(r, e)| format!("{r}: {e:?}")).collect::<Vec<_>>()
);
note_live_subscription(&out.value);
*pw = Some(out.value);
}
Err(e) => crate::log_warn!("[v2-sub] poolwide subscribe FAILED: {e}"),
}
}
let targeted: std::collections::HashMap<RelayUrl, Vec<Filter>> =
per_relay.into_iter().map(|(url, share)| (url, vec![live_filter(share, since)])).collect();
match client.subscribe(nostr_sdk::prelude::ReqTarget::manual(targeted.clone())).await {
Ok(out) => {
crate::live_subs::keep(&out.value, targeted);
crate::log_info!(
"[v2-sub] targeted {}: ok {:?} failed {:?}",
*out,
out.success.keys().map(|r| r.to_string()).collect::<Vec<_>>(),
out.failed.iter().map(|(r, e)| format!("{r}: {e:?}")).collect::<Vec<_>>()
);
note_live_subscription(&out.value);
*sub_guard = Some(out.value);
}
Err(e) => crate::log_warn!("[v2-sub] targeted subscribe FAILED: {e}"),
}
for old in retired {
crate::live_subs::forget(&old);
let _ = client.unsubscribe(&old).await;
retire_subscription(old);
}
mark_subscription_ready();
let swapped_at = crate::clock::now_ms();
crate::db::spawn_bound(async move {
crate::rt::time::sleep(std::time::Duration::from_millis(SWAP_REPLAY_DELAY_MS)).await;
crate::VectorCore::owe_live_replay(swapped_at.saturating_sub(SWAP_REPLAY_BACK_MS));
});
drop(fp_guard);
drop(sub_guard);
prime_auth_in_background(client, relays);
}
static PRIME_IN_FLIGHT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
fn prime_auth_in_background(client: &Client, relays: Vec<String>) {
use std::sync::atomic::Ordering;
if relays.is_empty() || PRIME_IN_FLIGHT.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() {
return;
}
let client = client.clone();
crate::db::spawn_bound(async move {
super::streamauth::prime_auth(&client, &relays).await;
PRIME_IN_FLIGHT.store(false, Ordering::Release);
});
}
pub(crate) async fn replay(client: &Client, since: Timestamp, only: Option<&str>, handler: Arc<dyn InboundEventHandler>) {
const PAGE: usize = 500;
const MAX_PAGES: usize = 20;
let SubPlan { per_relay, .. } = subscription_plan(&load_held_v2());
let budget = crate::relay_request_timeout(std::time::Duration::from_secs(10));
for (url, share) in per_relay.into_iter().filter(|(url, _)| only.is_none_or(|o| url.as_str().trim_end_matches('/') == o.trim_end_matches('/'))) {
let mut got: Vec<Event> = Vec::new();
let mut ids = HashSet::new();
let mut until: Option<Timestamp> = None;
for _ in 0..MAX_PAGES {
let mut filter = Filter::new().kinds([Kind::Custom(stream::KIND_WRAP)]).authors(share.clone()).since(since).limit(PAGE);
if let Some(until) = until {
filter = filter.until(until);
}
let page = match client.fetch_events(nostr_sdk::prelude::ReqTarget::single(url.clone(), [filter])).timeout(budget).await {
Ok(page) => page,
Err(e) => {
crate::log_debug!("[v2-sub] replay of {url} since {} failed: {e}", since.as_secs());
break;
}
};
let mut new = 0;
for e in page.into_iter() {
until = Some(until.map_or(e.created_at, |u| u.min(e.created_at)));
if ids.insert(e.id) {
got.push(e);
new += 1;
}
}
if new == 0 || until.is_none_or(|u| u <= since) {
break;
}
}
got.sort_by_key(|e| e.created_at);
crate::log_debug!("[v2-sub] replay of {url} since {}: {} event(s)", since.as_secs(), got.len());
for event in got {
dispatch_event(event, handler.clone()).await;
}
}
}
pub(crate) async fn resubscribe_relay(client: &Client, relay: &RelayUrl) {
note_resubscribe();
crate::VectorCore::owe_catch_up(false, false, [(relay.to_string(), crate::clock::now_ms().saturating_sub(10 * 60_000))]);
let targeted = V2_SUB_ID.lock().await.clone();
let poolwide = V2_POOLWIDE_SUB_ID.lock().await.clone();
if targeted.is_none() && poolwide.is_none() {
return; }
let communities = load_held_v2();
let SubPlan { authors, mut per_relay } = subscription_plan(&communities);
if authors.is_empty() {
return;
}
let since = live_since();
let sends = [
targeted.zip(per_relay.remove(relay)),
poolwide.map(|id| (id, authors)),
];
for (id, share) in sends.into_iter().flatten() {
let _ = client
.subscribe(nostr_sdk::prelude::ReqTarget::single(relay.clone(), [live_filter(share, since)]))
.with_id(id)
.await;
}
}
fn ingest_live(c: &CommunityV2, entry: super::guestbook::GuestbookEvent, wrap: &Event) -> bool {
let stored = super::service::ingest_guestbook_event(c, entry, wrap.created_at.as_secs());
if stored.is_ok() {
super::service::hold_guestbook_wrap(c, wrap);
}
stored.unwrap_or(false)
}
async fn apply_live_control(c: &CommunityV2, wrap: &Event, handler: &dyn InboundEventHandler) -> bool {
if follow_pending(c.id()) {
return false;
}
let lock = follow_lock(c.id());
let Ok(_guard) = lock.try_lock() else {
return false;
};
let Ok(Some(current)) = crate::db::community::load_community_v2(c.id()) else {
return false;
};
let Some(follow) = super::service::follow_control_live(¤t, wrap).await else {
return false;
};
let community_id = crate::simd::hex::bytes_to_hex_32(&c.id().0);
let planes = |c: &CommunityV2| {
let mut chans: Vec<_> = c
.channels
.iter()
.map(|ch| (ch.id.0, ch.private, ch.key, ch.epoch.0, ch.writers.clone(), ch.sealed.clone()))
.collect();
chans.sort_unstable_by_key(|ch| ch.0);
(chans, c.relays.clone(), c.control_pk, c.control_root)
};
let moved_planes = follow.updated.as_ref().is_some_and(|u| planes(u) != planes(¤t));
let banned = crate::my_public_key().is_some_and(|me| crate::db::community::is_author_banned(&community_id, &me));
if moved_planes {
if let Some(client) = crate::state::nostr_client() {
refresh_subscription(&client).await;
}
}
if follow.updated.is_some() {
refreshed(handler, &community_id);
} else if follow.authority_changed {
super::changes::notify(handler, &community_id);
}
if follow.authority_changed {
note_live_authority_move(c.id());
}
if moved_planes || follow.authority_changed || banned {
enqueue_follow_urgent(c.id());
}
true
}
pub async fn dispatch_event(event: Event, handler: Arc<dyn InboundEventHandler>) {
crate::db::scoped(async move {
let Some(my_pk) = crate::my_public_key() else {
return;
};
if !seen_wraps().lock().unwrap_or_else(|e| e.into_inner()).first_sight(event.id.as_bytes()) {
return;
}
let (wrap_id, wrap_at) = (event.id.to_bytes(), event.created_at.as_secs());
let durable = event.kind.as_u16() == stream::KIND_WRAP;
if durable
&& (crate::db::wrappers::processed_wrapper_exists(&wrap_id)
|| crate::db::events::wrapper_event_exists(&event.id.to_hex()).unwrap_or(false))
{
return;
}
let remember = || {
if durable {
let _ = crate::db::wrappers::save_processed_wrapper(&wrap_id, wrap_at, crate::db::wrappers::TRANSPORT_CONCORD);
}
};
let held = load_held_v2_cached();
let Some(c) = held.route(&event.pubkey) else {
return;
};
{
let wrap = &event;
match inbound::dispatch_wrap(&event, c, &my_pk, &*handler) {
inbound::DispatchedV2::NotOurs => return,
inbound::DispatchedV2::Control { .. } => {
if !apply_live_control(c, wrap, &*handler).await {
enqueue_follow_urgent(c.id());
}
return;
}
inbound::DispatchedV2::Rekey { .. } => {
enqueue_follow_urgent(c.id());
return;
}
inbound::DispatchedV2::Dissolved { community_id } => {
if crate::db::community::set_community_dissolved(&community_id).unwrap_or(false) {
stamp_dissolved_chats(c.id()).await;
dissolved(&*handler, &community_id);
if let Some(client) = crate::state::nostr_client() {
refresh_subscription(&client).await;
}
}
return;
}
inbound::DispatchedV2::Early { at_ms } => {
seen_wraps().lock().unwrap_or_else(|e| e.into_inner()).forget(wrap.id.as_bytes());
crate::early::hold(wrap.clone(), crate::early::Via::Community, at_ms);
return;
}
inbound::DispatchedV2::Chat { channel_id, event } => {
if event.opened().author == my_pk {
let plane = crate::community::id32_from_hex(&channel_id)
.and_then(|ch| super::service::plane_key_of(c, &crate::community::ChannelId(ch), wrap));
super::service::heal_own_wrap_key(&event, wrap, plane.as_ref(), &c.relays);
}
let outcome = inbound::persist_routed_chat_event(&event, &channel_id, &c.id().0, &my_pk).await;
if outcome.is_some() || !inbound::awaits_target(&event).await {
remember();
}
if let Some(outcome) = outcome {
inbound::notify_chat_outcome(&*handler, &channel_id, &event, outcome, true).await;
}
return;
}
inbound::DispatchedV2::Held { channel_id, author, at_ms, marked } => {
let held = crate::community::id32_from_hex(&channel_id).is_some_and(|ch| super::service::writing_hold(&c.id().0, &crate::community::ChannelId(ch), &event, &author, at_ms));
if !held {
return;
}
remember();
if let Some(marked) = marked {
if let Some(inbound::ChatPersist::New(message)) = inbound::persist_routed_chat_event(&marked, &channel_id, &c.id().0, &my_pk).await {
let news = crate::news::listening_since().is_some() && crate::news::is_news(message.at) && crate::news::first_telling_hex(&message.id);
handler.on_community_message(&channel_id, &message, news);
}
}
return;
}
inbound::DispatchedV2::Presence { event: ev, .. } => {
let joined = match &ev.entry {
super::guestbook::GuestbookEntry::Join { member, .. } => Some(*member),
_ => None,
};
let changed = ingest_live(c, *ev, &event);
remember();
if changed {
handler.on_community_refreshed(&crate::simd::hex::bytes_to_hex_32(&c.id().0));
if joined.is_some_and(|m| super::service::holds_grant(c, &m)) {
super::service::access_duty_now(c.id());
enqueue_follow(c.id());
}
}
return;
}
inbound::DispatchedV2::Nickname(ev) | inbound::DispatchedV2::Timeout(ev) => {
let changed = if matches!(ev.entry, super::guestbook::GuestbookEntry::Nickname { .. }) { "community_nicknames" } else { "community_timeouts" };
remember();
if ingest_live(c, *ev, &event) {
let community_id = crate::simd::hex::bytes_to_hex_32(&c.id().0);
crate::traits::emit_event_json(changed, serde_json::json!({ "community_id": community_id }));
super::changes::notify_soon(handler.clone(), &community_id);
}
return;
}
inbound::DispatchedV2::Kick { target, event: ev } => {
let (actor, kick_rumor, kick_at) = match &ev.entry {
super::guestbook::GuestbookEntry::Kick { actor, at_ms, .. } => (Some(*actor), ev.rumor_id, *at_ms),
_ => (None, ev.rumor_id, crate::clock::now_ms()),
};
if !ingest_live(c, *ev, &event) {
return;
}
let community_id = crate::simd::hex::bytes_to_hex_32(&c.id().0);
let kicked_at = (my_pk == target).then(|| super::service::stored_kick_at(c, &my_pk)).flatten();
if let Some(at) = kicked_at {
crate::log_warn!(
"[v2:teardown {}] KICK: the authorized guestbook fold rules us kicked",
&community_id[..8.min(community_id.len())]
);
super::service::record_eviction(c, at);
self_removed(&*handler, &community_id);
} else {
if my_pk != target && handler.wants_community_changes() && super::service::stored_kick_rumor(c, &target) == Some(kick_rumor) {
let change = super::changes::CommunityChange::new(
actor.and_then(|a| nostr_sdk::prelude::ToBech32::to_bech32(&a).ok()),
kick_at,
super::changes::ChangeKind::MemberKicked { member: nostr_sdk::prelude::ToBech32::to_bech32(&target).unwrap_or_else(|_| target.to_hex()) },
);
super::changes::notify_one(&*handler, &community_id, change);
}
refreshed(&*handler, &community_id);
}
return;
}
_ => {
remember();
return;
}
}
}
})
.await
}
pub fn follow_worker_running() -> bool {
V2_FOLLOW_TX.lock().unwrap().as_ref().map(|tx| !tx.is_closed()).unwrap_or(false)
}
pub fn enqueue_follow(id: &CommunityId) {
let mut pending = V2_FOLLOW_PENDING.lock().unwrap();
if !pending.insert(id.0) {
return; }
let closed = {
let tx = V2_FOLLOW_TX.lock().unwrap_or_else(|e| e.into_inner());
match tx.as_ref() {
Some(tx) if tx.send(*id).is_ok() => false,
Some(tx) => tx.is_closed(),
None => false,
}
};
if closed {
pending.remove(&id.0);
}
}
pub fn enqueue_follow_urgent(id: &CommunityId) {
V2_FOLLOW_URGENT.lock().unwrap_or_else(|e| e.into_inner()).insert(id.0);
enqueue_follow(id);
}
fn pop_next_follow(queue: &mut std::collections::VecDeque<CommunityId>) -> Option<CommunityId> {
let pos = {
let urgent = V2_FOLLOW_URGENT.lock().unwrap_or_else(|e| e.into_inner());
if urgent.is_empty() { None } else { queue.iter().position(|id| urgent.contains(&id.0)) }
};
match pos {
Some(i) => queue.remove(i),
None => queue.pop_front(),
}
}
fn prioritize_by_activity(
batch: Vec<CommunityId>,
activity: impl Fn(&CommunityId) -> u64,
) -> Vec<CommunityId> {
let mut keyed: Vec<(u64, CommunityId)> = batch.into_iter().map(|id| (activity(&id), id)).collect();
keyed.sort_by_key(|k| std::cmp::Reverse(k.0));
keyed.into_iter().map(|(_, id)| id).collect()
}
pub fn spawn_follow_worker(handler: Arc<dyn InboundEventHandler>) {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<CommunityId>();
{
let pending = V2_FOLLOW_PENDING.lock().unwrap_or_else(|e| e.into_inner());
for id in pending.iter() {
let _ = tx.send(CommunityId(*id));
}
}
*V2_FOLLOW_TX.lock().unwrap_or_else(|e| e.into_inner()) = Some(tx);
let session = crate::db::current_session();
crate::db::spawn_bound(async move {
while let Some(first) = rx.recv().await {
let mut batch = vec![first];
while let Ok(next) = rx.try_recv() {
batch.push(next);
}
if batch.len() > 1 {
let last_msgs = crate::db::events::get_all_chats_last_messages().await.unwrap_or_default();
let activity = |cid: &CommunityId| -> u64 {
crate::db::community::load_community_v2(cid)
.ok()
.flatten()
.map(|c| {
c.channels
.iter()
.filter_map(|ch| {
let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
last_msgs.get(&ch_hex).and_then(|v| v.first().map(|m| m.at))
})
.max()
.unwrap_or(0)
})
.unwrap_or(0)
};
batch = prioritize_by_activity(batch, activity);
}
let mut queue: std::collections::VecDeque<CommunityId> = batch.into();
loop {
while let Ok(next) = rx.try_recv() {
queue.push_back(next);
}
let Some(id) = pop_next_follow(&mut queue) else { break };
V2_FOLLOW_PENDING.lock().unwrap_or_else(|e| e.into_inner()).remove(&id.0);
V2_FOLLOW_URGENT.lock().unwrap_or_else(|e| e.into_inner()).remove(&id.0);
let one = std::panic::AssertUnwindSafe(follow_community(&session, &id, &*handler));
if futures_util::FutureExt::catch_unwind(one).await.is_err() {
crate::log_warn!(
"[v2:follow {}] worker caught a panic; the queue stays alive",
&crate::simd::hex::bytes_to_hex_32(&id.0)[..8]
);
}
}
}
});
}
async fn follow_community(session: &std::sync::Arc<crate::db::Session>, id: &CommunityId, handler: &dyn InboundEventHandler) {
crate::db::scoped(async move {
let Some(client) = crate::state::nostr_client() else {
return;
};
let community_id = crate::simd::hex::bytes_to_hex_32(&id.0);
if crate::db::community::get_community_dissolved(&community_id).unwrap_or(false) {
return;
}
if super::service::has_read_cuts(&community_id) || super::service::has_owed_settle(&community_id) {
let owed = *id;
crate::db::spawn_bound(async move { super::service::retry_owed_rotations(&owed).await });
}
let lock = follow_lock(id);
let _guard = lock.lock().await;
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let mut laps = Laps::start();
let moved_live = take_live_authority_move(id);
if moved_live {
note_roster_move(id);
keys_first(id, &community_id, &transport, &client, session, handler).await;
laps.mark("keys-first");
}
let Ok(Some(current)) = crate::db::community::load_community_v2(id) else {
return; };
let rekeys = super::service::follow_rekeys(&transport, ¤t, session).await;
let rekeys_ok = rekeys.is_ok();
match rekeys {
Ok(follow) if follow.dissolved => {
if !current.dissolved {
crate::log_warn!("[v2:teardown {}] DISSOLVED tombstone", &community_id[..8.min(community_id.len())]);
stamp_dissolved_chats(id).await;
dissolved(&*handler, &community_id);
}
return;
}
Ok(follow) if follow.self_removed => {
crate::log_warn!("[v2:teardown {}] REKEY EXCLUSION: an authorized rotation left us out", &community_id[..8.min(community_id.len())]);
super::service::record_eviction(¤t, follow.removed_at.unwrap_or_else(super::service::now_ms));
let _ = crate::db::community::delete_community_retain_keys(&community_id);
refresh_subscription(&client).await;
self_removed(&*handler, &community_id);
return;
}
Ok(follow) if follow.updated.is_some() => {
refresh_subscription(&client).await;
refreshed(&*handler, &community_id);
reread_moved_channels(¤t);
}
Ok(_) => {}
Err(e) => {
crate::log_warn!("[v2:follow {}] rekey follow failed (control pass still runs): {}", &community_id[..8.min(community_id.len())], e);
}
}
laps.mark("rekeys");
take_owed_keys(id, &community_id, &transport, &client, session, handler).await;
let Ok(Some(current)) = crate::db::community::load_community_v2(id) else {
return;
};
let followed = super::service::follow_control(&transport, ¤t).await;
laps.mark("control");
if followed.as_ref().is_ok_and(|c| c.authority_changed) {
note_roster_move(id);
}
take_owed_keys(id, &community_id, &transport, &client, session, handler).await;
let control_ok = followed.is_ok();
let control = match followed {
Ok(c) => c,
Err(e) => {
crate::log_warn!("[v2:follow {}] control follow failed: {}", &community_id[..8.min(community_id.len())], e);
super::service::ControlFollow::default()
}
};
let control_changed = control.updated.is_some();
let authority_changed = control.authority_changed || moved_live;
if control_ok {
super::changes::notify(&*handler, &community_id);
}
if control.moved() {
if let Ok(Some(latest)) = crate::db::community::load_community_v2(id) {
match super::service::follow_rekeys(&transport, &latest, session).await {
Ok(f) if f.self_removed || f.dissolved => {}
Ok(f) if f.updated.is_some() => {
refresh_subscription(&client).await;
refreshed(&*handler, &community_id);
}
Ok(_) => {}
Err(e) => crate::log_warn!(
"[v2:follow {}] post-authority rekey re-walk failed: {}",
&community_id[..8.min(community_id.len())], e
),
}
}
}
laps.mark("re-walk");
let collect = super::service::access_collect_due(id, authority_changed);
if let Some(current) = crate::db::community::load_community_v2(id).ok().flatten().filter(|_| collect) {
match super::service::collect_access(&transport, ¤t).await {
Ok(0) => {}
Ok(n) => crate::log_info!("[v2:follow {}] {n} key(s) waiting on access planes", &community_id[..8.min(community_id.len())]),
Err(e) => crate::log_warn!("[v2:follow {}] access plane read failed: {e}", &community_id[..8.min(community_id.len())]),
}
match super::service::collect_writers(&transport, ¤t).await {
Ok(0) => {}
Ok(n) => {
crate::log_info!("[v2:follow {}] took {n} writer key(s)", &community_id[..8.min(community_id.len())]);
refresh_subscription(&client).await;
refreshed(&*handler, &community_id);
}
Err(e) => crate::log_warn!("[v2:follow {}] writer key read failed: {e}", &community_id[..8.min(community_id.len())]),
}
}
laps.mark("access");
if rekeys_ok && control_ok && super::service::access_duty_due(id, authority_changed) {
let owed = *id;
crate::db::spawn_bound(async move {
crate::rt::time::sleep(std::time::Duration::from_millis(3_000 + rand::random::<u64>() % 12_000)).await;
if !crate::db::current_session().is_live() {
return;
}
let Ok(Some(c)) = crate::db::community::load_community_v2(&owed) else { return };
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
match super::service::access_duty(&transport, &c).await {
Ok(done) if done == Default::default() => {}
Ok(done) => crate::log_info!(
"[v2:access] delivered {} channel key(s), cut {} holder(s) a channel no longer lets in; writers: {} delivered, {} cut, {} ledger(s) moved",
done.delivered, done.cut, done.writers.delivered, done.writers.cut, done.writers.moved
),
Err(e) => crate::log_warn!("[v2:access] access duty failed: {e}"),
}
});
}
if authority_changed {
let again = *id;
crate::db::spawn_bound(async move {
let mut waited = 0;
for (at, whatever) in OWED_LOOKS_SECS {
crate::rt::time::sleep(std::time::Duration::from_secs(at - waited)).await;
waited = at;
if !crate::db::current_session().is_live() {
return;
}
let owed = crate::db::community::load_community_v2(&again).ok().flatten().is_some_and(|c| super::service::owed_keys(&c));
if owed || whatever {
super::service::access_collect_now(&again);
enqueue_follow(&again);
}
}
});
}
adopt_parked_keys(id, &community_id, &transport, &client, session, handler, authority_changed).await;
laps.mark("keys");
if control_changed {
refresh_subscription(&client).await;
refreshed(&*handler, &community_id);
reread_moved_channels(¤t);
enqueue_follow(id);
} else if control_ok {
super::changes::notify(&*handler, &community_id);
}
if let Some(me) = crate::my_public_key() {
if crate::db::community::is_author_banned(&community_id, &me) {
crate::log_warn!("[v2:teardown {}] SELF-BAN: our npub is in the folded banlist", &community_id[..8.min(community_id.len())]);
let banned_at = crate::db::community::get_community_ban_marks(&community_id)
.ok()
.and_then(|marks| marks.get(&me.to_hex()).map(|s| s.saturating_mul(1000)))
.unwrap_or_else(super::service::now_ms);
super::service::record_eviction(¤t, banned_at.min(super::service::now_ms()));
self_removed(&*handler, &community_id);
return;
}
}
laps.mark("notify");
let Ok(Some(current)) = crate::db::community::load_community_v2(id) else {
return;
};
if let Ok(fresh) = super::service::sync_guestbook(&transport, ¤t).await {
if let Some(at) = crate::state::my_public_key().and_then(|me| super::service::stored_kick_at(¤t, &me)) {
crate::log_warn!("[v2:teardown {}] KICK read on catch-up: the authorized guestbook fold rules us kicked", &community_id[..8.min(community_id.len())]);
super::service::record_eviction(¤t, at);
self_removed(&*handler, &community_id);
return;
}
if fresh.iter().any(|ev| matches!(&ev.entry, super::guestbook::GuestbookEntry::Join { member, .. } if super::service::holds_grant(¤t, member))) {
super::service::access_duty_now(id);
enqueue_follow(id);
}
if !fresh.is_empty() {
surface_presence(¤t, &fresh, handler);
surface_kicks(¤t, &fresh, handler);
refreshed(&*handler, &community_id);
}
match super::service::heal_my_join(&transport, ¤t).await {
Ok(true) => refreshed(&*handler, &community_id),
Ok(false) => {}
Err(e) => crate::log_debug!("[v2:join {}] restore deferred: {e}", &community_id[..8.min(community_id.len())]),
}
match super::service::heal_ban_departures(&transport, ¤t).await {
Ok(0) => {}
Ok(n) => {
crate::log_info!("[v2:ban {}] wrote {n} lifted ban(s) to the Guestbook", &community_id[..8.min(community_id.len())]);
refreshed(&*handler, &community_id);
}
Err(e) => crate::log_debug!("[v2:ban {}] departures deferred: {e}", &community_id[..8.min(community_id.len())]),
}
if let Err(e) = super::service::carry_my_nickname(&transport, ¤t).await {
crate::log_debug!("[v2:nickname {}] carry deferred: {e}", &community_id[..8.min(community_id.len())]);
}
if super::service::guestbook_walk_pending(¤t) {
let id = *id;
crate::db::spawn_bound(async move {
crate::rt::time::sleep(std::time::Duration::from_secs(10)).await;
enqueue_follow(&id);
});
}
}
if let Ok(Some(folded)) = crate::db::community::load_community_v2(id) {
super::service::owe_new_departures(&folded);
}
settle_owed_retractions(id, &transport, handler).await;
if let Ok(Some(folded)) = crate::db::community::load_community_v2(id) {
let released = super::service::rejudge_held(&folded, handler).await;
if released > 0 {
crate::log_info!("[v2:follow {}] {released} held post(s) stand now", &community_id[..8.min(community_id.len())]);
}
}
laps.mark("guestbook");
crate::log_debug!("[v2:follow {}] pass: {laps}", &community_id[..8.min(community_id.len())]);
})
.await
}
const KEYED_BACKFILL_CONCURRENCY: usize = 4;
async fn adopt_parked_keys(
id: &CommunityId,
community_id: &str,
transport: &crate::community::transport::LiveTransport,
client: &Client,
session: &Arc<crate::db::Session>,
handler: &dyn InboundEventHandler,
moved: bool,
) -> usize {
let Ok(Some(folded)) = crate::db::community::load_community_v2(id) else { return 0 };
let keyed = super::service::absorb_parked_channel_keys(&folded, session);
if !keyed.is_empty() {
crate::log_info!("[v2:follow {}] adopted {} vended private-channel key(s)", &community_id[..8.min(community_id.len())], keyed.len());
refresh_subscription(client).await;
}
let reread = crate::db::community::load_community_v2(id).ok().flatten();
let mut rooms: Vec<crate::community::ChannelId> = keyed.clone();
if let Some(now) = reread.filter(|_| super::service::history_collect_due(id, moved || !keyed.is_empty() || owed_history(id))) {
match super::service::collect_history_rooms(transport, &now).await {
Ok(took) if took.is_empty() => {}
Ok(took) => {
crate::log_info!("[v2:follow {}] {} past epoch(s) delivered read-only", &community_id[..8.min(community_id.len())], took.iter().map(|(_, n)| n).sum::<usize>());
rooms.extend(took.into_iter().map(|(ch, _)| ch).filter(|ch| !keyed.contains(ch)));
}
Err(e) => crate::log_warn!("[v2:follow {}] history read failed: {e}", &community_id[..8.min(community_id.len())]),
}
}
let rooms: Vec<String> = rooms.iter().map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.0)).collect();
for rooms in rooms.chunks(KEYED_BACKFILL_CONCURRENCY) {
let fills = futures_util::future::join_all(rooms.iter().map(|hex| {
crate::VectorCore::v2_backfill_channel(id, hex, 50, 2, None, None, crate::community::transport::Evidence::Fast, 12)
}))
.await;
for (hex, backfilled) in rooms.iter().zip(fills) {
handler.on_channel_keyed(community_id, hex, backfilled);
}
}
keyed.len()
}
struct OwedLooks;
fn owed_looks() -> Arc<StdMutex<HashMap<[u8; 32], u64>>> {
crate::db::current_session().scoped::<OwedLooks, _>()
}
const OWED_LOOKS_FOR_MS: u64 = 60_000;
fn owed_history(id: &CommunityId) -> bool {
owed_looks().lock().unwrap_or_else(|e| e.into_inner()).get(&id.0).is_some_and(|until| crate::clock::now_ms() < *until)
}
fn note_roster_move(id: &CommunityId) {
owed_looks().lock().unwrap_or_else(|e| e.into_inner()).insert(id.0, crate::clock::now_ms() + OWED_LOOKS_FOR_MS);
}
async fn take_owed_keys(
id: &CommunityId,
community_id: &str,
transport: &crate::community::transport::LiveTransport,
client: &Client,
session: &Arc<crate::db::Session>,
handler: &dyn InboundEventHandler,
) {
if owed_looks().lock().unwrap_or_else(|e| e.into_inner()).get(&id.0).is_none_or(|until| crate::clock::now_ms() >= *until) {
return;
}
let Ok(Some(current)) = crate::db::community::load_community_v2(id) else { return };
let (rooms, writers) = (super::service::owed_channel_keys(¤t), super::service::owed_writer_keys(¤t));
if rooms {
if let Err(e) = super::service::collect_access(transport, ¤t).await {
crate::log_warn!("[v2:follow {}] access plane read failed: {e}", &community_id[..8.min(community_id.len())]);
}
adopt_parked_keys(id, community_id, transport, client, session, handler, false).await;
}
if writers {
match super::service::collect_writers(transport, ¤t).await {
Ok(0) => {}
Ok(n) => {
crate::log_info!("[v2:follow {}] took {n} writer key(s)", &community_id[..8.min(community_id.len())]);
refresh_subscription(client).await;
refreshed(handler, community_id);
}
Err(e) => crate::log_warn!("[v2:follow {}] writer key read failed: {e}", &community_id[..8.min(community_id.len())]),
}
}
}
const OWED_LOOKS_SECS: [(u64, bool); 3] = [(3, false), (8, false), (20, true)];
const KEY_LOOKS_MS: [u64; 3] = [0, 400, 800];
async fn keys_first(
id: &CommunityId,
community_id: &str,
transport: &crate::community::transport::LiveTransport,
client: &Client,
session: &Arc<crate::db::Session>,
handler: &dyn InboundEventHandler,
) {
for wait in KEY_LOOKS_MS {
let Ok(Some(current)) = crate::db::community::load_community_v2(id) else { return };
if !super::service::owed_channel_keys(¤t) {
return;
}
crate::rt::time::sleep(std::time::Duration::from_millis(wait)).await;
if let Err(e) = super::service::collect_access(transport, ¤t).await {
crate::log_warn!("[v2:follow {}] access plane read failed: {e}", &community_id[..8.min(community_id.len())]);
}
adopt_parked_keys(id, community_id, transport, client, session, handler, false).await;
}
}
struct Laps {
last: web_time::Instant,
took: Vec<(&'static str, u128)>,
}
impl Laps {
fn start() -> Self {
Laps { last: web_time::Instant::now(), took: Vec::new() }
}
fn mark(&mut self, stage: &'static str) {
let now = web_time::Instant::now();
self.took.push((stage, now.duration_since(self.last).as_millis()));
self.last = now;
}
}
impl std::fmt::Display for Laps {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for (i, (stage, ms)) in self.took.iter().enumerate() {
write!(f, "{}{stage} {ms}ms", if i == 0 { "" } else { ", " })?;
}
Ok(())
}
}
fn surface_kicks(community: &CommunityV2, fresh: &[super::guestbook::GuestbookEvent], handler: &dyn InboundEventHandler) {
use nostr_sdk::prelude::ToBech32;
if !handler.wants_community_changes() {
return;
}
let me = crate::state::my_public_key();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
for ev in fresh {
let super::guestbook::GuestbookEntry::Kick { actor, target, at_ms, .. } = &ev.entry else { continue };
if Some(*target) == me || super::service::stored_kick_rumor(community, target) != Some(ev.rumor_id) {
continue;
}
let member = target.to_bech32().unwrap_or_else(|_| target.to_hex());
let change = super::changes::CommunityChange::new(actor.to_bech32().ok(), *at_ms, super::changes::ChangeKind::MemberKicked { member });
super::changes::notify_one(handler, &cid_hex, change);
}
}
fn surface_presence(
community: &CommunityV2,
fresh: &[super::guestbook::GuestbookEvent],
handler: &dyn InboundEventHandler,
) {
use super::guestbook::GuestbookEntry;
use nostr_sdk::prelude::ToBech32;
let Some(home) = community.presence_home() else {
return;
};
let channel_id = crate::simd::hex::bytes_to_hex_32(&home.channel.id.0);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let banned = crate::db::community::banned_set(&cid_hex);
for ev in fresh {
let (member, joined, at_ms, invited_by) = match &ev.entry {
GuestbookEntry::Join { member, at_ms, invited_by } => (member, true, *at_ms, invited_by.clone()),
GuestbookEntry::Leave { member, at_ms } => (member, false, *at_ms, None),
GuestbookEntry::Kick { .. } | GuestbookEntry::Snapshot { .. } | GuestbookEntry::Timeout { .. } | GuestbookEntry::Nickname { .. } => continue,
};
if banned.contains(&member.to_bytes()) {
continue;
}
let Ok(npub) = member.to_bech32();
let event_id = crate::simd::hex::bytes_to_hex_32(&ev.rumor_id);
let (by, label) = match &invited_by {
Some((c, l)) => (Some(c.as_str()), Some(l.as_str())),
None => (None, None),
};
if crate::news::first_telling(&ev.rumor_id) {
handler.on_community_presence(&crate::Presence {
community_id: &cid_hex,
channel_id: &channel_id,
shown: home.shown,
npub: &npub,
joined,
event_id: &event_id,
created_at: at_ms / 1000,
invited_by: by,
invited_label: label,
});
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn cid(b: u8) -> CommunityId {
CommunityId([b; 32])
}
#[test]
fn a_live_authority_move_is_owed_to_exactly_one_pass() {
let (a, b) = (cid(0xA1), cid(0xB2));
assert!(!take_live_authority_move(&a), "nothing moved yet");
note_live_authority_move(&a);
note_live_authority_move(&a);
assert!(!take_live_authority_move(&b), "another community's move is not this one's");
assert!(take_live_authority_move(&a), "the pass a live fold queued hears of the move");
assert!(!take_live_authority_move(&a), "and the pass after it does not");
}
#[test]
fn the_follow_queue_walks_the_community_you_are_actually_reading_first() {
let stale = cid(1);
let active = cid(2);
let middling = cid(3);
let batch = vec![stale, active, middling]; let out = prioritize_by_activity(batch, |c| match c.0[0] {
1 => 1_000, 2 => 9_000_000, 3 => 500_000,
_ => 0,
});
assert_eq!(
out,
vec![active, middling, stale],
"the most recently active community must be followed first regardless of arrival order",
);
}
#[test]
fn an_all_silent_batch_keeps_its_arrival_order() {
let batch = vec![cid(7), cid(8), cid(9)];
let out = prioritize_by_activity(batch.clone(), |_| 0);
assert_eq!(out, batch, "equal activity is a stable sort, not a reshuffle");
}
use super::super::control::{genesis, CommunityMetadata};
use crate::community::Epoch;
use nostr_sdk::prelude::Keys;
fn a_community(name: &str) -> CommunityV2 {
let owner = Keys::generate();
let g = genesis(&owner, CommunityMetadata { name: name.into(), ..Default::default() }, 1_000).unwrap();
CommunityV2::from_genesis(&g, name, None, vec!["wss://r".into()], 0)
}
#[test]
fn subscription_readiness_is_scoped_to_the_session_that_marked_it() {
let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
mark_subscription_ready();
assert!(subscription_ready(), "marked for the current session");
crate::db::close_database();
assert!(!subscription_ready(), "an account swap invalidates it");
mark_subscription_ready();
assert!(subscription_ready(), "the new session's own pass re-arms it");
}
#[test]
fn plane_authors_covers_the_dispatched_planes_only() {
let c = a_community("A");
let authors = plane_authors(std::slice::from_ref(&c));
let gb = derive::guestbook_group_key(&c.community_root, c.id(), c.root_epoch).pk();
let control = crate::community::v2::control::ControlPlane::of(&c).pk();
assert_ne!(control, derive::control_group_key(&c.community_root, c.id(), c.root_epoch).pk());
let general = {
let (s, e) = c.channel_secret(&c.channels[0]);
derive::channel_group_key(&s, &c.channels[0].id, e).pk()
};
let next_base = derive::base_rekey_group_key(&c.community_root, c.id(), Epoch(1)).pk();
let dissolved = derive::dissolved_group_key(c.id()).pk();
assert!(
authors.contains(&gb)
&& authors.contains(&control)
&& authors.contains(&general)
&& authors.contains(&next_base)
&& authors.contains(&dissolved)
);
assert_eq!(authors.len(), 5, "guestbook + control + dissolved + chat + base-rekey planes are subscribed");
}
#[test]
fn plane_authors_is_deterministic_deduped_and_multi_community() {
let a = a_community("A");
let b = a_community("B");
let one = plane_authors(std::slice::from_ref(&a));
assert_eq!(plane_authors(std::slice::from_ref(&a)), one);
let two = plane_authors(&[a.clone(), b.clone()]);
assert_eq!(two.len(), one.len() * 2);
assert_eq!(plane_authors(&[b, a]), two);
}
#[test]
fn an_older_load_finishing_last_never_stands_over_a_newer_one() {
let empty = || Arc::new(HeldV2 { communities: Box::new([]), routes: std::sync::OnceLock::new() });
let load = |generation: u64, written: &[([u8; 32], u64)], previous: Option<(web_time::Instant, Arc<HeldV2>)>| HeldLoad {
generation,
written: written.iter().copied().collect(),
whole: None,
previous,
unread: Vec::new(),
};
let y = [7u8; 32];
let t0 = web_time::Instant::now();
let mut held = HeldV2Cache { generation: 2, written: [(y, 2)].into_iter().collect(), whole: None, snapshot: Some((t0, 0, empty())) };
let (a, b) = (load(1, &[(y, 1)], Some((t0, empty()))), load(2, &[(y, 2)], Some((t0, empty()))));
let newer = empty();
b.settle(&mut held, Arc::clone(&newer), t0);
a.settle(&mut held, empty(), t0);
let (at, under, standing) = held.snapshot.as_ref().unwrap();
assert_eq!(*under, 2, "the later finisher's older snapshot is not installed");
assert!(Arc::ptr_eq(standing, &newer));
assert!(held.written.is_empty(), "y's write was read by the newer load");
assert_eq!(*at, t0);
let later = t0 + std::time::Duration::from_secs(5);
load(2, &[], None).settle(&mut held, empty(), later);
assert_eq!(held.snapshot.as_ref().unwrap().0, later, "a whole read restarts the backstop");
}
#[tokio::test]
async fn a_live_subscription_check_never_waits_on_a_refresh() {
let live = SubscriptionId::new("live-targeted");
let other = SubscriptionId::new("a-fetch");
*V2_SUB_ID.lock().await = Some(live.clone());
assert!(is_live_subscription(&live));
assert!(!is_live_subscription(&other), "a fetch's subscription is not the live one");
let replaced = SubscriptionId::new("replaced-by-a-refresh");
assert!(!is_live_subscription(&replaced));
retire_subscription(replaced.clone());
assert!(is_live_subscription(&replaced) && routes_live(&replaced), "a replaced subscription still routes");
for i in 0..RETIRED_SUBS_KEPT {
retire_subscription(SubscriptionId::new(format!("later-{i}")));
}
assert!(!routes_live(&replaced), "only the last few are kept");
let held = V2_POOLWIDE_SUB_ID.lock().await;
assert!(is_live_subscription(&other));
drop(held);
*V2_SUB_ID.lock().await = None;
assert!(!is_live_subscription(&live));
}
#[tokio::test]
async fn a_committed_key_or_epoch_change_reaches_the_live_routes_at_once() {
use crate::community::transport::memory::MemoryRelay;
let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
crate::db::close_database();
crate::db::clear_id_caches();
let acct = {
const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
let mut s = String::from("npub1");
for i in 0..58 {
s.push(B[(i * 23 + 3) % 32] as char);
}
s
};
crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
crate::db::set_current_account(acct.clone()).unwrap();
crate::db::init_database(&acct).unwrap();
let me = Keys::generate();
crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
crate::state::set_my_public_key(me.public_key());
let relay = MemoryRelay::new();
let c = super::super::service::create_community(&relay, "Routes", vec!["wss://r".into()], None).await.unwrap();
let cid = crate::simd::hex::bytes_to_hex_32(&c.id().0);
let general = c.channels[0].id;
let routed = |root: &[u8; 32], epoch: u64| {
let pk = derive::channel_group_key(root, &general, Epoch(epoch)).pk();
load_held_v2_cached().route(&pk).is_some()
};
assert!(routed(&c.community_root, 0));
let next = [0x5au8; 32];
assert!(crate::db::community::advance_server_root_epoch(&cid, 1, &next).unwrap());
assert!(routed(&next, 1), "the adopted epoch's plane routes without waiting out a cache");
assert!(!routed(&c.community_root, 0), "and the retired one no longer does");
let sibling = [0x11u8; 32];
assert!(crate::db::community::converge_server_root_epoch(&cid, 1, &sibling).unwrap());
assert!(routed(&sibling, 1));
let other = super::super::service::create_community(&relay, "Other", vec!["wss://r".into()], None).await.unwrap();
let other_general = other.channels[0].id;
let other_routed = || load_held_v2_cached().route(&derive::channel_group_key(&other.community_root, &other_general, Epoch(0)).pk()).is_some();
assert!(other_routed() && routed(&sibling, 1));
let third = [0x22u8; 32];
assert!(crate::db::community::advance_server_root_epoch(&cid, 2, &third).unwrap());
assert!(routed(&third, 2) && !routed(&sibling, 1), "the written community is read again");
assert!(other_routed(), "the other one still routes");
crate::db::community::delete_community(&crate::simd::hex::bytes_to_hex_32(&other.id().0)).unwrap();
assert!(!other_routed(), "a deleted community stops routing");
assert!(routed(&third, 2));
invalidate_held_v2_cache();
assert!(routed(&third, 2) && !other_routed(), "a whole reload agrees");
}
#[tokio::test]
async fn a_timeout_heard_live_counts_at_once() {
use crate::community::transport::memory::MemoryRelay;
use crate::community::transport::{Query, Transport};
struct Quiet;
impl InboundEventHandler for Quiet {}
let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
crate::db::close_database();
crate::db::clear_id_caches();
let acct = {
const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
let mut s = String::from("npub1");
for i in 0..58 {
s.push(B[(i * 19 + 5) % 32] as char);
}
s
};
crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
crate::db::set_current_account(acct.clone()).unwrap();
crate::db::init_database(&acct).unwrap();
let _ = crate::state::take_nostr_client();
let me = Keys::generate();
crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
crate::state::set_my_public_key(me.public_key());
let relay = MemoryRelay::new();
let community = super::super::service::create_community(&relay, "LiveTimeout", vec!["wss://r".into()], None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let member = Keys::generate().public_key();
let (before, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
super::super::service::timeout_member(&relay, &held(), &member, 600).await.unwrap();
crate::db::community::set_guestbook(&cid_hex, &before, cursor).unwrap();
assert!(!super::super::service::community_timeouts(&held()).unwrap().contains_key(&member));
let gb = derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![gb.pk_hex()], ..Default::default() };
let wraps = relay.fetch(&q, &community.relays).await.unwrap();
crate::community::v2::realtime::clear().await;
for wrap in wraps {
dispatch_event(wrap, Arc::new(Quiet)).await;
}
let running = super::super::service::community_timeouts(&held()).unwrap();
assert!(running.get(&member).is_some_and(|(_, until)| *until > crate::clock::now_secs()), "it runs without waiting for a guestbook read");
}
#[tokio::test]
async fn a_message_dated_ahead_waits_for_its_time_then_arrives() {
use super::super::stream::{self, SealForm};
use crate::community::transport::memory::MemoryRelay;
let _g = 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 acct = {
const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
let mut s = String::from("npub1");
for i in 0..58 {
s.push(B[(i * 17 + 11) % 32] as char);
}
s
};
std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
crate::db::set_current_account(acct.clone()).unwrap();
crate::db::init_database(&acct).unwrap();
let _ = crate::state::take_nostr_client();
let me = Keys::generate();
crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
crate::state::set_my_public_key(me.public_key());
crate::early::start(Arc::new(crate::event_handler::NoOpEventHandler));
let relay = MemoryRelay::new();
let community = super::super::service::create_community(&relay, "Clock", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let group = derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let member = Keys::generate();
let post = |text: &str, at_ms: u64| {
let rumor = super::super::chat::build_message_rumor(member.public_key(), &general, community.root_epoch, text, None, &[], vec![], at_ms);
let seal = stream::build_seal(&rumor, SealForm::Encrypted, &group, &member).unwrap();
let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, nostr_sdk::prelude::Timestamp::from_secs(at_ms / 1000)).unwrap();
(rumor.id.unwrap().to_hex(), wrap)
};
let now = crate::clock::now_ms();
let (late_id, late) = post("from a clock minutes fast", now + 4 * 60 * 1000);
let (soon_id, soon) = post("from a clock a little fast", now + crate::early::TOLERANCE_MS + 1_500);
let (fine_id, fine) = post("from a clock a hair fast", now + 2_000);
crate::community::v2::realtime::clear().await;
for wrap in [late.clone(), soon, fine] {
dispatch_event(wrap, Arc::new(crate::event_handler::NoOpEventHandler)).await;
}
let stored = |id: &str| crate::db::events::event_exists(id).unwrap();
assert!(stored(&fine_id), "a few seconds fast shows at once");
assert!(!stored(&late_id) && !stored(&soon_id), "ahead of the clock, they wait");
assert!(crate::early::held(&late.id));
assert!(!crate::db::wrappers::processed_wrapper_exists(&late.id.to_bytes()), "never marked handled, so a restart can't lose it");
for _ in 0..40 {
if stored(&soon_id) {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
assert!(stored(&soon_id), "released once its time came");
assert!(!stored(&late_id), "the other still waits");
}
#[tokio::test]
async fn a_live_message_from_my_other_device_arrives_fully_deletable() {
use super::super::stream::{self, SealForm};
use crate::community::message_delete::own_wrap_owner;
use crate::community::transport::memory::MemoryRelay;
let _g = 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 acct = {
const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
let mut s = String::from("npub1");
for i in 0..58 {
s.push(B[(i * 13 + 9) % 32] as char);
}
s
};
std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
crate::db::set_current_account(acct.clone()).unwrap();
crate::db::init_database(&acct).unwrap();
let _ = crate::state::take_nostr_client();
let me = Keys::generate();
crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
crate::state::set_my_public_key(me.public_key());
let relay = MemoryRelay::new();
let community = super::super::service::create_community(&relay, "Twin", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let group = derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let mine = |text: &str, at_ms: u64, derived: bool| {
let rumor = super::super::chat::build_message_rumor(me.public_key(), &general, community.root_epoch, text, None, &[], vec![], at_ms);
let rumor_id = rumor.id.unwrap();
let owner = if derived { own_wrap_owner(&me.public_key(), &group.pk(), &rumor_id).public_key() } else { Keys::generate().public_key() };
let seal = stream::build_seal(&rumor, SealForm::Encrypted, &group, &me).unwrap();
let wrap = stream::wrap_seal_for(&seal, &group, stream::KIND_WRAP, nostr_sdk::prelude::Timestamp::from_secs(at_ms / 1000), &[], &owner).unwrap();
(rumor_id.to_hex(), wrap)
};
let (twin, twin_wrap) = mine("from my phone", 5_000, true);
let (older, older_wrap) = mine("from an older build", 6_000, false);
crate::community::v2::realtime::clear().await;
dispatch_event(twin_wrap, Arc::new(crate::event_handler::NoOpEventHandler)).await;
dispatch_event(older_wrap, Arc::new(crate::event_handler::NoOpEventHandler)).await;
let has = |id: &str| (crate::db::community::has_wrap_owner(id).unwrap(), crate::db::community::has_message_key(id).unwrap());
assert_eq!(has(&twin), (true, true), "the owner this identity derives, and the plane key");
assert_eq!(has(&older), (false, true), "a random owner is no one's here");
let twin_wrap_hex = crate::db::community::wrap_owners(&twin).unwrap().pop().unwrap().1;
crate::db::community::delete_message_key(&twin).unwrap();
assert!(crate::db::events::community_wraps_settled(std::slice::from_ref(&twin_wrap_hex)).contains(&twin_wrap_hex));
}
#[tokio::test]
async fn dispatch_event_routes_a_v2_message_to_the_handler() {
use crate::community::transport::memory::MemoryRelay;
use crate::community::transport::{Query, Transport};
use crate::types::Message;
use std::sync::Mutex as StdMutex;
#[derive(Default)]
struct Recorder {
got: StdMutex<Vec<(String, String)>>,
}
impl InboundEventHandler for Recorder {
fn on_community_message(&self, chat_id: &str, msg: &Message, _new: bool) {
self.got.lock().unwrap().push((chat_id.to_string(), msg.content.clone()));
}
}
let _g = 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 acct = {
const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
let mut s = String::from("npub1");
for i in 0..58 {
s.push(B[(i * 5 + 1) % 32] as char);
}
s
};
std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
crate::db::set_current_account(acct.clone()).unwrap();
crate::db::init_database(&acct).unwrap();
let _ = crate::state::take_nostr_client();
let me = Keys::generate();
crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
crate::state::set_my_public_key(me.public_key());
let relay = MemoryRelay::new();
let community = super::super::service::create_community(&relay, "Live", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let member = Keys::generate();
let group = derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let rumor = super::super::chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "live ping", None, &[], vec![], 5_000);
let (wrap, _) = super::super::chat::seal_chat_rumor(&rumor, &group, &member, nostr_sdk::prelude::Timestamp::from_secs(5), false).unwrap();
let _ = relay.publish(&wrap, &community.relays).await;
let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
let wrap = relay.fetch(&q, &community.relays).await.unwrap().into_iter().find(|w| w.pubkey == group.pk()).unwrap();
let rec = Arc::new(Recorder::default());
crate::community::v2::realtime::clear().await; let first_id = wrap.id;
dispatch_event(wrap.clone(), rec.clone()).await;
dispatch_event(wrap, rec.clone()).await;
{
let got = rec.got.lock().unwrap();
assert_eq!(got.len(), 1, "a re-delivered wrap fires the handler exactly once");
assert_eq!(got[0].1, "live ping");
assert_eq!(got[0].0, crate::simd::hex::bytes_to_hex_32(&general.0));
}
assert!(crate::db::wrappers::processed_wrapper_exists(&first_id.to_bytes()), "a handled wrap joins the ledger");
let wrap_hex = first_id.to_hex();
assert!(crate::db::events::community_wraps_settled(std::slice::from_ref(&wrap_hex)).contains(&wrap_hex), "a stored foreign message is settled");
assert_eq!(crate::db::events::community_wraps_settled(&[wrap_hex.clone(), "cd".repeat(32)]).len(), 1, "an unknown wrap is not");
let w = crate::db::get_write_connection_guard_static().unwrap();
w.execute("UPDATE events SET mine = 1 WHERE wrapper_event_id = ?1", [&wrap_hex]).unwrap();
let rumor_hex: String = w.query_row("SELECT id FROM events WHERE wrapper_event_id = ?1", [&wrap_hex], |r| r.get(0)).unwrap();
drop(w);
assert!(!crate::db::events::community_wraps_settled(std::slice::from_ref(&wrap_hex)).contains(&wrap_hex), "my message without its delete key still heals on open");
crate::db::community::store_message_key(&rumor_hex, &wrap_hex, group.keys(), &community.relays).unwrap();
assert!(crate::db::events::community_wraps_settled(std::slice::from_ref(&wrap_hex)).contains(&wrap_hex), "with the key kept there is nothing left to heal");
crate::db::get_write_connection_guard_static().unwrap().execute("UPDATE events SET mine = 0 WHERE wrapper_event_id = ?1", [&wrap_hex]).unwrap();
let unseen = "ab".repeat(32);
let reaction = super::super::chat::build_reaction_rumor(
member.public_key(), &general, community.root_epoch, &unseen, &member.public_key().to_hex(), 14, "+", None, 7_000,
);
let (early, _) = super::super::chat::seal_chat_rumor(&reaction, &group, &member, nostr_sdk::prelude::Timestamp::from_secs(7), false).unwrap();
let early_id = early.id;
dispatch_event(early, rec.clone()).await;
assert!(!crate::db::wrappers::processed_wrapper_exists(&early_id.to_bytes()), "an early reaction is not ledgered");
let rumor2 = super::super::chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "second", None, &[], vec![], 6_000);
let (wrap2, _) = super::super::chat::seal_chat_rumor(&rumor2, &group, &member, nostr_sdk::prelude::Timestamp::from_secs(6), false).unwrap();
let moved = crate::db::get_write_connection_guard_static().unwrap().execute(
"UPDATE events SET wrapper_event_id = ?1 WHERE wrapper_event_id = ?2",
rusqlite::params![wrap2.id.to_hex(), first_id.to_hex()],
).unwrap();
assert_eq!(moved, 1, "the first message was stored under its outer id");
dispatch_event(wrap2, rec.clone()).await;
assert_eq!(rec.got.lock().unwrap().len(), 1, "a stored outer id never reaches the handler");
}
#[tokio::test]
async fn a_post_held_on_arrival_waits_and_a_manager_sees_it_unrung() {
use crate::community::v2::writers::{writer_address, Ledger, Spell};
use crate::types::Message;
use std::sync::Mutex as StdMutex;
#[derive(Default)]
struct Recorder {
got: StdMutex<Vec<(String, bool, bool)>>,
}
impl InboundEventHandler for Recorder {
fn on_community_message(&self, _chat_id: &str, msg: &Message, is_new: bool) {
self.got.lock().unwrap().push((msg.content.clone(), is_new, msg.unauthorized));
}
}
let _g = 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 acct = {
const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
let mut s = String::from("npub1");
for i in 0..58 {
s.push(B[(i * 11 + 9) % 32] as char);
}
s
};
std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
crate::db::set_current_account(acct.clone()).unwrap();
crate::db::init_database(&acct).unwrap();
let _ = crate::state::take_nostr_client();
let me = Keys::generate();
crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
crate::state::set_my_public_key(me.public_key());
let relay = crate::community::transport::memory::MemoryRelay::new();
let community = super::super::service::create_community(&relay, "Held live", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let (cid, chan) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
let ledger = Ledger::new(&general)
.appended(1_000, Spell::Writer { epoch: crate::community::Epoch(1), pk: writer_address(&[0x11; 32], &general, crate::community::Epoch(1)), root: community.root_epoch, by: me.public_key().to_bytes(), certifier: None })
.unwrap();
crate::db::community::set_community_writers(&cid, &chan, &ledger.to_json(), 1, true).unwrap();
invalidate_held_v2_cache();
let member = Keys::generate();
let group = derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let rumor = super::super::chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "not a writer", None, &[], vec![], 5_000);
let (wrap, _) = super::super::chat::seal_chat_rumor(&rumor, &group, &member, nostr_sdk::prelude::Timestamp::from_secs(5), false).unwrap();
let rec = Arc::new(Recorder::default());
clear().await;
dispatch_event(wrap.clone(), rec.clone()).await;
dispatch_event(wrap.clone(), rec.clone()).await;
assert_eq!(rec.got.lock().unwrap().clone(), vec![("not a writer".to_string(), false, true)], "the owner sees it once, marked, and nothing rings");
let held = crate::db::community::held_wraps(&cid).unwrap();
assert_eq!(held.iter().map(|(id, ..)| id.clone()).collect::<Vec<_>>(), vec![wrap.id.to_hex()], "its wrap waits for a later judgment");
assert!(crate::db::wrappers::processed_wrapper_exists(&wrap.id.to_bytes()), "never opened again off a relay");
let now_ms = || web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_millis() as u64;
let ahead = super::super::chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "from next week", None, &[], vec![], now_ms() + 7 * 86_400_000);
let (later, _) = super::super::chat::seal_chat_rumor(&ahead, &group, &member, nostr_sdk::prelude::Timestamp::from_secs(6), false).unwrap();
dispatch_event(later.clone(), rec.clone()).await;
assert_eq!(rec.got.lock().unwrap().len(), 1, "no copy of what isn't held");
assert!(!crate::db::wrappers::processed_wrapper_exists(&later.id.to_bytes()));
#[derive(Default)]
struct Removed(StdMutex<Vec<(String, bool)>>);
impl InboundEventHandler for Removed {
fn on_community_update(&self, _chat_id: &str, target: &str, msg: &Message) {
self.0.lock().unwrap().push((target.to_string(), msg.unauthorized));
}
}
let writer = Keys::generate();
let wgroup = derive::channel_writer_group_key(&[0x11; 32], &general, crate::community::Epoch(1));
let split = derive::GroupKey::from_parts(wgroup.keys().clone(), group.conv_key().clone());
let rumor = super::super::chat::with_writer_epoch(super::super::chat::build_message_rumor(writer.public_key(), &general, community.root_epoch, "after the stop", None, &[], vec![], now_ms() + 5_000), crate::community::Epoch(1));
let (posted, _) = super::super::chat::seal_chat_rumor(&rumor, &split, &writer, nostr_sdk::prelude::Timestamp::from_secs(now_ms() / 1000 + 5), false).unwrap();
crate::community::transport::Transport::publish(&relay, &posted, &community.relays).await.unwrap();
clear().await;
dispatch_event(posted.clone(), rec.clone()).await;
let stopped = ledger.appended(now_ms(), Spell::Stop { writer: writer.public_key().to_bytes() }).unwrap();
crate::db::community::set_community_writers(&cid, &chan, &stopped.to_json(), 2, true).unwrap();
let removed = Removed::default();
settle_owed_retractions(community.id(), &relay, &removed).await;
assert!(crate::db::community::owed_retractions(&cid).unwrap().is_empty(), "nothing owed once taken back");
struct Down;
#[async_trait::async_trait]
impl crate::community::transport::Transport for Down {
async fn fetch_plane(&self, _p: &Keys, _q: &crate::community::transport::Query, _r: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
Err("down".into())
}
async fn publish(&self, _e: &nostr_sdk::prelude::Event, _r: &[String]) -> Result<(), String> {
Err("down".into())
}
async fn publish_durable(&self, _e: &nostr_sdk::prelude::Event, _r: &[String]) -> Result<(), String> {
Err("down".into())
}
async fn fetch(&self, _q: &crate::community::transport::Query, _r: &[String]) -> Result<Vec<nostr_sdk::prelude::Event>, String> {
Err("down".into())
}
}
let stored = Message { id: "c".repeat(64), content: "shown".into(), at: now_ms(), npub: Some(nostr_sdk::prelude::ToBech32::to_bech32(&Keys::generate().public_key()).unwrap()), wrapper_event_id: Some("b".repeat(64)), ..Default::default() };
crate::db::events::save_message(&chan, &stored).await.unwrap();
crate::db::community::owe_writer_retraction(&cid, &chan, stored.at - 1).unwrap();
settle_owed_retractions(community.id(), &Down, &removed).await;
assert_eq!(crate::db::community::owed_retractions(&cid).unwrap().iter().map(|(c, s, _)| (c.clone(), *s)).collect::<Vec<_>>(), vec![(chan.clone(), stored.at - 1)], "still owed");
struct Hangs;
#[async_trait::async_trait]
impl crate::community::transport::Transport for Hangs {
async fn fetch_plane(&self, _p: &Keys, _q: &crate::community::transport::Query, _r: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
std::future::pending().await
}
async fn publish(&self, _e: &nostr_sdk::prelude::Event, _r: &[String]) -> Result<(), String> {
std::future::pending().await
}
async fn publish_durable(&self, _e: &nostr_sdk::prelude::Event, _r: &[String]) -> Result<(), String> {
std::future::pending().await
}
async fn fetch(&self, _q: &crate::community::transport::Query, _r: &[String]) -> Result<Vec<nostr_sdk::prelude::Event>, String> {
std::future::pending().await
}
}
let _ = tokio::time::timeout(std::time::Duration::from_millis(100), settle_owed_retractions(community.id(), &Hangs, &removed)).await;
assert_eq!(crate::db::community::owed_retractions(&cid).unwrap().len(), 1, "a drain that never finished leaves it owed");
let id = super::super::chat::open_writer_chat_event(&posted, &posted.pubkey, crate::community::Epoch(1), group.conv_key(), &general, community.root_epoch).unwrap().opened().rumor_id.to_hex();
assert_eq!(removed.0.lock().unwrap().clone(), vec![(id, true)], "the owner's device keeps it, marked");
}
#[tokio::test]
async fn a_stale_straggler_folds_like_a_live_event_without_ringing() {
use crate::community::transport::memory::MemoryRelay;
use crate::types::Message;
use std::sync::Mutex as StdMutex;
#[derive(Default)]
struct Recorder {
got: StdMutex<Vec<(String, bool)>>,
}
impl InboundEventHandler for Recorder {
fn on_community_message(&self, _chat_id: &str, msg: &Message, new: bool) {
self.got.lock().unwrap().push((msg.content.clone(), new));
}
}
let _g = 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 acct = {
const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
let mut s = String::from("npub1");
for i in 0..58 {
s.push(B[(i * 11 + 5) % 32] as char);
}
s
};
std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
crate::db::set_current_account(acct.clone()).unwrap();
crate::db::init_database(&acct).unwrap();
let _ = crate::state::take_nostr_client();
let me = Keys::generate();
crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
crate::state::set_my_public_key(me.public_key());
let relay = MemoryRelay::new();
let community = super::super::service::create_community(&relay, "Late", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let member = Keys::generate();
let group = derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let rumor = super::super::chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "old news", None, &[], vec![], 5_000);
let (wrap, _) = super::super::chat::seal_chat_rumor(&rumor, &group, &member, nostr_sdk::prelude::Timestamp::from_secs(5), false).unwrap();
let rec = Arc::new(Recorder::default());
crate::community::v2::realtime::clear().await;
crate::community::dispatch_inbound(wrap.clone(), rec.clone()).await;
crate::community::dispatch_inbound(wrap.clone(), rec.clone()).await;
assert_eq!(*rec.got.lock().unwrap(), vec![("old news".to_string(), false)], "folded once, never as new");
assert!(crate::db::wrappers::processed_wrapper_exists(&wrap.id.to_bytes()));
let channel_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
let chat_id = crate::db::id_cache::get_chat_id_by_identifier(&channel_hex).unwrap();
assert_eq!(crate::db::events::get_chat_message_count(chat_id).unwrap(), 1);
use nostr_sdk::prelude::FinalizeEvent;
let own = nostr_sdk::prelude::EventBuilder::new(nostr_sdk::prelude::Kind::Custom(super::super::kind::COMMUNITY_LIST_FRAG), "x")
.finalize(&me)
.unwrap();
crate::community::dispatch_inbound(own, rec.clone()).await;
assert_eq!(rec.got.lock().unwrap().len(), 1);
assert_eq!(crate::db::events::get_chat_message_count(chat_id).unwrap(), 1);
}
#[test]
fn every_plane_address_routes_to_its_own_community() {
let (a, b) = (a_community("A"), a_community("B"));
let held = HeldV2 { communities: vec![a.clone(), b.clone()].into(), routes: Default::default() };
for c in [&a, &b] {
for pk in community_addresses(c) {
assert_eq!(held.route(&pk).map(|r| r.id().0), Some(c.id().0));
}
}
assert!(held.route(&Keys::generate().public_key()).is_none(), "a stranger's wrap routes nowhere");
}
fn wrap_id(n: u32) -> [u8; 32] {
let mut id = [0x5C; 32];
id[..4].copy_from_slice(&n.to_le_bytes());
id
}
#[test]
fn a_wrap_is_dispatched_once_across_a_generation_turnover() {
let gen = SEEN_WRAPS_GEN as u32;
let mut seen = SeenWraps::default();
assert!(seen.first_sight(&wrap_id(0)));
assert!(!seen.first_sight(&wrap_id(0)), "a re-delivery is refused");
for n in 1..gen {
assert!(seen.first_sight(&wrap_id(n)));
}
assert!(seen.first_sight(&wrap_id(gen)));
assert_eq!((seen.cur.len(), seen.prev.len()), (1, SEEN_WRAPS_GEN), "a full generation ages whole");
for n in 0..=gen {
assert!(!seen.first_sight(&wrap_id(n)), "wrap {n} fired twice across a turnover");
}
for n in gen + 1..=2 * gen {
assert!(seen.first_sight(&wrap_id(n)));
}
assert!(seen.cur.len() + seen.prev.len() <= 2 * SEEN_WRAPS_GEN);
assert!(!seen.first_sight(&wrap_id(gen)), "the previous generation is still remembered");
assert!(seen.first_sight(&wrap_id(0)), "two generations back is let go");
}
#[tokio::test]
async fn each_account_keeps_its_own_seen_wraps() {
let (a, b) = (crate::db::Session::empty(), crate::db::Session::empty());
let id = wrap_id(77);
let first = |s| crate::db::with_session(s, async move { seen_wraps().lock().unwrap().first_sight(&id) });
assert!(first(a.clone()).await);
assert!(!first(a).await);
assert!(first(b).await, "a wrap one account dispatched is still new to another");
}
fn community_on(name: &str, relays: &[&str]) -> CommunityV2 {
let mut c = a_community(name);
c.relays = relays.iter().map(|r| r.to_string()).collect();
c
}
fn key_set(pks: impl IntoIterator<Item = PublicKey>) -> std::collections::BTreeSet<[u8; 32]> {
pks.into_iter().map(|p| p.to_bytes()).collect()
}
#[test]
fn each_relay_is_asked_for_exactly_the_planes_of_the_communities_that_list_it() {
let a = community_on("A", &["wss://one.example", "wss://one.example/", "wss://shared.example"]);
let b = community_on("B", &["wss://shared.example/", "wss://two.example"]);
let lost = community_on("C", &["not a relay"]);
let held = [a.clone(), b.clone(), lost.clone()];
let plan = subscription_plan(&held);
let url = |s: &str| RelayUrl::parse(s).unwrap();
let old_authors = plane_authors(&held);
let old_relays: std::collections::BTreeSet<RelayUrl> =
held.iter().flat_map(|c| c.relays.iter()).filter_map(|r| RelayUrl::parse(r).ok()).collect();
assert_eq!(plan.authors, old_authors, "the pool-wide filter is unchanged");
assert_eq!(plan.per_relay.keys().cloned().collect::<std::collections::BTreeSet<_>>(), old_relays);
assert_eq!(key_set(plan.per_relay.values().flatten().copied()), key_set(old_authors.iter().copied()), "no address is dropped");
for c in &held {
for r in c.relays.iter().filter_map(|r| RelayUrl::parse(r).ok()) {
let share = key_set(plan.per_relay[&r].iter().copied());
assert!(key_set(community_addresses(c)).is_subset(&share), "{} lost coverage on {r}", c.name);
}
}
let only = |cs: &[&CommunityV2]| key_set(cs.iter().flat_map(|c| community_addresses(c)));
assert_eq!(key_set(plan.per_relay[&url("wss://one.example")].iter().copied()), only(&[&a, &lost]));
assert_eq!(key_set(plan.per_relay[&url("wss://two.example")].iter().copied()), only(&[&b, &lost]));
assert_eq!(key_set(plan.per_relay[&url("wss://shared.example")].iter().copied()), only(&[&a, &b, &lost]));
for share in plan.per_relay.values() {
assert!(share.windows(2).all(|w| w[0].to_bytes() < w[1].to_bytes()), "each share is sorted and deduped");
}
}
#[test]
fn the_plan_fingerprint_moves_with_any_relays_share() {
let a = community_on("A", &["wss://one.example"]);
let b = community_on("B", &["wss://two.example"]);
let base = subscription_plan(&[a.clone(), b.clone()]);
assert_eq!(plan_fingerprint(&base), plan_fingerprint(&subscription_plan(&[b.clone(), a.clone()])));
let mut moved_b = b.clone();
moved_b.relays = vec!["wss://one.example".into()];
let moved = subscription_plan(&[a.clone(), moved_b]);
assert_eq!(moved.authors, base.authors);
assert_ne!(plan_fingerprint(&moved), plan_fingerprint(&base));
assert_ne!(plan_fingerprint(&subscription_plan(&[a])), plan_fingerprint(&base));
}
#[test]
fn an_idle_follow_lock_is_pruned_and_a_held_one_is_shared() {
let _serial = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
let (held_id, idle_id) = (CommunityId([0xA1; 32]), CommunityId([0xB2; 32]));
let held = follow_lock(&held_id);
assert!(Arc::ptr_eq(&held, &follow_lock(&held_id)), "every caller gets the one lock");
drop(follow_lock(&idle_id));
let _next = follow_lock(&CommunityId([0xC3; 32]));
let locks = V2_FOLLOW_LOCKS.lock().unwrap();
assert!(!locks.contains_key(&idle_id.0), "a lock nobody holds goes when a new one is made");
assert!(locks.contains_key(&held_id.0), "a held lock is never dropped from under its holder");
}
#[tokio::test]
async fn follow_queue_coalesces_a_burst_and_re_enqueues_after_processing() {
let _serial = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<CommunityId>();
*V2_FOLLOW_TX.lock().unwrap() = Some(tx);
V2_FOLLOW_PENDING.lock().unwrap().clear();
let id = CommunityId([0x11; 32]);
enqueue_follow(&id);
enqueue_follow(&id);
enqueue_follow(&id);
assert_eq!(rx.recv().await, Some(id), "first trigger queues a follow");
assert!(rx.try_recv().is_err(), "the burst coalesced to exactly one");
V2_FOLLOW_PENDING.lock().unwrap().remove(&id.0);
enqueue_follow(&id);
assert_eq!(rx.recv().await, Some(id), "a trigger after processing re-queues");
let id2 = CommunityId([0x22; 32]);
enqueue_follow(&id2);
assert_eq!(rx.recv().await, Some(id2));
*V2_FOLLOW_TX.lock().unwrap() = None;
V2_FOLLOW_PENDING.lock().unwrap().clear();
}
#[test]
fn a_live_rotation_is_taken_ahead_of_a_boot_backlog() {
V2_FOLLOW_URGENT.lock().unwrap().clear();
let backlog: Vec<CommunityId> = (1u8..=30).map(|n| CommunityId([n; 32])).collect();
let rotated = CommunityId([0xAA; 32]);
let mut queue: std::collections::VecDeque<CommunityId> = backlog.clone().into();
queue.push_back(rotated);
assert_eq!(pop_next_follow(&mut queue.clone()), Some(backlog[0]));
V2_FOLLOW_URGENT.lock().unwrap().insert(rotated.0);
assert_eq!(
pop_next_follow(&mut queue),
Some(rotated),
"a live rotation must not queue behind dozens of unrelated network walks"
);
assert_eq!(pop_next_follow(&mut queue), Some(backlog[0]));
V2_FOLLOW_URGENT.lock().unwrap().clear();
}
#[test]
fn urgency_promotes_an_id_already_queued() {
let _serial = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<CommunityId>();
*V2_FOLLOW_TX.lock().unwrap() = Some(tx);
V2_FOLLOW_PENDING.lock().unwrap().clear();
V2_FOLLOW_URGENT.lock().unwrap().clear();
let id = CommunityId([0x33; 32]);
enqueue_follow(&id); enqueue_follow_urgent(&id);
assert!(V2_FOLLOW_URGENT.lock().unwrap().contains(&id.0));
assert_eq!(rx.try_recv().ok(), Some(id));
assert!(rx.try_recv().is_err(), "still coalesced to one queue entry");
*V2_FOLLOW_TX.lock().unwrap() = None;
V2_FOLLOW_PENDING.lock().unwrap().clear();
V2_FOLLOW_URGENT.lock().unwrap().clear();
}
#[tokio::test]
async fn a_dissolved_community_honors_no_new_events_and_fires_death_once() {
use super::super::service;
use crate::community::transport::memory::MemoryRelay;
use crate::community::transport::Transport;
use crate::types::Message;
use std::sync::Mutex as StdMutex;
#[derive(Default)]
struct Recorder {
messages: StdMutex<Vec<String>>,
deaths: StdMutex<Vec<String>>,
}
impl InboundEventHandler for Recorder {
fn on_community_message(&self, _chat: &str, msg: &Message, _new: bool) {
self.messages.lock().unwrap().push(msg.content.clone());
}
fn on_community_dissolved(&self, community_id: &str) {
self.deaths.lock().unwrap().push(community_id.to_string());
}
}
let _g = 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 acct = {
const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
let mut s = String::from("npub1");
for i in 0..58 {
s.push(B[(i * 3 + 2) % 32] as char);
}
s
};
std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
crate::db::set_current_account(acct.clone()).unwrap();
crate::db::init_database(&acct).unwrap();
let _ = crate::state::take_nostr_client();
let me = Keys::generate();
crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
crate::state::set_my_public_key(me.public_key());
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "Doomed", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let rumor = super::super::dissolution::dissolved_tombstone_rumor(me.public_key(), community.id(), 8_000);
let tombstone = super::super::dissolution::seal_dissolved(&rumor, community.id(), &me, nostr_sdk::prelude::Timestamp::from_secs(8_000)).unwrap();
let _ = relay.publish(&tombstone, &community.relays).await;
assert!(!crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap(), "not yet locally sealed");
let rec = Arc::new(Recorder::default());
clear().await;
dispatch_event(tombstone.clone(), rec.clone()).await;
dispatch_event(tombstone, rec.clone()).await;
assert!(crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap());
let member = Keys::generate();
let cgroup = derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let rumor = super::super::chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "into the grave", None, &[], vec![], 9_000);
let (mw, _) = super::super::chat::seal_chat_rumor(&rumor, &cgroup, &member, nostr_sdk::prelude::Timestamp::from_secs(9), false).unwrap();
dispatch_event(mw, rec.clone()).await;
assert_eq!(rec.deaths.lock().unwrap().len(), 1, "death is announced exactly once");
assert!(rec.messages.lock().unwrap().is_empty(), "a post-tombstone message is never honored (CORD-02 ยง9)");
crate::state::set_nostr_client(crate::nostr_client_builder().build());
let session = crate::db::current_session();
for _ in 0..3 {
follow_community(&session, community.id(), &*rec).await;
}
let _ = crate::state::take_nostr_client();
assert_eq!(rec.deaths.lock().unwrap().len(), 1, "a follow of a known grave announces nothing");
}
#[test]
fn a_private_channel_subscribes_to_its_own_chat_plane() {
let mut c = a_community("Priv");
c.channels.push(super::super::community::ChannelV2 {
id: crate::community::ChannelId([0x33; 32]),
name: "mods".into(),
private: true,
key: Some([0x44; 32]),
epoch: Epoch(1),
voice: None,
meta_custom: None,
meta_extra: Default::default(),
writers: None,
sealed: None,
});
let authors = plane_authors(std::slice::from_ref(&c));
let priv_chat = derive::channel_group_key(&[0x44; 32], &c.channels[1].id, Epoch(1)).pk();
assert!(authors.contains(&priv_chat), "a private channel subscribes to its own chat plane");
let next_rekey = derive::channel_rekey_group_key(&c.community_root, &c.channels[1].id, Epoch(2)).pk();
assert!(authors.contains(&next_rekey), "a private channel's next rekey plane is subscribed");
}
}