//! Concord v2 service — the stateful orchestration binding the pure v2 modules
//! to storage + transport. Free functions, `std::sync::Arc<crate::db::Session>`-gated at every write
//! (a `swap_session` can land at any await — see CLAUDE.md).
//!
//! Signing + NIP-44 flow through the active [`VectorSigner`](crate::signer::VectorSigner) (`active_signer()`):
//! the live client's signer for a NIP-46 bunker / NIP-55 offline account, else the
//! local vault. Every identity op in v2 is `sign_event` / `nip44_encrypt` /
//! `nip44_decrypt` — a remote signer's whole surface — so create, send, join,
//! invite, moderate, rotate, and refound all work keylessly (CORD-06 D1/D5 made the
//! rekey locator public + its blobs pairwise NIP-44, so there is no raw-ECDH
//! exception).
use nostr_sdk::prelude::{Event, Keys, PublicKey, Timestamp};
use super::super::transport::{Query, Transport};
use super::super::{version, ChannelId, Epoch};
use super::chat::{self, ChatEvent};
use super::community::{ChannelV2, CommunityV2};
use super::control;
use super::derive::{base_rekey_group_key, channel_group_key, channel_rekey_group_key, GroupKey};
use super::invite::{self, CommunityInvite};
use super::rekey::{self, Continuity, RekeyScope};
use super::{guestbook, stream, vsk};
use crate::community::edition::ParsedEdition;
mod audit;
pub use audit::{audit_log, AuditEntry, AuditLog};
mod inspect;
pub use inspect::{inspect_bundle, inspect_public_link, InspectedChannel, InspectedMessage, InspectedPlane, Inspection, MessageRead};
mod relocate;
pub use relocate::{check_relays, move_relays, RelayCheck, RelayMove, RETIRED_RELAY_GRACE_MS};
pub(crate) use relocate::{clean_relays, relays_moved, resume_relay_copy, retired_relays};
pub(crate) use audit::{note_moderation_delete, note_voice_directive};
mod outbox;
pub use outbox::{confirm_in, discard_unconfirmed, retry_unconfirmed};
mod purge;
mod writing;
mod sealing;
mod control_store;
mod control_sync;
mod guestbook_reads;
mod guestbook_store;
mod plane_store;
pub use writing::{can_post, collect_writers, outbound_rumor, WriterDuty};
pub(crate) use writing::live_writer as live_writer_of;
pub(crate) use writing::{owe_if_departed, retract_by, hold as writing_hold, judge_arrival, rejudge_held, owe_if_moved, rejudge_page, retract_since, writers_head, sort_arrival, Arrival, Judge};
/// The active signer for v2 authority actions: the live client's signer — which
/// covers a NIP-46 bunker / NIP-55 offline signer — falling back to the local
/// vault keys when there is no client or no signer attached (local accounts,
/// headless/CLI paths, and tests). Every v2 seal, rekey blob, and control edition
/// signs / NIP-44-wraps through this, so a keyless account can create AND
/// administer a community. v2's rekey locator is public + its blobs are pairwise
/// NIP-44 (CORD-06 D1/D5), so there is no raw-ECDH exception.
/// The active identity's public key for addressing/tags — authoritative (set at
/// login), no signer round-trip. Used everywhere v2 needs "who am I" so a keyless
/// account (empty vault) still resolves its own identity.
fn me_pk() -> Result<PublicKey, String> {
crate::state::my_public_key().ok_or_else(|| "no active identity".to_string())
}
pub(crate) fn now_ms() -> u64 {
crate::clock::now_ms()
}
/// `now_ms`, but never twice the same value in this process.
///
/// Ordering is by the `ms` tag, and two sends can finish inside one millisecond
/// — so a sender's own back-to-back messages carried IDENTICAL stamps and fell
/// through to the reader's tiebreak, which is content-derived and therefore
/// indifferent to which was typed first. Bumping past the last stamp keeps a
/// single sender's sequence self-consistent; readers still tiebreak across
/// senders. Drifts at most a few ms ahead of the clock under a burst, and only
/// until the clock catches up.
fn next_send_ms() -> u64 {
use std::sync::atomic::{AtomicU64, Ordering};
static LAST: AtomicU64 = AtomicU64::new(0);
let now = now_ms();
// fetch_update: its rename, try_update, is newer than the toolchains Vector builds with.
#[allow(deprecated)]
let prev = LAST.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |last| Some(now.max(last + 1)));
prev.map(|last| now.max(last + 1)).unwrap_or(now)
}
/// Create a fresh v2 community owned by the local identity: mint the genesis
/// (self-certifying id + the two owner editions), persist, publish the genesis
/// control editions, and announce the owner's Guestbook Join. Returns the saved
/// community.
/// A new Community on Roles v2 from the start (CORD-04 §2): `@everyone` holds the defaults and the
/// genesis Channel is all the switch lists. A switch that can't land leaves it on the legacy Roster,
/// which the owner can still move from.
pub async fn create_community_on_roles_v2<T: Transport + ?Sized>(
transport: &T,
name: &str,
relays: Vec<String>,
description: Option<String>,
) -> Result<CommunityV2, String> {
let community = create_community(transport, name, relays, description).await?;
let mut last = String::new();
for _ in 0..2 {
match activate_roles_v2(transport, &community, super::roles::EVERYONE_DEFAULT).await {
Ok(_) => {
let _ = follow_control(transport, &community).await;
return Ok(crate::db::community::load_community_v2(community.id())?.unwrap_or(community));
}
Err(e) => last = e,
}
}
crate::log_warn!("[v2:create] the new community stays on the legacy roles: {last}");
Ok(community)
}
pub async fn create_community<T: Transport + ?Sized>(
transport: &T,
name: &str,
relays: Vec<String>,
description: Option<String>,
) -> Result<CommunityV2, String> {
crate::db::scoped(async move {
let signer = crate::signer::active_signer()?;
let owner_pk = me_pk()?;
let at_ms = now_ms();
let meta = control::CommunityMetadata {
name: name.to_string(),
description: description.clone(),
relays: relays.clone(),
..Default::default()
};
let genesis = control::genesis_signed(owner_pk, &signer, meta, at_ms / 1000).await.map_err(|e| e.to_string())?;
let community = CommunityV2::from_genesis(&genesis, name, description, relays.clone(), at_ms);
// Save-before-publish: no peers exist yet so there's no
// shared view to diverge from, and the fresh-random keys are irrecoverable
// if a publish hiccup rolled them back. Re-check the session after the genesis
// signing await (a bunker signs over the network) before the DB write.
// Seed the genesis edition heads (v1) as the owner's refuse-downgrade floor, so a
// later edit can't be rolled back by a relay serving only the genesis prefix. The
// live control sub is replay-free (limit 0), so the owner won't re-fold its own
// genesis to seed the floor otherwise. Floors land BEFORE the community row
// (floors-then-state ordering).
let control = control::ControlPlane::of(&community);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
for wrap in &genesis.wraps {
if let Ok(ed) = control.open_edition(wrap) {
let entity_hex = crate::simd::hex::bytes_to_hex_32(&ed.entity_id);
crate::db::community::set_family_head_at_epoch(&cid_hex, &entity_hex, ed.version, &ed.self_hash, &ed.inner_id, &ed.author.to_bytes(), community.root_epoch.0, floor_family(&ed.vsk))?;
}
}
crate::db::community::save_community_v2(&community)?;
// Archive the genesis root at epoch 0, so a later Refounding leaves this epoch's
// Public-channel history readable (CORD-03 §3 multi-epoch read).
let _ = crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, community.root_epoch.0, &community.community_root);
// Publish the two genesis control editions at the epoch-0 control plane.
// Durable, not single-shot: over a slow transport (Tor) one attempt is a coin
// flip, and a lost genesis leaves a community that exists only locally. Durable
// races every relay, returns on the first ACK, then heals stragglers in the bg.
for wrap in &genesis.wraps {
transport.publish_durable(wrap, &community.relays).await?;
hold_wrap(&community, wrap);
}
// Announce the owner's Guestbook Join so they appear in the memberlist. Relays are
// proven-alive by the genesis ACK above, so durable here just guarantees the owner's
// own join lands (member count) without a real block risk.
let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let join_rumor = guestbook::build_join_rumor(owner_pk, None, at_ms);
if let Ok((join_wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, owner_pk, &join_rumor, &gb_group, Timestamp::from_secs(at_ms / 1000)).await {
if transport.publish_durable(&join_wrap, &community.relays).await.is_ok() {
if let Ok(entry) = stream::open_wrap(&join_wrap, &gb_group).map_err(|e| e.to_string()).and_then(|o| guestbook::parse_guestbook_event(&o).map_err(|e| e.to_string())) {
if ingest_guestbook_event(&community, entry, join_wrap.created_at.as_secs()).is_ok() {
hold_guestbook_wrap(&community, &join_wrap);
}
}
}
}
// Sync the new membership across devices (CORD-02 §8), durably — see the join path.
match republish_community_list(transport, Some(community.id())).await {
Ok(true) => {}
Ok(false) => republish_community_list_durable(Some(*community.id())),
Err(e) => {
crate::log_warn!("[CommunityList] failed to record this community across devices ({}) — retrying", e);
republish_community_list_durable(Some(*community.id()));
}
}
Ok(community)
})
.await
}
/// Send a text message to a channel. Derives the channel's Chat-Plane group key
/// (community_root for a Public channel, the channel key for a Private one),
/// seals it encrypted, and publishes. Returns the message's rumor id (hex).
pub async fn send_message<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
content: &str,
) -> Result<String, String> {
send_chat_message(transport, community, channel_id, content, None, &[], vec![]).await
}
/// Full chat send: threaded reply (NIP-C7 `q`, the parent's `(rumor_id, author)`
/// hex pair), NIP-30 custom-emoji pairs, and verbatim extra tags (NIP-92 `imeta`
/// attachments). Returns the message's rumor id (hex).
pub async fn send_chat_message<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
content: &str,
reply_to: Option<(&str, &str)>,
emoji: &[(&str, &str)],
extra_tags: Vec<nostr_sdk::prelude::Tag>,
) -> Result<String, String> {
send_chat_message_at(transport, community, channel_id, content, reply_to, emoji, extra_tags, next_send_ms()).await
}
/// [`send_chat_message`] with an explicit event time. The rumor id is a pure
/// function of its inputs, so a GUI that picks `at_ms` can precompute the id for
/// its optimistic pending row — the in-process echo and the finalize then key
/// the SAME id (the pending → sent contract).
#[allow(clippy::too_many_arguments)]
pub async fn send_chat_message_at<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
content: &str,
reply_to: Option<(&str, &str)>,
emoji: &[(&str, &str)],
extra_tags: Vec<nostr_sdk::prelude::Tag>,
at_ms: u64,
) -> Result<String, String> {
let (author_pk, group, epoch) = chat_send_context(community, channel_id)?;
refuse_while_timed_out(community, &author_pk)?;
// An honest client posts only where it holds Send Messages (CORD-04 §8).
let roster = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap_or_default();
let owner = community.owner().ok().map(|o| o.to_hex());
if roster.everyone.is_some()
&& !roster
.channel_permissions(owner.as_deref(), &author_pk.to_hex(), &crate::simd::hex::bytes_to_hex_32(&channel_id.0), community.channel(channel_id).is_some_and(|c| c.private))
.contains(crate::community::roles::Permissions::SEND_MESSAGES)
{
return Err("you can't send messages in this channel".to_string());
}
let rumor = chat::build_message_rumor(author_pk, channel_id, epoch, content, reply_to, emoji, extra_tags, at_ms);
publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await
}
/// A member timed out doesn't post, edit or react until it ends (CORD-04 §8).
fn refuse_while_timed_out(community: &CommunityV2, author: &PublicKey) -> Result<(), String> {
match community_timeouts(community)?.get(author) {
Some((_, until)) => Err(format!("you're timed out here until {until}")),
None => Ok(()),
}
}
/// Refuse a reaction the Roster doesn't let `author` make in `channel_id`: readers don't count
/// it. Nothing to judge on the legacy roster.
fn refuse_unless_reacting(community: &CommunityV2, channel_id: &ChannelId, author: &PublicKey) -> Result<(), String> {
use crate::community::roles::Permissions;
let roster = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0))?;
if roster.everyone.is_none() {
return Ok(());
}
let ch = community.channel(channel_id).ok_or("no such channel in this community")?;
let held = roster.channel_permissions(Some(&community.owner()?.to_hex()), &author.to_hex(), &crate::simd::hex::bytes_to_hex_32(&channel_id.0), ch.private);
if held.contains(Permissions::ADD_REACTIONS) { Ok(()) } else { Err("you can't react in this channel".to_string()) }
}
/// React to a channel message (kind 7, NIP-25 shape). `target_id_hex` /
/// `target_author_hex` name the reacted-to message; `target_kind` is its rumor
/// kind (`kind::MESSAGE`, or `kind::COMMENT` for a threaded reply); `emoji`
/// carries the NIP-30 pair when `emoji_content` is a custom `:shortcode:`.
#[allow(clippy::too_many_arguments)]
pub async fn send_reaction<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
target_id_hex: &str,
target_author_hex: &str,
target_kind: u16,
emoji_content: &str,
emoji: Option<(&str, &str)>,
) -> Result<String, String> {
let (author_pk, group, epoch) = chat_send_context(community, channel_id)?;
refuse_while_timed_out(community, &author_pk)?;
refuse_unless_reacting(community, channel_id, &author_pk)?;
let at_ms = next_send_ms();
let rumor =
chat::build_reaction_rumor(author_pk, channel_id, epoch, target_id_hex, target_author_hex, target_kind, emoji_content, emoji, at_ms);
publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await
}
/// Edit one of your own messages (kind 3302): peers re-render `target_id_hex`
/// with the replacement text. Author-enforced on the read side — only the
/// original author's edit folds. Carries the target's own expiry, if it has one.
pub async fn send_edit<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
target_id_hex: &str,
new_content: &str,
emoji: &[(&str, &str)],
) -> Result<String, String> {
send_edit_tagged(transport, community, channel_id, target_id_hex, new_content, emoji, Vec::new()).await
}
/// [`send_edit`] carrying extra tags verbatim (the edit's colour spans).
pub async fn send_edit_tagged<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
target_id_hex: &str,
new_content: &str,
emoji: &[(&str, &str)],
extra_tags: Vec<nostr_sdk::prelude::Tag>,
) -> Result<String, String> {
let (author_pk, group, epoch) = chat_send_context(community, channel_id)?;
refuse_while_timed_out(community, &author_pk)?;
let expiration = crate::self_destruct::edit_expiry(target_id_hex).await?;
let at_ms = next_send_ms();
let rumor = chat::build_edit_rumor_tagged(author_pk, channel_id, epoch, target_id_hex, new_content, emoji, expiration, extra_tags, at_ms);
publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await
}
/// Cooperative in-plane delete (kind 5, NIP-09 semantics): peers stop rendering
/// `target_id_hex`, and relays drop it at `expiration`. The wrap itself leaves relays
/// separately, by the keys kept for it ([`crate::community::message_delete::scrub_own`]).
pub async fn send_delete<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
target_id_hex: &str,
target_kind: u16,
expiration: Option<u64>,
) -> Result<String, String> {
let (author_pk, group, epoch) = chat_send_context(community, channel_id)?;
let at_ms = next_send_ms();
let rumor = chat::build_delete_rumor_until(author_pk, channel_id, epoch, target_id_hex, target_kind, at_ms, None, expiration);
let id = publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await?;
// §7: deleting one's own pinned message obliges the immediate omitting
// edition. Hooked HERE and not only at ingest — the local delete drops the
// row before the relay echo returns, so the echo can't re-authorize and
// the ingest hook never sees an own delete.
let ch_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
spawn_pin_duty(&ch_hex, target_id_hex, None);
Ok(id)
}
/// Delete my own message (or reaction) in `channel_id`: its wraps off the relays by the keys
/// kept for them, then the in-plane delete, which leaves relays in time once their copies are
/// gone everywhere.
pub async fn delete_own<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
target_id_hex: &str,
target_kind: u16,
) -> Result<String, String> {
// Asked first: scrubbing the relay copy for a delete that can't be sent splits what readers see.
let (_, read, _) = chat_send_context(community, channel_id)?;
if let Some(ch) = community.channel(channel_id) {
writing::send_group(community, ch, &read, super::kind::DELETE)?;
}
let scrubbed = crate::community::message_delete::scrub_own(transport, &community.relays, target_id_hex)
.await
.unwrap_or_else(|e| {
crate::log_warn!("[Community] relay delete of {target_id_hex} failed, in-plane delete only: {e}");
Default::default()
});
let expiration = crate::community::message_delete::in_plane_delete_expiry(target_id_hex, scrubbed).await;
send_delete(transport, community, channel_id, target_id_hex, target_kind, expiration).await
}
/// Moderation-hide: remove SOMEONE ELSE's message under `MANAGE_MESSAGES`
/// (CORD-04 §3/§5). Same kind-5 the author's own delete uses — CORD defines no
/// separate hide, the authority is what differs, and every reader re-derives it
/// from the seal's real npub against the folded Roster.
///
/// Gated locally against the same predicate peers enforce, so the button can't
/// promise what the plane will refuse; a non-owner cites the Grant it acts under.
/// `target_author` comes from the caller's resident copy — you can only moderate
/// a message you can see.
pub async fn moderation_delete<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
target_id_hex: &str,
target_kind: u16,
target_author: &PublicKey,
) -> Result<String, String> {
let (author_pk, group, epoch) = chat_send_context(community, channel_id)?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
return Err("this community is dissolved — it accepts no new moderation actions".to_string());
}
let owner_hex = community.owner()?.to_hex();
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let private = community.channel(channel_id).is_some_and(|c| c.private);
if !crate::community::moderation::can_hide_in_channel(
Some(&owner_hex),
&roster,
&author_pk.to_hex(),
&target_author.to_hex(),
&crate::simd::hex::bytes_to_hex_32(&channel_id.0),
private,
) {
return Err("you can't hide that message in this channel".to_string());
}
let at_ms = next_send_ms();
let citation = required_authority_citation(community, &author_pk)?;
let rumor = chat::build_delete_rumor(author_pk, channel_id, epoch, target_id_hex, target_kind, at_ms, citation.as_ref());
let id = publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await?;
// §7: a moderation-hide of a pinned message obliges the omission too, and
// the moderator here provably holds the bit's neighbourhood (MANAGE_MESSAGES
// curators usually hold PIN_MESSAGES); the duty itself re-checks.
let ch_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
spawn_pin_duty(&ch_hex, target_id_hex, None);
Ok(id)
}
/// WebXDC realtime peer signal (kind 3310): the shared content shape, sealed on the
/// channel's chat plane, DURABLE (a reopening peer backfills a recent ad).
/// Signed by the member's real identity — a member can't forge another
/// player's presence. Failure is non-fatal to callers (the next re-advertise
/// covers a missed ad).
pub async fn send_webxdc_signal<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
topic_id: &str,
node_addr: Option<&str>,
) -> Result<(), String> {
let (author_pk, group, epoch) = chat_send_context(community, channel_id)?;
let at_ms = now_ms();
let content = crate::webxdc::peer_signal_content(topic_id, node_addr);
let rumor = chat::build_webxdc_rumor(author_pk, channel_id, epoch, &content, vec![], at_ms);
publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await.map(|_| ())
}
/// Voice presence (CORD-07 §4): `Some(endpoint)` is a `joined` heartbeat over iroh, None a `left`.
/// Ephemeral, at the Channel's read address: being in a call is CONNECT, whatever its writers.
pub async fn send_voice_presence<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
endpoint: Option<([u8; 32], Option<String>)>,
showing: super::voice::Showing,
) -> Result<(), String> {
let (author_pk, group, epoch) = chat_send_context(community, channel_id)?;
let at_ms = now_ms();
let rumor = chat::build_voice_presence_rumor(author_pk, channel_id, epoch, endpoint.as_ref().map(|(e, r)| (e, r.as_deref())), showing, at_ms);
publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, true).await?;
let channel = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
super::voice::note(&channel, author_pk, at_ms, super::voice::Heard::announcing(endpoint, showing), at_ms);
Ok(())
}
/// The mutes and deafens this device stands behind, per (Channel, target): re-sent whenever the
/// target comes back into the call, since a directive lasts only while they stay (CORD-07 §7).
struct StandingDirectives;
type Standing = std::collections::HashMap<(String, PublicKey), std::collections::BTreeSet<super::voice::Directive>>;
fn standing_directives() -> std::sync::Arc<std::sync::Mutex<Standing>> {
crate::db::current_session().scoped::<StandingDirectives, _>()
}
/// Mute, deafen, move or disconnect `target` in a voice Channel's call (CORD-07 §7): the signer
/// holds the directive's bit and strictly outranks them, judged on today's Roster.
pub async fn send_voice_directive<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
target: &PublicKey,
directive: super::voice::Directive,
to: Option<[u8; 32]>,
) -> Result<(), String> {
use super::voice::Directive;
let (author_pk, group, epoch) = chat_send_context(community, channel_id)?;
let cid = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let owner = community.owner()?.to_hex();
let roles = crate::db::community::get_community_roles(&cid).unwrap_or_default();
let me = author_pk.to_hex();
if !((me == owner && target.to_hex() != owner) || roles.can_act_on_member(&me, Some(&owner), &target.to_hex(), directive.permission())) {
return Err("you can't do that to this member".into());
}
if directive == Directive::Move && to.is_none_or(|t| !community.channels.iter().any(|c| c.id.0 == t && c.view() == super::community::ChannelView::Voice)) {
return Err("move them to a voice channel".into());
}
let at_ms = now_ms();
let rumor = chat::build_voice_directive_rumor(author_pk, channel_id, epoch, target, directive, to.as_ref(), my_authority_citation(community, &author_pk).as_ref(), at_ms);
let id = publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, true).await?;
let channel = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
note_voice_directive(&cid, &id, at_ms, &me, &target.to_hex(), &channel, directive, to.as_ref());
super::voice::apply_directive(&channel, target, directive, at_ms, at_ms);
let standing = standing_directives();
let mut held = standing.lock().unwrap_or_else(|e| e.into_inner());
let set = held.entry((channel, *target)).or_default();
match directive {
Directive::Mute => {
set.insert(Directive::Mute);
}
Directive::Unmute => {
set.remove(&Directive::Mute);
}
Directive::Deafen => {
set.insert(Directive::Deafen);
}
Directive::Undeafen => {
set.remove(&Directive::Deafen);
}
Directive::Move | Directive::Disconnect => set.clear(),
}
Ok(())
}
/// A newer lift from any moderator ends what this device stood behind: re-asserting it on the
/// target's return would undo a decision made after ours.
pub(crate) fn yield_voice_directive(channel_hex: &str, target: &PublicKey, directive: super::voice::Directive) {
use super::voice::Directive;
let lifted = match directive {
Directive::Unmute => Directive::Mute,
Directive::Undeafen => Directive::Deafen,
_ => return,
};
if let Some(set) = standing_directives().lock().unwrap_or_else(|e| e.into_inner()).get_mut(&(channel_hex.to_string(), *target)) {
set.remove(&lifted);
}
}
/// Re-send what this device stands behind against `target`, now back in the call.
pub fn reassert_voice_directives(community: &CommunityV2, channel_hex: &str, target: &PublicKey) {
let standing: Vec<super::voice::Directive> = standing_directives()
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(&(channel_hex.to_string(), *target))
.map(|s| s.iter().copied().collect())
.unwrap_or_default();
if standing.is_empty() || !crate::rt::can_spawn() {
return;
}
let (community, target) = (community.clone(), *target);
let Some(channel) = crate::community::id32_from_hex(channel_hex).map(ChannelId) else { return };
crate::db::spawn_bound(async move {
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
for d in standing {
if let Err(e) = send_voice_directive(&transport, &community, &channel, &target, d, None).await {
crate::log_warn!("[voice] re-asserting a {} failed: {e}", d.as_str());
}
}
});
}
/// Ephemeral typing indicator (kind 23311 in a 21059 wrap — relays never store it).
pub async fn send_typing<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
) -> Result<(), String> {
let (author_pk, group, epoch) = chat_send_context(community, channel_id)?;
let at_ms = now_ms();
let rumor = chat::build_typing_rumor(author_pk, channel_id, epoch, at_ms);
publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, true).await.map(|_| ())
}
/// Everything a chat-plane send needs: local keys, the channel's group key +
/// epoch, and the session snapshot taken BEFORE any await. Refuses a dissolved
/// community (every honest member sealed it read-only) and a keyless Private
/// channel — deriving from the root would post to the public plane; its key
/// arrives over the rekey plane.
fn chat_send_context(community: &CommunityV2, channel_id: &ChannelId) -> Result<(PublicKey, GroupKey, Epoch), String> {
let author_pk = me_pk()?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
return Err("this community has been dissolved".to_string());
}
// A self-ban: every honest peer drops our events (CORD-04 §4) and the send
// echo would silently no-op, so fail loudly instead of a message that seems
// to send but shows up nowhere.
if crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default().contains(&author_pk.to_hex()) {
return Err("you are banned from this community".to_string());
}
let ch = community.channel(channel_id).ok_or("no such channel in this community")?;
if ch.private && ch.key.is_none() {
return Err("this private channel has no key yet (awaiting rekey delivery)".to_string());
}
let (secret, epoch) = community.channel_secret(ch);
Ok((author_pk, channel_group_key(&secret, channel_id, epoch), epoch))
}
/// Seal one chat rumor, publish, and echo the send into the
/// shared store. Returns the rumor id (hex).
#[allow(clippy::too_many_arguments)]
/// §7: an OWN edit must refresh its pinned target's proof bundle from the SEND
/// side — the relay echo of an own send deduplicates against the local echo, so
/// the ingest hook never sees it (send_delete's omission duty, same reason).
/// Without this the author's pin lags behind their message while everyone
/// else's follows. Returns the duty's arguments when the echo applied an edit.
fn own_echo_pin_duty(
outcome: &super::inbound::ChatPersist,
event: &ChatEvent,
) -> Option<(String, super::stream::OpenedStream)> {
match (outcome, event) {
(super::inbound::ChatPersist::Updated { .. }, ChatEvent::Edit { opened, target, .. }) => {
Some((crate::simd::hex::bytes_to_hex_32(target), opened.clone()))
}
_ => None,
}
}
#[allow(clippy::too_many_arguments)]
async fn publish_chat<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
group: &GroupKey,
author_pk: PublicKey,
channel_id: &ChannelId,
epoch: Epoch,
rumor: nostr_sdk::prelude::UnsignedEvent,
at_ms: u64,
ephemeral: bool,
) -> Result<String, String> {
crate::db::scoped(async move {
let ch = community.channel(channel_id).ok_or("no such channel in this community")?;
let (sending, wepoch) = writing::send_group(community, ch, group, rumor.kind.as_u16())?;
let group = &sending;
let rumor = match wepoch {
Some(w) => writing::as_writer(community, ch, rumor, w),
None => rumor,
};
let rumor_event_id = rumor.id.ok_or("rumor has no id")?;
let rumor_id = rumor_event_id.to_hex();
let owner = if ephemeral {
Keys::generate()
} else {
crate::community::message_delete::own_wrap_owner(&author_pk, &group.pk(), &rumor_event_id)
};
let signer = crate::signer::active_signer()?;
let wrap = chat::seal_chat_rumor_signed(&signer, author_pk, &rumor, group, Timestamp::from_secs(at_ms / 1000), ephemeral, &owner.public_key()).await
.map_err(|e| e.to_string())?;
// Both keys that can delete this wrap, frozen per message so a later rekey can't
// strand them: its owner for relays following CORD-01, the plane key for the rest.
// Kept before the publish: an unconfirmed send may still have landed.
if !ephemeral {
crate::db::community::store_wrap_owner(&rumor_id, &wrap.id.to_hex(), &owner, &community.relays)?;
crate::db::community::store_message_key(&rumor_id, &wrap.id.to_hex(), group.keys(), &community.relays)?;
}
// Reactions are left out: one that lands long after the user moved on surprises.
let kept = !ephemeral
&& matches!(rumor.kind.as_u16(), super::kind::MESSAGE | super::kind::COMMENT | super::kind::EDIT | super::kind::DELETE);
if kept {
outbox::keep(&rumor_id, &wrap);
}
if let Err(e) = transport.publish(&wrap, &community.relays).await {
// No relay answered, which is not the same as none taking it: ask before failing.
if !outbox::on_relays(transport, group.keys(), &wrap, &community.relays).await {
if kept {
outbox::resend_later(rumor_id.clone());
}
return Err(e);
}
}
if kept {
outbox::release(&rumor_id);
}
// Local echo: open our OWN wrap through the exact inbound path so
// send-then-read works with no listen loop, and the relay's re-delivery dedups
// against this row instead of re-firing callbacks. Best-effort — the publish
// already succeeded. Ephemeral kinds (typing) apply to nothing and skip out.
if !ephemeral {
let echo = match wepoch {
Some(w) => chat::open_writer_chat_event(&wrap, &group.pk(), w, group.conv_key(), channel_id, epoch),
None => chat::open_chat_event(&wrap, group, channel_id, epoch),
};
if let Ok(event) = echo {
let channel_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
super::inbound::hydrate_target(&event, &channel_hex).await;
let outcome = {
let mut st = crate::state::STATE.lock().await;
super::inbound::apply_chat_to_state(&mut st, &event, &channel_hex, &author_pk)
};
if let Some(outcome) = outcome {
super::inbound::persist_chat(&channel_hex, &outcome).await;
if let Some((target_hex, opened)) = own_echo_pin_duty(&outcome, &event) {
spawn_pin_duty(&channel_hex, &target_hex, Some(opened));
}
}
}
}
Ok(rumor_id)
})
.await
}
/// A chat event opened from a channel fetch, tagged with the epoch its key
/// decrypted under.
pub struct FetchedEvent {
pub event: ChatEvent,
pub epoch: Epoch,
/// The wrap it came in, so a later judgment can hold it.
pub wrap: Option<nostr_sdk::prelude::Event>,
}
/// Keep the delete keys of an OWN wrap met on a relay: one sent from another device or
/// before they were kept. The UI caches full-vs-limited verdicts per message, so one that
/// just became fully deletable is told to re-resolve.
pub(crate) fn heal_own_wrap_key(event: &ChatEvent, wrap: &nostr_sdk::prelude::Event, plane: Option<&Keys>, relays: &[String]) {
if crate::community::message_delete::heal_own_wrap(event, wrap, plane, relays) {
crate::traits::emit_event("message_delete_meta_changed", &serde_json::json!({ "id": event.opened().rumor_id.to_hex() }));
}
}
/// The key that signed `wrap` in `channel_id`, at its live read plane or a writer address,
/// when this device holds it.
pub(crate) fn plane_key_of(community: &CommunityV2, channel_id: &ChannelId, wrap: &nostr_sdk::prelude::Event) -> Option<Keys> {
let ch = community.channel(channel_id)?;
let (secret, epoch) = community.channel_secret(ch);
let group = channel_group_key(&secret, &ch.id, epoch);
if group.pk() == wrap.pubkey {
return Some(group.keys().clone());
}
let (wepoch, ..) = ch.writers.as_ref()?.writers().find(|(_, pk, _)| *pk == wrap.pubkey.to_bytes())?;
writing::writer_keys_at(community, ch, wepoch, &wrap.pubkey)
}
/// The most pages holding messages dated ahead one history read steps past for free.
const MAX_EARLY_PAGES: usize = 20;
/// Whether `event` is a message dated ahead of this device, now held for its time
/// ([`crate::early`]) instead of joining the page.
fn early_message(event: &ChatEvent, wrap: &nostr_sdk::prelude::Event) -> bool {
let early = matches!(event, ChatEvent::Message { .. }) && crate::early::is_early(event.opened().at_ms);
if early {
crate::early::hold(wrap.clone(), crate::early::Via::Community, event.opened().at_ms);
}
early
}
/// One epoch a channel read covers: keyed, or a past epoch held read-only (CORD-03 §5).
enum ReadPlane {
Keyed(GroupKey),
View(PublicKey, nostr_sdk::prelude::nip44::v2::ConversationKey),
/// A root plane a Private Channel used while it was public, which stands only for what was
/// sent there before the Channel went private (unix ms).
Public(GroupKey, u64),
}
impl ReadPlane {
fn address(&self) -> PublicKey {
match self {
ReadPlane::Keyed(group) | ReadPlane::Public(group, _) => group.pk(),
ReadPlane::View(address, _) => *address,
}
}
fn conv(&self) -> &nostr_sdk::prelude::nip44::v2::ConversationKey {
match self {
ReadPlane::Keyed(group) | ReadPlane::Public(group, _) => group.conv_key(),
ReadPlane::View(_, conv) => conv,
}
}
/// The key a gated relay authenticates this plane by, when this device holds it.
fn group(&self) -> Option<&GroupKey> {
match self {
ReadPlane::Keyed(group) | ReadPlane::Public(group, _) => Some(group),
ReadPlane::View(..) => None,
}
}
/// Whether an event sent at `at_ms` stands on this plane.
fn holds(&self, at_ms: u64) -> bool {
match self {
ReadPlane::Public(_, until) => at_ms < *until,
_ => true,
}
}
fn open(&self, wrap: &Event, channel_id: &ChannelId, epoch: Epoch) -> Option<chat::ChatEvent> {
let opened = match self {
ReadPlane::Keyed(group) | ReadPlane::Public(group, _) => chat::open_chat_event(wrap, group, channel_id, epoch),
ReadPlane::View(address, conv) => chat::open_chat_event_at(wrap, address, conv, channel_id, epoch),
};
opened.ok().filter(|ev| self.holds(ev.opened().at_ms))
}
}
/// Every read plane this device holds for `ch`, with its epoch: a Public Channel's under every
/// held root, a Private one's under its own keys and the past epochs it may only read.
fn read_planes(community: &CommunityV2, ch: &ChannelV2) -> Vec<(ReadPlane, Epoch)> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let coords: Vec<([u8; 32], Epoch)> = if ch.private {
let Some(current) = ch.key else {
return Vec::new();
};
let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
let mut held = crate::db::community::held_epoch_keys(&cid_hex, &ch_hex).unwrap_or_default();
if !held.iter().any(|(ep, _)| *ep == ch.epoch) {
held.push((ch.epoch, current));
}
// Only real grants are archived, but keep the invariant local: a private
// plane is never read with the root value.
held.into_iter().filter(|(_, k)| *k != community.community_root).map(|(ep, k)| (k, ep)).collect()
} else {
let mut roots = crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap_or_default();
if !roots.iter().any(|(ep, _)| *ep == community.root_epoch) {
roots.push((community.root_epoch, community.community_root));
}
roots.into_iter().map(|(ep, root)| (root, ep)).collect()
};
let mut planes: Vec<(ReadPlane, Epoch)> = coords.into_iter().map(|(secret, epoch)| (ReadPlane::Keyed(channel_group_key(&secret, &ch.id, epoch)), epoch)).collect();
if ch.private {
// Past epochs delivered read-only with Read Message History (CORD-03 §5).
let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
for (epoch, view) in crate::db::community::history_views(&cid_hex, &ch_hex).unwrap_or_default() {
if planes.iter().any(|(_, e)| *e == epoch) {
continue;
}
if let Ok(address) = PublicKey::from_slice(&view.address) {
planes.push((ReadPlane::View(address, nostr_sdk::prelude::nip44::v2::ConversationKey::new(view.conv_key)), epoch));
}
}
// What it said while public is its history too, read at the roots it used (CORD-03 §2).
if let Some(until) = ch.public_until() {
let mut roots = crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap_or_default();
if !roots.iter().any(|(ep, _)| *ep == community.root_epoch) {
roots.push((community.root_epoch, community.community_root));
}
planes.extend(roots.into_iter().map(|(ep, root)| (ReadPlane::Public(channel_group_key(&root, &ch.id, ep), until), ep)));
}
}
// The earlier planes its metadata publishes, last, so a live plane of the same epoch number
// sorts ahead of them.
for (epoch, group) in ch.published_history() {
if !planes.iter().any(|(p, _)| p.address() == group.pk()) {
planes.push((ReadPlane::Keyed(group), epoch));
}
}
planes
}
/// Open `wrap` as a post in `ch` under `planes`, with the writer epoch whose address carried it.
fn open_on_planes(ch: &ChannelV2, planes: &[(ReadPlane, Epoch)], wrap: &Event) -> Option<(chat::ChatEvent, Option<Epoch>)> {
if let Some((wepoch, ..)) = ch.writers.as_ref().and_then(|l| l.writers().find(|(_, pk, _)| *pk == wrap.pubkey.to_bytes())) {
return planes.iter().find_map(|(plane, epoch)| chat::open_writer_chat_event(wrap, &wrap.pubkey, wepoch, plane.conv(), &ch.id, *epoch).ok().filter(|ev| plane.holds(ev.opened().at_ms))).map(|ev| (ev, Some(wepoch)));
}
let (plane, epoch) = planes.iter().find(|(p, _)| p.address() == wrap.pubkey)?;
plane.open(wrap, &ch.id, *epoch).map(|ev| (ev, None))
}
/// How many of the newest held epochs a newest-first catch-up reads. One: a
/// rotation moves the conversation, so the live epoch is where it is. Rotated-past
/// epochs are reached by back-paging, when a reader actually scrolls for them.
const LIVE_COORD_EPOCHS: usize = 1;
/// Fetch a channel's newest messages — one page of [`fetch_channel_history`].
/// `limit` is one relay-side bound across the whole epoch-author OR-set, not
/// per epoch; deeper history pages backwards via the walk.
pub async fn fetch_channel<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
limit: usize,
) -> Result<Vec<FetchedEvent>, String> {
fetch_channel_history(transport, community, channel_id, limit, 1, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await
}
/// Walk a channel's history newest-first (CORD-03 §3 "clients load a Channel
/// newest-first and paginate backwards"), querying every held epoch's Chat-Plane
/// address one `page`-sized query at a time until `max_pages`, a drained relay,
/// or `keep_paging` returns false for a page (the caller's "I already hold
/// these" early stop — consulted only on pages that opened something, so junk
/// at the address can't fake exhaustion). Pages step by INCLUSIVE `until` with
/// wrap-id dedup, so a page boundary landing mid-second can't skip siblings; a
/// full page of only-already-seen wraps is a same-second WALL (relay filters
/// are second-granular) and steps past it accepting that unseen same-second
/// siblings beyond the relay cap are unreachable — logged, and a protocol-level
/// limitation (the `ms` tag can't be filtered server-side).
///
/// Returns everything opened, deduped by rumor id, oldest→newest; `settled` wraps are not
/// opened and not returned.
#[allow(clippy::too_many_arguments)]
pub async fn fetch_channel_history<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
page: usize,
max_pages: usize,
since: Option<u64>,
// Unix-seconds upper bound for the FIRST page (inclusive) — the back-paging
// cursor. `None` starts at the newest.
start_until: Option<u64>,
evidence: crate::community::transport::Evidence,
// Given a page's opened events and how many of its wraps were `settled`.
keep_paging: impl FnMut(&[FetchedEvent], usize) -> bool,
// Of a page's wraps, those the caller already holds in full: skipped unopened, and counted
// for `keep_paging`.
settled: impl Fn(&[nostr_sdk::prelude::EventId]) -> std::collections::HashSet<nostr_sdk::prelude::EventId>,
) -> Result<Vec<FetchedEvent>, String> {
let mut keep_paging = keep_paging;
fetch_channel_history_paged(transport, community, channel_id, page, max_pages, since, start_until, evidence, |p, s, _| keep_paging(p, s), settled).await.map(|(events, ..)| events)
}
/// Whether a catch-up pages on past this page: while it holds a message we don't (`held` by
/// rumor id), or no message at all (reactions and edits decide nothing), or only held messages
/// but the next page (`next`) still starts above `floor`. Held rows up there may have arrived
/// live over a stretch nothing read.
pub fn catch_up_pages_on(page: &[FetchedEvent], settled: usize, next: Option<u64>, floor: Option<u64>, held: impl Fn(&str) -> bool) -> bool {
let mut saw_message = settled > 0;
for f in page {
if matches!(&f.event, ChatEvent::Message { .. }) {
saw_message = true;
if !held(&f.event.opened().rumor_id.to_hex()) {
return true;
}
}
}
!saw_message || floor.zip(next).is_some_and(|(f, n)| n > f)
}
/// [`fetch_channel_history`], with where to page on from (Unix seconds) when it stopped with
/// addresses still unread: every row it returns is at or above that, so a caller that pages
/// from there skips nothing, even after a page whose rows were all dropped. `keep_paging` is
/// also told where the next page would start (None: this one wasn't full, so none follows).
/// Last, whether every relay answered every plane read: only then is an absence proven.
#[allow(clippy::too_many_arguments)]
pub async fn fetch_channel_history_paged<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
page: usize,
max_pages: usize,
since: Option<u64>,
start_until: Option<u64>,
evidence: crate::community::transport::Evidence,
keep_paging: impl FnMut(&[FetchedEvent], usize, Option<u64>) -> bool,
settled: impl Fn(&[nostr_sdk::prelude::EventId]) -> std::collections::HashSet<nostr_sdk::prelude::EventId>,
) -> Result<(Vec<FetchedEvent>, Option<u64>, bool), String> {
fetch_channel_history_since_epoch(transport, community, channel_id, page, max_pages, since, start_until, evidence, keep_paging, settled, None, &[]).await
}
/// [`fetch_channel_history_paged`], where a newest-first walk also reads the Channel's epochs from
/// `past.0` up: the one a proof was read under from `since`, and each later one from `past.1`,
/// since no walk read those; and so too each published plane at an address in `unread`.
#[allow(clippy::too_many_arguments)]
pub async fn fetch_channel_history_since_epoch<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
page: usize,
max_pages: usize,
since: Option<u64>,
start_until: Option<u64>,
evidence: crate::community::transport::Evidence,
mut keep_paging: impl FnMut(&[FetchedEvent], usize, Option<u64>) -> bool,
settled: impl Fn(&[nostr_sdk::prelude::EventId]) -> std::collections::HashSet<nostr_sdk::prelude::EventId>,
past: Option<(Epoch, Option<u64>)>,
unread: &[PublicKey],
) -> Result<(Vec<FetchedEvent>, Option<u64>, bool), String> {
crate::db::scoped(async move {
// Guards the opportunistic scrub-key heals below — the fetch loop straddles
// network I/O, and an account swap must not write into the new account's DB.
let ch = community.channel(channel_id).ok_or("no such channel in this community")?;
// A Public channel reads across EVERY held base-root epoch, and a Private one
// across its OWN held epochs (CORD-03 §3), so history spanning a rotation stays
// continuous either way. A keyless Private channel is unreadable — never derived
// from the root (that would address the public plane).
let mut planes = read_planes(community, ch);
if planes.is_empty() {
return Ok((Vec::new(), None, true));
}
// Every epoch is its own address on this plane, so the full set costs one
// fetch per held epoch per page and grows with the community's whole
// rotation history. A newest-first catch-up wants the live epoch, which is
// the only one anyone should be speaking on; reaching back through a
// rotation is what back-paging (`start_until`) is for — the same division
// the boot volley already draws.
// A restricted Channel's writer addresses, opened under the read epochs above: those whose
// window reaches what this read covers, or for a first look the live one and the one it closed.
let windows: Vec<(PublicKey, Epoch, u64, Option<u64>)> = ch
.writers
.iter()
.flat_map(|l| l.writers().map(move |(e, pk, end)| (e, pk, l.writer_start(e).unwrap_or(0), end)))
.filter_map(|(e, pk, start, end)| PublicKey::from_slice(&pk).ok().map(|a| (a, e, start, end)))
.collect();
let mut writer_planes: Vec<(PublicKey, Epoch)> = match (start_until, since) {
// A slow clock dates a post a little before its window opened.
(Some(u), _) => windows.iter().filter(|w| w.2.saturating_sub(super::writers::HORIZON_MS) <= u.saturating_mul(1000)).map(|w| (w.0, w.1)).collect(),
(None, Some(s)) => windows.iter().filter(|w| w.3.is_none_or(|end| end > s.saturating_mul(1000))).map(|w| (w.0, w.1)).collect(),
(None, None) => windows.iter().map(|w| (w.0, w.1)).collect(),
};
if start_until.is_none() && since.is_none() {
writer_planes.sort_by_key(|(_, e)| std::cmp::Reverse(e.0));
writer_planes.truncate(2);
}
let live_writer = writing::live_writer(community, ch);
let mut whole: std::collections::HashSet<PublicKey> = std::collections::HashSet::new();
if start_until.is_none() {
// Root epochs and the Channel's own count apart, so each keeps its newest.
let (mut public, rest): (Vec<_>, Vec<_>) = planes.into_iter().partition(|(p, _)| matches!(p, ReadPlane::Public(..)));
let (fresh, mut own): (Vec<_>, Vec<_>) = rest.into_iter().partition(|(p, _)| unread.contains(&p.address()));
public.sort_by_key(|(_, e)| std::cmp::Reverse(e.0));
public.truncate(LIVE_COORD_EPOCHS);
own.sort_by_key(|(_, e)| std::cmp::Reverse(e.0));
let kept = past.map_or(0, |(from, _)| own.iter().filter(|(_, e)| e.0 >= from.0).count());
own.truncate(kept.max(LIVE_COORD_EPOCHS));
if let Some((from, _)) = past {
whole = own.iter().filter(|(_, e)| e.0 > from.0).map(|(p, _)| p.address()).collect();
}
whole.extend(fresh.iter().map(|(p, _)| p.address()));
planes = own.into_iter().chain(fresh).chain(public).collect();
}
// The writers' rules judge what arrives: what they don't stand behind reaches only managers.
let judge = writing::Judge::of(community, ch);
// Below a seal the read address is read by the ids it names, never by date; above it, by
// date in the stretches it took things in, never inside a quiet one.
let seal = ch.writers.as_ref().and_then(|l| l.seal.clone());
let mut walk = seal.as_ref().map(|s| sealing::SealWalk::new(s, start_until.map_or(u64::MAX, |u| u.saturating_mul(1000).saturating_add(999))));
let mut seen_wraps: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
// Read by date in seconds, a stretch's floor second also holds what was dated below it:
// that stands only as the seal names it, and is read again when the seal does.
let mut sealed_ids: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
let mut unsealed: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
let below_seal = |at_ms: u64| seal.as_ref().is_some_and(|s| at_ms < s.until);
let mut seen_rumors = std::collections::HashSet::new();
let mut out: Vec<(u64, FetchedEvent)> = Vec::new();
let mut until: Option<u64> = start_until;
let mut ended = false;
let mut complete = true;
let (mut pages_left, mut early_pages) = (max_pages, 0usize);
while pages_left > 0 {
pages_left -= 1;
let mut early = 0usize;
// Each address pages on its own: the next page starts below the newest bottom of the
// ones that came back full, so a busy address never pushes a quiet one past a gap.
let mut full_oldest: Option<u64> = None;
let mut note_page = |evs: &[Event]| {
if evs.len() >= page {
full_oldest = full_oldest.max(evs.iter().map(|e| e.created_at.as_secs()).min());
}
};
// Fetch each held epoch's Chat-Plane AUTHED AS that plane key. AUTH-gating
// relays (Ditto) require the connection authed as the author queried and
// reject a multi-author REQ ("all authors must be authenticated"), so a
// single merged fetch returns nothing there — the latest messages under a
// freshly-adopted epoch never load. Per-plane authed fetches + union.
let mut wraps: Vec<Event> = Vec::new();
let mut wrap_ids: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
// An empty page means drained only when a relay said so: silence everywhere is not the start.
let mut answered = false;
// The read address's stretch at or below this page's top, and where it goes on below it.
let top_ms = until.map_or_else(now_ms, |u| u.saturating_mul(1000).saturating_add(999));
let range = match ch.writers.as_ref() {
Some(l) => l.read_range(top_ms),
None => Some((0, top_ms)),
};
let (read_on, read_until) = match range {
Some((_, t)) => (true, if t >= top_ms { until } else { Some(t / 1000) }),
None => (false, until),
};
let read_since = since.max(range.map(|(f, _)| f / 1000).filter(|f| *f > 0));
let whole_since = past.and_then(|(_, s)| s).max(range.map(|(f, _)| f / 1000).filter(|f| *f > 0));
let below = range.and_then(|(f, _)| (f > 0).then(|| (f / 1000).checked_sub(1)).flatten()).filter(|b| since.is_none_or(|s| s <= *b));
let mut read_full = false;
let lowest_since = if whole.is_empty() { read_since } else { read_since.min(whole_since) };
let read_planes_here: &[(ReadPlane, Epoch)] = if read_on && !lowest_since.zip(read_until).is_some_and(|(s, u)| s > u) { &planes } else { &[] };
for (plane, _) in read_planes_here {
let since = if whole.contains(&plane.address()) { whole_since } else { read_since };
let q = Query { since, evidence, ..plane_page(plane.address().to_hex(), page, read_until) };
// A read view holds no key to authenticate as the plane, so it asks plainly.
let fetched = match plane.group() {
Some(group) => transport.fetch_plane(group.keys(), &q, &community.relays).await.map(|f| {
complete &= f.is_complete();
f.events
}),
None => transport.fetch(&q, &community.relays).await,
};
complete &= fetched.is_ok();
if let Ok(evs) = fetched {
answered = true;
read_full |= evs.len() >= page;
note_page(&evs);
for e in evs {
if wrap_ids.insert(e.id) {
wraps.push(e);
}
}
}
}
for (address, wepoch) in &writer_planes {
let q = Query { since, evidence, ..plane_page(address.to_hex(), page, until) };
// Only a writer can authenticate as the address.
let fetched = match &live_writer {
Some((e, _, group)) if e == wepoch => transport.fetch_plane(group.keys(), &q, &community.relays).await.map(|f| {
complete &= f.is_complete();
f.events
}),
_ => transport.fetch(&q, &community.relays).await,
};
complete &= fetched.is_ok();
let Ok(fetched) = fetched else { continue };
answered = true;
note_page(&fetched);
for e in fetched {
if wrap_ids.insert(e.id) {
wraps.push(e);
}
}
}
// A stretch run dry hands on to the one below it, or to the seal, rather than ending
// the walk; below the seal its ids page on with the rest.
let hand_on = below.filter(|_| !read_full);
full_oldest = full_oldest.max(hand_on);
let mut seal_on: Option<u64> = None;
if let (Some(w), Some(s)) = (walk.as_mut(), seal.as_ref()) {
if !read_on && since.is_none_or(|f| f.saturating_mul(1000) < s.until) && !w.done() {
match w.next(transport, community, ch, page).await {
Ok(step) => {
// A page owed and not served leaves what lies past it unread, not absent.
complete &= !w.broken();
let mut by_plane: Vec<(PublicKey, Vec<[u8; 32]>)> = Vec::new();
for (id, address) in step.ids {
match by_plane.iter_mut().find(|(a, _)| *a == address) {
Some((_, ids)) => ids.push(id),
None => by_plane.push((address, vec![id])),
}
}
for (address, ids) in by_plane {
let plane = planes.iter().find(|(p, _)| p.address() == address).and_then(|(p, _)| p.group());
match sealing::fetch_ids(transport, community, plane, &ids, evidence).await {
Ok(evs) => {
answered = true;
for e in evs {
sealed_ids.insert(e.id);
if unsealed.remove(&e.id) {
seen_wraps.remove(&e.id);
}
if wrap_ids.insert(e.id) {
wraps.push(e);
}
}
}
Err(_) => complete = false,
}
}
// The walk goes on from its pages' own dates, whatever the ids came back as.
if !w.done() {
seal_on = step.bottom_ms.map(|b| b / 1000);
full_oldest = full_oldest.max(seal_on);
}
}
Err(_) => complete = false,
}
}
}
if !answered {
if out.is_empty() {
return Err("no relay answered".into());
}
break; // keeps `until` as the cursor: the walk goes on from here next time
}
if wraps.is_empty() {
if let Some(next) = hand_on.or(seal_on) {
until = Some(next);
continue;
}
ended = true;
break;
}
let mut fresh = 0usize;
let mut held = 0usize;
let unseen: Vec<_> = wraps.iter().map(|w| w.id).filter(|id| !seen_wraps.contains(id)).collect();
let settled_here = if unseen.is_empty() { Default::default() } else { settled(&unseen) };
let mut page_events: Vec<FetchedEvent> = Vec::new();
// The page's signatures in one batch, each wrap under the keys the loop below opens it
// with: a writer address under every read epoch (and its own signature checked), a
// plane's under that plane's. The opens then confirm ids for what the batch vouched for.
let every_plane: Vec<&nostr_sdk::prelude::nip44::v2::ConversationKey> = planes.iter().map(|(p, _)| p.conv()).collect();
let to_open: Vec<(&Event, Vec<&nostr_sdk::prelude::nip44::v2::ConversationKey>, bool)> = wraps
.iter()
.filter(|w| !seen_wraps.contains(&w.id) && !settled_here.contains(&w.id))
.filter_map(|w| {
if writer_planes.iter().any(|(a, _)| *a == w.pubkey) {
return Some((w, every_plane.clone(), true));
}
planes.iter().find(|(p, _)| p.address() == w.pubkey).map(|(p, _)| (w, vec![p.conv()], false))
})
.collect();
let batch = stream::check_signatures_together(&to_open);
for wrap in &wraps {
if !seen_wraps.insert(wrap.id) {
continue;
}
fresh += 1;
if settled_here.contains(&wrap.id) {
held += 1;
continue;
}
if let Some((address, wepoch)) = writer_planes.iter().find(|(a, _)| *a == wrap.pubkey) {
let opened = planes.iter().find_map(|(plane, epoch)| {
chat::open_writer_chat_event(wrap, address, *wepoch, plane.conv(), channel_id, *epoch).ok().filter(|ev| plane.holds(ev.opened().at_ms)).map(|ev| (ev, *epoch))
});
if opened.as_ref().is_some_and(|(ev, _)| early_message(ev, wrap)) {
early += 1;
continue;
}
if let Some((event, epoch)) = opened.and_then(|(ev, e)| writing::judge_arrival(judge.as_ref(), &community.id().0, channel_id, wrap, ev, Some(*wepoch)).map(|ev| (ev, e))) {
if seen_rumors.insert(event.opened().rumor_id) {
if crate::state::my_public_key() == Some(event.opened().author) {
let writer = community.channel(channel_id).and_then(|ch| writing::writer_keys_at(community, ch, *wepoch, address));
heal_own_wrap_key(&event, wrap, writer.as_ref(), &community.relays);
}
page_events.push(FetchedEvent { event, epoch, wrap: Some(wrap.clone()) });
}
}
continue;
}
// Select the epoch whose group key authored this wrap (no trial decrypt).
for (plane, epoch) in &planes {
if wrap.pubkey != plane.address() {
continue;
}
let opened = plane.open(wrap, channel_id, *epoch);
if opened.as_ref().is_some_and(|ev| below_seal(ev.opened().at_ms)) && !sealed_ids.contains(&wrap.id) {
unsealed.insert(wrap.id);
break;
}
if opened.as_ref().is_some_and(|ev| early_message(ev, wrap)) {
early += 1;
break;
}
let opened = opened.and_then(|ev| writing::judge_arrival(judge.as_ref(), &community.id().0, channel_id, wrap, ev, None));
if let Some(event) = opened {
let id = event.opened().rumor_id;
if seen_rumors.insert(id) {
heal_own_wrap_key(&event, wrap, plane.group().map(GroupKey::keys), &community.relays);
page_events.push(FetchedEvent { event, epoch: *epoch, wrap: Some(wrap.clone()) });
}
}
break;
}
}
drop(batch);
// Messages dated ahead took page slots without joining the page, and their place in
// it bounds what an older address may show: page again for free, or the caller could
// read the end of history. Bounded, so a flood of them can't page forever.
if early > 0 && early_pages < MAX_EARLY_PAGES {
early_pages += 1;
pages_left += 1;
}
if fresh == 0 {
// A full page of already-seen wraps: a same-second WALL. Step past it;
// same-second siblings beyond the relay's cap are unreachable by a
// second-granular filter. No full page means drained.
let Some(o) = full_oldest else {
ended = true;
break;
};
if o == 0 {
ended = true;
break;
}
crate::log_warn!("v2: same-second history wall at {o} — stepping past it (messages beyond the relay page cap in that second are unreachable)");
until = Some(o - 1);
continue;
}
let stop = (!page_events.is_empty() || held > 0) && !keep_paging(&page_events, held, full_oldest);
out.extend(page_events.into_iter().map(|e| (e.event.opened().at_ms, e)));
if stop {
ended = true;
break; // the caller holds everything from here back.
}
// Inclusive — wrap-id dedup absorbs the boundary overlap.
let Some(next) = full_oldest else {
ended = true;
break;
};
until = Some(next);
}
// Out of pages with addresses still unread below the frontier: what a quieter one gave
// below it would let a caller paging on from its oldest row skip the rest.
let cursor = (!ended).then_some(until).flatten();
if let Some(frontier) = cursor {
out.retain(|(ms, _)| ms / 1000 >= frontier);
}
// Ties break on the content-derived rumor id, so every client orders a
// same-millisecond pair identically. A bare `ms` sort left ties to whatever
// order the relay happened to serve across pages, so two readers could show
// the same two messages in opposite orders.
out.sort_by(|a, b| {
a.0.cmp(&b.0)
.then_with(|| a.1.event.opened().rumor_id.as_bytes().cmp(b.1.event.opened().rumor_id.as_bytes()))
});
Ok((out.into_iter().map(|(_, e)| e).collect(), cursor, complete))
})
.await
}
// ── Invites (CORD-05) ────────────────────────────────────────────────────────
/// Who an invite bundle is FOR — which decides the Private-Channel keys it may
/// carry (CORD-05 §1 vs §2).
///
/// A **Link** has no recipient: "anyone the link reaches can join", so its
/// audience holds no Role by construction and is entitled to no Private Channel
/// at all. A **Member** is a specific npub whose entitlement is computable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BundleAudience {
/// A public link (33301 bundle event): public channels only.
Link,
/// A direct invite (3313) to this npub: may carry Private-Channel keys.
Member(PublicKey),
}
/// Build the §1 invite bundle for this community, scoped to `audience`. A
/// Public channel carries the `community_root` as its "key" (the joiner derives
/// the real secret from the root); a Private one its own key — and only for a
/// Member the folded roster shows entitled. The bundle self-certifies the owner,
/// so the inviter's identity is irrelevant to trust.
pub fn bundle_of(
community: &CommunityV2,
audience: BundleAudience,
creator: Option<PublicKey>,
expires_at_ms: Option<u64>,
label: Option<String>,
) -> CommunityInvite {
bundle_of_with_overlay(community, audience, creator, expires_at_ms, label, &[], &[])
}
/// [`bundle_of`] settling entitlement against a Grant this client JUST published
/// (`with`/`without` role ids), since the fold lags its own publish. This is the
/// grant-vend path (CORD-03 "delivered on grant").
pub fn bundle_of_with_overlay(
community: &CommunityV2,
audience: BundleAudience,
creator: Option<PublicKey>,
expires_at_ms: Option<u64>,
label: Option<String>,
with: &[String],
without: &[String],
) -> CommunityInvite {
let hex = crate::simd::hex::bytes_to_hex_32;
let cid_hex = hex(&community.identity.community_id.0);
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let owner_hex = community.owner().ok().map(|o| o.to_hex());
let recipient_hex = match audience {
BundleAudience::Link => None,
BundleAudience::Member(pk) => Some(pk.to_hex()),
};
let lane = match audience {
BundleAudience::Link => invite::BundleLane::Link,
BundleAudience::Member(_) => invite::BundleLane::Direct,
};
let channels = community
.vendable_channels(&roster, owner_hex.as_deref(), recipient_hex.as_deref(), with, without)
.into_iter()
.map(|c| invite::ChannelGrant {
id: hex(&c.id.0),
key: hex(&c.key.unwrap_or(community.community_root)),
epoch: c.epoch.0,
name: c.name.clone(),
})
.collect();
let mut bundle = CommunityInvite {
community_id: hex(&community.identity.community_id.0),
owner: hex(&community.identity.owner_xonly),
owner_salt: hex(&community.identity.owner_salt),
community_root: hex(&community.community_root),
root_epoch: community.root_epoch.0,
// Read access to the Control Plane, never write (CORD-02 §7); absent
// on a legacy pre-split epoch.
control_pk: community.control_pk.map(|p| p.to_hex()),
channels,
relays: community.relays.clone(),
name: community.name.clone(),
// Mint-time snapshot so a parked invite renders the real logo before any
// fold; the Control Plane stays the authority after joining.
icon: community.icon.clone(),
expires_at: expires_at_ms,
creator_npub: creator.map(|p| p.to_hex()),
label: invite::clamp_label(label),
extra: Default::default(),
};
bundle.fit(lane);
bundle
}
/// Gift-wrap a Direct Invite (kind 3313) of this community straight to `recipient`
/// and publish it to the community relays. `expires_at_ms` (unix ms) optionally
/// bounds its shelf life; `label` is echoed in the joiner's Guestbook Join. The
/// bundle hands over the keys; the recipient consents by accepting (nothing joins
/// on receipt). Returns the wrap.
pub async fn send_direct_invite<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
recipient: &PublicKey,
expires_at_ms: Option<u64>,
label: Option<String>,
) -> Result<Event, String> {
crate::db::scoped(async move {
// A stale bundle is worse than a stale edit: it hands the joiner keys to a
// buried epoch, and their client later self-evicts on the rekey exclusion.
assert_current_root(community)?;
let signer = crate::signer::active_signer()?;
let inviter_pk = me_pk()?;
let bundle = bundle_of(community, BundleAudience::Member(*recipient), Some(inviter_pk), expires_at_ms, label);
let wrap = invite::build_direct_invite_signed(&signer, inviter_pk, recipient, &bundle).await.map_err(|e| e.to_string())?;
transport.publish(&wrap, &community.relays).await?;
Ok(wrap)
})
.await
}
/// A minted public link: the shareable URL plus the addressable bundle event to
/// publish and the link keypair to retain (in the Invite List) for later refresh
/// or revocation.
#[derive(Clone)]
pub struct MintedLink {
pub url: String,
pub bundle_event: Event,
pub link_signer: Keys,
pub token: [u8; super::derive::TOKEN_LEN],
/// Unix ms, mirrored from the bundle. The Invite List is the creator's only
/// record of it, and the Registry prunes on it — the coordinate a member
/// folds carries no expiry, so a lapsed link the creator never pruned reads
/// as a live door forever (CORD-05 §4/§5).
pub expires_at_ms: Option<u64>,
pub label: Option<String>,
}
/// Mint a public invite link for this community: a fresh token + link keypair, the
/// bundle encrypted under the token key and published at `(33301, link_signer,
/// "")`, and the `base/invite/<naddr>#<fragment>` URL. `base` is the deep-link
/// domain (e.g. `https://vectorapp.io`); the fragment carries the token + bootstrap
/// relays and never reaches a server.
pub async fn mint_public_link<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
base: &str,
expires_at_ms: Option<u64>,
label: Option<String>,
) -> Result<MintedLink, String> {
crate::db::scoped(async move {
let minted = publish_public_link(transport, community, base, expires_at_ms, label).await?;
// Best-effort: the link works without the sync.
let _ = record_minted_link(transport, community, &minted).await;
Ok(minted)
})
.await
}
/// [`mint_public_link`] for a caller waiting to show the link: it returns once the bundle is
/// durable, and the cross-device record finishes on a task bound to this account.
pub async fn mint_public_link_sync_later(
community: &CommunityV2,
base: &str,
expires_at_ms: Option<u64>,
label: Option<String>,
) -> Result<MintedLink, String> {
crate::db::scoped(async move {
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let minted = publish_public_link(&transport, community, base, expires_at_ms, label).await?;
if !crate::rt::can_spawn() {
let _ = record_minted_link(&transport, community, &minted).await;
return Ok(minted);
}
let (community, record) = (community.clone(), minted.clone());
crate::db::spawn_bound(async move {
if let Err(e) = record_minted_link(&transport, &community, &record).await {
crate::log_warn!("[Invites] syncing a new link across devices failed: {e}");
}
});
Ok(minted)
})
.await
}
/// Mint and publish a link's bundle, and mirror it locally; the Invite List and Registry are
/// [`record_minted_link`]'s.
async fn publish_public_link<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
base: &str,
expires_at_ms: Option<u64>,
label: Option<String>,
) -> Result<MintedLink, String> {
crate::db::scoped(async move {
// Readers ignore a registry whose author lacks CREATE_INVITE (it can't even
// flip the community Public) — refuse before minting a link nobody honors.
ensure_folded_permission(community, &me_pk()?, crate::community::roles::Permissions::CREATE_INVITE, "minting a public invite link")?;
let label = invite::clamp_label(label);
let mut token = [0u8; super::derive::TOKEN_LEN];
token.copy_from_slice(&super::super::random_32()[..super::derive::TOKEN_LEN]);
let link_signer = Keys::generate();
let bundle = bundle_of(community, BundleAudience::Link, Some(me_pk()?), expires_at_ms, label.clone());
let bundle_key = super::derive::invite_bundle_key(&token);
let bundle_event = invite::build_bundle_event(&link_signer, &bundle, &bundle_key).map_err(|e| e.to_string())?;
let url = invite::build_invite_url(base, &link_signer.public_key(), &token, &community.relays).map_err(|e| e.to_string())?;
let minted = MintedLink { url, bundle_event, link_signer, token, expires_at_ms, label: label.clone() };
// A link the Invite List can't sync is one no other device can retire: refuse it up front.
{
let gate = invite_list_gate();
let _held = gate.lock().await;
if let Some(mut list) = fetch_invite_list(transport, &invite_list_relays(community).await).await? {
list.prune_expired(now_ms());
list.entries.push(link_entry(community, &minted));
if !list.fits() {
return Err("Too many invite links to sync: revoke some, or let them expire, first".into());
}
}
}
transport.publish_durable(&minted.bundle_event, &community.relays).await?;
// Local mirror so `list_public_invites` stays a sync local read;
// the 13303 list remains the cross-device record.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let token_hex = crate::simd::hex::bytes_to_hex_16(&minted.token);
let _ = crate::db::community::save_public_invite(&token_hex, &cid_hex, &minted.url, expires_at_ms.map(|e| e as i64), label.as_deref());
Ok(minted)
})
.await
}
// ── The Invite Registry (vsk 8) + Invite List (13303), CORD-05 §4/§5 ──────────
/// Fetch the creator's own 13303 Invite List from `relays` (newest wins; a
/// decrypt/parse failure is "no news", never a clobber of the local mirror).
/// Transport failure is Err, NOT None: the 13303 is REPLACEABLE, so a caller
/// that mistakes "couldn't reach the relays" for "no list yet" and publishes a
/// fresh one wipes every link minted on other devices. Full evidence for the
/// same reason — this read feeds replaceable-event writes.
async fn fetch_invite_list<T: Transport + ?Sized>(
transport: &T,
relays: &[String],
) -> Result<Option<invite::InviteList>, String> {
Ok(read_invite_list(transport, relays).await?.map(|(l, _)| l))
}
/// Every copy of this account's Invite List (CORD-05 §4) merged, with the newest copy's
/// `created_at`. A copy that won't open is an error, never an empty list: it may hold the only
/// secret of a live link, and a write built without it would lose that link for good.
async fn read_invite_list<T: Transport + ?Sized>(transport: &T, relays: &[String]) -> Result<Option<(invite::InviteList, u64)>, String> {
read_invite_list_with(transport, relays, true).await
}
/// [`read_invite_list`], `strict` refusing on a copy that won't open (a writer), or skipping it (a reader).
async fn read_invite_list_with<T: Transport + ?Sized>(transport: &T, relays: &[String], strict: bool) -> Result<Option<(invite::InviteList, u64)>, String> {
let signer = crate::signer::active_signer()?;
let my_pk = me_pk()?;
let query = Query {
kinds: vec![super::kind::INVITE_LIST],
authors: vec![my_pk.to_hex()],
limit: Some(16),
evidence: crate::community::transport::Evidence::Full,
..Default::default()
};
let events = transport.fetch(&query, relays).await?;
let mut merged: Option<(invite::InviteList, u64)> = None;
let mut seen = std::collections::HashSet::new();
for e in events {
// A relay may answer with anything signed; only this account's own list is a copy of it.
if e.pubkey != my_pk || e.kind.as_u16() != super::kind::INVITE_LIST || !seen.insert(e.id) {
continue;
}
let l = match invite::parse_invite_list_event_signed(&signer, my_pk, &e).await {
Ok(l) => l,
Err(_) if !strict => continue,
Err(err) => return Err(format!("a copy of your invite list couldn't be read, so it isn't written over: {err}")),
};
let at = e.created_at.as_secs();
merged = Some(match merged {
None => (l, at),
Some((held, newest)) => (invite::merge_invite_lists(held, l), newest.max(at)),
});
}
Ok(merged)
}
/// Where this account's Invite List lives (CORD-05 §4): its own write relays and the stock set,
/// as for the Community List, and the Community's, where earlier builds kept it.
async fn invite_list_relays(community: &CommunityV2) -> Vec<String> {
let mut set = own_list_relays().await;
set.extend(invite::stock_relays());
set.extend(community.relays.iter().cloned());
set.sort();
set.dedup();
set
}
/// Publish this account's Invite List, dated after the newest copy it read.
async fn publish_invite_list<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, list: &invite::InviteList, newest: Option<u64>) -> Result<(), String> {
let signer = crate::signer::active_signer()?;
let my_pk = me_pk()?;
let at = (now_ms() / 1000).max(newest.map_or(0, |n| n + 1));
let event = invite::build_invite_list_event_at(&signer, my_pk, list, at).await.map_err(|e| e.to_string())?;
transport.publish(&event, &invite_list_relays(community).await).await
}
/// The creator's LIVE link-signer pubkeys for one community — the Registry's
/// content (CORD-05 §5), derived from the stored link secrets.
///
/// Live means neither tombstoned nor EXPIRED. An expired link cannot be joined
/// (`InviteBundle::expired`, CORD-05 §1), so leaving it in the Registry states
/// a door that isn't there: the aggregate never empties, the community reads
/// Public forever, and every gate hanging off that reading silently inverts.
fn live_signers_for(list: &invite::InviteList, community_id_hex: &str, now_ms: u64) -> Vec<PublicKey> {
let dead: std::collections::HashSet<&str> = list.tombstones.iter().map(|t| t.token.as_str()).collect();
list.entries
.iter()
.filter(|e| e.community_id == community_id_hex && !dead.contains(e.token.as_str()))
.filter(|e| e.expires_at_ms().is_none_or(|exp| now_ms <= exp))
.filter_map(|e| Keys::parse(&e.signer_sk).ok().map(|k| k.public_key()))
.collect()
}
/// Publish the creator's Registry (vsk-8) edition — their live link signers for this
/// community — so members fold it into the Public/Private source of truth (a
/// non-empty aggregate = Public).
async fn publish_invite_registry<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, __session: &std::sync::Arc<crate::db::Session>, live_signers: &[PublicKey]) -> Result<(), String> {
let my_pk = me_pk()?;
let eid = super::derive::invite_links_locator(community.id(), &my_pk.to_bytes());
let content = invite::build_registry_content(live_signers);
publish_control_edition(transport, community, vsk::INVITE_LINKS, &eid, &content).await?;
// Refresh the cache from the PLANE, not from `live_signers`: the column aggregates
// every creator, so writing only mine would clobber theirs, and a union could never
// shrink — retiring the last link would leave the community reading Public forever.
refresh_invite_registry_cache(transport, community).await;
Ok(())
}
/// Re-fold the whole invite Registry and cache it, so Public/Private stays a sync
/// LOCAL read. Silent no-op when the plane can't be read whole — a partial fold
/// would under-state Public, leaving a live link open behind a ban.
async fn refresh_invite_registry_cache<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) {
crate::db::scoped(async move {
let Ok(owner) = community.owner() else { return };
let Some(editions) = fetch_control_plane_whole(transport, community).await else { return };
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)
.unwrap_or_default()
.into_iter()
.filter(|(_, f)| f.0 == community.root_epoch.0)
.map(|(entity, f)| (entity, (f.1, f.2, f.3, f.4, f.5)))
.collect();
let authority = fold_authority(community, &editions, &floors);
let sets = live_invite_link_sets(community.id(), &owner.to_hex(), &editions, &authority, &floors);
let _ = crate::db::community::set_community_invite_registry(&cid_hex, &flatten_link_sets(&sets));
let _ = crate::db::community::replace_invite_link_sets(&cid_hex, &sets);
})
.await
}
/// A minted link's Invite List entry (CORD-05 §4).
fn link_entry(community: &CommunityV2, minted: &MintedLink) -> invite::InviteEntry {
invite::InviteEntry {
token: crate::simd::hex::bytes_to_hex_16(&minted.token),
signer_sk: minted.link_signer.secret_key().to_secret_hex(),
community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0),
url: minted.url.clone(),
label: minted.label.clone(),
created_at: now_ms() / 1000,
expires_at: minted.expires_at_ms.map(|ms| ms / 1000),
epoch: Some(community.root_epoch.0),
extra: Default::default(),
}
}
/// Bring this device's list of my public links in line with the Invite List every device writes
/// (CORD-05 §4): a link minted on another joins it, one retired on another leaves it. Returns
/// whether anything changed.
pub async fn adopt_invite_list<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<bool, String> {
crate::db::scoped(async move {
let Some(mut list) = fetch_invite_list(transport, &invite_list_relays(community).await).await? else { return Ok(false) };
list.prune_expired(now_ms());
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let held: std::collections::HashSet<String> = crate::db::community::list_public_invites(&cid_hex)?.into_iter().map(|r| r.token).collect();
let retired: std::collections::HashSet<&str> = list.tombstones.iter().filter(|t| t.community_id == cid_hex).map(|t| t.token.as_str()).collect();
let mut changed = false;
for token in held.iter().filter(|t| retired.contains(t.as_str())) {
crate::db::community::delete_public_invite(token)?;
changed = true;
}
for e in list.entries.iter().filter(|e| e.community_id == cid_hex && !held.contains(&e.token) && !retired.contains(e.token.as_str())) {
let expires = e.expires_at_ms().map(|ms| ms as i64);
crate::db::community::adopt_public_invite(&e.token, &cid_hex, &e.url, expires, e.label.as_deref(), e.created_at as i64)?;
changed = true;
}
Ok(changed)
})
.await
}
struct InviteListWrite;
/// Held across each Invite List read-modify-publish: the 13303 is replaceable, so two at once
/// drop one's change, and a revoke must see a link whose record is still in flight.
fn invite_list_gate() -> std::sync::Arc<tokio::sync::Mutex<()>> {
crate::db::current_session().scoped::<InviteListWrite, _>()
}
/// Record a freshly-minted public link across the creator's devices: append it to the
/// 13303 Invite List and refresh the Registry (CORD-05 §4/§5).
async fn record_minted_link<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, minted: &MintedLink) -> Result<(), String> {
crate::db::scoped(async move {
let gate = invite_list_gate();
let _held = gate.lock().await;
let session = crate::db::current_session();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let token_hex = crate::simd::hex::bytes_to_hex_16(&minted.token);
// Err aborts the sync half (the link's bundle already published durably;
// a retry re-records it) — an unreachable relay set must never be mistaken
// for "no list yet" and clobber the replaceable 13303. Ok(None) IS a fresh
// creator's honest first list.
let (mut list, newest) = read_invite_list(transport, &invite_list_relays(community).await).await?.map_or((Default::default(), None), |(l, n)| (l, Some(n)));
list.prune_expired(now_ms());
if !list.entries.iter().any(|e| e.token == token_hex) {
list.entries.push(link_entry(community, minted));
}
publish_invite_list(transport, community, &list, newest).await?;
let signers = live_signers_for(&list, &cid_hex, now_ms());
publish_invite_registry(transport, community, &session, &signers).await
})
.await
}
/// Revoke a public link by its token hex (CORD-05 §2/§5): re-post its coordinate as a
/// revocation tombstone (retiring the bundle behind the URL, so a fetcher finds the
/// grave), tombstone the Invite List entry, and refresh the Registry. Retiring the
/// LAST live link empties the Registry → the community reads Private (a Refounding is
/// the owner's separate read-cut).
pub async fn revoke_public_link<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, token_hex: &str) -> Result<(), String> {
crate::db::scoped(async move {
let gate = invite_list_gate();
let held = gate.lock().await;
let session = crate::db::current_session();
let my_pk = me_pk()?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let (mut list, newest) = read_invite_list(transport, &invite_list_relays(community).await).await?.map(|(l, n)| (l, Some(n))).ok_or("no invite list found to revoke from")?;
let entry = list.entries.iter().find(|e| e.token == token_hex && e.community_id == cid_hex).cloned();
let Some(entry) = entry else {
// The list is OURS and was positively fetched; a token it neither vends is a
// husk — a local row kept past a revocation or privatize performed elsewhere
// (another device, Armada). The row carries no signer_sk, so no revocation
// can EVER be built from it: erroring here just leaves an entry the owner can
// neither use nor remove. Pruning the local record is the only completion.
// (Ok(None) above still errors — an unreadable list is not proof of absence.)
let tombstoned = list.tombstones.iter().any(|t| t.token == token_hex && t.community_id == cid_hex);
crate::log_warn!(
"[Invites] link {} is not in the fetched invite list ({}) — pruning the local record",
&token_hex[..token_hex.len().min(8)],
if tombstoned { "already tombstoned" } else { "retired elsewhere" }
);
let _ = crate::db::community::delete_public_invite(token_hex);
return Ok(());
};
// Re-post the bundle coordinate as a revocation tombstone (creator-signed).
let link_signer = Keys::parse(&entry.signer_sk).map_err(|_| "malformed link signer")?;
let revocation = invite::build_revocation(&link_signer).map_err(|e| e.to_string())?;
transport.publish_durable(&revocation, &community.relays).await?;
// Tombstone the Invite List entry (permanent — a stale device can't resurrect it).
list.tombstones.push(invite::InviteTombstone::of(&entry));
list.entries.retain(|e| e.token != token_hex);
list.prune_expired(now_ms());
publish_invite_list(transport, community, &list, newest).await?;
let signers = live_signers_for(&list, &cid_hex, now_ms());
// Does anyone ELSE still vend a live link? Folded BEFORE our own registry
// republish: a fold taken after it would race relay propagation and read our
// own stale (pre-revoke) registry, so the privatize decision would flip to
// "still public" almost every time. Links are per-creator (CORD-05 §5), so
// only the other creators' sets matter here — ours is `signers`.
let others_vend = if signers.is_empty() {
match fetch_control_plane_whole(transport, community).await {
Some(editions) => {
let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)
.unwrap_or_default()
.into_iter()
.filter(|(_, f)| f.0 == community.root_epoch.0)
.map(|(entity, f)| (entity, (f.1, f.2, f.3, f.4, f.5)))
.collect();
let owner_hex = community.owner().map(|o| o.to_hex()).unwrap_or_default();
let authority = fold_authority(community, &editions, &floors);
live_invite_link_sets(community.id(), &owner_hex, &editions, &authority, &floors)
.iter()
.any(|s| s.creator_hex != my_pk.to_hex())
}
// Unreadable plane: assume someone else still vends. Rotating on a
// guess would burn an epoch (and strand pre-split clients) over a
// transport blip; the community simply stays public until a read
// that succeeds says otherwise.
None => true,
}
} else {
false
};
publish_invite_registry(transport, community, &session, &signers).await?;
let _ = crate::db::community::delete_public_invite(token_hex);
// Released before the Refounding, which severs links under this same gate.
drop(held);
// CORD-06 §3: converting a Public Community to Private is a Refounding
// trigger. Revoking only stops NEW acquisitions — everyone who already
// fetched the bundle keeps the `community_root` until it rolls, so without
// this the community reads Private while every past link-holder retains
// read access forever.
//
// Best-effort and retried, NEVER the revocation's verdict: the tombstone has
// already landed, and reporting failure here would read as "the link is
// still live" — the opposite of the truth — while a retry would fail anyway
// (its list entry is gone). A Refounding needs BAN, so a link creator who
// holds only CREATE_INVITE legitimately can't rotate; that surfaces as a
// logged warning, not a broken revoke.
if signers.is_empty() && !others_vend {
let mut rotated = false;
for attempt in 0..3u8 {
match refound_community(transport, community, &[]).await {
Ok(_) => {
rotated = true;
break;
}
Err(e) if attempt == 2 => {
crate::log_warn!(
"[v2] privatizing {} could not rotate the base key ({e}); the community reads Private but everyone who took a link keeps read access until it rotates",
&cid_hex[..8.min(cid_hex.len())]
);
crate::emit_event(
"community_privatize_rotation_failed",
&serde_json::json!({ "community_id": cid_hex, "error": e }),
);
}
Err(_) => continue,
}
}
if rotated {
crate::log_info!("[v2] {} privatized: base key rotated so link-joined readers are cut off", &cid_hex[..8.min(cid_hex.len())]);
}
}
Ok(())
})
.await
}
// ── Severing containment (CORD-06 Severing Refounding) ──────────────────────
/// Persisted sever marks for a community: `root_epoch -> rotation at_secs`.
/// A mark means "epoch E was a containment": link severance retries against it
/// on every follow pass, and a rescue extension of that hop re-stamps the tag.
pub(crate) fn sever_marks(cid_hex: &str) -> std::collections::BTreeMap<u64, u64> {
crate::db::settings::get_sql_setting(format!("v2_sever:{cid_hex}"))
.ok()
.flatten()
.and_then(|v| serde_json::from_str(&v).ok())
.unwrap_or_default()
}
/// Who minted each epoch: `root_epoch -> rotator hex`. CORD-02 §5 honors a
/// Guestbook snapshot "only from the npub whose Refounding minted that epoch",
/// so the fold has to remember which npub that was — the owner is only the
/// answer when the owner did the refounding.
pub(crate) fn epoch_minters(cid_hex: &str) -> std::collections::BTreeMap<u64, String> {
crate::db::settings::get_sql_setting(format!("v2_minter:{cid_hex}"))
.ok()
.flatten()
.and_then(|v| serde_json::from_str(&v).ok())
.unwrap_or_default()
}
/// Remember the rotator that minted `epoch`. Recorded at ADOPTION (and by the
/// refounder for its own mint), so it is always an npub this device verified as
/// an authorized rotator — never one a snapshot claims for itself.
pub(crate) fn record_epoch_minter(cid_hex: &str, epoch: u64, rotator_hex: &str) {
let mut m = epoch_minters(cid_hex);
if m.get(&epoch).is_some_and(|held| held == rotator_hex) {
return;
}
m.insert(epoch, rotator_hex.to_string());
if let Ok(v) = serde_json::to_string(&m) {
let _ = crate::db::settings::set_sql_setting(format!("v2_minter:{cid_hex}"), v);
}
}
/// Keep `epoch`'s Control Plane address, so its history reads back once the plane has moved on.
pub(crate) fn archive_control_address(cid_hex: &str, epoch: u64, control_pk: Option<&PublicKey>) {
let Some(pk) = control_pk else { return };
if let Err(e) = crate::db::community::store_epoch_key(cid_hex, crate::community::CONTROL_PK_SCOPE, epoch, &pk.to_bytes()) {
crate::log_warn!("v2: control address archive failed (that epoch's audit history may not read back): {e}");
}
}
/// Record a severed rotation. Idempotent; marks only accumulate — the row is a
/// few bytes and clearing one would let a failed severance read as done (B4).
pub(crate) fn add_sever_mark(cid_hex: &str, epoch: u64, at_secs: u64) {
let mut marks = sever_marks(cid_hex);
marks.insert(epoch, at_secs);
if let Ok(v) = serde_json::to_string(&marks) {
let _ = crate::db::settings::set_sql_setting(format!("v2_sever:{cid_hex}"), v);
}
}
/// Sever MY OWN condemned public links: revoke (not refresh) every live link of
/// mine for this community whose minted-at epoch sits below the highest severed
/// epoch. The epoch is the discriminator — deterministic on every device, so a
/// second device adopting the containment late can never eat the fresh link the
/// owner minted to re-open (it carries the post-raid epoch), while a link minted
/// mid-raid by a not-yet-adopted device carries the raid-era epoch and dies.
/// Batched: every tombstone publishes, then ONE 13303 republish and ONE registry
/// edition for the whole set. Deliberately WITHOUT `revoke_public_link`'s
/// last-link refound escalation: every caller here sits inside a rotation
/// (refound or follow), where that escalation self-deadlocks on `follow_lock` —
/// and the severed rotation IS the read-cut the escalation exists to provide.
/// Returns the number revoked; `Ok(0)` when there is nothing of mine to sever.
async fn sever_own_links<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
) -> Result<usize, String> {
crate::db::scoped(async move {
let session = crate::db::current_session();
let my_pk = me_pk()?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let Some(condemn_below) = sever_marks(&cid_hex).keys().copied().max() else {
return Ok(0); // no containment on record — nothing is condemned.
};
// Local fast-path: the folded Registry names every creator with a live
// link, and my own mints also leave local rows. Neither names me → no
// 13303 fetch; a plain member pays nothing here.
let maybe_mine = crate::db::community::invite_link_set_creators(&cid_hex)
.map(|cs| cs.contains(&my_pk.to_hex()))
.unwrap_or(true)
|| !crate::db::community::list_public_invites(&cid_hex).unwrap_or_default().is_empty();
if !maybe_mine {
return Ok(0);
}
let gate = invite_list_gate();
let _held = gate.lock().await;
let Some((mut list, newest)) = read_invite_list(transport, &invite_list_relays(community).await).await?.map(|(l, n)| (l, Some(n))) else {
return Ok(0); // no list ever published — nothing of mine exists.
};
let dead: std::collections::HashSet<&str> = list.tombstones.iter().map(|t| t.token.as_str()).collect();
let victims: Vec<invite::InviteEntry> = list
.entries
.iter()
.filter(|e| e.community_id == cid_hex && !dead.contains(e.token.as_str()) && e.epoch.unwrap_or(0) < condemn_below)
.cloned()
.collect();
if victims.is_empty() {
return Ok(0);
}
let mut revoked_tokens: Vec<String> = Vec::with_capacity(victims.len());
for entry in &victims {
// One corrupt entry must not wedge the batch (and with it the
// community's Public/Private reading) forever: tombstone the husk —
// no revocation can ever be built from it anyway.
match Keys::parse(&entry.signer_sk) {
Ok(link_signer) => {
let revocation = invite::build_revocation(&link_signer).map_err(|e| e.to_string())?;
transport.publish_durable(&revocation, &community.relays).await?;
}
Err(_) => crate::log_warn!("[Sever] link {} carries a malformed signer — tombstoning the husk", &entry.token[..entry.token.len().min(8)]),
}
list.tombstones.push(invite::InviteTombstone::of(entry));
revoked_tokens.push(entry.token.clone());
}
list.entries.retain(|e| !revoked_tokens.contains(&e.token));
list.prune_expired(now_ms());
publish_invite_list(transport, community, &list, newest).await?;
let signers = live_signers_for(&list, &cid_hex, now_ms());
publish_invite_registry(transport, community, &session, &signers).await?;
for token in &revoked_tokens {
let _ = crate::db::community::delete_public_invite(token);
}
crate::log_info!("[Sever] revoked {} own public link(s) (containment)", revoked_tokens.len());
Ok(revoked_tokens.len())
})
.await
}
/// The follow-pass severance retry (B4): while a sever mark exists and I still
/// hold live links at-or-below its line, re-attempt. A miss here is load-bearing
/// — a stale registry keeps the community reading Public, which silently skips
/// every future ban's refound — so this runs on every follow until it drains.
pub(crate) async fn retry_pending_severance<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
if sever_marks(&cid_hex).is_empty() {
return;
}
if let Err(e) = sever_own_links(transport, community).await {
crate::log_warn!("[Sever] pending link severance retry failed (will retry next follow): {e}");
}
}
/// Refresh every live public link's bundle behind its stable URL (CORD-05 §2) — e.g.
/// after a Rekey/Refounding rolled the keys — by re-posting the bundle at the same
/// coordinate with the CURRENT community state, so a link shared once keeps working
/// across rotations. Best-effort.
pub async fn refresh_public_links<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<(), String> {
crate::db::scoped(async move {
let session = crate::db::current_session();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
// A transport failure propagates, so a post-Refounding refresh retries rather than leave
// live links serving the old root. Refreshing writes no list, so a copy that won't open
// is skipped here, never written over.
let my_pk = me_pk()?;
let Some((list, _)) = read_invite_list_with(transport, &invite_list_relays(community).await, false).await? else {
return Ok(());
};
let creator = my_pk;
let now = now_ms();
let dead: std::collections::HashSet<&str> = list.tombstones.iter().map(|t| t.token.as_str()).collect();
// A containment condemns every link below its epoch. Refreshing one would
// RE-ARM the exact door the severing rotation closed (with the new root,
// no less) — and once re-armed, no retry could tell it from a legitimate
// link. Skip here; the severance retry owns their burial.
let condemn_below = sever_marks(&cid_hex).keys().copied().max().unwrap_or(0);
for entry in &list.entries {
if entry.community_id != cid_hex || dead.contains(entry.token.as_str()) || entry.token.len() != 2 * super::derive::TOKEN_LEN {
continue;
}
if entry.epoch.unwrap_or(0) < condemn_below {
continue;
}
// An expired link can't be joined, so refreshing it just re-states a
// door that isn't there (CORD-05 §1/§5).
if entry.expires_at_ms().is_some_and(|exp| now > exp) {
continue;
}
let Ok(link_signer) = Keys::parse(&entry.signer_sk) else { continue };
let token = crate::simd::hex::hex_to_bytes_16(&entry.token);
let bundle = bundle_of(community, BundleAudience::Link, Some(creator), entry.expires_at_ms(), entry.label.clone());
let bundle_key = super::derive::invite_bundle_key(&token);
if let Ok(event) = invite::build_bundle_event(&link_signer, &bundle, &bundle_key) {
let _ = transport.publish_durable(&event, &community.relays).await;
}
}
// Republish the Registry from the same pruned view. Expiry is the one way a
// link dies with no user action, so without a heal point here the aggregate
// never empties and the community reads Public long after its last door
// shut (CORD-05 §5). Idempotent when nothing lapsed.
//
// Only for a creator who actually minted here: one Invite List spans every
// community, so a member holding links ELSEWHERE would otherwise publish an
// empty Registry edition into this one on every rotation they adopt — a
// control-plane write, and a version bump, for a coordinate they never owned.
let mine_here = list.entries.iter().any(|e| e.community_id == cid_hex);
if !mine_here {
return Ok(());
}
let signers = live_signers_for(&list, &cid_hex, now);
let _ = publish_invite_registry(transport, community, &session, &signers).await;
Ok(())
})
.await
}
/// Whether this community is PUBLIC (CORD-05 §5): fold every creator's Registry
/// (vsk-8) that its author is authorized for (`CREATE_INVITE`, bound to their
/// coordinate) into an aggregate live-link set — non-empty ⇒ a live link exists ⇒
/// Public; empty ⇒ Private. Retiring the last link is what flips it back.
pub async fn community_is_public<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> bool {
let Ok(owner) = community.owner() else { return false };
// Truncation fails toward Public: over-stating it only makes a caller take the
// stronger remedy (privatise + re-found + reissue), while under-stating it
// leaves a live link open behind a ban.
let Some(editions) = fetch_control_plane_whole(transport, community).await else { return true };
let cid = community.id();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)
.unwrap_or_default()
.into_iter()
.filter(|(_, f)| f.0 == community.root_epoch.0)
.map(|(entity, f)| (entity, (f.1, f.2, f.3, f.4, f.5)))
.collect();
let authority = fold_authority(community, &editions, &floors);
!live_invite_link_sets(cid, &owner.to_hex(), &editions, &authority, &floors).is_empty()
}
/// What this client's control fold makes of the plane now, saving none of it: whether
/// authority settles, and per entity the held floor against the newest edition served.
/// For a device whose view froze. Structure only (entity prefixes, versions, verdicts, signers
/// by role, ages in days): no content, keys or exact times, so a private community's can be shared.
pub async fn debug_control_report(community: &CommunityV2) -> Result<serde_json::Value, String> {
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
let ControlRead { floors, editions, authority, fold, truncated, pages_read, healed, refusals } = read_control(&transport, community).await?;
let hex = crate::simd::hex::bytes_to_hex_32;
let short = |h: &str| h[..12.min(h.len())].to_string();
// Signers by role, never by key: a key prefix would name a private community's staff.
let owner = community.owner().ok().map(|o| o.to_hex());
let me = crate::state::my_public_key().map(|m| m.to_hex());
let mut signers: Vec<String> = Vec::new();
let mut signer = |pk: &str| -> String {
if owner.as_deref() == Some(pk) {
return "owner".into();
}
if me.as_deref() == Some(pk) {
return "me".into();
}
let n = signers.iter().position(|s| s == pk).unwrap_or_else(|| {
signers.push(pk.to_string());
signers.len() - 1
});
format!("signer {}", n + 1)
};
let now = now_ms() / 1000;
let mine = crate::state::my_public_key().map(|me| hex(&super::derive::grant_locator(community.id(), &me.to_bytes())));
let folded: std::collections::HashMap<&str, &FoldedHead> =
fold.heads.iter().chain(authority.heads.iter()).map(|h| (h.entity_hex.as_str(), h)).collect();
let mut by_entity: std::collections::BTreeMap<String, Vec<&ParsedEdition>> = Default::default();
for e in &editions {
by_entity.entry(hex(&e.entity_id)).or_default().push(e);
}
// A held entity the relays serve nothing for is part of the picture too.
for held in floors.keys() {
by_entity.entry(held.clone()).or_default();
}
let rows: Vec<serde_json::Value> = by_entity
.iter()
.map(|(eid, eds)| {
let newest = eds.iter().max_by_key(|e| (e.version, e.created_at));
let floor = floors.get(eid);
let mut served: Vec<u64> = eds.iter().map(|e| e.version).collect();
served.sort_unstable();
served.dedup();
serde_json::json!({
"entity": short(eid),
"kind": newest.map(|e| e.vsk.clone()),
"mine": mine.as_deref() == Some(eid.as_str()),
"served": served,
"newest": newest.map(|e| serde_json::json!({
"version": e.version,
"age_days": now.saturating_sub(e.created_at) / 86_400,
"author": signer(&e.author.to_hex()),
"admitted": fold.admitted.contains(&e.inner_id) || authority.admitted.contains(&e.inner_id),
"is_floor": floor.is_some_and(|f| f.1 == e.self_hash),
"extends_floor": floor.filter(|f| f.1 != e.self_hash).map(|f| e.prev_hash == Some(f.1)),
})),
"floor": floor.map(|f| serde_json::json!({ "version": f.0, "served": eds.iter().any(|e| e.self_hash == f.1) })),
"folds_to": folded.get(eid.as_str()).map(|h| serde_json::json!({ "version": h.version, "rebased": h.rebased })),
"refused": refusals.get(eid).copied().or_else(|| authority.refused.contains(eid).then_some("refused")),
"carried": authority.carried.contains(eid),
"kept": fold.kept.contains(eid),
})
})
.collect();
Ok(serde_json::json!({
"root_epoch": community.root_epoch.0,
"converged": authority.converged,
"complete": authority.complete,
"activated": authority.activated,
"authority_gapped": authority.gapped,
"fold_gapped": fold.gapped,
"truncated": truncated,
"pages_read": pages_read,
"editions": editions.len(),
"would_update": fold.updated.is_some(),
"healed": healed.iter().map(|h| short(&h.entity_hex)).collect::<Vec<_>>(),
"entities": rows,
}))
}
/// Page the WHOLE control plane, not the newest window: a registry pushed out of a
/// single page reads as retired, and any member can push it out since the plane key
/// comes from the community root they hold. `None` = it could NOT be read whole
/// (transport failure, same-second wall, pager depth), so a caller must not mistake
/// an empty fold for absence.
/// Every Control edition on the relays, newest first, for forensics: who wrote what, and
/// whether this client's fold kept a head for it. Content is cut short; it holds no secret.
pub async fn debug_control_editions(community: &CommunityV2) -> Result<serde_json::Value, String> {
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
let mut editions = fetch_control_plane_whole(&transport, community).await.ok_or("the Control Plane couldn't be read whole")?;
editions.sort_by(|a, b| b.created_at.cmp(&a.created_at));
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let heads: std::collections::HashMap<String, (u64, [u8; 32])> = crate::db::community::get_all_edition_heads_full(&cid_hex)
.unwrap_or_default()
.into_iter()
.map(|(entity, f)| (entity, (f.1, f.2)))
.collect();
let rows: Vec<serde_json::Value> = editions
.iter()
.map(|e| {
let eid = crate::simd::hex::bytes_to_hex_32(&e.entity_id);
let head = heads.get(&eid);
serde_json::json!({
"at": e.created_at,
"vsk": e.vsk,
"entity": &eid[..12],
"version": e.version,
"author": &e.author.to_hex()[..12],
"marked": e.binding.is_some(),
"cites": e.authority.is_some(),
"is_head": head.is_some_and(|h| h.1 == e.self_hash),
"head_version": head.map(|h| h.0),
"content": e.content.chars().take(240).collect::<String>(),
})
})
.collect();
let owner = community.owner().map(|o| o.to_hex()).unwrap_or_default();
Ok(serde_json::json!({ "owner": owner, "control_pk": community.control_pk.map(|p| p.to_hex()), "editions": rows }))
}
/// Every edition on the Control Plane, or `None` when it could not be read whole: through the
/// wraps held once the store is on, else page by page off the relays.
async fn fetch_control_plane_whole<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Option<Vec<ParsedEdition>> {
match control_store::mode() {
control_store::Mode::Off => fetch_control_plane_whole_paged(transport, community).await,
control_store::Mode::On => match whole_held(transport, community).await {
Ok(editions) => editions,
Err(why) => {
crate::log_debug!("[v2:control {}] whole read by pages ({why})", &community.id().to_hex()[..8]);
fetch_control_plane_whole_paged(transport, community).await
}
},
control_store::Mode::Shadow => {
let paged = fetch_control_plane_whole_paged(transport, community).await;
if let (Some(paged), Ok(Some(held))) = (&paged, whole_held(transport, community).await) {
let held: std::collections::HashSet<[u8; 32]> = held.iter().map(|e| e.inner_id).collect();
let pages: std::collections::HashSet<[u8; 32]> = paged.iter().map(|e| e.inner_id).collect();
let (lost, more) = (pages.difference(&held).count(), held.difference(&pages).count());
if lost > 0 || more > 0 {
#[cfg(test)]
if std::env::var("VECTOR_CONTROL_SHADOW_STRICT").is_ok() {
panic!("the whole read through the store differs from the paged one: {lost} edition(s) lost, {more} more");
}
crate::log_warn!("[v2:control {}] shadow: the whole read through the store differs: {lost} lost, {more} more", &community.id().to_hex()[..8]);
}
}
paged
}
}
}
/// [`fetch_control_plane_whole`] through the wraps held, every relay heard first. `Err` when the
/// wraps held cannot serve it and the pages must.
async fn whole_held<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<Option<Vec<ParsedEdition>>, String> {
let Some(wraps) = whole_wraps_held(transport, community).await? else { return Ok(None) };
let control = control::ControlPlane::of(community);
let mut editions = Vec::with_capacity(wraps.len());
for page in wraps.chunks(FOLLOW_PAGE) {
let _batch = control.check_page(&page.iter().collect::<Vec<_>>());
editions.extend(page.iter().filter_map(|w| control.open_edition(w).ok()));
}
Ok(Some(editions))
}
/// Every wrap held of the Control Plane once it is known whole, newest first: see [`whole_held`].
async fn whole_wraps_held<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<Option<Vec<Event>>, String> {
use control_sync::{sync_plane, Unsynced, Wait};
crate::db::scoped(async move {
let kept = || match crate::db::community::community_held(community.id()) {
Ok(true) => Ok(()),
_ => Err("the community is not held".to_string()),
};
kept()?;
let view = control_store::View::of(community);
if control_sync::flooded(community, &view) {
return Err("more wraps than a pass reads".into());
}
let sync = match sync_plane(transport, community, &view, Wait::All).await {
Ok(sync) if sync.flooded => return Err("more wraps than a pass reads".into()),
Ok(sync) => sync,
Err(Unsynced::NoRelay(_)) => return Ok(None),
Err(Unsynced::Store(e)) => return Err(e),
};
kept()?;
if sync.unread {
return Ok(None);
}
// A whole read is what the relays hold now. A wrap only this device still has is left
// out, as their pages would leave it out, and telling which needs each relay's whole
// set: with one read by pages (where a second can be walled) the pages serve it.
let Some(unserved) = control_sync::unserved_by_all(transport, &view, &sync).await else { return Err("a relay's whole set is not known".into()) };
let mut all: Vec<Event> = Vec::new();
let mut below: Option<(u64, nostr_sdk::prelude::EventId)> = None;
loop {
let wraps = view.page(below, FOLLOW_PAGE)?;
let Some(last) = wraps.last() else { break };
below = Some((last.created_at.as_secs(), last.id));
all.extend(wraps.into_iter().filter(|w| !unserved.contains(&w.id)));
}
Ok(Some(all))
})
.await
}
async fn fetch_control_plane_whole_paged<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Option<Vec<ParsedEdition>> {
let control = control::ControlPlane::of(community);
let mut editions: Vec<ParsedEdition> = Vec::new();
let mut seen_wraps: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
let mut oldest: Option<u64> = None;
let mut until: Option<u64> = None;
for page in 0..COMPACT_MAX_PAGES {
// Full, not Quorum: `None` here means "could not be read whole", and a
// majority that simply lacks another creator's Registry answers as fast as
// one that has it — so a Quorum read returns Some(empty) and the plane reads
// link-free. The ban path turns that into a Refounding of a PUBLIC community,
// which CORD-05 §5 forbids: the link refresh re-posts the bundle behind the
// same URL, so the rotation severs nothing and buries foreign-link joiners.
let query = Query { evidence: crate::community::transport::Evidence::Full, ..plane_page(control.pk_hex(), FOLLOW_PAGE, until) };
let Ok(wraps) = transport.fetch(&query, &community.relays).await else { return None };
let mut fresh = 0usize;
let _batch = control.check_page(&wraps.iter().filter(|w| !seen_wraps.contains(&w.id)).collect::<Vec<_>>());
for w in &wraps {
if !seen_wraps.insert(w.id) {
continue;
}
fresh += 1;
let at = w.created_at.as_secs();
if oldest.is_none_or(|o| at < o) {
oldest = Some(at);
}
if let Ok(ed) = control.open_edition(w) {
editions.push(ed);
}
}
if fresh == 0 {
if wraps.len() >= FOLLOW_PAGE {
return None; // same-second wall: the plane can't be read whole
}
return Some(editions);
}
until = oldest;
if page + 1 == COMPACT_MAX_PAGES {
return None;
}
}
Some(editions)
}
/// The live link coordinates PER AUTHORISED CREATOR across every Registry (vsk-8);
/// non-empty ⇒ the Community is Public, and the per-creator split is what drives
/// "X has N active invite links". Pure over an already-fetched edition set so the
/// on-demand probe and the control follow fold it identically.
fn live_invite_link_sets(
cid: &crate::community::CommunityId,
owner_hex: &str,
editions: &[ParsedEdition],
authority: &AuthoritySet,
floors: &Floors,
) -> Vec<crate::db::community::InviteLinkSetRow> {
use crate::community::roles::Permissions;
use std::collections::BTreeMap;
let mut by_eid: BTreeMap<[u8; 32], Vec<&ParsedEdition>> = BTreeMap::new();
for e in editions {
if e.vsk == vsk::INVITE_LINKS {
by_eid.entry(e.entity_id).or_default().push(e);
}
}
let mut sets: Vec<crate::db::community::InviteLinkSetRow> = Vec::new();
for (eid, group) in &by_eid {
// Authority BEFORE the fold, matching `apply_control_fold`. `fold_head`
// picks an equal-version winner author-blind (lowest inner id, which an
// author can grind), so folding first would let any member occupy the head
// slot and have the whole registry dropped by the check below — silently
// retiring a live invite link, i.e. flipping the community to Private.
let authed: Vec<&ParsedEdition> = group
.iter()
.copied()
.filter(|p| {
let author = p.author.to_hex();
// The creator must hold CREATE_INVITE, not be banned, AND own this coordinate.
!authority.banned.contains(&author)
&& authority.roles.is_authorized(&author, Some(owner_hex), Permissions::CREATE_INVITE)
&& super::derive::invite_links_locator(cid, &p.author.to_bytes()) == *eid
})
.collect();
if authed.is_empty() {
continue;
}
let fold_eds: Vec<version::Edition> = authed.iter().map(|p| p.to_fold_edition()).collect();
let (Some(hi), _) = fold_head(&fold_eds, floors.get(&crate::simd::hex::bytes_to_hex_32(eid)), &|_| 0) else { continue };
if let Ok(signers) = invite::parse_registry_content(&authed[hi].content) {
if signers.is_empty() {
continue; // a creator who retired every link is absent, not a zero row
}
sets.push(crate::db::community::InviteLinkSetRow {
creator_hex: authed[hi].author.to_hex(),
locators: signers.iter().map(|p| p.to_hex()).collect(),
});
}
}
sets
}
/// Flatten per-creator sets into the aggregate the `invite_registry` column holds.
fn flatten_link_sets(sets: &[crate::db::community::InviteLinkSetRow]) -> Vec<String> {
let mut flat: Vec<String> = sets.iter().flat_map(|s| s.locators.iter().cloned()).collect();
flat.sort();
flat.dedup();
flat
}
/// Accept an already-unwrapped bundle: verify the owner commitment AND that the
/// delivered community_root is genuinely the owner's, persist the community, and
/// announce a Guestbook Join (with invite attribution). Shared tail of both accept
/// paths. Takes the caller's `std::sync::Arc<crate::db::Session>` (captured BEFORE any network fetch the
/// caller did) so the whole operation stays with one account across that I/O.
///
/// `member_since` is `None` for a join made now, or the membership time of keys the account
/// already holds elsewhere (a List adoption): the hold is stamped with it, so a removal made
/// after that membership still outranks the copy.
async fn accept_bundle<T: Transport + ?Sized>(
transport: &T,
bundle: &CommunityInvite,
invited_by: Option<PublicKey>,
member_since: Option<u64>,
) -> Result<CommunityV2, String> {
crate::db::scoped(async move {
let signer = crate::signer::active_signer()?;
let my_pk = me_pk()?;
let at_ms = now_ms();
let announce_join = member_since.is_none();
let held_since = member_since.filter(|&t| t > 0).map_or(at_ms, |t| t.min(at_ms));
// Expiry gate: a past invite still previews but must not join (CORD-05 §1).
if bundle.expired(at_ms) {
return Err("this invite has expired".to_string());
}
// `from_bundle` re-validates bounds + the owner commitment fail-closed.
let community = CommunityV2::from_bundle(bundle, held_since)?;
// Captured before the save below: a re-accept of a held community must not
// re-announce a membership this account already declared.
let already_held = crate::db::community::load_community_v2(community.id()).ok().flatten().is_some();
// A seat taken anew is owed every delivery again: one back after leaving, in the same
// session, would otherwise find each already opened and never look at it twice.
if !already_held {
forget_opened_deliveries();
}
// Authenticate the delivered community_root before trusting it. The owner
// commitment proves WHO the owner is, but community_root (and channel keys) are
// NOT in that commitment, so a forged invite can pair a real (id, owner, salt)
// with an attacker-chosen root and silently partition the joiner onto planes
// only the attacker controls. Requiring the owner's genesis to open under the
// delivered root closes that eclipse; also reconciles channel classification.
// A preview verified the SAME (id, root) moments ago → reuse its fold instead
// of re-walking the plane (the bundle re-fetch above kept the revocation gate).
let handoff = VERIFIED_PREVIEW.lock().unwrap().take().filter(|v| {
v.session.upgrade().is_some_and(|s| s.is_live())
&& v.at.elapsed() < VERIFIED_PREVIEW_TTL
&& v.community_id == community.id().0
&& v.community_root == community.community_root
});
let (community, join_heads, join_banlist, (join_pins, join_writers), join_banlist_content, join_roles, join_authority_heads) =
match handoff {
Some(v) => {
let mut c = v.folded;
// The preview holds no acquisition time — stamp the JOIN's.
c.created_at_ms = held_since;
(c, v.heads, v.banned, (v.pins, v.writers), v.banlist_persist, v.roles, v.authority_heads)
}
None => {
let vj = verify_owner_root_and_reconcile(transport, community).await?;
(vj.community, vj.heads, vj.banned, (vj.pins, vj.writers), vj.banlist_persist, vj.roles, vj.authority_heads)
}
};
// A dissolved community is a grave (CORD-02 §9): refuse to join it.
if is_dissolved(transport, &community).await {
return Err(ERR_DISSOLVED.to_string());
}
// Join-time ban gate (CORD-04 §4, Armada parity): an honest client refuses to join a
// community whose authorized banlist names it — before the Guestbook Join publishes
// and before any local write. Every door funnels through here (direct invite, parked,
// public link, migration), so none of them needs its own exclusion.
if join_banlist.contains(&my_pk.to_hex()) {
return Err("you are banned from this community".to_string());
}
// The account must not have swapped since the guard was captured (which was
// before any fetch the caller / the verify above performed) — else we'd write
// A's join into B.
// Seed the verified heads as the initial refuse-downgrade floor BEFORE the
// community row lands (floors-then-state, so a mid-seed error can't leave saved
// state outrunning its floor); the first post-join follow then can't persist a
// state below what this join already showed.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let families = join_heads.iter().map(|h| (h, crate::db::community::FLOOR_CONTROL)).chain(join_authority_heads.iter().map(|h| (h, crate::db::community::FLOOR_AUTHORITY)));
for (h, family) in families {
crate::db::community::set_family_head_at_epoch(&cid_hex, &h.entity_hex, h.version, &h.self_hash, &h.inner_id, &h.author, community.root_epoch.0, family)?;
}
crate::db::community::save_community_v2(&community)?;
// Archive the joined root at its epoch, so this member reads Public-channel
// history from their join epoch onward across later Refoundings (CORD-03 §3).
let _ = crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, community.root_epoch.0, &community.community_root);
// Same for each granted Private-channel key: the archive is what lets its
// history stay readable after the channel rotates away from this key.
for ch in &community.channels {
if let (true, Some(key)) = (ch.private, ch.key) {
let _ = crate::db::community::store_epoch_key(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&ch.id.0), ch.epoch.0, &key);
}
}
// Persist what the verification walk already folded: the control plane WAS
// read, so making the fresh member wait for the follow worker's queued
// re-walk to see pins or enforce bans is pure lag (it read 20-30s on a busy
// queue). The system "modified the Pins" line still arrives via that first
// follow — a join backfills state, it doesn't announce edits.
if let Some((banned_list, version)) = &join_banlist_content {
store_banlist(&cid_hex, banned_list, *version as i64);
}
// The ROSTER, same rule as the banlist and pins above: the walk already
// paid for it. Persisted BEFORE the channels register, because the first
// history ingest reads it to honor moderation hides — an empty roster
// authorizes nobody, so every admin-hidden message would render to the
// fresh member until the follow worker's queued re-walk landed.
if let Some((roles, at)) = &join_roles {
let _ = crate::db::community::set_community_roles(&cid_hex, roles, *at);
}
for (channel_hex, content, version, _) in &join_writers {
persist_writers(&cid_hex, channel_hex, content, *version, true);
}
for (channel_hex, content, version, _author, _at) in &join_pins {
if matches!(
crate::db::community::set_community_pins(&cid_hex, channel_hex, content, *version as i64),
Ok(true)
) {
crate::emit_event(
"community_pins_updated",
&serde_json::json!({ "community_id": cid_hex, "channel_id": channel_hex }),
);
}
}
// Announce our Guestbook Join, echoing the invite attribution when present.
// Only an ACTUAL join speaks: a re-accept of a held community, or a
// cross-device key sync (`member_since` set), is not a membership event —
// the account's original Join already stands in the guestbook, and every
// re-publish renders as "<user> has joined" spam for the whole community.
if announce_join && !already_held {
let (bundle_creator, bundle_label) = bundle.attribution();
let attribution = invited_by
.map(|p| p.to_hex())
.or_else(|| bundle_creator.map(str::to_string))
.zip(Some(bundle_label.unwrap_or_default().to_string()));
let attr_ref = attribution.as_ref().map(|(c, l)| (c.as_str(), l.as_str()));
let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let join_rumor = guestbook::build_join_rumor(my_pk, attr_ref, at_ms);
if let Ok((join_wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &join_rumor, &gb_group, Timestamp::from_secs(at_ms / 1000)).await {
publish_my_join(transport, &community, join_wrap).await;
}
}
// Record the membership across devices (CORD-02 §8). The inline attempt covers the
// happy path; anything else hands off to the durable retry, because an unrecorded
// join is what strands a community behind a stale tombstone.
//
// Only for a REAL join. A `member_since` is the list-sync adoption path,
// and those entries were just read FROM this list — republishing it re-records what
// it already holds. A device adopting N entries would otherwise rebuild and publish
// the whole document N times, concurrently, every copy identical, on the boot path
// that is already the slowest thing the app does.
if announce_join {
match republish_community_list(transport, Some(community.id())).await {
Ok(true) => {}
Ok(false) => republish_community_list_durable(Some(*community.id())),
Err(e) => {
crate::log_warn!("[CommunityList] failed to record this join across devices ({}) — retrying", e);
republish_community_list_durable(Some(*community.id()));
}
}
}
Ok(community)
})
.await
}
/// Prove the delivered `community_root` is genuinely the owner's, and reconcile
/// channel classification from the owner's editions. `community_id` commits only
/// to `(owner_xonly, owner_salt)` — both semi-public (they ride every bundle and
/// every synced Community List) — so a forged invite can present a real community's
/// id/owner/salt with an attacker-chosen root; every plane then derives from that
/// root, silently eclipsing the joiner onto attacker-controlled addresses while the
/// owner commitment still "verifies". The defense: the owner's genesis metadata
/// edition (vsk-0, `eid == community_id`) only opens under the AUTHENTIC root — an
/// attacker can't forge the owner's seal — so its presence on the control plane
/// derived from the delivered root proves that root. On a ROTATED plane (epoch > 0)
/// the compaction may have carried an admin-signed metadata head instead (CORD-06
/// re-wraps heads with their original signatures), so the anchor there is the
/// community-bound metadata head plus any owner-signed edition under the same root.
/// Fail-closed: no anchor (forged invite, or relays unreachable) → refuse to join.
/// On success, folds the owner's authoritative editions to heal a bundle that
/// misclassified a channel.
/// Everything the join-time verification walk folded, handed to the accept path so
/// what the join VERIFIED is also what it PERSISTS. The walk already paid for the
/// control plane read; deferring persistence to the first post-join follow re-pays
/// the network cost and leaves the fresh member pins-blind and banlist-blind for
/// the whole follow-queue delay.
struct VerifiedJoin {
community: CommunityV2,
heads: Vec<FoldedHead>,
/// The join-gate banlist (authorized fold over the any-author edition set).
banned: std::collections::BTreeSet<String>,
/// Pin List heads folded under the FULL join-time authority (curators included,
/// same §5 gate as any later follow): `(channel_hex, content, version, author_npub, created_at)`.
pins: Vec<(String, String, u64, String, u64)>,
/// Writers ledger heads from the same fold: `(channel_hex, content, version)`.
writers: Vec<(String, String, u64, bool)>,
/// The authorized banlist head's content + version, for local persistence.
banlist_persist: Option<(Vec<String>, u64)>,
/// The FULL authorized roster (admins included) from the same walk, with the
/// newest roster edition's `created_at`. `None` when the fold saw a gap.
///
/// This is the one authority artifact the join used to throw away — and a
/// fresh member whose roster is empty until the follow worker's re-walk
/// renders every moderator-hidden message in the meantime: the hide gate
/// reads the stored roster, and an empty roster authorizes nobody.
roles: Option<(crate::community::roles::CommunityRoles, i64)>,
/// Role/Grant/Banlist heads folded under the full authority, so an
/// ADMIN-signed grant seeds the same refuse-downgrade floor an owner-signed
/// one does.
authority_heads: Vec<FoldedHead>,
}
async fn verify_owner_root_and_reconcile<T: Transport + ?Sized>(
transport: &T,
community: CommunityV2,
) -> Result<VerifiedJoin, String> {
let owner = community.owner()?;
let control = control::ControlPlane::of(&community);
let control_pk = control.pk_hex();
// AUTH-gating relays (ditto-relay's default gates kind-1059) serve a plane's
// wraps ONLY to a connection authenticated AS the stream key — Concord's
// group-addressed wraps aren't p-tagged to the joiner, so the login alone can't
// satisfy the gate and the control plane reads back empty. Register this
// community's stream keys + start the challenge responder so the fetch below
// (whose REQ triggers the relay's AUTH challenge) reads the plane after auth.
super::streamauth::prime(&community);
// Authenticity = the owner's GENESIS metadata edition (vsk-0, `eid ==
// community_id`) at the root-derived control plane. The genesis eid pins it to
// THIS community, and it lives ONLY under the real root — so a forged root can't
// produce one: an edition's seal carries no community binding, but another
// community's genesis has a different eid, and this community's own genesis is
// unreadable without its real root (which the forger lacks). ("Any owner edition"
// is NOT sound: an owner sig from any co-owned community, rewrapped onto the fake
// plane, would pass — reopening the eclipse.) The residual — a T-member replaying
// T's genesis onto a fake root to MITM another T-joiner — is closed only by
// binding the root into community_id (protocol, deferred).
//
// Seed `until` with a FAR-FUTURE constant (NOT now-based), and request
// Evidence::Full EXPLICITLY below: this walk draws an ABSENCE verdict (no
// owner-signed genesis ⇒ reject), which trusts only the completest union —
// an open partial window misses a genesis on a lagging relay (routine over
// Tor). A constant beyond any real created_at clips NOTHING — so neither
// a clock-skewed future-dated genesis nor a >1h-slow-clock joiner is excluded (a
// now-based bound could clip either). Break on an EMPTY page (a short page is a
// relay cap). A forged root walks to exhaustion and rejects; a flood/deep plane
// that buries the genesis past the walk is the deferred protocol residual.
const PAGE: usize = 500;
const MAX_PAGES: usize = 4;
const FAR_FUTURE_SECS: u64 = 4_102_444_800; // ~year 2100 — above any real edition, safe as a relay `until`.
let mut editions: Vec<ParsedEdition> = Vec::new();
let mut all_editions: Vec<ParsedEdition> = Vec::new();
let mut found_genesis = false;
// Rotated planes (CORD-06): compaction re-wraps each entity's CURRENT head with
// its ORIGINAL signature, so if an admin last edited the metadata the plane holds
// no owner-signed vsk-0 at all — the strict genesis anchor is unsatisfiable there.
// Fallback pair for epoch > 0: the community-bound metadata head (any signer) PLUS
// at least one owner-signed edition opened under this root. A non-member forger
// can produce neither; the sibling-community rewrap residual this reopens is the
// same class the spec defers to root-in-id binding.
let mut compacted_metadata = false;
crate::log_debug!(
"[JoinVerify] control_pk={} root_epoch={:?} relays={:?}",
&control_pk[..12], community.root_epoch, community.relays
);
let anchored = |found_genesis: bool, compacted_metadata: bool, owner_editions: usize, epoch: Epoch| {
found_genesis || (epoch.0 > 0 && compacted_metadata && owner_editions > 0)
};
for attempt in 0..2 {
editions.clear();
all_editions.clear();
compacted_metadata = false;
let mut until: Option<u64> = Some(FAR_FUTURE_SECS);
let mut seen_wraps: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
for page_no in 0..MAX_PAGES {
let query = Query { evidence: crate::community::transport::Evidence::Full, ..plane_page(control_pk.clone(), PAGE, until) };
let wraps = transport.fetch(&query, &community.relays).await?;
crate::log_trace!(
"[JoinVerify] attempt {} page {}: fetched {} wraps",
attempt, page_no, wraps.len()
);
// INCLUSIVE `until` + wrap-id dedup: a `-1` step can skip same-second
// siblings at a page boundary (and the genesis with them); re-served
// boundary events are free, and no-new-events means exhausted.
let mut oldest = u64::MAX;
let mut fresh = 0usize;
let _batch = control.check_page(&wraps.iter().filter(|w| !seen_wraps.contains(&w.id)).collect::<Vec<_>>());
for w in &wraps {
if !seen_wraps.insert(w.id) {
continue;
}
fresh += 1;
oldest = oldest.min(w.created_at.as_secs());
if let Ok(ed) = control.open_edition(w) {
crate::log_trace!(
"[JoinVerify] edition vsk={} eid={} owner={} at={}",
ed.vsk, crate::simd::hex::bytes_to_hex_32(&ed.entity_id)[..12].to_string(),
ed.author == owner, w.created_at.as_secs()
);
if ed.vsk == vsk::COMMUNITY_METADATA && ed.entity_id == community.id().0 {
if ed.author == owner {
found_genesis = true;
} else {
compacted_metadata = true;
}
}
if ed.author == owner {
editions.push(ed.clone());
}
// Any-author set for the join-time authority fold below: the banlist head
// may be admin-signed, and its authority chains to the owner regardless.
all_editions.push(ed);
}
}
crate::log_debug!(
"[JoinVerify] attempt {} page {}: fresh={} opened_owner={} opened_any={} genesis={} compacted={}",
attempt, page_no, fresh, editions.len(), all_editions.len(), found_genesis, compacted_metadata
);
if anchored(found_genesis, compacted_metadata, editions.len(), community.root_epoch) || fresh == 0 {
break; // authenticated, or the relay is exhausted.
}
until = Some(oldest);
}
if anchored(found_genesis, compacted_metadata, editions.len(), community.root_epoch) {
break;
}
if attempt == 0 {
// AUTH-gating relays: the first walk's REQ triggers the NIP-42 challenge,
// but nostr-sdk's own retry re-auths as the USER key — which doesn't
// satisfy a stream-authors gate — and can land before the responder's
// stream-key auth settles, reading the plane back EMPTY. Replay the
// remembered challenges for every registered stream key, then walk once
// more on the settled connection.
if let Some(client) = crate::state::nostr_client() {
super::streamauth::prime_auth(&client, &community.relays).await;
}
}
}
if !anchored(found_genesis, compacted_metadata, editions.len(), community.root_epoch) {
return Err(
"could not verify this community from its relays (the invite may be forged, the relays are unreachable, or the control plane is being flooded); not joining"
.to_string(),
);
}
// Join-time reconcile: the joiner holds no floors yet (empty map → bootstrap per
// entity). The heads this fold verified are returned for the caller to SEED as
// the initial floor once the community row is saved — without that, the first
// post-join follow would bootstrap floor-less and could persist a state BELOW
// what this join already verified and showed.
// Join-time reconcile folds only the owner's editions (genesis-authenticated
// above), and the owner is supreme — so owner-only authority suffices. The full
// roster (admins) folds on the first post-join follow_control.
let empty_floors = Floors::default();
// Join-time banlist: fold authority over the ANY-author edition set (roles/grants
// chain to the genesis-verified owner; the banlist head is honored only if its signer
// held BAN). Returned so the accept path can refuse a banned self BEFORE it publishes
// a Guestbook Join — the gate every join door shares (Armada parity, CORD-04 §4).
let authority_full = fold_authority(&community, &all_editions, &empty_floors);
let mut authority = AuthoritySet::owner_only();
// The owner's own list of the Channels that stood bounds the document too (CORD-04 §2).
authority.roles.legacy_channels = authority_full.roles.legacy_channels.clone();
let fold = apply_control_fold(&community, &editions, &empty_floors, &authority);
// Pins under the FULL authority: a curator-authored Pin List is as valid at join
// as on any later follow (same PIN_MESSAGES + citation gate, same owner-chained
// roster). Only the pins are taken from this pass — the DOCUMENT adoption above
// stays owner-only, its stricter envelope unchanged.
let ControlFold { pins_persist: pins, writers_persist: writers, .. } = apply_control_fold(&community, &all_editions, &empty_floors, &authority_full);
// The newest roster edition's stamp, exactly as follow_control computes it, so
// the follow's own freshness gate composes with a join-seeded roster.
let newest_roster_at = roster_stamp(&all_editions, &authority_full.heads);
// An anchored walk read the plane back to genesis, so the window is complete
// by construction; `gapped` still gates the persist for the same reason
// follow_control's does — a withheld edition must not fold into a baseline.
// A Roster fold that ran out its bound seeds nothing it judged; the first follow folds again.
let settled = authority_full.converged;
let roles = (!authority_full.gapped && settled).then(|| (authority_full.roles.clone(), newest_roster_at));
Ok(VerifiedJoin {
community: fold.updated.unwrap_or(community),
heads: fold.heads,
banned: authority_full.banned,
pins: if settled { pins } else { Vec::new() },
writers: if settled { writers } else { Vec::new() },
banlist_persist: authority_full.banlist_persist.filter(|_| settled),
roles,
authority_heads: if settled { authority_full.heads } else { Vec::new() },
})
}
/// Accept a Direct Invite: unwrap the 3313 giftwrap (Schnorr-verifying the seal),
/// then run the shared accept path. The recipient's consent IS this call. No
/// network await precedes the accept, so the guard captured here suffices.
pub async fn accept_direct_invite<T: Transport + ?Sized>(transport: &T, wrap: &Event) -> Result<CommunityV2, String> {
let signer = crate::signer::active_signer()?;
let (inviter, bundle) = invite::unwrap_direct_invite_signed(&signer, wrap).await.map_err(|e| e.to_string())?;
accept_bundle(transport, &bundle, Some(inviter), None).await
}
/// Accept a PARKED Direct Invite from its stored bundle JSON (the wrap was already
/// unwrapped + owner-verified at park time). Re-parses through the same fail-closed
/// bundle validation, then runs the shared accept path (which re-verifies the owner
/// root over the network). `inviter_hex` is the parked seal signer, for Guestbook
/// Join attribution.
pub async fn accept_parked_invite<T: Transport + ?Sized>(
transport: &T,
bundle_json: &str,
inviter_hex: Option<&str>,
) -> Result<CommunityV2, String> {
let bundle = CommunityInvite::from_bundle_json(bundle_json).map_err(|e| e.to_string())?;
let invited_by = inviter_hex.and_then(|h| PublicKey::parse(h).ok());
accept_bundle(transport, &bundle, invited_by, None).await
}
/// Fetch + decrypt the newest Live bundle at a public link's coordinate
/// (`(33301, link_signer, "")`). **Revocation is authoritative-if-present**: if
/// ANY signer-valid tombstone is among the fetched events, refuse — never trust
/// fetch ordering (a cross-relay union has no global newest-first sort, so a
/// stale Live could otherwise win a partial-propagation race). Otherwise pick
/// the newest valid Live by `created_at`. Read-only.
pub async fn fetch_public_bundle<T: Transport + ?Sized>(transport: &T, url: &str) -> Result<CommunityInvite, String> {
let parsed = invite::parse_invite_link(url).map_err(|e| e.to_string())?;
let relays = if parsed.bootstrap_relays.is_empty() {
invite::stock_relays()
} else {
parsed.bootstrap_relays.clone()
};
fetch_bundle_on(transport, &parsed, &relays).await
}
/// [`fetch_public_bundle`] on a chosen relay set.
async fn fetch_bundle_on<T: Transport + ?Sized>(transport: &T, parsed: &invite::ParsedInviteLink, relays: &[String]) -> Result<CommunityInvite, String> {
// NO `#d` filter, even though the coordinate's `d` is empty (CORD-05 §2). Relays disagree on
// indexing an empty tag value: some answer the REQ and then never EOSE, so the fetch burns its
// whole union grace on every invite. The per-link signer pins the coordinate on its own (it
// signs nothing else), and `parse_bundle_event` re-checks the empty `d` locally.
let query = Query {
kinds: vec![super::kind::INVITE_BUNDLE],
authors: vec![parsed.link_signer.to_hex()],
..Default::default()
};
// One bounded retry: a join fired while the pool is still warming (bootstrap
// relays mid-handshake, routine during boot contention) reads back a transport
// error, not an absent bundle. The pool add already happened on the first try,
// so wait for a socket rather than guessing with a fixed sleep.
let events = match transport.fetch(&query, relays).await {
Ok(evs) => evs,
Err(_) => {
wait_for_bootstrap_relay(relays).await;
transport.fetch(&query, relays).await?
}
};
let bundle_key = super::derive::invite_bundle_key(&parsed.token);
// Scan EVERY event: a tombstone beats a Live unconditionally (order-independent).
let mut newest_live: Option<(u64, CommunityInvite)> = None;
for event in &events {
match invite::parse_bundle_event(event, &parsed.link_signer, &bundle_key) {
Ok(invite::BundleState::Revoked) => return Err("this invite link has been revoked".to_string()),
Ok(invite::BundleState::Live(bundle)) => {
let at = event.created_at.as_secs();
if newest_live.as_ref().is_none_or(|(t, _)| at > *t) {
newest_live = Some((at, *bundle));
}
}
Err(_) => {} // a foreign/garbage event at the coordinate — ignore.
}
}
newest_live.map(|(_, b)| b).ok_or_else(|| "invite bundle not found on relays".to_string())
}
/// Wait — bounded — for ANY of the targets to report Connected before a retry:
/// the fetch's own warm path bounds its connect wait tighter than a cold TLS
/// handshake takes under boot contention.
async fn wait_for_bootstrap_relay(relays: &[String]) {
let Some(client) = crate::state::nostr_client() else { return };
let deadline = crate::rt::time::Instant::now() + crate::relay_connect_timeout(std::time::Duration::from_secs(8));
loop {
for url in relays {
if let Ok(Some(relay)) = client.relay(url).await {
if relay.status() == nostr_sdk::prelude::RelayStatus::Connected {
return;
}
}
}
if crate::rt::time::Instant::now() >= deadline {
return;
}
crate::rt::time::sleep(std::time::Duration::from_millis(400)).await;
}
}
/// The most recent owner-root verification a PREVIEW completed, handed to a join
/// so accepting seconds later doesn't re-walk the control plane. Single-slot,
/// short-lived, session-guarded, and keyed on `(community_id, community_root)` —
/// a different delivered root never matches. The join's own bundle re-fetch is
/// untouched, so the revocation gate always runs live.
struct VerifiedPreview {
/// Weak: the slot is process-wide and must not keep a swapped-out account alive.
session: std::sync::Weak<crate::db::Session>,
at: web_time::Instant,
/// Which preview this is, so its expiry never takes a newer one.
seq: u64,
community_id: [u8; 32],
community_root: [u8; 32],
folded: CommunityV2,
heads: Vec<FoldedHead>,
/// The join-time authorized banlist from the SAME verified walk — carried so the
/// handoff path keeps the ban gate (a preview-then-join must not skip it).
banned: std::collections::BTreeSet<String>,
/// Folded pins + banlist content from the same walk, so a preview-handoff join
/// persists them exactly like a direct join.
pins: Vec<(String, String, u64, String, u64)>,
writers: Vec<(String, String, u64, bool)>,
banlist_persist: Option<(Vec<String>, u64)>,
roles: Option<(crate::community::roles::CommunityRoles, i64)>,
authority_heads: Vec<FoldedHead>,
}
static VERIFIED_PREVIEW: std::sync::Mutex<Option<VerifiedPreview>> = std::sync::Mutex::new(None);
const VERIFIED_PREVIEW_TTL: std::time::Duration = std::time::Duration::from_secs(120);
/// Park a verified preview for the join, dropping it once its TTL lapses unjoined:
/// a full fold of a large community has no business staying resident.
fn stash_verified_preview(mut preview: VerifiedPreview) {
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
preview.seq = seq;
*VERIFIED_PREVIEW.lock().unwrap_or_else(|e| e.into_inner()) = Some(preview);
if !crate::rt::can_spawn() {
return;
}
// spawn-detached: clears a process-wide slot that holds its session weakly; binding would pin it.
crate::rt::spawn(async move {
crate::rt::time::sleep(VERIFIED_PREVIEW_TTL).await;
expire_verified_preview(seq);
});
}
fn expire_verified_preview(seq: u64) {
let mut slot = VERIFIED_PREVIEW.lock().unwrap_or_else(|e| e.into_inner());
if slot.as_ref().is_some_and(|v| v.seq == seq) {
*slot = None;
}
}
/// Read-only rich preview of a public link: the decrypted bundle plus the LATEST
/// display metadata folded live from the Control Plane (a v2 bundle deliberately
/// carries no icon — the fold is the authority). Owner-root verification rides
/// the fold, so a forged-root link can't render a convincing preview; on a
/// fold/transport failure the bundle snapshot is the fallback. Nothing persists
/// — the caller hasn't joined.
pub async fn preview_public_link<T: Transport + ?Sized>(transport: &T, url: &str) -> Result<CommunityV2, String> {
let bundle = fetch_public_bundle(transport, url).await?;
preview_bundle(transport, &bundle).await
}
/// The fold half of [`preview_public_link`], over an already-fetched bundle. Split out so a caller
/// that only needs the community's IDENTITY can read it off the bundle (it is self-certifying) and
/// skip the Control-Plane walk entirely — the walk is the join gate, and `accept_public_link` runs
/// it again regardless.
pub async fn preview_bundle<T: Transport + ?Sized>(transport: &T, bundle: &CommunityInvite) -> Result<CommunityV2, String> {
preview_bundle_checked(transport, bundle).await.map(|(c, _)| c)
}
/// [`preview_bundle`], saying whether the owner's root verified: when it didn't, the name,
/// description and icon are the link creator's word.
pub async fn preview_bundle_checked<T: Transport + ?Sized>(transport: &T, bundle: &CommunityInvite) -> Result<(CommunityV2, bool), String> {
let community = CommunityV2::from_bundle(bundle, 0)?;
match verify_owner_root_and_reconcile(transport, community.clone()).await {
Ok(vj) => {
let folded = vj.community;
stash_verified_preview(VerifiedPreview {
session: std::sync::Arc::downgrade(&crate::db::current_session()),
at: web_time::Instant::now(),
seq: 0,
community_id: folded.id().0,
community_root: folded.community_root,
folded: folded.clone(),
heads: vj.heads,
banned: vj.banned,
pins: vj.pins,
writers: vj.writers,
banlist_persist: vj.banlist_persist,
roles: vj.roles,
authority_heads: vj.authority_heads,
});
Ok((folded, true))
}
Err(_) => Ok((community, false)),
}
}
/// Accept a public invite link: fetch its bundle (revocation-aware) and join.
pub async fn accept_public_link<T: Transport + ?Sized>(transport: &T, url: &str) -> Result<CommunityV2, String> {
crate::db::scoped(async move {
// Held across the network fetch so the join stays with one account.
let bundle = fetch_public_bundle(transport, url).await?;
accept_bundle(transport, &bundle, None, None).await
})
.await
}
/// Leave a community: publish a Guestbook Leave and tear down the local hold.
pub async fn leave_community<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<(), String> {
crate::db::scoped(async move {
let at_ms = now_ms();
publish_leave(transport, community, at_ms).await?;
// Tombstone the membership across devices (CORD-02 §8) BEFORE the local delete.
// Best-effort, but never silent: an unpublished tombstone is what lets a stale
// copy of the list rejoin this community on a later boot.
record_leave(transport, community.id(), &community.relays, at_ms).await;
crate::db::community::delete_community(&crate::simd::hex::bytes_to_hex_32(&community.id().0))?;
Ok(())
})
.await
}
/// The local half of a leave, for a caller that repaints at once: the List tombstone
/// kept pending (it outlives a restart), then the community dropped here, its epoch
/// keys kept for scrubbing our own past messages. Returns the leave's time for
/// [`announce_leave`].
pub fn leave_locally(community: &CommunityV2) -> Result<u64, String> {
let at_ms = now_ms();
add_pending_tombstone(community.id(), at_ms);
crate::db::community::delete_community_retain_keys(&crate::simd::hex::bytes_to_hex_32(&community.id().0))?;
Ok(at_ms)
}
/// [`leave_locally`] for a community this device lists but no longer holds, its chats having
/// outlived its row: they go, and the List tombstone is kept pending. `None` when nothing here
/// names the community.
pub async fn leave_unheld_locally(community_id: &crate::community::CommunityId) -> Option<u64> {
let id_hex = crate::simd::hex::bytes_to_hex_32(&community_id.0);
let named = crate::state::STATE.lock().await.chats.iter().any(|c| c.metadata.community_id() == Some(id_hex.as_str()));
if !named {
return None;
}
let at_ms = now_ms();
add_pending_tombstone(community_id, at_ms);
forget_community_chats(&id_hex, &[]).await;
Some(at_ms)
}
/// The network half of [`leave_unheld_locally`]: the List tombstone alone, as no key is left
/// to seal a Guestbook Leave. The stock set stands in for the community's unknown relays.
pub async fn announce_unheld_leave<T: Transport + ?Sized>(transport: &T, community_id: &crate::community::CommunityId, at_ms: u64) {
crate::db::scoped(async move { record_leave(transport, community_id, &invite::stock_relays(), at_ms).await }).await
}
/// Drop a left community's channel chats, messages included, from STATE and the database,
/// with any chat that still names the community.
pub async fn forget_community_chats(community_id: &str, channel_ids: &[String]) {
let mut gone: Vec<String> = channel_ids.to_vec();
{
let mut st = crate::state::STATE.lock().await;
for chat in &st.chats {
if chat.metadata.community_id() == Some(community_id) && !gone.contains(&chat.id) {
gone.push(chat.id.clone());
}
}
st.chats.retain(|c| !gone.contains(&c.id));
}
for id in &gone {
let _ = crate::db::chats::delete_chat(id);
}
}
/// The network half of [`leave_locally`]: the Guestbook Leave, then the List
/// tombstone, which retries from its pending record until it lands.
pub async fn announce_leave<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, at_ms: u64) {
crate::db::scoped(async move {
if let Err(e) = publish_leave(transport, community, at_ms).await {
crate::log_net_fail!("[Leave] no Guestbook Leave for {} ({})", &crate::simd::hex::bytes_to_hex_32(&community.id().0)[..8], e);
}
record_leave(transport, community.id(), &community.relays, at_ms).await;
})
.await
}
/// The Guestbook Leave, best-effort once sealed: the List tombstone is what makes a leave stick.
async fn publish_leave<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, at_ms: u64) -> Result<(), String> {
let signer = crate::signer::active_signer()?;
let my_pk = me_pk()?;
let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let leave_rumor = guestbook::build_leave_rumor(my_pk, at_ms);
if let Ok((wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &leave_rumor, &gb_group, Timestamp::from_secs(at_ms / 1000)).await {
let _ = transport.publish(&wrap, &community.relays).await;
}
Ok(())
}
/// Cooperative Kick (CORD-04 §6, Guestbook plane): name the target; every reader
/// honors it iff the signer holds KICK and strictly outranks them (the coalesce's
/// `can_kick`), so publishing without authority is inert. A kicked member may
/// rejoin with a fresh invite — cryptographic severance is the ban/refound path.
pub async fn kick_member<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, target: &PublicKey) -> Result<(), String> {
crate::db::scoped(async move {
assert_current_root(community)?;
let signer = crate::signer::active_signer()?;
let my_pk = me_pk()?;
// Fast local pre-check; readers re-verify independently.
let authority = fetch_authority(transport, community).await;
let owner_hex = community.owner()?.to_hex();
if !authority.roles.can_act_on_member(
&my_pk.to_hex(),
Some(&owner_hex),
&target.to_hex(),
crate::community::roles::Permissions::KICK,
) {
return Err("not authorized to kick this member".to_string());
}
// CORD-04 §6 composition: a Kick is Role Removal THEN the directive — strip
// first, so the target's rank is gone before the departure lands. Without it a
// kicked admin leaves the memberlist still holding every management bit, and
// every client keeps honoring their control editions.
//
// SKIPPED (not refused) when the strip isn't ours to make: a revoke needs
// MANAGE_ROLES + strict outrank, and a KICK-only moderator still kicks — the
// target just keeps their rank until an authorized strip lands. Each layer
// validates on its own rule, so a missing one is a weaker removal, never a
// broken one. A strip we DO attempt and lose is a hard error: proceeding would
// publish a directive we know leaves rank behind.
let target_hex = target.to_hex();
let holds_roles = authority.roles.grants.iter().any(|g| g.member == target_hex && !g.role_ids.is_empty());
let may_strip = authority.roles.can_act_on_member(
&my_pk.to_hex(),
Some(&owner_hex),
&target_hex,
crate::community::roles::Permissions::MANAGE_ROLES,
);
if holds_roles && may_strip {
grant_roles_sealing(transport, community, target, Vec::new(), Seal::BestEffort)
.await
.map_err(|e| format!("could not strip this member's roles before kicking: {e}"))?;
}
let at_ms = now_ms();
let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
// A Kick is an authority action, so it cites its Grant like any other
// (CORD-02 §5 / CORD-04 §5).
let citation = required_authority_citation(community, &my_pk)?;
let rumor = guestbook::build_kick_rumor(my_pk, *target, citation.as_ref(), at_ms);
let (wrap, _) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(at_ms / 1000)).await
.map_err(|e| e.to_string())?;
transport.publish(&wrap, &community.relays).await?;
Ok(())
})
.await
}
/// Write each ban's departure to the Guestbook (CORD-04 §6): a Kick dated at the ban, which the
/// banlist alone never records, so lifting it doesn't count a pre-ban Join again. Only for a
/// member whose standing Join predates their ban; a Join after it is a return and outranks the
/// Kick anyway. Dated by the ban, one signer's departure for a member is the same rumor from any
/// of their devices. Best-effort: returns how many landed.
async fn publish_ban_departures<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, targets: &[PublicKey]) -> usize {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let marks = crate::db::community::get_community_ban_marks(&cid_hex).unwrap_or_default();
let (Ok((events, _)), Ok(owner), Ok(my_pk), Ok(signer)) =
(crate::db::community::get_guestbook_shared(&cid_hex), community.owner(), me_pk(), crate::signer::active_signer())
else {
return 0;
};
let Ok(citation) = required_authority_citation(community, &my_pk) else { return 0 };
let owner_hex = owner.to_hex();
let roles = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let coalesced = guestbook::coalesce(&events, now_ms(), snapshot_authority_for(&cid_hex, community, &owner, &events, &roles).as_ref(), &kick_judge(&cid_hex, &owner_hex, &roles));
drop(events);
let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let mut landed = 0;
for target in targets {
let Some(&banned_secs) = marks.get(&target.to_hex()) else { continue };
let at_ms = banned_secs.saturating_mul(1000);
if !coalesced.get(target).is_some_and(|st| st.verdict == guestbook::Verdict::Joined && st.at_ms <= at_ms) {
continue;
}
let rumor = guestbook::build_kick_rumor(my_pk, *target, citation.as_ref(), at_ms);
let Some(rumor_id) = rumor.id.map(|id| id.to_bytes()) else { continue };
let Ok((wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(banned_secs)).await else { continue };
if let Err(e) = transport.publish(&wrap, &community.relays).await {
crate::log_warn!("[Ban] departure for an un-banned member not published: {e}");
continue;
}
landed += 1;
let kick = guestbook::GuestbookEvent {
rumor_id,
entry: guestbook::GuestbookEntry::Kick { actor: my_pk, target: *target, citation: citation.clone(), at_ms },
epoch: Some(community.root_epoch.0),
observed_at: Some(now_ms() / 1000),
};
let _ = ingest_guestbook_event(community, kick, 0);
}
landed
}
/// Once a session, the owner writes the departure of every ban lifted before un-bans wrote
/// their own: a member whose ban this device remembers, still standing on a pre-ban Join and
/// silent since. Owner-only, so one signer writes it and each member gets one rumor.
pub async fn heal_ban_departures<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<usize, String> {
if !guestbook_walked_this_session(community) || community.owner()? != me_pk()? {
return Ok(0);
}
if !session_plane_once::<BanDeparturesHealed>(community) {
return Ok(0);
}
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let banned = crate::db::community::get_community_banlist(&cid_hex)?;
let active: std::collections::HashMap<PublicKey, u64> = crate::db::community::community_member_activity_capped(&cid_hex, false)?
.into_iter()
.filter_map(|(npub, secs)| PublicKey::parse(&npub).ok().map(|pk| (pk, secs)))
.collect();
let lifted: Vec<PublicKey> = crate::db::community::get_community_ban_marks(&cid_hex)?
.into_iter()
.filter(|(hex, _)| !banned.contains(hex))
.filter_map(|(hex, at)| PublicKey::from_hex(&hex).ok().map(|pk| (pk, at)))
.filter(|(pk, at)| active.get(pk).is_none_or(|seen| seen <= at))
.map(|(pk, _)| pk)
.collect();
if lifted.is_empty() {
return Ok(0);
}
Ok(publish_ban_departures(transport, community, &lifted).await)
}
struct BanDeparturesHealed;
struct JoinAnnounced;
/// True the first time this session asks for `community`'s current Guestbook plane under `K`.
fn session_plane_once<K: 'static>(community: &CommunityV2) -> bool {
let set = crate::db::current_session().scoped::<K, std::sync::Mutex<std::collections::HashSet<[u8; 32]>>>();
let mut held = set.lock().unwrap_or_else(|e| e.into_inner());
held.insert(guestbook_plane(community))
}
/// Publish my Join, keeping the same signed wrap going until a relay holds it, so a retry can
/// only ever land the one event. Marks the plane as announced this session.
async fn publish_my_join<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, wrap: Event) {
session_plane_once::<JoinAnnounced>(community);
if transport.publish(&wrap, &community.relays).await.is_ok() || crate::state::nostr_client().is_none() {
return;
}
let relays = community.relays.clone();
crate::db::spawn_bound(async move {
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
if let Err(e) = transport.publish_durable(&wrap, &relays).await {
crate::log_warn!("[Guestbook] Join still unpublished; the next session's walk will restore it: {e}");
}
});
}
/// CORD-02 §5: a member finding no state of their own on the Guestbook publishes a fresh Join.
/// Only after a whole walk of the plane, once a session, and dated by the plane itself (the
/// Refounding's cut, else its oldest entry), so my devices healing at once write one rumor.
pub async fn heal_my_join<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<bool, String> {
if !guestbook_walked_this_session(community) {
return Ok(false);
}
let my_pk = me_pk()?;
let owner = community.owner()?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
if my_pk == owner || crate::db::community::is_author_banned(&cid_hex, &my_pk) {
return Ok(false);
}
let at_ms = {
let (events, _) = crate::db::community::get_guestbook_shared(&cid_hex)?;
let roles = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let authority = snapshot_authority_for(&cid_hex, community, &owner, &events, &roles);
let state = guestbook::coalesce(&events, now_ms(), authority.as_ref(), &kick_judge(&cid_hex, &owner.to_hex(), &roles)).remove(&my_pk);
if state.is_some_and(|st| st.verdict != guestbook::Verdict::Refounded) {
return Ok(false);
}
let live = Some(community.root_epoch.0);
let Some(at_ms) = guestbook::live_refound(&events, authority.as_ref(), now_ms().saturating_add(guestbook::MAX_FUTURE_MS))
.map(|r| r.cut)
.or_else(|| events.iter().filter(|e| e.epoch == live).map(|e| e.entry.at_ms()).min())
else {
return Ok(false);
};
at_ms
};
if !session_plane_once::<JoinAnnounced>(community) {
return Ok(false);
}
let signer = crate::signer::active_signer()?;
let rumor = guestbook::build_join_rumor(my_pk, None, at_ms);
let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let (wrap, _) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(at_ms / 1000))
.await
.map_err(|e| e.to_string())?;
crate::log_info!("[Guestbook] no Join of ours stands on this plane; restoring it");
publish_my_join(transport, community, wrap).await;
Ok(true)
}
/// The Timeouts running now (CORD-04 §8), by target: judged against the Roster as it
/// stands, like every authority action. Returns target → (from, until), unix seconds.
pub fn community_timeouts(community: &CommunityV2) -> Result<std::collections::BTreeMap<PublicKey, (u64, u64)>, String> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let events = crate::db::community::get_guestbook_standing(&cid_hex)?;
Ok(guestbook::active_timeouts(&events, now_ms() / 1000, &timeout_judge(community)?))
}
/// Who a Timeout may silence: MODERATE_MEMBERS, unbanned, a strict outrank and the Grant it cites.
pub(crate) fn timeout_judge(community: &CommunityV2) -> Result<impl Fn(&PublicKey, &PublicKey, Option<&crate::community::edition::AuthorityCitation>) -> bool, String> {
use crate::community::roles::Permissions;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let roster = crate::db::community::get_community_roles(&cid_hex)?;
let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
let owner = community.owner()?.to_hex();
Ok(move |actor: &PublicKey, target: &PublicKey, vac: Option<&crate::community::edition::AuthorityCitation>| {
let (a, t) = (actor.to_hex(), target.to_hex());
// The roster check first: it is in memory, the citation's is a database read.
t != owner
&& !banned.contains(&a)
&& roster.can_act_on_member(&a, Some(&owner), &t, Permissions::MODERATE_MEMBERS)
&& citation_is_synced(&cid_hex, &owner, &a, vac)
})
}
/// Silence `target` for `seconds` (at most 28 days; 0 lifts a running Timeout). Every
/// reader honours it iff the signer holds MODERATE_MEMBERS and strictly outranks them.
pub async fn timeout_member<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, target: &PublicKey, seconds: u64) -> Result<(), String> {
crate::db::scoped(async move {
assert_current_root(community)?;
let signer = crate::signer::active_signer()?;
let my_pk = me_pk()?;
let authority = fetch_authority(transport, community).await;
let owner_hex = community.owner()?.to_hex();
if !authority.roles.can_act_on_member(&my_pk.to_hex(), Some(&owner_hex), &target.to_hex(), crate::community::roles::Permissions::MODERATE_MEMBERS) {
return Err("you can only time out members beneath you, with Timeout Members".to_string());
}
// Strictly after every Timeout that counts for them, so a lift outranks the one it lifts
// even when a co-moderator's clock runs ahead.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let judge = timeout_judge(community)?;
let newest_held = crate::db::community::get_guestbook_standing(&cid_hex)?
.iter()
.filter_map(|e| match &e.entry {
guestbook::GuestbookEntry::Timeout { actor, target: t, citation, at_ms, .. } if t == target && judge(actor, t, citation.as_ref()) => Some(*at_ms),
_ => None,
})
.max()
.unwrap_or(0);
let at_ms = next_send_ms().max(newest_held.saturating_add(1).min(now_ms() + guestbook::MAX_FUTURE_MS));
// A lift's `until` is past for every reader, however its date runs ahead.
let until = if seconds == 0 { 0 } else { (now_ms() / 1000).saturating_add(seconds.min(guestbook::MAX_TIMEOUT_SECS)) };
let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let citation = required_authority_citation(community, &my_pk)?;
let rumor = guestbook::build_timeout_rumor(my_pk, *target, until, citation.as_ref(), at_ms);
let rumor_id = rumor.id.map(|id| id.to_bytes()).unwrap_or_default();
let (wrap, _) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(at_ms / 1000)).await.map_err(|e| e.to_string())?;
transport.publish(&wrap, &community.relays).await?;
// Held at once, so this device honours its own Timeout before the follow reads it back.
let gate = guestbook_write_gate();
let _gate = gate.lock().unwrap_or_else(|e| e.into_inner());
let (events, cursor) = crate::db::community::get_guestbook_shared(&cid_hex)?;
if events.get(&rumor_id).is_none() {
let timeout = guestbook::GuestbookEvent {
rumor_id,
entry: guestbook::GuestbookEntry::Timeout { actor: my_pk, target: *target, until_secs: until, citation, at_ms },
epoch: Some(community.root_epoch.0),
observed_at: Some(at_ms / 1000),
};
store_guestbook_and_departures(community, &cid_hex, &[timeout], cursor)?;
}
Ok(())
})
.await
}
/// Whom a Nickname may name (CORD-04 §10), judged against the Roster as it stands: their own
/// takes `CHANGE_NICKNAME` and no citation; anyone else's takes `MANAGE_NICKNAMES`, a strict
/// outrank and the Grant it cites.
pub(crate) fn nickname_judge(community: &CommunityV2) -> Result<impl Fn(&PublicKey, &PublicKey, Option<&crate::community::edition::AuthorityCitation>) -> bool, String> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let roster = crate::db::community::get_community_roles(&cid_hex)?;
let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
let owner = community.owner()?.to_hex();
Ok(move |actor: &PublicKey, target: &PublicKey, vac: Option<&crate::community::edition::AuthorityCitation>| {
let (a, t) = (actor.to_hex(), target.to_hex());
!banned.contains(&a) && roster.may_name(&a, Some(&owner), &t) && (a == t || citation_is_synced(&cid_hex, &owner, &a, vac))
})
}
/// Every Nickname standing in a community, with the entry each stands on. A Refounding starts a
/// fresh Guestbook, so only the live epoch's count: what is carried across stands, for every reader.
pub fn standing_nicknames(community: &CommunityV2) -> Result<std::collections::BTreeMap<PublicKey, guestbook::Nickname>, String> {
nicknames_on(community, Some(community.root_epoch.0))
}
/// The Nicknames standing over `epoch`'s Guestbook, or over every one this device holds.
fn nicknames_on(community: &CommunityV2, epoch: Option<u64>) -> Result<std::collections::BTreeMap<PublicKey, guestbook::Nickname>, String> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let held = crate::db::community::get_guestbook_standing(&cid_hex)?;
let events: Vec<guestbook::GuestbookEvent> = held.iter().filter(|e| epoch.is_none() || e.epoch == epoch).cloned().collect();
let judge = nickname_judge(community)?;
let silenced = community_timeouts(community)?;
Ok(guestbook::standing_nicknames(&events, now_ms(), &judge, &silenced))
}
/// What each member is called in a community, for those who have a Nickname there.
/// The Nicknames as their writers set them, before a Timeout silences any: a Timeout is its
/// own change, not a Nickname one.
pub(crate) fn nicknames_as_set(community: &CommunityV2) -> Result<std::collections::BTreeMap<PublicKey, guestbook::Nickname>, String> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let held = crate::db::community::get_guestbook_standing(&cid_hex)?;
let events: Vec<guestbook::GuestbookEvent> = held.iter().filter(|e| e.epoch == Some(community.root_epoch.0)).cloned().collect();
let judge = nickname_judge(community)?;
Ok(guestbook::standing_nicknames(&events, now_ms(), &judge, &Default::default()))
}
pub fn community_nicknames(community: &CommunityV2) -> Result<std::collections::BTreeMap<PublicKey, String>, String> {
Ok(standing_nicknames(community)?.into_iter().map(|(pk, n)| (pk, n.nick)).collect())
}
/// A Nickname as a writer sends it: trimmed, at most [`guestbook::MAX_NICKNAME_CHARS`], no
/// control characters. `""` clears.
pub fn clean_nickname(nick: &str) -> Result<String, String> {
let nick = nick.trim();
if nick.chars().any(char::is_control) {
return Err("a nickname can't hold line breaks or control characters".to_string());
}
if nick.chars().count() > guestbook::MAX_NICKNAME_CHARS {
return Err(format!("a nickname is at most {} characters", guestbook::MAX_NICKNAME_CHARS));
}
Ok(nick.to_string())
}
/// Seal and publish one Nickname, then hold it, so this device shows it before the follow
/// reads it back.
async fn publish_nickname<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, rumor: nostr_sdk::prelude::UnsignedEvent, entry: guestbook::GuestbookEntry) -> Result<(), String> {
let signer = crate::signer::active_signer()?;
let my_pk = me_pk()?;
let at_ms = entry.at_ms();
let rumor_id = rumor.id.map(|id| id.to_bytes()).unwrap_or_default();
let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let (wrap, _) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(now_ms() / 1000)).await.map_err(|e| e.to_string())?;
transport.publish(&wrap, &community.relays).await?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let gate = guestbook_write_gate();
let _gate = gate.lock().unwrap_or_else(|e| e.into_inner());
let (events, cursor) = crate::db::community::get_guestbook_shared(&cid_hex)?;
// A member's own carried Nickname is the very rumor they first sent, now on this epoch too.
let stored = match events.get(&rumor_id) {
Some(held) if held.epoch == Some(community.root_epoch.0) => return Ok(()),
Some(held) => guestbook::GuestbookEvent { epoch: Some(community.root_epoch.0), ..held.clone() },
None => guestbook::GuestbookEvent { rumor_id, entry, epoch: Some(community.root_epoch.0), observed_at: Some(at_ms / 1000) },
};
drop(events);
store_guestbook_and_departures(community, &cid_hex, &[stored], cursor)
}
/// Name `target` in this community (`""` clears it): your own with Change Nickname, a member
/// beneath you with Manage Nicknames.
pub async fn set_nickname<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, target: &PublicKey, nick: &str) -> Result<(), String> {
crate::db::scoped(async move {
assert_current_root(community)?;
let nick = clean_nickname(nick)?;
let my_pk = me_pk()?;
let authority = fetch_authority(transport, community).await;
let owner_hex = community.owner()?.to_hex();
let mine = *target == my_pk;
if !authority.roles.may_name(&my_pk.to_hex(), Some(&owner_hex), &target.to_hex()) {
return Err(if mine { "you can't change your nickname here".to_string() } else { "you can only change the nicknames of members beneath you, with Manage Nicknames".to_string() });
}
if mine {
refuse_while_timed_out(community, &my_pk)?;
}
// Strictly after every Nickname that counts for them, so this one stands even when a
// co-moderator's clock runs ahead.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let judge = nickname_judge(community)?;
let newest_held = crate::db::community::get_guestbook_standing(&cid_hex)?
.iter()
.filter_map(|e| match &e.entry {
guestbook::GuestbookEntry::Nickname { actor, target: t, citation, at_ms, .. } if t == target && judge(actor, t, citation.as_ref()) => Some(*at_ms),
_ => None,
})
.max()
.unwrap_or(0);
let at_ms = next_send_ms().max(newest_held.saturating_add(1).min(now_ms() + guestbook::MAX_FUTURE_MS));
let citation = if mine { None } else { required_authority_citation(community, &my_pk)? };
let rumor = guestbook::build_nickname_rumor(my_pk, *target, &nick, citation.as_ref(), at_ms);
let entry = guestbook::GuestbookEntry::Nickname { actor: my_pk, target: *target, nick, citation, at_ms };
publish_nickname(transport, community, rumor, entry).await
})
.await
}
/// Carry my own Nickname onto the Guestbook a Refounding began, dated as first issued, when the
/// Refounder didn't. Best-effort; a later sync tries again.
pub async fn carry_my_nickname<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<(), String> {
crate::db::scoped(async move {
let my_pk = me_pk()?;
let Some(mine) = nicknames_on(community, None)?.remove(&my_pk) else { return Ok(()) };
let carried = standing_nicknames(community)?.remove(&my_pk);
if carried.is_some_and(|c| c.nick == mine.nick || c.at_ms > mine.at_ms) || !nickname_judge(community)?(&my_pk, &my_pk, None) {
return Ok(());
}
let rumor = guestbook::build_nickname_rumor(my_pk, my_pk, &mine.nick, None, mine.at_ms);
let entry = guestbook::GuestbookEntry::Nickname { actor: my_pk, target: my_pk, nick: mine.nick, citation: None, at_ms: mine.at_ms };
publish_nickname(transport, community, rumor, entry).await
})
.await
}
/// What a [`kick_members`] sweep actually managed to do.
#[derive(Debug, Default)]
pub struct KickSweep {
pub kicked: Vec<PublicKey>,
/// Targets the caller has no standing over, with the reason. Collected rather than
/// returned as an error: one unkickable member must not sink the rest of the wave.
pub refused: Vec<(PublicKey, String)>,
/// Publishes that failed on the wire — transient, and safe to retry.
pub failed: Vec<PublicKey>,
}
/// Kick many members in one sweep.
///
/// A Kick is an individual directive, unlike a Banlist edition which names every npub in
/// one document, so the wire cost here is inherently linear and there is nothing to
/// batch. What this saves is everything around it: [`kick_member`] folds the whole
/// control plane per call, so kicking a raid one at a time spends a paged network fetch
/// per target. Authority, citation and the plane key are resolved once and reused.
///
/// `on_progress(done, total)` fires after every target, refusals included, so a caller
/// can drive a counter through a sweep that takes minutes.
pub async fn kick_members<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
targets: &[PublicKey],
on_progress: &(dyn Fn(usize, usize) + Sync),
) -> Result<KickSweep, String> {
crate::db::scoped(async move {
assert_current_root(community)?;
let mut out = KickSweep::default();
if targets.is_empty() {
return Ok(out);
}
let signer = crate::signer::active_signer()?;
let my_pk = me_pk()?;
let my_hex = my_pk.to_hex();
let owner_hex = community.owner()?.to_hex();
// ONCE. This is the paged control-plane fetch that makes the per-member path
// unusable in bulk.
let authority = fetch_authority(transport, community).await;
let citation = required_authority_citation(community, &my_pk)?;
let gb_group =
super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let total = targets.len();
for (i, target) in targets.iter().enumerate() {
let target_hex = target.to_hex();
let outranks = |perm: u64| {
authority.roles.can_act_on_member(&my_hex, Some(&owner_hex), &target_hex, perm)
};
if !outranks(crate::community::roles::Permissions::KICK) {
out.refused.push((*target, "you do not outrank this member".to_string()));
on_progress(i + 1, total);
continue;
}
// CORD-04 §6: a Kick is Role Removal THEN the directive. Only a role-holder
// pays for the strip, so a wave of plain members never touches the control
// plane at all. A strip we attempt and lose skips the target rather than
// publishing a directive we know leaves rank behind.
let holds_roles =
authority.roles.grants.iter().any(|g| g.member == target_hex && !g.role_ids.is_empty());
if holds_roles && outranks(crate::community::roles::Permissions::MANAGE_ROLES) {
if let Err(e) = grant_roles_sealing(transport, community, target, Vec::new(), Seal::BestEffort).await {
out.refused.push((*target, format!("could not strip roles before kicking: {e}")));
on_progress(i + 1, total);
continue;
}
}
let at_ms = now_ms();
let rumor = guestbook::build_kick_rumor(my_pk, *target, citation.as_ref(), at_ms);
match guestbook::seal_guestbook_rumor_signed(
&signer,
my_pk,
&rumor,
&gb_group,
Timestamp::from_secs(at_ms / 1000),
)
.await
{
Ok((wrap, _)) => match transport.publish(&wrap, &community.relays).await {
Ok(_) => out.kicked.push(*target),
Err(_) => out.failed.push(*target),
},
Err(_) => out.failed.push(*target),
}
on_progress(i + 1, total);
}
Ok(out)
})
.await
}
/// A community's folded, delegation-authorized authority — the on-demand read
/// view (a paged control-plane fetch + fold, nothing persisted). `roles` is the
/// owner-seeded authorized roster; `banned` the
/// enforced banlist. `floored`/`head_entities` let a writer detect a WITHHELD
/// entity (floored locally but no head folded) before replacing it blind.
pub struct AuthorityView {
pub roles: crate::community::roles::CommunityRoles,
pub banned: std::collections::BTreeSet<String>,
/// Any authority entity's fold hit a floor gap (withheld / evicted link).
pub gapped: bool,
/// Entity hexes holding a persisted floor at this epoch (all vsk kinds).
pub floored: std::collections::BTreeSet<String>,
/// Authority entities (role/grant/banlist) that folded a head this fetch.
pub head_entities: std::collections::BTreeSet<String>,
/// Ban history (npub hex → secs), outliving the ban so an un-ban raises no phantom.
pub banned_at: std::collections::BTreeMap<String, u64>,
/// Roles v2 is active (CORD-04 §2): Roles are vsk 13, ordered by rank key.
pub activated: bool,
/// Who signed each member's Grant head, by member hex.
pub grant_authors: std::collections::BTreeMap<String, String>,
/// `@everyone`'s head was served this read, not carried from what this device held.
pub everyone_served: bool,
}
/// Fetch + fold the community's current authority (CORD-04), paging older like
/// `follow_control` while the fold is gapped so a busy control plane can't push
/// the roster off the newest window. A fetch failure degrades fail-safe:
/// owner-only authority plus the PERSISTED banlist — nobody gains standing from
/// an outage, and a ban never lifts on withheld data.
/// Why a Control Plane read is no verdict: it stopped short of what this device tracks.
pub(super) const CONTROL_SHORT: &str = "the Control Plane couldn't be read whole";
/// The head a reader folds for the Writers ledger at `eid` from what the relays serve now, read
/// as deep as a follow and without persisting anything: `(self_hash, version)`. A read short of
/// what this device tracks is no verdict either way.
pub(super) async fn writers_head_on_relays<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, eid: &[u8; 32]) -> Result<Option<([u8; 32], u64)>, String> {
let read = read_control(transport, community).await?;
let eid_hex = crate::simd::hex::bytes_to_hex_32(eid);
let head = read.fold.heads.iter().find(|h| h.entity_hex == eid_hex).map(|h| (h.self_hash, h.version));
// A gap above the head is an edition nobody can link: it moves no reader past it.
if read.truncated || read.authority.gapped || (head.is_none() && read.floors.contains_key(&eid_hex)) {
return Err(CONTROL_SHORT.to_string());
}
Ok(head)
}
pub async fn fetch_authority<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> AuthorityView {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
// As deep as a follow reads; a failed read keeps the persisted banlist (an empty fold retains it).
let (floors, a, short) = match read_control(transport, community).await {
Ok(read) => (read.floors, read.authority, read.truncated),
Err(_) => {
let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)
.unwrap_or_default()
.into_iter()
.filter(|(_, f)| f.0 == community.root_epoch.0)
.map(|(entity, f)| (entity, (f.1, f.2, f.3, f.4, f.5)))
.collect();
let a = fold_authority(community, &[], &floors);
(floors, a, true)
}
};
let floors = floors_of_family(&floors, crate::db::community::FLOOR_AUTHORITY);
let head_entities = a.settled().into_iter().map(String::from).collect();
// The first head held for each entity, as a scan of the list would find it.
let mut first_head: std::collections::HashMap<&str, &FoldedHead> = std::collections::HashMap::with_capacity(a.heads.len());
for h in &a.heads {
first_head.entry(h.entity_hex.as_str()).or_insert(h);
}
let grant_authors = a
.roles
.grants
.iter()
.filter_map(|g| {
let member = crate::simd::hex::hex_to_bytes_32_checked(&g.member)?;
let eid = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(community.id(), &member));
let head = first_head.get(eid.as_str())?;
Some((g.member.clone(), crate::simd::hex::bytes_to_hex_32(&head.author)))
})
.collect();
let everyone_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::everyone_locator(community.id()));
let everyone_served = a.heads.iter().any(|h| h.entity_hex == everyone_hex);
AuthorityView {
roles: a.roles,
banned: a.banned,
gapped: a.gapped || short,
floored: floors.keys().cloned().collect(),
head_entities,
banned_at: a.banned_at,
activated: a.activated,
grant_authors,
everyone_served,
}
}
/// When each member provably arrived, seconds: the earliest of their Joins across
/// the live plane and every epoch this client holds, lowered by any snapshot an
/// npub that may rotate the base already listed them in. A member re-joining
/// through a new link has been here since their first trace.
///
/// A Join's time is written by its author. With `watched` (this client was
/// following before the window opened), a member it saw arrive is dated by those
/// arrivals alone, each no earlier than when it was seen: an unwatched Join can
/// only be a backdate. Only members with a Join on the live plane appear; what this
/// client holds can date them earlier, never make anyone read as new.
fn earliest_arrivals(
fetched: &[guestbook::GuestbookEvent],
held: &[guestbook::GuestbookEvent],
watched: bool,
may_rotate: impl Fn(&PublicKey) -> bool,
) -> std::collections::BTreeMap<PublicKey, u64> {
let seen_at: std::collections::HashMap<[u8; 32], u64> =
fetched.iter().chain(held).filter_map(|ev| ev.observed_at.map(|o| (ev.rumor_id, o))).collect();
let on_plane: std::collections::BTreeSet<PublicKey> = fetched
.iter()
.filter_map(|ev| match &ev.entry {
guestbook::GuestbookEntry::Join { member, .. } => Some(*member),
_ => None,
})
.collect();
let mut claimed: std::collections::BTreeMap<PublicKey, u64> = std::collections::BTreeMap::new();
let mut observed: std::collections::BTreeMap<PublicKey, u64> = std::collections::BTreeMap::new();
for ev in fetched.iter().chain(held) {
let guestbook::GuestbookEntry::Join { member, at_ms, .. } = &ev.entry else { continue };
if !on_plane.contains(member) {
continue;
}
let claim = at_ms / 1000;
claimed.entry(*member).and_modify(|e| *e = (*e).min(claim)).or_insert(claim);
if let Some(seen) = seen_at.get(&ev.rumor_id).filter(|_| watched) {
let at = claim.max(*seen);
observed.entry(*member).and_modify(|e| *e = (*e).min(at)).or_insert(at);
}
}
let mut first = claimed;
first.extend(observed);
for ev in fetched.iter().chain(held) {
if let guestbook::GuestbookEntry::Snapshot { refounder, members, at_ms, .. } = &ev.entry {
if !may_rotate(refounder) {
continue;
}
for m in members {
if let Some(e) = first.get_mut(m) {
*e = (*e).min(at_ms / 1000);
}
}
}
}
first
}
/// Page the Guestbook plane newest-to-oldest, stopping once a page's oldest wrap
/// falls below `since_secs` (everything older is already held) or the plane is
/// exhausted. Returns the parsed events at/after the window plus the newest wrap
/// time seen (the caller's next cursor; `since_secs` when nothing newer arrived).
///
/// PAGE bound rationale: a single 500-window silently drops a member whose Join
/// aged out (organic growth, or an insider flooding throwaway Joins), and
/// `refound_community` consumes the fold as its rekey recipient set — a dropped
/// member is SEVERED. Beyond this depth a community needs sharding (documented);
/// the granted-member union in [`fold_members`] is the consensus-complete
/// backstop regardless of Guestbook depth.
async fn fetch_guestbook_events<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
since_secs: u64,
) -> Result<(Vec<guestbook::GuestbookEvent>, u64, bool), String> {
fetch_guestbook_from(transport, community, &community.relays, since_secs, None, &Default::default()).await.map(|(events, newest, end, _)| (events, newest, end))
}
/// [`fetch_guestbook_events`] over `relays` from `start_until` down, with where it stopped when
/// the page cap came first, so a long walk goes on from there. A wrap in `opened` was opened by
/// another relay's read and is skipped here; each one opened is added.
async fn fetch_guestbook_from<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
relays: &[String],
since_secs: u64,
start_until: Option<u64>,
opened: &std::sync::Mutex<std::collections::HashSet<nostr_sdk::prelude::EventId>>,
) -> Result<(Vec<guestbook::GuestbookEvent>, u64, bool, Option<u64>), String> {
let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
const GB_PAGE: usize = 500;
const GB_MAX_PAGES: usize = 12;
let mut events = Vec::new();
let mut newest: u64 = since_secs;
let mut seen: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
let mut until: Option<u64> = start_until;
let mut oldest: Option<u64> = None;
// Did the walk run out of PLANE, or out of PAGES? Only the former means the
// caller holds everything down to `since_secs` — advancing a cursor on the
// latter skips whatever the walk never reached, permanently.
let mut reached_end = false;
for _ in 0..GB_MAX_PAGES {
// Full: this set becomes the refound's recipient list — a member's
// Join visible only on a minority relay must not be severed.
let query = Query {
since: (since_secs > 0).then_some(since_secs),
evidence: crate::community::transport::Evidence::Full,
..plane_page(gb_group.pk_hex(), GB_PAGE, until)
};
let wraps = transport.fetch(&query, relays).await?;
let mut fresh = 0usize;
let to_open: Vec<&Event> = {
let opened = opened.lock().unwrap_or_else(|e| e.into_inner());
wraps.iter().filter(|w| !seen.contains(&w.id) && w.created_at.as_secs() >= since_secs && !opened.contains(&w.id)).collect()
};
let _batch = stream::check_page(&to_open, &gb_group);
for wrap in &wraps {
if !seen.insert(wrap.id) {
continue;
}
fresh += 1;
let at = wrap.created_at.as_secs();
if oldest.is_none_or(|o| at < o) {
oldest = Some(at);
}
if at > newest {
newest = at;
}
// Older than the cursor window — already held; skip the decrypt.
if at < since_secs {
continue;
}
if !opened.lock().unwrap_or_else(|e| e.into_inner()).insert(wrap.id) {
continue;
}
if let Ok(opened) = stream::open_wrap(wrap, &gb_group) {
if let Ok(ev) = guestbook::parse_guestbook_event(&opened) {
events.push(ev);
}
}
}
// A full page all seen before is a same-second wall, not the end: step past it.
if fresh == 0 && wraps.len() >= GB_PAGE {
match until {
Some(u) if u > since_secs => {
until = Some(u - 1);
continue;
}
_ => {
reached_end = true;
break;
}
}
}
if fresh == 0 || wraps.len() < GB_PAGE || oldest.is_some_and(|o| o < since_secs) {
reached_end = true;
break;
}
match oldest {
Some(o) if o > 0 => until = Some(o),
// Nothing older to ask for.
_ => {
reached_end = true;
break;
}
}
}
Ok((events, newest, reached_end, until))
}
/// The shared membership fold: coalesce Guestbook events under the community's
/// authority (owner-supreme kicks, refounder snapshots), union observed authors
/// plus every roster grantee, subtract the banlist, and pin the proven owner.
/// One implementation, so the live and stored reads can't drift.
/// Whose Guestbook snapshot seeds this community's CURRENT epoch (CORD-02 §5):
/// "honored only from the npub whose Refounding minted that epoch". That is the
/// owner only when the owner did the refounding.
///
/// The minter comes from the rotation this device VERIFIED and adopted, never from
/// the snapshot, so writing a snapshot grants nobody authority over it. Genesis
/// (epoch 0) has no refounder and therefore no snapshot power at all.
///
/// A device that arrived after the rotation (a joiner, a re-joiner) holds only this
/// epoch and never saw it. It takes the earliest of this epoch's snapshots written by
/// someone the roster lets rotate the base (the owner or a BAN holder, CORD-06): the
/// Refounder writes its snapshot as it mints the epoch, and a rival branch's snapshot
/// lands under that branch's own root, never this one. Failing that, the owner.
fn snapshot_authority_for(
cid_hex: &str,
community: &CommunityV2,
owner: &PublicKey,
events: &[guestbook::GuestbookEvent],
roles: &crate::community::roles::CommunityRoles,
) -> Option<PublicKey> {
let epoch = community.root_epoch.0;
if epoch == 0 {
return None;
}
if let Some(minted_by) = epoch_minters(cid_hex).get(&epoch).and_then(|h| PublicKey::from_hex(h).ok()) {
return Some(minted_by);
}
let owner_hex = owner.to_hex();
let may_rotate = |pk: &PublicKey| {
pk == owner || roles.is_authorized(&pk.to_hex(), Some(&owner_hex), crate::community::roles::Permissions::BAN)
};
let earliest = events
.iter()
.filter(|ev| ev.epoch == Some(epoch))
.filter_map(|ev| match &ev.entry {
guestbook::GuestbookEntry::Snapshot { refounder, at_ms, .. } if may_rotate(refounder) => Some((*at_ms, *refounder)),
_ => None,
})
.min_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.to_bytes().cmp(&b.1.to_bytes())));
Some(earliest.map_or(*owner, |(_, pk)| pk))
}
fn fold_members(
community: &CommunityV2,
events: &[guestbook::GuestbookEvent],
observed: std::collections::BTreeMap<PublicKey, u64>,
roles: &crate::community::roles::CommunityRoles,
banlist: &std::collections::BTreeSet<PublicKey>,
banned_at: &std::collections::BTreeMap<PublicKey, u64>,
) -> Result<Vec<PublicKey>, String> {
let parts = fold_member_parts(community, events, observed, roles, banlist, banned_at)?;
let mut all = parts.counted;
all.extend(parts.unlisted.into_keys());
Ok(all.into_iter().collect())
}
/// [`fold_members`], split into who counts and who is only seen posting.
fn fold_member_parts(
community: &CommunityV2,
events: &[guestbook::GuestbookEvent],
mut observed: std::collections::BTreeMap<PublicKey, u64>,
roles: &crate::community::roles::CommunityRoles,
banlist: &std::collections::BTreeSet<PublicKey>,
banned_at: &std::collections::BTreeMap<PublicKey, u64>,
) -> Result<guestbook::MemberParts, String> {
let owner = community.owner()?;
let owner_hex = owner.to_hex();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
// CONSENSUS-COMPLETE backstop: every member the folded roster GRANTS a role to
// is provably a member (a Grant binds member_xonly, CORD-02 A.6) — count them
// even if their Join aged out of the Guestbook entirely and they never posted.
// This is what keeps a Refounding from severing a lurking admin. `observed`
// carries them at ts 0 (presence, not recency); the banlist subtraction below
// still removes a banned grantee whose grant wasn't yet stripped.
for g in &roles.grants {
if let Some(pk) = PublicKey::from_hex(&g.member).ok().filter(|_| !g.role_ids.is_empty()) {
observed.entry(pk).or_insert(0);
}
}
// Snapshot authority (CORD-02 §5): whoever's Refounding minted the current epoch, an
// admin's or a bot's as much as the owner's, so its survivors stay members without re-posting.
let snapshot_authority_pk = snapshot_authority_for(&cid_hex, community, &owner, events, roles);
let snapshot_authority = snapshot_authority_pk.as_ref();
let can_kick = kick_judge(&cid_hex, &owner_hex, roles);
let now = now_ms();
let coalesced = guestbook::coalesce(events, now, snapshot_authority, &can_kick);
// The live refound's guest list also gates the observed-forward path in
// complete_memberlist, so a raid spammer whose Kick was buried by the rotation
// isn't silently re-admitted by their old spam.
let refound = guestbook::live_refound(events, snapshot_authority, now);
let mut parts = guestbook::memberlist_parts(&coalesced, &observed, banlist, banned_at, refound.as_ref());
// A role-holder the fold lists counts, however their activity is stamped: a Grant is
// consensus, the same on every client.
for g in roles.grants.iter().filter(|g| !g.role_ids.is_empty()) {
if let Some(pk) = PublicKey::from_hex(&g.member).ok().filter(|pk| parts.unlisted.remove(pk).is_some()) {
parts.counted.insert(pk);
}
}
// The owner is a member by definition, independent of any fetched Join.
if !banlist.contains(&owner) {
parts.unlisted.remove(&owner);
parts.counted.insert(owner);
}
Ok(parts)
}
/// What a [`rescue_stranded_members`] pass published.
#[derive(Debug, Default, serde::Serialize)]
pub struct RescueReport {
/// Epoch hops that received catch-up blobs (1..=current, minus any with a missing root).
pub hops: usize,
/// Hops skipped because an archived root was missing — those members stay wedged there.
pub hops_skipped: usize,
pub chunks_published: usize,
pub targets: usize,
}
/// Re-vend the epoch chain to members a past rotation forgot.
///
/// DELIBERATELY not surfaced in any client: [`refound_community`]'s recipient union
/// exists so this situation cannot arise from our own rotations. This stays as the
/// operator/SDK primitive for strandings we don't control — another client's rotation
/// folding a narrower memberlist, or a pre-union build. It re-keyed 39 live members
/// once; prevention is the product, this is the fire axe.
///
/// A client follows rekeys hop by hop: from its held root it derives ONE plane —
/// `base_rekey_group(held_root, cid, held_epoch + 1)` — and can never jump. A member
/// excluded from the recipient set at hop N therefore wedges at N−1 forever; no later
/// rotation can reach them because they cannot even derive where to look.
///
/// The rotator holds every archived root, so it can publish what should have existed:
/// for each hop, additional blobs addressed to the stranded set, built with the SAME
/// (rotator, scope, epoch, prev-commitment) as the original rotation. `collect_rotations`
/// correlates on exactly that key, so the catch-up blobs merge into the rotation every
/// client already validated — the stranded client's next follow simply finds its blob
/// and walks the whole chain forward. No action needed on their side; works on any
/// client version.
///
/// Intermediate blobs carry the CURRENT control pair (the historical pairs are not
/// archived). A mid-walk client briefly holds a future control address, and the final
/// hop — which every walk ends on — sets the same, correct pair.
///
/// A Guestbook snapshot addendum at the current epoch re-seeds the rescued members for
/// outside readers (the invite page) and for clients whose fold lost them.
pub async fn rescue_stranded_members<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
targets: &[PublicKey],
) -> Result<RescueReport, String> {
crate::db::scoped(async move {
let mut report = RescueReport { targets: targets.len(), ..Default::default() };
if targets.is_empty() {
return Ok(report);
}
let signer = crate::signer::active_signer()?;
let my_pk = me_pk()?;
let cid = community.id();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
let owner = community.owner()?;
let owner_hex = owner.to_hex();
// Key-granting is rotation-shaped authority: the receive side only honors blobs
// inside rotations whose rotator it admits, so an unauthorized caller could only
// publish noise — but fail loudly here rather than publish it.
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
if my_pk != owner && !roster.is_authorized(&my_pk.to_hex(), Some(&owner_hex), crate::community::roles::Permissions::BAN) {
return Err("rescuing stranded members requires rotation authority (owner or BAN)".to_string());
}
let control_pk = community.control_pk.ok_or("rescue requires a split community (no control pk held)")?;
let citation = my_authority_citation(community, &my_pk);
// Every archived root, plus the live head (belt-and-suspenders: the head is
// archived at rotation time, but the union costs nothing).
let mut roots: std::collections::BTreeMap<u64, [u8; 32]> =
crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX)?
.into_iter()
.map(|(e, k)| (e.0, k))
.collect();
roots.insert(community.root_epoch.0, community.community_root);
let at_secs = now_ms() / 1000;
for e in 1..=community.root_epoch.0 {
let (Some(prev_root), Some(new_root)) = (roots.get(&(e - 1)).copied(), roots.get(&e).copied()) else {
crate::log_warn!("[Rescue] no archived root for hop {} -> {} — members wedged there stay wedged", e - 1, e);
report.hops_skipped += 1;
continue;
};
let group = super::derive::base_rekey_group_key(&prev_root, cid, Epoch(e));
let prev_commit = super::derive::epoch_key_commitment(Epoch(e - 1), &prev_root);
// The catch-up EXTENDS the original rotation's chunk set: same correlation
// key, indices past its highest slot. Re-claiming a slot is not an option —
// collect_rotations keeps the first chunk per index, and if ours won, the
// original recipients in the losing chunk would fold as removed.
let existing = fetch_rekey_chunks(transport, &community, &group).await?;
let start_after = existing
.iter()
.filter(|c| {
c.rotator == my_pk
&& c.scope == super::rekey::RekeyScope::Root
&& c.new_epoch == Epoch(e)
&& c.prev_commit == prev_commit
})
.map(|c| c.chunk.0.max(c.chunk.1))
.max()
.unwrap_or(0);
// The owner rides every catch-up chunk: an extension inherits the original
// chunks' owner blob, but a plane a relay withheld folds ours standalone,
// and a rotation without an owner blob is inadmissible by design.
let mut recipients: Vec<PublicKey> = targets.to_vec();
if !recipients.contains(&my_pk) {
recipients.push(my_pk);
}
let mut blobs = Vec::with_capacity(recipients.len());
for r in &recipients {
// Staff get the control secret exactly as a live rotation would give it.
let staff = *r == my_pk || roster.is_staff(&r.to_hex(), Some(&owner_hex));
let ctl_root = if staff { community.control_root.as_ref() } else { None };
blobs.push(
super::rekey::build_base_blob(&signer, &my_pk.to_bytes(), r, Epoch(e), &new_root, &control_pk.to_bytes(), ctl_root)
.await
.map_err(|e| e.to_string())?,
);
}
// A rescue extension can fold STANDALONE on a withheld plane, so it
// must re-state the hop's sever itself: from the fetched siblings, or
// from the persisted mark when the plane withheld even those.
let severed_hop = existing
.iter()
.any(|c| c.scope == super::rekey::RekeyScope::Root && c.new_epoch == Epoch(e) && c.severed)
|| sever_marks(&cid_hex).contains_key(&e);
let chunks = super::rekey::build_rekey_chunk_extension(
&signer,
my_pk,
&group,
super::rekey::RekeyScope::Root,
Epoch(e),
Epoch(e - 1),
&prev_commit,
&blobs,
at_secs,
citation.as_ref(),
severed_hop,
start_after,
)
.await
.map_err(|e| e.to_string())?;
for c in &chunks {
transport.publish_durable(c, &community.relays).await?;
report.chunks_published += 1;
}
report.hops += 1;
}
// Re-seed them in the current epoch's Guestbook: snapshot chunks are
// independently useful (CORD-02 §5), so an addendum under a fresh snap id folds
// as Joined on every client and every outside reader. Best-effort, like a
// rotation's own snapshot.
let gb_group = super::derive::guestbook_group_key(&community.community_root, cid, community.root_epoch);
let snap_id = crate::community::random_32();
for rumor in guestbook::build_snapshot_rumors(my_pk, targets, snap_id, at_secs * 1000) {
if let Ok((wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(at_secs)).await {
let _ = transport.publish(&wrap, &community.relays).await;
}
}
crate::log_info!(
"[Rescue] {} member(s): {} hop(s) re-vended ({} skipped), {} chunk(s) published, snapshot addendum at epoch {}",
targets.len(),
report.hops,
report.hops_skipped,
report.chunks_published,
community.root_epoch.0
);
Ok(report)
})
.await
}
/// Diagnostic: the memberlist as the WIRE alone tells it — the current epoch's
/// guestbook plane fetched fresh and folded with no local observation and no roster
/// backstop. This is what an outside reader (the invite page) computes, so the diff
/// against [`stored_memberlist`] is exactly the set a rotation left behind: counted
/// locally, absent from the snapshot, holding no current key.
pub async fn wire_guestbook_members<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
) -> Result<Vec<PublicKey>, String> {
let (events, _newest, _reached_end) = fetch_guestbook_events(transport, community, 0).await?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let owner = community.owner()?;
let owner_hex = owner.to_hex();
let roles = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let snapshot_authority_pk = snapshot_authority_for(&cid_hex, community, &owner, &events, &roles);
let snapshot_authority = snapshot_authority_pk.as_ref();
let can_kick = kick_judge(&cid_hex, &owner_hex, &roles);
let coalesced = guestbook::coalesce(&events, now_ms(), snapshot_authority, &can_kick);
let banlist: std::collections::BTreeSet<PublicKey> = crate::db::community::get_community_banlist(&cid_hex)
.unwrap_or_default()
.iter()
.filter_map(|h| PublicKey::from_hex(h).ok())
.collect();
Ok(coalesced
.iter()
.filter(|(pk, st)| st.verdict == guestbook::Verdict::Joined && !banlist.contains(pk))
.map(|(pk, _)| *pk)
.collect())
}
/// Who the stored Guestbook folds as gone, by a Leave, an authorized Kick or a Refounding.
pub(crate) fn stored_departures(community: &CommunityV2) -> Vec<PublicKey> {
stored_departure_times(community).into_keys().collect()
}
/// [`stored_departures`] with when each took effect: the Leave or Kick, or the Refounding's cut.
pub(crate) fn stored_departure_times(community: &CommunityV2) -> std::collections::HashMap<PublicKey, u64> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let Ok((events, _cursor)) = crate::db::community::get_guestbook_shared(&cid_hex) else { return Default::default() };
let Ok(owner) = community.owner() else { return Default::default() };
let owner_hex = owner.to_hex();
let roles = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let snapshot_authority_pk = snapshot_authority_for(&cid_hex, community, &owner, &events, &roles);
let can_kick = kick_judge(&cid_hex, &owner_hex, &roles);
guestbook::coalesce(&events, now_ms(), snapshot_authority_pk.as_ref(), &can_kick).into_iter().filter(|(_, st)| st.verdict != guestbook::Verdict::Joined).map(|(pk, st)| (pk, st.at_ms)).collect()
}
pub(crate) type DepartureSpans = crate::db::community::DepartureSpans;
struct DepartureCache;
/// Each member's spans away from `community`, per its stored Guestbook (CORD-03 §1). Folded once
/// per change to what the fold reads, not once per post judged.
pub(crate) fn stored_departure_windows(community: &CommunityV2) -> std::sync::Arc<DepartureSpans> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let generation = crate::db::community::membership_generation();
let cache = departure_cache();
if let Some(held) = cache.lock().ok().and_then(|c| c.get(&cid_hex).cloned()) {
if held.generation == generation {
return held.spans;
}
}
let (spans, due) = fold_departure_windows(community, &cid_hex);
let spans = std::sync::Arc::new(spans);
if let Ok(mut c) = cache.lock() {
if c.get(&cid_hex).is_none_or(|held| held.generation <= generation) {
c.insert(cid_hex, HeldDepartures { generation, spans: spans.clone(), due });
}
}
spans
}
#[derive(Clone)]
struct HeldDepartures {
generation: u64,
spans: std::sync::Arc<DepartureSpans>,
/// The earliest entry the fold left out as too far ahead: once it is due, fold again.
due: Option<u64>,
}
fn departure_cache() -> std::sync::Arc<std::sync::Mutex<std::collections::HashMap<String, HeldDepartures>>> {
crate::db::current_session().scoped::<DepartureCache, std::sync::Mutex<std::collections::HashMap<String, HeldDepartures>>>()
}
/// What storing some entries does to the windows held at the current membership generation.
enum DeparturesAfter {
/// Only these members' windows can move: none for a Join or snapshot seed of members never away.
Members(u64, Vec<PublicKey>),
Refold,
}
/// Past this many members moved, one fold of everyone costs less than one fold each.
const MEMBER_REFOLDS_MAX: usize = 8;
fn departures_after<'a>(cid_hex: &str, entries: impl IntoIterator<Item = &'a guestbook::GuestbookEntry>) -> DeparturesAfter {
use guestbook::GuestbookEntry;
let cache = departure_cache();
let Ok(c) = cache.lock() else { return DeparturesAfter::Refold };
let Some(held) = c.get(cid_hex).filter(|h| h.generation == crate::db::community::membership_generation() && !h.is_due()) else {
return DeparturesAfter::Refold;
};
let mut moved: Vec<PublicKey> = Vec::new();
for entry in entries {
let member = match entry {
GuestbookEntry::Join { member, .. } if !held.spans.contains_key(member) => continue,
GuestbookEntry::Join { member, .. } | GuestbookEntry::Leave { member, .. } | GuestbookEntry::Kick { target: member, .. } => member,
GuestbookEntry::Snapshot { members, .. } if members.iter().all(|m| !held.spans.contains_key(m)) => continue,
GuestbookEntry::Snapshot { .. } => return DeparturesAfter::Refold,
_ => continue,
};
if !moved.contains(member) {
moved.push(*member);
}
if moved.len() > MEMBER_REFOLDS_MAX {
return DeparturesAfter::Refold;
}
}
DeparturesAfter::Members(held.generation, moved)
}
impl HeldDepartures {
fn is_due(&self) -> bool {
self.due.is_some_and(|due| now_ms().saturating_add(guestbook::MAX_FUTURE_MS) >= due)
}
/// `due` once entries dated `at_ms` are stored: one too far ahead to fold yet comes due later.
fn due_with(&self, at_ms: impl IntoIterator<Item = u64>) -> Option<u64> {
let horizon = now_ms().saturating_add(guestbook::MAX_FUTURE_MS);
self.due.into_iter().chain(at_ms.into_iter().filter(|&at| at > horizon)).min()
}
}
/// Store `events` with the Guestbook write gate held, and bring the departure windows over the
/// write without folding everyone again.
fn store_guestbook_and_departures(community: &CommunityV2, cid_hex: &str, events: &[guestbook::GuestbookEvent], cursor_secs: u64) -> Result<(), String> {
let after = departures_after(cid_hex, events.iter().map(|e| &e.entry));
crate::db::community::store_guestbook_events(cid_hex, events, cursor_secs)?;
departures_stored(community, cid_hex, after, events.iter().map(|e| e.entry.at_ms()));
Ok(())
}
/// Bring windows held at `generation` over the one write that moved it on, which stored entries
/// dated `at_ms`. Any other write since moved it further, so what is brought over is never served.
fn departures_stored(community: &CommunityV2, cid_hex: &str, after: DeparturesAfter, at_ms: impl IntoIterator<Item = u64>) {
let DeparturesAfter::Members(generation, moved) = after else { return };
let cache = departure_cache();
let held = cache.lock().ok().and_then(|c| c.get(cid_hex).filter(|h| h.generation == generation).cloned());
let Some(held) = held else { return };
if held.is_due() {
return;
}
let spans = if moved.is_empty() {
held.spans.clone()
} else {
let Some(folded) = with_departure_fold(community, cid_hex, |events, now, authority, can_kick| {
moved.iter().map(|member| (*member, guestbook::member_departure_windows(events, member, now, authority, can_kick))).collect::<Vec<_>>()
}) else {
return;
};
let changed: Vec<_> = folded.into_iter().filter(|(member, windows)| !held.spans.get(member).map_or(windows.is_empty(), |was| was[..] == windows[..])).collect();
if changed.is_empty() {
held.spans.clone()
} else {
let mut spans = (*held.spans).clone();
for (member, windows) in changed {
if windows.is_empty() {
spans.remove(&member);
} else {
spans.insert(member, windows.into());
}
}
std::sync::Arc::new(spans)
}
};
let due = held.due_with(at_ms);
let mut c = cache.lock().unwrap_or_else(|e| e.into_inner());
if let Some(entry) = c.get_mut(cid_hex).filter(|h| h.generation == generation) {
*entry = HeldDepartures { generation: generation + 1, spans, due };
}
}
/// Run `f` over the stored Guestbook with the Kick and snapshot judgements every departure
/// fold makes.
fn with_departure_fold<R>(
community: &CommunityV2,
cid_hex: &str,
f: impl FnOnce(&[guestbook::GuestbookEvent], u64, Option<&PublicKey>, &dyn Fn(&PublicKey, &PublicKey, Option<&crate::community::edition::AuthorityCitation>) -> bool) -> R,
) -> Option<R> {
let (events, _cursor) = crate::db::community::get_guestbook_shared(cid_hex).ok()?;
let owner = community.owner().ok()?;
let owner_hex = owner.to_hex();
let roles = crate::db::community::get_community_roles(cid_hex).unwrap_or_default();
let snapshot_authority_pk = snapshot_authority_for(cid_hex, community, &owner, &events, &roles);
let can_kick = kick_judge(cid_hex, &owner_hex, &roles);
Some(f(&events, now_ms(), snapshot_authority_pk.as_ref(), &can_kick))
}
fn fold_departure_windows(community: &CommunityV2, cid_hex: &str) -> (DepartureSpans, Option<u64>) {
with_departure_fold(community, cid_hex, |events, now, authority, can_kick| {
let horizon = now.saturating_add(guestbook::MAX_FUTURE_MS);
let due = events.iter().map(|e| e.entry.at_ms()).filter(|&at| at > horizon).min();
(guestbook::departure_windows(events, now, authority, can_kick).into_iter().map(|(member, spans)| (member, spans.into())).collect(), due)
})
.unwrap_or_default()
}
/// A departure this device hasn't owed for yet undoes what its member posted at a writer address
/// while it held, in every Channel that keeps a ledger: a Leave until the Join that ends it, a
/// Kick until the writer window it fell in ends, since one back after a Kick posts on a fresh
/// epoch. Judged against a durable record, so a departure that appears by a Roster or citation
/// landing later, or a pass cut short, is owed all the same. Only that member's writer posts are
/// owed, never from before the Channel's first writer window.
pub(crate) fn owe_new_departures(community: &CommunityV2) {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let Ok(seen) = crate::db::community::departures_seen(&cid_hex) else { return };
let now = stored_departure_windows(community);
if std::sync::Arc::ptr_eq(&now, &seen.spans) {
return;
}
let mut ledgers: Option<Vec<(String, &super::writers::Ledger)>> = None;
let (mut moved, mut owed) = (false, false);
// Both are in key order: one walk pairs each member with what was seen of them.
let mut was = seen.spans.iter().peekable();
for (pk, spans) in now.iter() {
while was.next_if(|(k, _)| *k < pk).is_some() {
moved = true;
}
let before = was.next_if(|(k, _)| *k == pk).map(|(_, s)| s);
if before == Some(spans) {
continue;
}
moved = true;
let mut fresh = spans.iter().filter(|w| !before.is_some_and(|s| s.contains(w))).peekable();
if fresh.peek().is_none() {
continue;
}
let ledgers = ledgers.get_or_insert_with(|| community.channels.iter().filter_map(|c| Some((crate::simd::hex::bytes_to_hex_32(&c.id.0), c.writers.as_ref()?))).collect());
let author = pk.to_hex();
let Ok(npub) = nostr_sdk::prelude::ToBech32::to_bech32(pk);
for &(from, until, kicked) in fresh {
for (chan, ledger) in ledgers.iter() {
let Some(first) = ledger.writers().filter_map(|(e, ..)| ledger.writer_start(e)).min() else { continue };
let since = from.max(first);
let end = if kicked { ledger.writers().find(|(e, _, end)| ledger.writer_start(*e).is_some_and(|s| s <= since) && end.is_none_or(|end| end > since)).and_then(|(_, _, end)| end) } else { until };
// A read that fails leaves the record unwritten, so the next pass owes it again.
let Ok(posts) = crate::db::events::posts_since_by(chan, since, Some(&npub)) else { return };
if posts.iter().any(|p| p.writer && end.is_none_or(|end| p.at_ms < end)) {
if crate::db::community::owe_author_retraction(&cid_hex, chan, &author, since, end).is_err() {
return;
}
owed = true;
}
}
}
}
if !moved && was.next().is_none() {
return;
}
if crate::db::community::set_departures_seen(&cid_hex, now.clone()).is_ok() && owed {
super::realtime::enqueue_follow(community.id());
}
}
/// Did the AUTHORIZED Guestbook coalesce rule `member` KICKED, per the stored plane?
///
/// This is the only sound basis for acting on a kick against ourselves. The
/// memberlist is the wrong question: it also folds the banlist, the ban marks and
/// observed authors, so a member whose Guestbook hasn't caught up yet — a REJOIN,
/// where the store starts empty while the control fold has already re-derived their
/// old ban mark — is absent from it while being perfectly joined. Coalescing asks
/// only "what is the latest authorized entry for this npub", so a fresh Join
/// supersedes an old Kick and an empty store yields no verdict at all.
pub fn stored_kick_verdict(community: &CommunityV2, member: &PublicKey) -> bool {
stored_kick_at(community, member).is_some()
}
/// When the authorized Guestbook fold last ruled `member` kicked, if it does now.
/// The rumor of the Kick the authorized fold rules `member` kicked by, if it does.
pub fn stored_kick_rumor(community: &CommunityV2, member: &PublicKey) -> Option<[u8; 32]> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let (events, _cursor) = crate::db::community::get_guestbook_shared(&cid_hex).ok()?;
let owner = community.owner().ok()?;
let owner_hex = owner.to_hex();
let roles = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let snapshot_authority = snapshot_authority_for(&cid_hex, community, &owner, &events, &roles);
let can_kick = kick_judge(&cid_hex, &owner_hex, &roles);
guestbook::coalesce(&events, now_ms(), snapshot_authority.as_ref(), &can_kick)
.get(member)
.filter(|st| st.verdict == guestbook::Verdict::Kicked)
.map(|st| st.rumor_id)
}
pub fn stored_kick_at(community: &CommunityV2, member: &PublicKey) -> Option<u64> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let (events, _cursor) = crate::db::community::get_guestbook_shared(&cid_hex).ok()?;
let owner = community.owner().ok()?;
let owner_hex = owner.to_hex();
let roles = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let snapshot_authority_pk = snapshot_authority_for(&cid_hex, community, &owner, &events, &roles);
let snapshot_authority = snapshot_authority_pk.as_ref();
let can_kick = kick_judge(&cid_hex, &owner_hex, &roles);
guestbook::coalesce(&events, now_ms(), snapshot_authority, &can_kick)
.get(member)
.filter(|st| st.verdict == guestbook::Verdict::Kicked)
.map(|st| st.at_ms)
}
/// The latest a local hold can date from. Rows keep whole seconds, so a join is never ruled older
/// than a removal it may have followed within the same second.
fn hold_bound_ms(c: &CommunityV2) -> u64 {
c.created_at_ms.saturating_add(999)
}
/// Record an eviction this device obeyed in the synced List, at the evicting act's time: siblings and
/// the next boot then don't re-adopt it, and an invite sent after the act still lands.
pub fn record_eviction(community: &CommunityV2, removed_at: u64) {
tombstone_community_list_durable(*community.id(), community.relays.clone(), removed_at);
}
/// Catch the persisted Guestbook up with what each relay holds of its plane: a relay that
/// reconciles is asked only for the wraps this device has not read, and one that cannot is read
/// by pages from its own cursor (see `control_sync`). Returns the entries that were NEW to the
/// store: the caller surfaces them (presence lines) and refreshes on non-empty.
pub async fn sync_guestbook<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
) -> Result<Vec<guestbook::GuestbookEvent>, String> {
sync_guestbook_pass(transport, community).await.map(|(added, _)| added)
}
/// [`sync_guestbook`], and how the pass against the relays ended.
async fn sync_guestbook_pass<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
) -> Result<(Vec<guestbook::GuestbookEvent>, control_sync::PlaneSync), String> {
// The store holds the Guestbook's entries, not its wraps, so it cannot tell an entry on the
// plane from one only this device holds: what must be exactly the plane (a Refounding's
// recipients, the late-joiner cut) still walks it.
crate::db::scoped(async move {
let view = guestbook_store::GuestbookView::of(community);
let began = crate::rt::time::Instant::now();
// Every relay is waited for: its Joins may be nobody else's.
let sync = match control_sync::sync_plane(transport, community, &view, control_sync::Wait::All).await {
Ok(sync) => sync,
Err(control_sync::Unsynced::NoRelay(e) | control_sync::Unsynced::Store(e)) => return Err(e),
};
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
if !sync.unread {
// Read to the end on every relay that answered: the cursor says as of when.
let gate = guestbook_write_gate();
let _gate = gate.lock().unwrap_or_else(|e| e.into_inner());
let now = crate::clock::now_secs();
if crate::db::community::get_guestbook_shared(&cid_hex)?.1 < now {
store_guestbook_and_departures(community, &cid_hex, &[], now)?;
mark_guestbook_observed_since(&cid_hex);
}
drop(_gate);
mark_guestbook_walked(community);
}
crate::log_debug!(
"[v2:guestbook {}] {} wrap(s) read in, {} of {} relay(s) answered, short={} in {:?}",
&cid_hex[..8],
sync.opened,
sync.answered(),
sync.relays.len(),
sync.unread,
began.elapsed()
);
Ok((view.added(), sync))
})
.await
}
/// Store `fresh` entries read off the Guestbook plane this community holds the key to, merged
/// into the store as it stands. `newest` is their wraps' latest timestamp. Returns the ones the
/// store did not hold.
fn merge_guestbook(community: &CommunityV2, fresh: Vec<guestbook::GuestbookEvent>, newest: u64) -> Result<Vec<guestbook::GuestbookEvent>, String> {
if fresh.is_empty() {
return Ok(Vec::new());
}
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
// The stamp is what lets the fold tell a Join carried over from a buried epoch apart from a
// live one; a row stored before stamping existed earns its stamp on re-read.
let live = Some(community.root_epoch.0);
// Merged into the store as it stands now: another walk may have written while this one read.
let gate = guestbook_write_gate();
let _gate = gate.lock().unwrap_or_else(|e| e.into_inner());
let (held, cursor) = crate::db::community::get_guestbook_shared(&cid_hex)?;
// Where in `events` a rumor this walk stored sits; the rest are found in `held`.
let mut written: std::collections::HashMap<[u8; 32], usize> = std::collections::HashMap::new();
let mut events: Vec<guestbook::GuestbookEvent> = Vec::new();
let mut added = Vec::new();
let mut restamped = false;
// A member's carried Nickname is the very rumor they first sent, now on this plane.
let stamp = |had: &guestbook::GuestbookEvent| (had.epoch.is_none() || matches!(had.entry, guestbook::GuestbookEntry::Nickname { .. }) && had.epoch < live).then(|| guestbook::GuestbookEvent { epoch: live, ..had.clone() });
for mut ev in fresh {
ev.epoch = live;
if let Some(&j) = written.get(&ev.rumor_id) {
if let Some(stamped) = stamp(&events[j]) {
events[j] = stamped;
restamped = true;
}
} else if let Some(had) = held.get(&ev.rumor_id) {
if let Some(stamped) = stamp(had) {
written.insert(stamped.rumor_id, events.len());
events.push(stamped);
restamped = true;
}
} else {
// First sight on THIS client. The author writes `at_ms`; they do not write this.
if ev.observed_at.is_none() {
ev.observed_at = Some(crate::clock::now_secs());
}
written.insert(ev.rumor_id, events.len());
events.push(ev.clone());
added.push(ev);
}
}
drop(held);
let advanced = cursor.max(newest);
if !added.is_empty() || advanced > cursor || restamped {
store_guestbook_and_departures(community, &cid_hex, &events, advanced)?;
mark_guestbook_observed_since(&cid_hex);
if !added.is_empty() {
owe_new_departures(community);
}
}
Ok(added)
}
/// Record a Guestbook wrap that came in live as read, once its entry is stored: a sync then
/// never asks a relay for it.
pub(crate) fn hold_guestbook_wrap(community: &CommunityV2, wrap: &Event) {
guestbook_store::GuestbookView::of(community).hold(wrap);
}
/// Guestbook planes read to the end this session on every relay that answered: a Refounding
/// moves the plane, and the read starts again. Lives on the Session, so an account swap drops it
/// and the next account reads its own rather than inheriting this one's coverage.
struct GuestbookWalked;
fn guestbook_walked_set() -> std::sync::Arc<std::sync::Mutex<std::collections::HashSet<[u8; 32]>>> {
crate::db::current_session().scoped::<GuestbookWalked, _>()
}
fn guestbook_walked_this_session(community: &CommunityV2) -> bool {
guestbook_walked_set().lock().is_ok_and(|s| s.contains(&guestbook_plane(community)))
}
/// The Guestbook plane a community reads now: a Refounding moves it, and a walk with it.
fn guestbook_plane(community: &CommunityV2) -> [u8; 32] {
super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch).pk().to_bytes()
}
/// Whether a relay's read of `community`'s Guestbook stopped short and has more to read.
pub(crate) fn guestbook_walk_pending(community: &CommunityV2) -> bool {
control_sync::pending(community, &guestbook_store::GuestbookView::of(community))
}
fn mark_guestbook_walked(community: &CommunityV2) {
if let Ok(mut s) = guestbook_walked_set().lock() {
s.insert(guestbook_plane(community));
}
}
/// A new session: no Guestbook read yet.
#[cfg(test)]
pub(crate) fn forget_session_walks_for_test() {
guestbook_walked_set().lock().unwrap().clear();
}
struct GuestbookWrite;
/// Held across a Guestbook store's read, merge and write, never across an await, so one writer
/// never drops what another just stored.
fn guestbook_write_gate() -> std::sync::Arc<std::sync::Mutex<()>> {
crate::db::current_session().scoped::<GuestbookWrite, _>()
}
/// Fold ONE live guestbook event into the store (the realtime path — no fetch).
/// Returns whether it was new.
pub fn ingest_guestbook_event(community: &CommunityV2, mut ev: guestbook::GuestbookEvent, wrap_secs: u64) -> Result<bool, String> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let gate = guestbook_write_gate();
let _gate = gate.lock().unwrap_or_else(|e| e.into_inner());
let (events, cursor) = crate::db::community::get_guestbook_shared(&cid_hex)?;
let live = Some(community.root_epoch.0);
let stored = match events.get(&ev.rumor_id) {
// A member's carried Nickname is the very rumor they first sent, now on this plane.
Some(held) if !matches!(held.entry, guestbook::GuestbookEntry::Nickname { .. }) || held.epoch >= live => return Ok(false),
Some(held) => guestbook::GuestbookEvent { epoch: live, ..held.clone() },
None => {
ev.epoch = live;
ev
}
};
drop(events);
store_guestbook_and_departures(community, &cid_hex, std::slice::from_ref(&stored), cursor.max(wrap_secs))?;
drop(_gate);
owe_new_departures(community);
Ok(true)
}
/// The memberlist from LOCAL state only: the persisted Guestbook, plus locally
/// observed authors (the synced events DB), plus roster grantees, minus the
/// banlist. Instant and offline-correct; [`sync_guestbook`] (post-join, boot,
/// reconnect, live ingest) keeps the store current. The live [`memberlist`]
/// remains the authoritative walk — a refounding's rekey recipient set must
/// never trust a possibly-stale store.
/// Unix seconds from which this client has been following `cid_hex`'s guestbook.
///
/// Set once, on the first sync that stores anything, and never moved forward. It is
/// what makes `observed_at` usable as evidence: a client that only started watching
/// AFTER a raid began sees every member as new, so its observations prove nothing and
/// must not be allowed to evict anyone.
fn guestbook_observed_since(cid_hex: &str) -> Option<u64> {
crate::db::settings::get_sql_setting(format!("gb_observed_since:{cid_hex}"))
.ok()
.flatten()
.and_then(|v| v.parse::<u64>().ok())
}
fn mark_guestbook_observed_since(cid_hex: &str) {
let key = format!("gb_observed_since:{cid_hex}");
if crate::db::settings::get_sql_setting(key.clone()).ok().flatten().is_some() {
return; // never moves forward — a later stamp would erase our own coverage
}
let now = crate::clock::now_secs();
let _ = crate::db::settings::set_sql_setting(key, now.to_string());
}
pub fn stored_memberlist(community: &CommunityV2) -> Result<Vec<PublicKey>, String> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let (events, _cursor) = crate::db::community::get_guestbook_shared(&cid_hex)?;
stored_memberlist_from(community, &events)
}
/// [`stored_memberlist`] over a guestbook the caller already holds, so a read that needs
/// the cursor too decrypts and parses the plane once.
pub fn stored_memberlist_from(community: &CommunityV2, events: &[guestbook::GuestbookEvent]) -> Result<Vec<PublicKey>, String> {
memberlist_folded(community, events, false)
}
/// [`stored_memberlist`] where leaving counts whatever Role lingers: who may post and who
/// manages a restricted Channel's writers.
pub fn stored_memberlist_strict(community: &CommunityV2) -> Result<Vec<PublicKey>, String> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let (events, _cursor) = crate::db::community::get_guestbook_shared(&cid_hex)?;
memberlist_folded(community, &events, true)
}
/// The stored memberlist split into who counts and who is only seen posting: what a member
/// list and its counters show.
pub fn stored_member_parts(community: &CommunityV2, events: &[guestbook::GuestbookEvent]) -> Result<guestbook::MemberParts, String> {
let (observed, roles, banlist, banned_at) = memberlist_inputs(community, false)?;
fold_member_parts(community, events, observed, &roles, &banlist, &banned_at)
}
fn memberlist_folded(community: &CommunityV2, events: &[guestbook::GuestbookEvent], strict: bool) -> Result<Vec<PublicKey>, String> {
let (observed, roles, banlist, banned_at) = memberlist_inputs(community, strict)?;
fold_members(community, events, observed, &roles, &banlist, &banned_at)
}
type MemberlistInputs = (
std::collections::BTreeMap<PublicKey, u64>,
crate::community::roles::CommunityRoles,
std::collections::BTreeSet<PublicKey>,
std::collections::BTreeMap<PublicKey, u64>,
);
/// What the stored fold reads besides the Guestbook: activity, the roster, the banlist and ban history.
fn memberlist_inputs(community: &CommunityV2, strict: bool) -> Result<MemberlistInputs, String> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let mut observed: std::collections::BTreeMap<PublicKey, u64> = std::collections::BTreeMap::new();
let activity = if strict { crate::db::community::community_member_activity_strict(&cid_hex) } else { crate::db::community::community_member_activity(&cid_hex) };
for (npub, last_active_secs) in activity.unwrap_or_default() {
if let Ok(pk) = PublicKey::parse(&npub) {
observed.insert(pk, last_active_secs.saturating_mul(1000));
}
}
// For posting, only a newer Join brings back one who left, was kicked or refounded out.
if strict {
let gone: std::collections::HashSet<PublicKey> = stored_departures(community).into_iter().collect();
observed.retain(|pk, ms| *ms == 0 || !gone.contains(pk));
}
let roles = crate::db::community::get_community_roles(&cid_hex)?;
let banlist: std::collections::BTreeSet<PublicKey> = crate::db::community::get_community_banlist(&cid_hex)
.unwrap_or_default()
.iter()
.filter_map(|h| PublicKey::from_hex(h).ok())
.collect();
// Ban history gates observation (CORD-02 §5). Read from the store, since this path never
// folds editions.
let banned_at: std::collections::BTreeMap<PublicKey, u64> = crate::db::community::get_community_ban_marks(&cid_hex)
.unwrap_or_default()
.into_iter()
.filter_map(|(h, at)| PublicKey::from_hex(&h).ok().map(|pk| (pk, at)))
.collect();
Ok((observed, roles, banlist, banned_at))
}
/// Fold the Complete Memberlist from the Guestbook plane. The proven owner is
/// ALWAYS a member (derived from the self-certifying community_id — no network,
/// so a lost/evicted genesis Join can't drop them). Observed authors — anyone
/// seen publishing on a channel — are folded in FORWARD-only per CORD-02 §5, so a
/// member whose Join was lost still counts.
pub async fn memberlist<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<Vec<PublicKey>, String> {
let (events, _newest, _reached_end) = fetch_guestbook_events(transport, community, 0).await?;
// Observed authors: fold each held channel's recent authorship (real author +
// newest ms), so a member who posted but whose Join was lost is still counted.
let mut observed: std::collections::BTreeMap<PublicKey, u64> = std::collections::BTreeMap::new();
for ch in &community.channels {
if let Ok(page) = fetch_channel(transport, community, &ch.id, 200).await {
for f in &page {
let e = observed.entry(f.event.opened().author).or_insert(0);
*e = (*e).max(f.event.opened().at_ms);
}
}
}
// Fold the Control Plane roster + banlist (CORD-04) for Kick authority and the
// ban subtraction. A control fetch failure degrades to owner-only authority + no
// bans (fail-open on availability is safe here: a Kick still needs a real signer,
// and a missed ban only fails to HIDE, never to wrongly admit authority).
let authority = fetch_authority(transport, community).await;
// The authorized banlist, as pubkeys (a malformed hex entry is simply dropped).
let banlist: std::collections::BTreeSet<PublicKey> =
authority.banned.iter().filter_map(|h| PublicKey::from_hex(h).ok()).collect();
// Union the live fold's ban history with the stored marks: the fetch only reaches the
// editions still in its window, and a ban that aged out is exactly the one whose
// pre-ban Join would phantom.
let mut banned_at: std::collections::BTreeMap<PublicKey, u64> = crate::db::community::get_community_ban_marks(
&crate::simd::hex::bytes_to_hex_32(&community.id().0),
)
.unwrap_or_default()
.into_iter()
.filter_map(|(h, at)| PublicKey::from_hex(&h).ok().map(|pk| (pk, at)))
.collect();
for (h, at) in &authority.banned_at {
if let Ok(pk) = PublicKey::from_hex(h) {
let slot = banned_at.entry(pk).or_insert(0);
*slot = (*slot).max(*at);
}
}
fold_members(community, &events, observed, &authority.roles, &banlist, &banned_at)
}
// ── Dissolution (CORD-02 §9) ─────────────────────────────────────────────────
/// Owner dissolution / "Delete Community" (CORD-02 §9): publish the terminal
/// tombstone at the dissolved plane (`community_id`-derived, epoch-free, so every
/// past or present member resolves the same grave and a Refounding can never strand
/// it). The tombstone's presence IS the state; only the owner's seal counts.
/// Irreversible — on success the local hold is sealed read-only AND the owner's
/// own membership is tombstoned out of the §8 List: dissolving is also leaving,
/// so the owner's other devices tear the community down on their next list sync
/// instead of keeping a sealed husk they believe is still held.
pub async fn dissolve_community<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<(), String> {
crate::db::scoped(async move {
let signer = crate::signer::active_signer()?;
let my_pk = me_pk()?;
if community.owner()? != my_pk {
return Err("only the owner can dissolve a community".to_string());
}
let at_ms = now_ms();
let at = at_ms / 1000;
let rumor = super::dissolution::dissolved_tombstone_rumor(my_pk, community.id(), at);
let wrap = super::dissolution::seal_dissolved_signed(&signer, my_pk, &rumor, community.id(), Timestamp::from_secs(at)).await.map_err(|e| e.to_string())?;
// Durable broadcast: death must propagate (a rekey racing a dissolution loses).
transport.publish_durable(&wrap, &community.relays).await?;
crate::db::community::set_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&community.id().0))?;
// Dissolving IS leaving (same discipline as `leave_community`): retire the
// membership from the cross-device List (kind 33302) in the same breath as the
// grave, or sibling devices and §8 clients keep the entry LIVE and show a
// dissolved husk. Best-effort with a durable
// retry, never failing the dissolve: the grave is already published, and an
// unrecorded leave only costs the husk lingering until the retry lands.
record_leave(transport, community.id(), &community.relays, at_ms).await;
Ok(())
})
.await
}
/// Whether a valid owner-signed dissolution tombstone exists for this community on
/// its relays (CORD-02 §9). A join refuses a dead community, and a live follow seals
/// on sight. Fail-OPEN on a fetch error (absence of proof is not death), but any
/// owner-verified tombstone found is authoritative.
pub async fn is_dissolved<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> bool {
let group = super::derive::dissolved_group_key(community.id());
let query = Query {
kinds: vec![stream::KIND_WRAP],
authors: vec![group.pk_hex()],
limit: Some(20),
..Default::default()
};
let Ok(wraps) = transport.fetch(&query, &community.relays).await else {
return false;
};
wraps.iter().any(|w| super::dissolution::verify_dissolved(w, &community.identity))
}
// ── Refounding (CORD-06 §3) ──────────────────────────────────────────────────
/// Owner/admin Refounding (CORD-06 §3): roll the `community_root` to
/// cryptographically remove `removed` from a Private community (a Ban's read-cut).
/// Compacts the Control Plane under the new root (re-wraps each head VERBATIM — the
/// inner owner/actor signatures survive, so no re-authoring), rekeys the base plus
/// every Private channel (each sealed under the PRIOR root, D2, so a base-fork loser
/// can still open them), and seeds the new epoch's Guestbook snapshot. Requires BAN.
///
/// **Acquire-before-commit:** the compaction is fetched + re-sealed BEFORE any
/// publish, and a head we can't fetch ABORTS with ZERO published state — so a
/// transient miss never strands a published rekey with a half-anchored plane.
pub async fn refound_community<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, removed: &[PublicKey]) -> Result<CommunityV2, String> {
refound_community_with(transport, community, removed, false, 0, None).await
}
/// A SEVERING Refounding (CORD-06 Severing): the rotation carries the `sever`
/// marker, and every adopter — this client included — revokes its own public
/// invite links instead of refreshing them into the new epoch. The read-cut is
/// real even while the community was Public: the door closes with the rotation,
/// and only a deliberate fresh mint re-opens it.
pub async fn refound_community_severing<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, removed: &[PublicKey], joined_after_cut: u64) -> Result<CommunityV2, String> {
refound_community_with(transport, community, removed, true, joined_after_cut, None).await
}
/// `joined_after_cut`: seconds. A member whose EARLIEST Join is at or after this is
/// vended no key. 0 disables it. The test is positive evidence only — a member with no
/// Join on the reachable guestbook (buried epoch, aged-out window) is NOT excluded, and
/// an unreadable guestbook excludes nobody. Absence must never evict: five rotations
/// once shed 39 real members that way.
/// Re-found vending keys to `retain` ONLY (plus the owner and this device).
///
/// An operator picked a list; anyone not on it gets nothing, whenever they arrived.
/// The removal-list form cannot express that: it is computed from the memberlist at
/// one instant while the refound fetches its own later, so an account that appears in
/// between is on neither list and is vended a key by default — implicitly RETAINED by
/// the very purge meant to be exhaustive. An allow-list has no such gap, and unlike a
/// join-time cut it is immune to a backdated (author-claimed) Join.
pub async fn refound_community_retaining<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
removed: &[PublicKey],
retain: &[PublicKey],
) -> Result<CommunityV2, String> {
refound_community_with(transport, community, removed, false, 0, Some(retain)).await
}
async fn refound_community_with<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, removed: &[PublicKey], sever: bool, joined_after_cut: u64, allow_only: Option<&[PublicKey]>) -> Result<CommunityV2, String> {
crate::db::scoped(async move {
let cid = community.id();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
// Death wins every race: a dissolved community never re-founds (CORD-02 §9).
if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
return Err("this community has been dissolved; it cannot be re-founded".to_string());
}
let signer = crate::signer::active_signer()?;
let my_pk = me_pk()?;
// Serialize with the follow worker for the whole rotation: the commit tail
// whole-row-saves, and an unserialized concurrent follow could otherwise be
// rolled back (or adopt a half-published sibling of this very rotation).
let lock = super::realtime::follow_lock(cid);
let _guard = lock.lock().await;
// Read whole before the rotation replaces the Guestbook that records them.
let _ = writing::read_whole(transport, community).await;
let away = (*stored_departure_windows(community)).clone();
// Reload the FRESHEST base state: a stale caller struct would address the rotation
// under a superseded root (a base fork with no heal). The community_id is
// self-certifying + stable, so re-loading by it is safe.
let fresh = crate::db::community::load_community_v2(cid)?.ok_or("community gone before re-founding")?;
let community = &fresh;
let owner = community.owner()?;
// CORD-06 §Authority: a Refounding requires the BAN permission and the rotator
// must strictly OUTRANK every removed target — the owner is supreme (BAN ⊂
// owner). Mirrors the receive counterpart (`advance_scope::base_rotator_ok`)
// and the banlist authority fold: any admin holding BAN may re-found, checked
// against the folded Roster. Fail-closed — an empty/unauthorized roster leaves
// only the owner able to re-found.
{
let owner_hex = owner.to_hex();
let me_hex = my_pk.to_hex();
// Persisted (last-folded) roster — the receive side is authoritative, so
// this is a belt-and-suspenders gate. Fail-closed: a stale/empty roster
// collapses to owner-only, which can only OVER-restrict a fresh admin whose
// grant hasn't folded into their own DB (the caller's ban flow folds control
// first). It can never grant authority no one has.
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
let authorized = my_pk == owner
|| (!banned.contains(&me_hex)
&& roster.is_authorized(&me_hex, Some(&owner_hex), crate::community::roles::Permissions::BAN)
&& removed.iter().all(|t| {
roster.can_act_on_member(&me_hex, Some(&owner_hex), &t.to_hex(), crate::community::roles::Permissions::BAN)
}));
if !authorized {
return Err("re-founding requires the BAN permission and outranking every removed member".to_string());
}
}
// Fold the current roster: the opened editions are reused for the compaction (their
// seals re-wrap under the new epoch), and the roster gates which admin-authored
// heads carry forward.
let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)?
.into_iter()
.filter(|(_, f)| f.0 == community.root_epoch.0)
.map(|(entity, f)| (entity, (f.1, f.2, f.3, f.4, f.5)))
.collect();
let current_control = control::ControlPlane::of(community);
// Page the ENTIRE control plane, not just the newest window: the compaction MUST
// carry EVERY committed (floored) entity to the new epoch, so a head buried under a
// flood of newer editions (100 roles + 400 grants already exceeds one page) or a
// head a relay withholds can't silently drop. CORD-06 §3 mandates aborting if the
// Refounder cannot fold all Control Events — a dropped Banlist would unban a member
// at the new epoch a fresh joiner bootstraps.
const UNREAD: &str = "The community's control plane is too deep to read in full right now; re-founding stopped so no member is left behind.";
// Through the wraps held once the store is on, each relay's own read behind them; by
// pages when the store cannot serve it.
let held_wraps = match control_store::mode() {
control_store::Mode::On => whole_wraps_held(transport, community).await.ok(),
_ => None,
};
let opened: Vec<(ParsedEdition, super::stream::OpenedStream)> = match held_wraps {
Some(None) => return Err(UNREAD.to_string()),
Some(Some(wraps)) => {
let mut opened = Vec::with_capacity(wraps.len());
for page in wraps.chunks(FOLLOW_PAGE) {
let _batch = current_control.check_page(&page.iter().collect::<Vec<_>>());
opened.extend(page.iter().filter_map(|w| current_control.open(w).ok()));
}
opened
}
None => {
let mut opened: Vec<(ParsedEdition, super::stream::OpenedStream)> = Vec::new();
let mut seen_wraps: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
let mut oldest: Option<u64> = None;
let mut until: Option<u64> = None;
// Read to EXHAUSTION, not to coverage: an entity with no floor yet (a
// first-ever Banlist published while we were away) is invisible to a
// coverage test, so stopping there could compact it away.
let mut truncated = false;
for page in 0..COMPACT_MAX_PAGES {
// Full: compaction re-wraps the head set it can SEE — a control
// edition (a ban head) reachable only on a minority relay must not be
// compacted away by a partial union.
let query = Query { evidence: crate::community::transport::Evidence::Full, ..plane_page(current_control.pk_hex(), FOLLOW_PAGE, until) };
let wraps = transport.fetch(&query, &community.relays).await?;
let mut fresh = 0usize;
let _batch = current_control.check_page(&wraps.iter().filter(|w| !seen_wraps.contains(&w.id)).collect::<Vec<_>>());
for w in &wraps {
if !seen_wraps.insert(w.id) {
continue;
}
fresh += 1;
let at = w.created_at.as_secs();
if oldest.is_none_or(|o| at < o) {
oldest = Some(at);
}
if let Ok(parsed) = current_control.open(w) {
opened.push(parsed);
}
}
if fresh == 0 {
// `until` is inclusive: a FULL page with nothing new is a same-second
// wall no cursor steps past, so older editions stay unreachable. A
// short page is simply the end of the plane.
truncated = wraps.len() >= FOLLOW_PAGE;
break;
}
until = oldest;
if page + 1 == COMPACT_MAX_PAGES {
truncated = true;
}
}
if truncated {
return Err(UNREAD.to_string());
}
opened
}
};
let prev_epoch = community.root_epoch;
let new_epoch = Epoch(prev_epoch.0.checked_add(1).ok_or("root epoch overflow")?);
let prev_commit = super::derive::epoch_key_commitment(prev_epoch, &community.community_root);
// Mint-or-REUSE the new root, keyed by (scope, new_epoch) and archived BEFORE any
// publish: a retried Refounding re-delivers the SAME root at this epoch/address, so
// it can't double-mint two roots a receiver's correlation dedup would collapse into
// a permanent fork (CORD-06 §3 idempotency). The compaction fetch above straddled
let new_root = mint_or_reuse_rotation_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, new_epoch.0)?;
// Every compliant base rotation mints the split beside the root (CORD-06
// §3) — a legacy community upgrades as a side effect of this Refounding.
// Reserved under the same retry-idempotency: both attempts must deliver ONE
// pair, or staff adopt whichever secret rode the chunk with their locator.
let new_control_root = mint_or_reuse_rotation_key(&cid_hex, crate::community::CONTROL_ROOT_SCOPE, new_epoch.0)?;
let new_control_pk = super::derive::control_signer_group_key(&new_control_root, cid, new_epoch).pk();
// The new epoch's Control plane is SPLIT: wraps sign with the fresh
// control_root-derived signer and encrypt under the new community_root-
// derived read key. Editions are never ALSO mirrored to the legacy-derived
// address — that would re-open exactly the member-writable surface the
// split closes (CORD-06 §3).
let new_control = control::split_write_group(&new_control_root, &new_root, cid, new_epoch);
let at = now_ms();
let at_secs = at / 1000;
// ACQUIRE + COVERAGE GATE (CORD-06 §3 MUST): re-wrap the head of EVERY committed
// (floored) entity under the new epoch — FLOOR-driven, so nothing silently drops,
// including entities the metadata/roster folds don't touch (the invite Registry
// vsk-8, whose coordinate survives the rekey per CORD-05 §5). A floor whose head
// can't be folded (buried past the pager / withheld) ABORTS before any publish.
use std::collections::BTreeMap;
let mut by_eid: BTreeMap<String, Vec<usize>> = BTreeMap::new();
for (i, (e, _)) in opened.iter().enumerate() {
by_eid.entry(crate::simd::hex::bytes_to_hex_32(&e.entity_id)).or_default().push(i);
}
// A held head the Roster now refuses, kept on this device for want of a fallback, is
// not re-founded as if it stood: carry what a reader holding no floor folds instead.
// Carry what this fold decides, never the floor as such: a head the fold steps down
// from, or a banned signer's, would be read on its own at the new epoch.
let eds: Vec<ParsedEdition> = opened.iter().map(|(e, _)| e.clone()).collect();
let decided_authority = fold_authority(community, &eds, &floors);
if !decided_authority.converged {
return Err("re-founding aborted: the roster fold did not settle; no state published".to_string());
}
let decided_control = apply_control_fold(community, &eds, &floors, &decided_authority);
// Authority heads first: a control head never takes an authority entity's place.
let mut decided: std::collections::HashMap<String, [u8; 32]> = decided_control.heads.iter().map(|h| (h.entity_hex.clone(), h.inner_id)).collect();
decided.extend(decided_authority.heads.iter().map(|h| (h.entity_hex.clone(), h.inner_id)));
let (kept, kept_control, settled_absent) = (&decided_authority.carried, &decided_control.kept, &decided_authority.refused);
// For a kept head, a floorless reader's pick (CORD-06 §3), and only one this device's own
// evidence admits too.
let cold: std::collections::HashMap<String, [u8; 32]> = if kept.is_empty() && kept_control.is_empty() {
Default::default()
} else {
let cold_authority = fold_authority(community, &eds, &Floors::default());
if !cold_authority.converged {
return Err("re-founding aborted: the roster fold of a reader holding no floor did not settle; no state published".to_string());
}
let cold_control = apply_control_fold(community, &eds, &Floors::default(), &cold_authority);
let mut cold: std::collections::HashMap<String, [u8; 32]> = cold_control
.heads
.into_iter()
.filter(|h| decided_control.admitted.contains(&h.inner_id))
.map(|h| (h.entity_hex, h.inner_id))
.collect();
cold.extend(cold_authority.heads.into_iter().filter(|h| decided_authority.admitted.contains(&h.inner_id)).map(|h| (h.entity_hex, h.inner_id)));
cold
};
let mut carried: Vec<(FoldedHead, Event, &'static str)> = Vec::new();
for (floor_key, floor) in &floors {
// Re-wrap the AUTHORIZED head — the exact edition the persisted floor commits to,
// signer included: the hash alone would take a copy re-signed under another key.
// The floor advances ONLY to authorized heads (author-aware fold). `fold_head`'s
// version-chain TIP is author-BLIND: a member can seal a forged higher-version
// edition chaining onto the floor, which the tip would carry and honest folders
// then DROP as unauthorized — silently suppressing that role/grant/banlist across
// the refounding. Abort if the committed head isn't served (fail-closed).
if settled_absent.contains(floor_key) {
continue;
}
let pick = if kept.contains(floor_key) || kept_control.contains(floor_key) {
// Refused whole for a floorless reader: nothing stands to carry.
let Some(id) = cold.get(floor_key) else { continue };
Some(*id)
} else {
decided.get(floor_key).copied()
};
let head_idx = match pick {
Some(id) => by_eid.get(floor_key).and_then(|v| v.iter().copied().find(|&i| opened[i].0.inner_id == id)),
None => by_eid.get(floor_key).and_then(|v| v.iter().copied().find(|&i| held_is(floor, &opened[i].0))),
};
let Some(head_idx) = head_idx else {
return Err(format!("re-founding aborted: the committed head of control entity {floor_key} (v{}) was not served; no state published", floor.0));
};
let (head_ed, head_os) = &opened[head_idx];
let h = FoldedHead { entity_hex: floor_key.clone(), version: head_ed.version, self_hash: head_ed.self_hash, inner_id: head_ed.inner_id, author: head_ed.author.to_bytes(), rebased: false };
let (rewrapped, _) = super::stream::rewrap_seal(&head_os.seal, &new_control, Timestamp::from_secs(at_secs)).map_err(|e| e.to_string())?;
carried.push((h, rewrapped, floor_family(&head_ed.vsk)));
}
// And every head the fold decided for an entity this device never floored: a first
// Banlist published while it was away is as current as the rest.
for (entity, id) in &decided {
if floors.contains_key(entity) {
continue;
}
let Some(i) = by_eid.get(entity).and_then(|v| v.iter().copied().find(|&i| opened[i].0.inner_id == *id)) else { continue };
let (head_ed, head_os) = &opened[i];
let h = FoldedHead { entity_hex: entity.clone(), version: head_ed.version, self_hash: head_ed.self_hash, inner_id: head_ed.inner_id, author: head_ed.author.to_bytes(), rebased: false };
let (rewrapped, _) = super::stream::rewrap_seal(&head_os.seal, &new_control, Timestamp::from_secs(at_secs)).map_err(|e| e.to_string())?;
carried.push((h, rewrapped, floor_family(&head_ed.vsk)));
}
// A sync is judged against the Category its predecessor names, so that predecessor
// crosses beside it. The floor stays on the head.
let mut beside: Vec<Event> = Vec::new();
for (h, _, _) in &carried {
let Some(group) = by_eid.get(&h.entity_hex) else { continue };
let Some(head) = group.iter().map(|&i| &opened[i].0).find(|e| e.inner_id == h.inner_id) else { continue };
let (true, Some(prev)) = (head.vsk == vsk::CHANNEL_SYNC, head.prev_hash) else { continue };
// Compacted away before predecessors crossed: readers will refuse this sync either way.
let Some(&pi) = group.iter().find(|&&i| opened[i].0.self_hash == prev) else {
crate::log_warn!("[v2:refound] channel sync {} crosses without its predecessor", h.entity_hex);
continue;
};
let (rewrapped, _) = super::stream::rewrap_seal(&opened[pi].1.seal, &new_control, Timestamp::from_secs(at_secs)).map_err(|e| e.to_string())?;
beside.push(rewrapped);
}
// The Timeouts to carry, read after the Guestbook catches up so a lift this device
// hasn't seen yet isn't undone.
let _ = sync_guestbook(transport, community).await;
let running_timeouts = community_timeouts(community).unwrap_or_default();
let nicknames = standing_nicknames(community).unwrap_or_default();
// Recipients: the current members minus `removed`, plus me (multi-device).
//
// UNION of the network fold and the LOCAL memberlist. The network fold only
// observes the recent window, so a quiet member whose Join lives on a buried
// epoch falls out of it — and out of the key set and snapshot — on every
// rotation. Five rotations in one evening shed 39 real members that way, each
// left wedged at the hop that first forgot them. Locally-known members are
// vended keys too; being forgotten is not a removal, only `removed` is.
let members = memberlist(transport, community).await?;
let removed_set: std::collections::HashSet<[u8; 32]> = removed.iter().map(|p| p.to_bytes()).collect();
let net_len = members.len();
let mut union: std::collections::BTreeSet<PublicKey> = members.into_iter().collect();
let local = stored_memberlist(community)?;
let local_len = local.len();
union.extend(local);
let mut recipients: Vec<PublicKey> = union.into_iter().filter(|m| !removed_set.contains(&m.to_bytes())).collect();
if !recipients.contains(&my_pk) {
recipients.push(my_pk);
}
// The freshest roster reachable, for two per-recipient decisions below:
// channel entitlement AND staff-ness (who receives the 136-byte blob).
// Entitlement must come from a CURRENT roster, not the last-folded cache:
// the base recipients above are a fresh network fold, and mixing the two
// strands anyone granted since this client last folded — they keep a dead
// key and the new epoch's rekey plane carries no blob for them. Fetched,
// then merged over the cache so a role we published ourselves survives too.
let mut roster_for_channels = fetch_authority(transport, community).await.roles;
{
let cached = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
for r in cached.roles {
if !roster_for_channels.roles.iter().any(|x| x.role_id == r.role_id) {
roster_for_channels.roles.push(r);
}
}
for g in cached.grants {
if !roster_for_channels.grants.iter().any(|x| x.member == g.member) {
roster_for_channels.grants.push(g);
}
}
}
let owner_hex_for_channels = community.owner().ok().map(|o| o.to_hex());
// Operator purge: vend ONLY to the chosen list.
//
// Not a time test — a hard allow-list, so an account that arrived between the
// operator's selection and this fetch is excluded by NOT BEING ON IT, with no
// window to slip through and nothing to backdate. Owner and this device are
// always kept: a purge must not orphan the community or lock out the operator
// running it.
if let Some(allow) = allow_only {
let allowed: std::collections::HashSet<[u8; 32]> = allow.iter().map(|p| p.to_bytes()).collect();
let before = recipients.len();
recipients.retain(|r| {
*r == my_pk
|| Some(r.to_hex()) == owner_hex_for_channels
|| allowed.contains(&r.to_bytes())
});
let dropped = before.saturating_sub(recipients.len());
if dropped > 0 {
crate::log_info!(
"[Refound {}] purge: {} member(s) not on the retain list vended no key",
&cid_hex[..8.min(cid_hex.len())], dropped
);
}
}
// Containment: vend no key to anyone who walked in DURING the raid.
//
// `removed` is a list computed at one instant; the recipient set above is a
// LIVE fetch taken later, and re-taken on every retry. A bot joining in that
// gap lands in the memberlist, misses the list, and is handed a working key
// for the epoch meant to evict it. Testing the join TIME instead of matching a
// frozen list is immune to when the fetch happens: a later read only surfaces
// more late joiners, and each one fails the same test.
//
// Positive evidence only. No Join on the reachable guestbook means OLD (or
// buried), never "new" — and an unreadable guestbook filters nobody, because
// failing closed here would evict the whole community on one bad read.
if joined_after_cut > 0 {
match fetch_guestbook_events(transport, community, 0).await {
Ok((events, _, _)) => {
// A Join's `at_ms` is written by its author, so a raider can
// backdate under any window computed from it. What this client
// WATCHED arrive, they cannot forge — but only if we were already
// following before the window opened. A client that started
// watching later sees everyone as new, and trusting it would evict
// the whole community.
let watched = guestbook_observed_since(&cid_hex).is_some_and(|since| since < joined_after_cut);
let (held, _) = crate::db::community::get_guestbook(&cid_hex).unwrap_or_default();
let first_seen = earliest_arrivals(&events, &held, watched, |pk| {
Some(pk.to_hex()) == owner_hex_for_channels
|| roster_for_channels.is_authorized(
&pk.to_hex(),
owner_hex_for_channels.as_deref(),
crate::community::roles::Permissions::BAN,
)
});
let before = recipients.len();
recipients.retain(|r| {
if *r == my_pk || Some(r.to_hex()) == owner_hex_for_channels {
return true;
}
// A moderator who joined moments before a raid is still a moderator.
if roster_for_channels.is_staff(&r.to_hex(), owner_hex_for_channels.as_deref()) {
return true;
}
first_seen.get(r).is_none_or(|joined| *joined < joined_after_cut)
});
let dropped = before.saturating_sub(recipients.len());
if dropped > 0 {
crate::log_info!(
"[Refound {}] containment: {} raid-window joiner(s) vended no key",
&cid_hex[..8.min(cid_hex.len())], dropped
);
}
}
Err(e) => crate::log_warn!(
"[Refound {}] guestbook unreadable — raid-window joiners NOT filtered, only the named cut is severed ({e})",
&cid_hex[..8.min(cid_hex.len())]
),
}
}
// STAFF COVERAGE GATE: a granted member who is not a recipient would be
// stranded at this hop for good — they can only ever derive `held + 1`, so
// no later rotation reaches them, while every other client still reads them
// as staff. That is silent and permanent, and it happened: an admin holding
// a valid grant was vended no key and only surfaced because a human noticed
// the member list had shrunk.
//
// A grant is consensus-complete proof of membership — the same claim
// `fold_members` makes when it counts granted members "even if their Join
// aged out of the Guestbook entirely". So the recipients must cover them.
// Refusing here matches the entity carry-forward directly above, which
// ABORTS rather than publish a rotation that drops a floored head: better a
// rotation that did not happen than one that quietly severs the staff.
//
// Only the CUT are exempt — removing someone is the one thing a rotation is
// allowed to do to them.
{
// A banned member is not owed a key; every other grant-holder is.
let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
let missing: Vec<String> = roster_for_channels
.grants
.iter()
.filter(|g| !g.role_ids.is_empty())
.filter_map(|g| PublicKey::from_hex(&g.member).ok())
.filter(|pk| !removed_set.contains(&pk.to_bytes()))
.filter(|pk| !banned.contains(&pk.to_hex()))
.filter(|pk| !recipients.contains(pk))
.map(|pk| pk.to_hex())
.collect();
if !missing.is_empty() {
// The counts ride the message: which of the two folds lost them is
// the whole diagnosis, and a refusal that does not say leaves the
// next person guessing exactly as long as this one did.
return Err(format!(
"re-founding aborted: {} granted member(s) would be vended no key and stranded at epoch {} — {}; \
recipients={} (network fold {}, local fold {}); no state published",
missing.len(),
prev_epoch.0,
missing.iter().map(|h| h[..8.min(h.len())].to_string()).collect::<Vec<_>>().join(", "),
recipients.len(),
net_len,
local_len
));
}
}
// Base rekey blobs, sealed under the PRIOR root: every member's carries the
// new root + control_pk (104 bytes); a STAFF recipient's (CORD-04 §3)
// appends the control_root itself (136) — the rotator is staff by
// construction (a Refounding takes BAN). A stale-roster overshoot hands a
// just-demoted member only flooding power until the next rotation, the
// spec's accepted erosion; an undershoot self-heals via the Grant's
// control_wrap re-delivery.
let mut base_blobs = Vec::new();
for r in &recipients {
let staff = *r == my_pk || roster_for_channels.is_staff(&r.to_hex(), owner_hex_for_channels.as_deref());
base_blobs.push(
super::rekey::build_base_blob(&signer, &my_pk.to_bytes(), r, new_epoch, &new_root, &new_control_pk.to_bytes(), staff.then_some(&new_control_root))
.await
.map_err(|e| e.to_string())?,
);
}
let base_group = super::derive::base_rekey_group_key(&community.community_root, cid, new_epoch);
let base_chunks =
super::rekey::build_rekey_chunks(&signer, my_pk, &base_group, super::rekey::RekeyScope::Root, new_epoch, prev_epoch, &prev_commit, &base_blobs, at_secs, my_authority_citation(community, &my_pk).as_ref(), sever)
.await
.map_err(|e| e.to_string())?;
// Private-channel rekeys: each mints a fresh key at its next channel-epoch, sealed
// under the PRIOR root (D2). Public channels ride the base — no per-channel rekey.
//
// Each private channel goes only to ITS entitled set, never the base recipient
// list: a Refounding that re-broadcast every private key to every member would
// undo the access lists on every rotation (CORD-03).
let mut channel_updates: Vec<(ChannelId, [u8; 32], Epoch)> = Vec::new();
let mut channel_chunk_sets: Vec<Vec<Event>> = Vec::new();
for ch in &community.channels {
let (Some(old_key), true) = (ch.key, ch.private) else { continue };
let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
let entitled: Vec<PublicKey> = recipients
.iter()
.copied()
.filter(|r| {
*r == my_pk
|| roster_for_channels.is_entitled(owner_hex_for_channels.as_deref(), &r.to_hex(), &ch_hex, &[], &[])
})
.collect();
let ch_new_epoch = Epoch(ch.epoch.0.checked_add(1).ok_or("channel epoch overflow")?);
// Mint-or-reuse per channel too, keyed by (channel_id, next epoch) — same
// retry-idempotency as the base root. The base-rekey signing above is a bunker
// round-trip; re-check before this per-channel DB write straddles it.
let ch_new_key = mint_or_reuse_rotation_key(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&ch.id.0), ch_new_epoch.0)?;
let ch_prev_commit = super::derive::epoch_key_commitment(ch.epoch, &old_key);
let mut ch_blobs = Vec::new();
for r in &entitled {
ch_blobs.push(
super::rekey::build_blob(&signer, &my_pk.to_bytes(), r, super::rekey::RekeyScope::Channel(ch.id), ch_new_epoch, &ch_new_key)
.await
.map_err(|e| e.to_string())?,
);
}
let ch_group = super::derive::channel_rekey_group_key(&community.community_root, &ch.id, ch_new_epoch);
let ch_chunks = super::rekey::build_rekey_chunks(&signer, my_pk, &ch_group, super::rekey::RekeyScope::Channel(ch.id), ch_new_epoch, ch.epoch, &ch_prev_commit, &ch_blobs, at_secs, my_authority_citation(community, &my_pk).as_ref(), false)
.await
.map_err(|e| e.to_string())?;
channel_updates.push((ch.id, ch_new_key, ch_new_epoch));
channel_chunk_sets.push(ch_chunks);
}
// COMMIT (durable publishes only — all fetching is done). Base rekey first
// (delivers the new root), then channel rekeys, then the compacted control.
for c in &base_chunks {
transport.publish_durable(c, &community.relays).await?;
}
for set in &channel_chunk_sets {
for c in set {
transport.publish_durable(c, &community.relays).await?;
}
}
for wrap in carried.iter().map(|(_, w, _)| w).chain(&beside) {
transport.publish_durable(wrap, &community.relays).await?;
}
// Guestbook snapshot at the new epoch — best-effort (a Refounding succeeds without
// it; an omitted member heals by publishing their own Join).
let gb_group = super::derive::guestbook_group_key(&new_root, cid, new_epoch);
let snap_id = crate::community::random_32();
for rumor in guestbook::build_snapshot_rumors(my_pk, &recipients, snap_id, at) {
if let Ok((wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(at_secs)).await {
let _ = transport.publish(&wrap, &community.relays).await;
}
}
// A running Timeout lives on the old Guestbook: the refounder re-issues, in its own
// name, those it may issue itself, dated as issued so a later lift still wins and the
// window doesn't move. Best-effort, like the snapshot.
let owner_hex = community.owner()?.to_hex();
let citation = required_authority_citation(community, &my_pk).ok().flatten();
for (target, (from, until)) in running_timeouts {
if removed_set.contains(&target.to_bytes())
|| !decided_authority.roles.can_act_on_member(&my_pk.to_hex(), Some(&owner_hex), &target.to_hex(), crate::community::roles::Permissions::MODERATE_MEMBERS)
{
continue;
}
let rumor = guestbook::build_timeout_rumor(my_pk, target, until, citation.as_ref(), from * 1000);
if let Ok((wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(at_secs)).await {
let _ = transport.publish_durable(&wrap, &community.relays).await;
}
}
// Nicknames someone set for another member, each it could set itself, to the
// millisecond. A member's own stands on their own word, so their client carries it.
for (target, n) in nicknames {
if n.actor == target || target == my_pk || !recipients.contains(&target) || !decided_authority.roles.may_name(&my_pk.to_hex(), Some(&owner_hex), &target.to_hex()) {
continue;
}
let rumor = guestbook::build_nickname_rumor(my_pk, target, &n.nick, citation.as_ref(), n.at_ms);
if let Ok((wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(at_secs)).await {
let _ = transport.publish_durable(&wrap, &community.relays).await;
}
}
// COMMIT locally, only now that the new root + compacted plane are on relays.
if !crate::db::community::community_held(cid)? {
return Ok(community.clone()); // left/deleted mid-rotation — don't resurrect.
}
// Save the new root/epoch + rekeyed channel keys in ONE tx FIRST, so a crash can
// never leave the base root advanced while the channel keys lag (which would
// re-derive the channel rekey address under the wrong root and orphan them).
let mut updated = community.clone();
updated.community_root = new_root;
updated.root_epoch = new_epoch;
updated.control_pk = Some(new_control_pk);
updated.control_root = Some(new_control_root);
for (id, key, ep) in &channel_updates {
if let Some(c) = updated.channels.iter_mut().find(|c| c.id.0 == id.0) {
c.key = Some(*key);
c.epoch = *ep;
}
}
crate::db::community::save_community_v2(&updated)?;
for wrap in carried.iter().map(|(_, w, _)| w).chain(&beside) {
hold_wrap(&updated, wrap);
}
archive_control_address(&cid_hex, community.root_epoch.0, community.control_pk.as_ref());
archive_control_address(&cid_hex, new_epoch.0, updated.control_pk.as_ref());
// Archive the new epoch key + confirm the monotonic base head (the root was already
// archived by mint_or_reuse, so this is idempotent). Record the carried heads at
// the NEW epoch; if a crash skips this, the epoch-filtered floors bootstrap the
// compacted control on the next follow, so they self-heal.
crate::db::community::advance_server_root_epoch(&cid_hex, new_epoch.0, &new_root)?;
for (h, _, family) in &carried {
crate::db::community::set_family_head_at_epoch(&cid_hex, &h.entity_hex, h.version, &h.self_hash, &h.inner_id, &h.author, new_epoch.0, family)?;
}
// Re-subscribe NOW: the rotation changed every plane author, and the live sub
// still carries the OLD epoch's set. Members adopt via the follow worker
// (which refreshes); the REFOUNDER has no such path — without this, the very
// client that performed the ban goes deaf to the new epoch (a rejoin lands on
// the relays and never arrives live).
if let Some(client) = crate::state::nostr_client() {
super::realtime::refresh_subscription(&client).await;
}
// We minted this epoch, so our own snapshot is what seeds it (CORD-02 §5).
// Recorded here so the local fold agrees with every follower's without
// waiting to adopt our own rotation back off the wire.
record_epoch_minter(&cid_hex, new_epoch.0, &my_pk.to_hex());
if sever {
// Severing: the mark persists FIRST (a crash between it and the revoke
// must retry, not forget — B4), then my own links are tombstoned. Other
// creators' links die when their clients adopt the marked rotation.
add_sever_mark(&cid_hex, new_epoch.0, at_secs);
for attempt in 0..3u8 {
match sever_own_links(transport, &updated).await {
Ok(_) => break,
Err(e) if attempt == 2 => {
crate::log_warn!("v2: post-severing link revocation failed after retries ({e}); the sever mark retries it on the next follow");
}
Err(_) => continue,
}
}
} else {
// Refresh any live public links so their bundles carry the NEW root behind the
// same URL (a link shared once survives the rotation, CORD-05 §2). Idempotent,
// so retry a transient failure — a stranded link lands a new joiner on the dead
// pre-refound epoch, and there's no other trigger to heal it before the next
// refounding. A persistent failure is logged (refound already succeeded).
for attempt in 0..3u8 {
match refresh_public_links(transport, &updated).await {
Ok(()) => break,
Err(e) if attempt == 2 => {
crate::log_warn!("v2: post-refounding public-link refresh failed after retries ({e}); live links may serve the prior root until the next refresh");
}
Err(_) => continue,
}
}
}
for (id, ..) in &channel_updates {
reseal_rotated(transport, &updated, id).await;
}
// A restricted Channel's writer key may be held by those this Refounding removed.
writing::retire_after_refounding(transport, &updated, &away).await;
Ok(updated)
})
.await
}
/// Mint a fresh 32-byte rotation key for `(scope, new_epoch)`, or REUSE the one
/// already archived from a prior (aborted) attempt — so a retried Refounding re-
/// delivers the SAME key at the same epoch/address instead of double-minting two roots
/// a receiver's correlation dedup would collapse into a permanent fork (CORD-06 §3
/// idempotency). Archived BEFORE the first publish; `scope` is the all-zero server-root
/// sentinel for a base rotation, else the channel_id hex.
fn mint_or_reuse_rotation_key(community_id_hex: &str, scope_hex: &str, new_epoch: u64) -> Result<[u8; 32], String> {
if let Some(existing) = crate::db::community::held_epoch_key(community_id_hex, scope_hex, new_epoch)? {
return Ok(existing);
}
let fresh = crate::community::random_32();
crate::db::community::store_epoch_key(community_id_hex, scope_hex, new_epoch, &fresh)?;
Ok(fresh)
}
// ── The Community List (kind 33302, CORD-02 §8) ──────────────────────────────
/// This community's MEMBERSHIP subset for the Community List (CORD-02 §8): never the
/// icon (a rehydrating device folds it from the Control Plane), never the link
/// fields. Only PRIVATE channel keys ride — public channels derive from the root.
fn join_material(community: &CommunityV2) -> super::list::JoinMaterial {
let hex = crate::simd::hex::bytes_to_hex_32;
let channels = community
.channels
.iter()
.filter(|c| c.private)
// Keyed channels ONLY. A keyless entry is readable by this build but is
// rejected outright by shipped ones (their `key` is a required String),
// so emitting one would strand every older client on a stale list.
.filter_map(|c| {
c.key.map(|k| super::list::ChannelKeyRef { id: hex(&c.id.0), key: Some(hex(&k)), epoch: c.epoch.0, name: c.name.clone(), extra: Default::default() })
})
.collect();
super::list::JoinMaterial {
community_id: hex(&community.identity.community_id.0),
owner: hex(&community.identity.owner_xonly),
owner_salt: hex(&community.identity.owner_salt),
community_root: hex(&community.community_root),
root_epoch: community.root_epoch.0,
control_pk: community.control_pk.map(|p| p.to_hex()),
// The list carries every private key its holder has (CORD-02 §8) — a
// staffer's own devices must be able to write. Same trust class as the
// community_root beside it: NIP-44-encrypted to self.
control_root: community.control_root.map(|r| hex(&r)),
channels,
relays: community.relays.clone(),
name: community.name.clone(),
rev: 0,
extra: Default::default(),
}
}
/// Our snapshot as this write publishes it: what this device holds, merged with the
/// same epoch's copy it read, one revision past that copy when the merge changes
/// anything (CORD-02 §8).
///
/// The merge is what makes revisions safe: a newer revision wins outright, so a
/// device behind its sibling — a channel key it has not received, a staff key, a
/// peer client's own fields (Armada's `priors` are retired keys) — would otherwise
/// publish its smaller view one revision up and erase them everywhere. Only names
/// and relays are ours to overwrite: both come from this device's Control fold.
/// Across a Refounding the read copy is a different snapshot and nothing is merged.
fn rebuild_snapshot(mut ours: super::list::JoinMaterial, theirs: Option<&super::list::JoinMaterial>) -> super::list::JoinMaterial {
let Some(theirs) = theirs else {
ours.channels.sort_by(|a, b| a.id.cmp(&b.id));
return ours;
};
if theirs.root_epoch == ours.root_epoch {
if ours.control_root.is_none() && ours.control_pk == theirs.control_pk {
ours.control_root = theirs.control_root.clone();
}
for t in &theirs.channels {
let Some(c) = ours.channels.iter_mut().find(|c| c.id == t.id) else {
ours.channels.push(t.clone());
continue;
};
if t.epoch > c.epoch {
c.epoch = t.epoch;
c.key = t.key.clone();
} else if t.epoch == c.epoch && c.key.is_none() {
c.key = t.key.clone();
}
if t.epoch == c.epoch {
for (k, v) in &t.extra {
c.extra.entry(k.clone()).or_insert_with(|| v.clone());
}
}
}
for (k, v) in &theirs.extra {
ours.extra.entry(k.clone()).or_insert_with(|| v.clone());
}
}
// One canonical order, or two devices read each other's copies as changes.
ours.channels.sort_by(|a, b| a.id.cmp(&b.id));
let unrevised = |jm: &super::list::JoinMaterial| {
let mut jm = jm.clone();
jm.rev = 0;
jm.channels.sort_by(|a, b| a.id.cmp(&b.id));
jm
};
ours.rev = if unrevised(&ours) == unrevised(theirs) {
theirs.effective_rev()
} else {
theirs.effective_rev() + 1
};
ours
}
/// Rebuild an invite bundle from list join material, for a cross-device rehydrate
/// (the material IS the membership subset of a bundle). The owner root is still
/// verified over the network before the community is trusted (accept_bundle).
fn material_to_invite(jm: &super::list::JoinMaterial) -> CommunityInvite {
// A keyless listing records that the channel EXISTS, not a grant — there is
// nothing to seat, and it keys up when access is granted.
let channels = jm
.channels
.iter()
.filter_map(|c| {
c.key.as_ref().map(|k| invite::ChannelGrant { id: c.id.clone(), key: k.clone(), epoch: c.epoch, name: c.name.clone() })
})
.collect();
CommunityInvite {
community_id: jm.community_id.clone(),
owner: jm.owner.clone(),
owner_salt: jm.owner_salt.clone(),
community_root: jm.community_root.clone(),
root_epoch: jm.root_epoch,
control_pk: jm.control_pk.clone(),
channels,
relays: jm.relays.clone(),
name: jm.name.clone(),
icon: None,
expires_at: None,
creator_npub: None,
label: None,
extra: Default::default(),
}
}
/// The account's OWN relays — where an account-level list belongs. Published to a
/// community's relays instead, the list stops being readable the moment that
/// community is left, which is exactly when its tombstone has to be found.
/// Empty without a client (tests), where the caller falls back to the held set.
async fn own_list_relays() -> Vec<String> {
let Some(client) = crate::state::nostr_client() else { return Vec::new() };
client
.relays()
.await
.iter()
.filter(|(_, r)| r.capabilities().load().can_write())
.map(|(url, _)| url.to_string())
.collect()
}
/// Read the list from everywhere a copy could be: our own relays, the stock CORD
/// set (where it lands when ours refuse the kind), and the held communities'
/// (where every list published before the move still lives). Missing one of these
/// reads a stale copy and republishes it over a newer tombstone.
async fn list_read_relays(extra: &[String]) -> Vec<String> {
let mut set = own_list_relays().await;
set.extend(invite::stock_relays());
set.extend(held_v2_relays());
set.extend(extra.iter().cloned());
set.sort();
set.dedup();
set
}
/// What a fragment fetch found: the unioned list, and each index's `created_at`
/// so the next write to that fragment can exceed it.
pub struct FragSet {
pub list: super::list::CommunityList,
pub created_at: std::collections::BTreeMap<usize, u64>,
/// `frags` as declared by the newest fragment seen.
pub declared: usize,
/// The winning parsed fragment per index — what the relays currently hold,
/// so a rewrite can skip publishing byte-identical fragments.
pub read_frags: std::collections::BTreeMap<usize, super::list_frag::FragList>,
/// The winning signed event per index and the relays that returned it, so an unchanged
/// fragment still reaches a relay that lacks it.
pub on_relays: std::collections::BTreeMap<usize, (Event, Vec<String>)>,
}
impl FragSet {
/// Coverage, not agreement: we hold every index below `declared`, whatever
/// their individual ages. A short read is read-only, never a write.
pub fn is_complete(&self) -> bool {
(0..self.declared).all(|i| self.created_at.contains_key(&i))
}
}
/// One read of the list: what it found, and which relays actually answered it.
struct FragRead {
set: Option<FragSet>,
/// Relays that answered (EOSE). A write goes only here: a relay we didn't hear from may
/// hold a newer copy, and a newer `created_at` would replace it unseen.
answered: Vec<String>,
/// A fragment that wouldn't open: it may be the newest copy, so no write may build on
/// this read.
unreadable: bool,
}
/// Fetch the account's 33302 fragments and union them. Newest wins PER INDEX —
/// each fragment is its own addressable coordinate, so they age independently.
async fn fetch_fragments<T: Transport + ?Sized>(transport: &T, relays: &[String]) -> Result<Option<FragSet>, String> {
read_fragments(transport, relays).await.map(|r| r.set)
}
/// Read the list from every relay, each asked on its own and waited for: a read that stops at
/// the first answer can be a relay holding nothing, or a stale copy, and a write built on it
/// replaces the real list everywhere. Every readable version is merged (the List is a CRDT:
/// a stale copy can't revive what a newer one removed), so one relay's copy never hides
/// another's tombstone.
async fn read_fragments<T: Transport + ?Sized>(transport: &T, relays: &[String]) -> Result<FragRead, String> {
let signer = crate::signer::active_signer()?;
let my_pk = me_pk()?;
let query = Query {
kinds: vec![super::kind::COMMUNITY_LIST_FRAG],
authors: vec![my_pk.to_hex()],
limit: Some(64),
..Default::default()
};
let per_relay = futures_util::future::join_all(
relays.iter().map(|r| async { (r.clone(), transport.fetch(&query, std::slice::from_ref(r)).await) }),
)
.await;
let mut answered = Vec::new();
let mut holders: std::collections::HashMap<nostr_sdk::prelude::EventId, Vec<String>> = Default::default();
let mut events = Vec::new();
for (relay, res) in per_relay {
if let Ok(evs) = res {
for e in evs {
let held_by = holders.entry(e.id).or_default();
if held_by.is_empty() {
events.push(e);
}
held_by.push(relay.clone());
}
answered.push(relay);
}
}
// Folded oldest first, so where versions disagree on an unmerged field the newest
// has the last word whatever order the relays answered in.
events.sort_by(|a, b| (a.created_at, a.id).cmp(&(b.created_at, b.id)));
if answered.is_empty() {
return Err(format!("no relay answered the list read (0/{})", relays.len()));
}
if events.is_empty() {
return Ok(FragRead { set: None, answered, unreadable: false });
}
let mut newest: std::collections::BTreeMap<usize, (u64, [u8; 32], super::list_frag::FragList)> = Default::default();
let mut newest_event: std::collections::BTreeMap<usize, Event> = Default::default();
let mut list = super::list::CommunityList::default();
// Unreadable versions by index: they matter only if one could be the newest.
let mut unopened: Vec<(usize, u64)> = Vec::new();
for e in events {
let at = e.created_at.as_secs();
let id = *e.id.as_bytes();
// Not one of our fragment coordinates: nothing we read or write, so nothing to block.
let Some(index) = e.tags.identifier().and_then(|d| d.parse::<usize>().ok()) else { continue };
match super::list_frag::parse_fragment_event(&signer, my_pk, &e).await {
Ok((index, frag)) => {
list = list.merge(&super::list_frag::defragment(std::slice::from_ref(&frag)));
// Mirror relay resolution (CORD-02 §8): newest created_at holds the
// coordinate, an age tie falls to the LOWEST event id.
let wins = match newest.get(&index) {
None => true,
Some((prev_at, prev_id, _)) => at > *prev_at || (at == *prev_at && id < *prev_id),
};
if wins {
newest.insert(index, (at, id, frag));
newest_event.insert(index, e);
}
}
Err(_) => unopened.push((index, at)),
}
}
// An older copy that won't open is history; one at or past the newest we read may be the
// current list, and writing over it unseen is the loss this read exists to prevent.
let blocking = unopened.iter().filter(|(i, at)| newest.get(i).is_none_or(|(n, _, _)| at >= n)).count();
if blocking > 0 {
crate::log_warn!("[CommunityList] {} current fragment(s) would not open — reading what did, refusing to write", blocking);
}
if newest.is_empty() {
return Ok(FragRead { set: None, answered, unreadable: blocking > 0 });
}
// Fragment-level unknowns belong to the List, not the version fold: each index
// speaks through its newest copy, and the lowest index wins a key (CORD-02 §8).
list.extra = Default::default();
for (_, _, frag) in newest.values() {
for (k, v) in &frag.extra {
list.extra.entry(k.clone()).or_insert_with(|| v.clone());
}
}
// The newest fragment governs `frags`; an age tie resolves to the LARGER count
// (CORD-02 §8) — too large reads an index that turns out empty, too small sends
// live fragments out of range and dormant.
let declared = newest
.values()
.max_by_key(|(at, _, f)| (*at, f.frags))
.map(|(_, _, f)| f.frags)
.unwrap_or(1)
.max(1);
let read_frags: std::collections::BTreeMap<usize, super::list_frag::FragList> =
newest.iter().map(|(i, (_, _, f))| (*i, f.clone())).collect();
let on_relays = newest_event
.into_iter()
.map(|(i, e)| {
let held_by = holders.remove(&e.id).unwrap_or_default();
(i, (e, held_by))
})
.collect();
let set = FragSet {
list,
created_at: newest.iter().map(|(i, (at, _, _))| (*i, *at)).collect(),
declared,
read_frags,
on_relays,
};
if !set.is_complete() {
crate::log_warn!(
"[CommunityList] INCOMPLETE: hold {} of {} fragment(s) — reading, refusing to write",
set.created_at.len(),
declared
);
}
Ok(FragRead { set: Some(set), answered, unreadable: blocking > 0 })
}
/// Publish a list as fragments. Each fragment's `created_at` must exceed that
/// fragment's own previous value — relays resolve an addressable event on
/// `created_at` alone and break a tie on the lowest event id, so a same-second
/// rewrite can silently discard the newer content.
async fn publish_fragments<T: Transport + ?Sized>(
transport: &T,
list: &super::list::CommunityList,
prev: &std::collections::BTreeMap<usize, u64>,
read: &std::collections::BTreeMap<usize, super::list_frag::FragList>,
on_relays: &std::collections::BTreeMap<usize, (Event, Vec<String>)>,
targets: &ListTargets,
) -> Result<usize, String> {
let signer = crate::signer::active_signer()?;
let my_pk = me_pk()?;
let frags = super::list_frag::fragment(list);
let now = now_ms() / 1000;
// A fragment serializing to the bytes we just read is already on the relay:
// republishing it only churns created_at — and hands a same-second sibling
// write a lowest-id coin-flip it didn't need to enter.
let unchanged = |index: usize, frag: &super::list_frag::FragList| -> bool {
let Some(old) = read.get(&index) else { return false };
matches!(
(serde_json::to_string(old), serde_json::to_string(frag)),
(Ok(a), Ok(b)) if a == b
)
};
// Persisted, not level-gated: a List write that silently never lands is the failure
// mode this whole format exists to end, and it is only ever diagnosed after the fact.
crate::log_net_info!(
"[CommunityList] publishing {} fragment(s): {} live entries ({} retired), {} tombstones",
frags.len(),
frags.iter().map(|f| f.entries.len()).sum::<usize>(),
list.entries.len() - frags.iter().map(|f| f.entries.len()).sum::<usize>(),
frags.iter().map(|f| f.tombstones.len()).sum::<usize>(),
);
let mut skipped = 0usize;
for (index, frag) in frags.iter().enumerate() {
if unchanged(index, frag) {
skipped += 1;
spread_unchanged(transport, on_relays.get(&index), targets).await;
continue;
}
let created_at = now.max(prev.get(&index).copied().unwrap_or(0) + 1);
let event = super::list_frag::build_fragment_event(&signer, my_pk, frag, index, created_at).await?;
publish_list_event(transport, &event, targets).await?;
}
// A shrunk set leaves the fragments above it in place; empty them so a later
// growth into that index cannot re-read stale memberships.
for index in frags.len()..prev.len() {
let empty = super::list_frag::FragList {
frags: frags.len(),
entries: vec![],
tombstones: vec![],
extra: Default::default(),
};
if unchanged(index, &empty) {
skipped += 1;
spread_unchanged(transport, on_relays.get(&index), targets).await;
continue;
}
let created_at = now.max(prev.get(&index).copied().unwrap_or(0) + 1);
let event = super::list_frag::build_fragment_event(&signer, my_pk, &empty, index, created_at).await?;
publish_list_event(transport, &event, targets).await?;
}
if skipped > 0 {
crate::log_net_info!("[CommunityList] {} fragment(s) skipped — byte-identical to the relay copy", skipped);
}
Ok(frags.len())
}
/// Publish an account-level list, falling back to the stock CORD relays when our
/// own reject it — 33302 is a custom kind, and a relay with a kind whitelist drops
/// it silently. The list is the vault: it has to land somewhere every client reads.
/// Held across a list write's whole read, merge and publish. Two overlapping writes read the
/// same version and publish in the same second, and a relay keeps only one of them.
static LIST_WRITE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
/// The list write lock, waited for (a background retry) or only if free (a user action,
/// which hands off to the background rather than queue behind someone else's write).
async fn list_write_turn(wait: bool) -> Option<tokio::sync::MutexGuard<'static, ()>> {
if wait { Some(LIST_WRITE.lock().await) } else { LIST_WRITE.try_lock().ok() }
}
const LIST_BUSY: &str = "another list write is in flight";
/// Our own leaves still on their way, as tombstones a write carries along: one write lands
/// every leave queued behind it.
fn pending_tombstones() -> super::list::CommunityList {
let tombstones = load_pending()
.tombstones
.into_iter()
.map(|t| super::list::Tombstone { community_id: t.community_id, removed_at: t.removed_at, extra: Default::default() })
.collect();
super::list::CommunityList { tombstones, ..Default::default() }
}
/// Drop every pending leave and join the relays now show.
fn settle_pending(landed: &super::list::CommunityList) {
edit_pending(|p| {
p.tombstones.retain(|t| !landed.tombstones.iter().any(|l| l.community_id == t.community_id && l.removed_at >= t.removed_at));
p.joins.retain(|j| !landed.entries.iter().any(|e| e.community_id == j.community_id && e.added_at >= j.joined_at));
});
}
/// Where a list write goes: our own relays and the stock set, each only if it answered the
/// read the write was built on (a relay we didn't hear from may hold a newer copy, and a newer
/// `created_at` would replace it unseen). Both, always: the stock set is in every device's read
/// set where our own relays may not be, and a relay can accept a kind it then discards.
struct ListTargets {
own: Vec<String>,
fallback: Vec<String>,
}
impl ListTargets {
fn new(own: Vec<String>, answered: &[String]) -> Self {
let pick = |set: Vec<String>| -> Vec<String> { set.into_iter().filter(|r| answered.contains(r)).collect() };
ListTargets { own: pick(own), fallback: pick(invite::stock_relays()) }
}
fn is_empty(&self) -> bool {
self.own.is_empty() && self.fallback.is_empty()
}
}
async fn publish_list_event<T: Transport + ?Sized>(transport: &T, event: &Event, targets: &ListTargets) -> Result<(), String> {
let mut all = targets.own.clone();
all.extend(targets.fallback.iter().filter(|r| !targets.own.contains(r)).cloned());
if all.is_empty() {
return Err("no relay that answered the read took the list".to_string());
}
transport.publish(event, &all).await
}
/// An unchanged fragment needs no new version, but a target relay that lacks the current one
/// (it held nothing, or a stale copy) still gets it, as signed.
async fn spread_unchanged<T: Transport + ?Sized>(transport: &T, current: Option<&(Event, Vec<String>)>, targets: &ListTargets) {
let Some((event, held_by)) = current else { return };
let lacking: Vec<String> = targets.own.iter().chain(&targets.fallback).filter(|r| !held_by.contains(r)).cloned().collect();
if !lacking.is_empty() {
if let Err(e) = transport.publish(event, &lacking).await {
crate::log_warn!("[CommunityList] could not copy the current fragment to {} relay(s): {e}", lacking.len());
}
}
}
/// The union of every held v2 community's relays — a fallback write target, and
/// where every list published before the move to our own relays still lives.
fn held_v2_relays() -> Vec<String> {
let mut set: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
if let Ok(ids) = crate::db::community::list_community_ids() {
for id in ids {
if matches!(crate::db::community::community_held(&id), Ok(true)) {
if let Ok(Some(c)) = crate::db::community::load_community_v2(&id) {
set.extend(c.relays);
}
}
}
}
set.into_iter().collect()
}
/// Rebuild this account's Community List from its held v2 communities, MERGE with the remote
/// copy (preserving tombstones, other-device entries, unknown fields), and publish.
/// `just_joined` is the community THIS call is recording a create/join for — the
/// ONLY community whose entry is (re)stamped `now`, so it beats any prior tombstone
/// (a deliberate re-join resurrects). Every OTHER held community that the remote
/// has tombstoned is left tombstoned (a sibling device's leave is NOT undone just
/// because we joined something else — the W1 resurrection hole). Idempotent;
/// best-effort — a list-publish failure never fails the membership change itself.
/// Returns `Ok(true)` when the list was PUBLISHED, `Ok(false)` when the attempt was
/// skipped without failing the caller (a failed remote fetch — see below). Callers that
/// need the membership to actually land use [`republish_community_list_durable`].
pub async fn republish_community_list<T: Transport + ?Sized>(transport: &T, just_joined: Option<&crate::community::CommunityId>) -> Result<bool, String> {
republish_community_list_at(transport, just_joined.map(|id| (id, now_ms())), false).await
}
/// [`republish_community_list`] with the join's own time: a retry stamps when the join
/// happened, not when the retry ran.
async fn republish_community_list_at<T: Transport + ?Sized>(
transport: &T,
joined: Option<(&crate::community::CommunityId, u64)>,
wait: bool,
) -> Result<bool, String> {
let just_joined = joined.map(|(id, _)| id);
crate::db::scoped(async move {
// A user action never queues behind another write: it reports a skip and the caller
// hands it to the durable retry, which waits its turn.
let Some(_write) = list_write_turn(wait).await else { return Ok(false) };
let held = held_v2_relays();
if held.is_empty() {
return Ok(false); // nothing held → nothing to sync
}
let relays = list_read_relays(&[]).await;
let own = own_list_relays().await;
// Written to our own relays, read from both: the copy has to outlive any
// one membership. Falls back to the held set when we have no relays of
// our own to write to.
let write_relays = if own.is_empty() { held.clone() } else { own };
// A FAILED remote fetch must not drive this replaceable-event write: publishing
// a list built without the remote seeds would drop older-epoch backfill anchors
// and re-stamp add-times (the W2 seed-regression + a resurrection window).
let read = match read_fragments(transport, &relays).await {
Ok(read) => read,
Err(e) => {
// SILENT-SKIP HAZARD: bailing is correct (publishing a list built without the
// remote seeds drops backfill anchors), but the membership this call was meant
// to record is now simply unrecorded. A join that lands here leaves a community
// held locally with no list entry — and if it also carries an older tombstone,
// nothing ever out-ranks it again. Say so loudly; `Ok(())` keeps it non-fatal.
crate::log_warn!(
"[CommunityList] republish SKIPPED (remote fetch failed: {}){}",
e,
just_joined
.map(|c| format!(" — the join of {} is NOT recorded across devices", &crate::simd::hex::bytes_to_hex_32(&c.0)[..8]))
.unwrap_or_default()
);
return Ok(false);
}
};
if read.unreadable {
crate::log_warn!("[CommunityList] republish SKIPPED — a fragment would not open, and it may be the newest copy");
return Ok(false);
}
let targets = ListTargets::new(write_relays, &read.answered);
if targets.is_empty() {
crate::log_warn!("[CommunityList] republish SKIPPED — no relay we write to answered the read");
return Ok(false);
}
let (remote, prev_created, read_frags, on_relays) = match read.set {
Some(set) if !set.is_complete() => {
crate::log_net_fail!(
"[CommunityList] republish SKIPPED — hold {} of {} fragments; rewriting a set we haven't fully read would drop the memberships in the ones we're missing",
set.created_at.len(),
set.declared
);
return Ok(false);
}
Some(set) => (set.list, set.created_at, set.read_frags, set.on_relays),
// No fragment on any relay that answered, and we write only to those: nothing
// there to lose, and local state is the source.
None => Default::default(),
};
let just_joined_hex = just_joined.map(|c| crate::simd::hex::bytes_to_hex_32(&c.0));
let now = now_ms();
let pending = pending_tombstones();
let mut local = super::list::CommunityList::default();
for id in crate::db::community::list_community_ids()? {
if !matches!(crate::db::community::community_held(&id), Ok(true)) {
continue;
}
let Some(c) = crate::db::community::load_community_v2(&id)? else { continue };
let cid_hex = crate::simd::hex::bytes_to_hex_32(&c.id().0);
let is_join = just_joined_hex.as_deref() == Some(cid_hex.as_str());
// A held community the remote has tombstoned (a sibling device left it) that
// we are NOT currently (re)joining stays LEFT — don't re-add it, or joining a
// different community would silently undo the leave everywhere.
//
// UNLESS our hold POST-DATES the removal. A rejoin whose membership never
// reached the list (this publish is best-effort — a failed remote fetch
// silently skips it) leaves a tombstone with no entry, and nothing can ever
// out-rank it again: every boot the list sync reads "removed", tears the
// community down, the rejoin re-adds it, and it loops forever. Our own hold
// is first-hand evidence of membership, so let it settle the tie by the same
// add-vs-remove rule the list already uses everywhere else.
let tombstoned_at = remote
.tombstones
.iter()
.find(|t| t.community_id == cid_hex)
.map(|t| t.removed_at)
.unwrap_or(0);
let held_since = hold_bound_ms(&c);
if !is_join && !remote.is_live(&cid_hex) && tombstoned_at > 0 && held_since <= tombstoned_at {
crate::log_warn!(
"[CommunityList] holding {} but NOT recording it: a tombstone at {} post-dates our hold ({}) — treated as a leave from another device",
&cid_hex[..8], tombstoned_at, held_since
);
continue;
}
// Keep an already-live entry's add time (no churn); the joined community (or a
// genuinely-new one) stamps `now` so a re-join beats a stale tombstone. A hold
// that outlived a tombstone re-asserts itself at its own join time, which is
// already newer than the removal.
let added_at = if remote.is_live(&cid_hex) && !is_join {
remote.entries.iter().find(|e| e.community_id == cid_hex).map(|e| e.added_at).unwrap_or(now)
} else if is_join {
// A join outranks every removal already known: one stamped later than the join
// was noticed late or on a skewed clock, never made after it.
let known = pending.tombstones.iter().filter(|t| t.community_id == cid_hex).map(|t| t.removed_at).fold(tombstoned_at, u64::max);
joined.map_or(now, |(_, at)| at).max(known.saturating_add(1))
} else {
// Recorded at its own hold time: `now` would out-date a removal this read missed.
held_since
};
let jm = join_material(&c);
let theirs = remote.entries.iter().find(|e| e.community_id == cid_hex);
let current = rebuild_snapshot(jm.clone(), theirs.map(|e| &e.current));
let seed = rebuild_snapshot(jm, theirs.map(|e| &e.seed));
local.entries.push(super::list::CommunityListEntry { community_id: cid_hex, seed, current, added_at, extra: Default::default() });
}
let merged = remote.merge(&local).merge(&pending);
// No whole-list cap: fragmentation is what keeps each event publishable,
// and the count limit is gone (CORD-02 §8).
match publish_fragments(transport, &merged, &prev_created, &read_frags, &on_relays, &targets).await {
Ok(_) => {}
Err(e) => {
crate::log_net_fail!("[CommunityList] publish FAILED ({}) — memberships stay local-only until the next edit", e);
return Err(e);
}
}
// A join counts as recorded only once the relays show it: a write from another device
// in the same second can win the coordinate, and an accepted publish says nothing of that.
let shown = fetch_fragments(transport, &relays).await.ok().flatten().map(|set| set.list).unwrap_or_default();
settle_pending(&shown);
if let Some(hex) = just_joined_hex.as_deref().filter(|h| local.entries.iter().any(|e| e.community_id == *h)) {
let at = joined.map_or(now, |(_, at)| at);
let landed = shown.entries.iter().any(|e| e.community_id == hex && e.added_at >= at);
if !landed {
crate::log_warn!("[CommunityList] the join of {} was published but isn't on the relays — retrying", &hex[..8]);
return Ok(false);
}
}
Ok(true)
})
.await
}
/// Retry budget for [`republish_community_list_durable`]. An unrecorded membership is
/// invisible to the user and self-heals only on their NEXT join, so ride out a relay
/// blip rather than a single shot. Bounded: a permanently dead relay set gives up
/// instead of spinning.
const LIST_REPUBLISH_BACKOFF_SECS: [u64; 6] = [2, 5, 15, 45, 120, 300];
/// Record a membership across devices DURABLY: retry in the background until the list
/// actually lands.
///
/// [`republish_community_list`] must never fail a join, and it deliberately publishes
/// NOTHING when the remote fetch fails (a list built without the remote seeds would drop
/// other devices' entries). One shot at that means a relay blip during a join leaves the
/// membership unrecorded until the user happens to join something else — and if a stale
/// tombstone out-ranks it, the community is stranded until a manual leave+rejoin.
///
/// Non-blocking. Skipped entirely without a live client (headless/unit tests drive the
/// generic fn directly). Bound to its account, so a swap mid-backoff leaves it
/// publishing A's list from A's client rather than from B's.
pub fn republish_community_list_durable(just_joined: Option<crate::community::CommunityId>) {
match just_joined {
Some(id) => record_join_durable(id, now_ms()),
None => retry_republish(None),
}
}
/// Record a join made at `joined_at`, kept until it lands.
fn record_join_durable(id: crate::community::CommunityId, joined_at: u64) {
let hex = crate::simd::hex::bytes_to_hex_32(&id.0);
edit_pending(|p| {
if !p.joins.iter().any(|j| j.community_id == hex) {
p.joins.push(PendingJoin { community_id: hex.clone(), joined_at });
}
});
retry_republish(Some((id, joined_at)));
}
fn retry_republish(join: Option<(crate::community::CommunityId, u64)>) {
if crate::state::nostr_client().is_none() {
return;
}
crate::db::spawn_bound(async move {
for (attempt, wait) in LIST_REPUBLISH_BACKOFF_SECS.iter().enumerate() {
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
match republish_community_list_at(&transport, join.as_ref().map(|(id, at)| (id, *at)), true).await {
Ok(true) => {
if let Some((id, _)) = &join {
let hex = crate::simd::hex::bytes_to_hex_32(&id.0);
edit_pending(|p| p.joins.retain(|j| j.community_id != hex));
}
if attempt > 0 {
crate::log_info!("[CommunityList] membership recorded on retry #{}", attempt);
}
return;
}
Ok(false) => {} // skipped — already logged; retry
Err(e) => crate::log_warn!("[CommunityList] republish attempt #{} failed: {}", attempt, e),
}
crate::rt::time::sleep(std::time::Duration::from_secs(*wait)).await;
}
crate::log_warn!(
"[CommunityList] membership not recorded after {} attempts — kept, retried on the next boot",
LIST_REPUBLISH_BACKOFF_SECS.len()
);
});
}
/// Record a permanent leave tombstone for `community_id` in the List. Written to
/// our OWN relays: the departing community's are about to stop being read at all,
/// so a tombstone left only there is one no later sync can ever fetch — the
/// community then rejoins itself from a stale copy on the next boot.
async fn tombstone_community_list<T: Transport + ?Sized>(
transport: &T,
community_id: &crate::community::CommunityId,
relays: &[String],
removed_at: u64,
wait: bool,
) -> Result<(), String> {
let Some(_write) = list_write_turn(wait).await else { return Err(LIST_BUSY.to_string()) };
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community_id.0);
let read_relays = list_read_relays(relays).await;
let own = own_list_relays().await;
let write_relays = if own.is_empty() { relays.to_vec() } else { own };
// A failed fetch here would drop other communities' entries (only the
// tombstone would survive); preserve them by bailing — the leave re-records
// on the next attempt, and the local teardown already happened.
let read = read_fragments(transport, &read_relays).await?;
if read.unreadable {
return Err("a fragment would not open, and it may be the newest copy — refusing to write".to_string());
}
let targets = ListTargets::new(write_relays, &read.answered);
if targets.is_empty() {
return Err("no relay we write to answered the read".to_string());
}
let (mut doc, prev_created, read_frags, on_relays) = match read.set {
Some(set) if !set.is_complete() => {
return Err(format!("hold {} of {} fragments — refusing to rewrite a set we haven't fully read", set.created_at.len(), set.declared));
}
Some(set) => (set.list, set.created_at, set.read_frags, set.on_relays),
None => Default::default(),
};
// A late retry must never replace a newer removal with its own older one.
let removed_at = doc.tombstones.iter().filter(|t| t.community_id == cid_hex).map(|t| t.removed_at).fold(removed_at, u64::max);
doc.tombstones.retain(|t| t.community_id != cid_hex);
doc.tombstones.push(super::list::Tombstone { community_id: cid_hex.clone(), removed_at, extra: Default::default() });
let doc = doc.merge(&pending_tombstones());
// No size gate on the way out: a tombstone strictly shrinks the live set, and
// a guard that blocks the only operation able to restore compliance is a
// deadlock, not a guard (CORD-02 §8).
publish_fragments(transport, &doc, &prev_created, &read_frags, &on_relays, &targets).await?;
// Landed only once the relays show it: a write from another device in the same second can
// win the coordinate, and an accepted publish says nothing of that.
let shown = fetch_fragments(transport, &read_relays).await?.map(|set| set.list).unwrap_or_default();
settle_pending(&shown);
if shown.tombstones.iter().any(|t| t.community_id == cid_hex && t.removed_at >= removed_at) {
Ok(())
} else {
Err("the tombstone was published but isn't on the relays".to_string())
}
}
/// Retry a leave tombstone until it lands, on the same budget a join gets. A leave
/// that fails to record is the worse of the two: the local hold is already gone, so
/// this device shows the community left while every other one still holds it, and
/// nothing re-records it until some unrelated edit happens to carry it.
///
/// `removed_at` is the caller's, not `now` — re-stamping it here would let a retry
/// that fires after a genuine rejoin bury that rejoin.
pub fn tombstone_community_list_durable(community_id: crate::community::CommunityId, relays: Vec<String>, removed_at: u64) {
retry_pending_tombstone(add_pending_tombstone(&community_id, removed_at), relays);
}
fn add_pending_tombstone(community_id: &crate::community::CommunityId, removed_at: u64) -> PendingTombstone {
let pending = PendingTombstone { community_id: crate::simd::hex::bytes_to_hex_32(&community_id.0), removed_at };
mirror_tombstones([(pending.community_id.as_str(), removed_at)]);
edit_pending(|p| {
p.tombstones.retain(|t| t.community_id != pending.community_id || t.removed_at > pending.removed_at);
if !p.tombstones.iter().any(|t| t.community_id == pending.community_id) {
p.tombstones.push(pending.clone());
}
});
pending
}
/// Record a leave in the List: kept as pending first, written now when no other list write
/// is running, else left to the background queue (which carries every pending leave).
async fn record_leave<T: Transport + ?Sized>(transport: &T, community_id: &crate::community::CommunityId, relays: &[String], removed_at: u64) {
let pending = add_pending_tombstone(community_id, removed_at);
match tombstone_community_list(transport, community_id, relays, removed_at, false).await {
Ok(()) => {}
Err(e) => {
if e != LIST_BUSY {
crate::log_net_fail!("[CommunityList] leave tombstone failed ({}) — retrying in the background", e);
}
retry_pending_tombstone(pending, relays.to_vec());
}
}
}
fn retry_pending_tombstone(pending: PendingTombstone, relays: Vec<String>) {
if crate::state::nostr_client().is_none() {
return;
}
let Some(id) = crate::simd::hex::hex_to_bytes_32_checked(&pending.community_id).map(crate::community::CommunityId) else { return };
crate::db::spawn_bound(async move {
for (attempt, wait) in LIST_REPUBLISH_BACKOFF_SECS.iter().enumerate() {
crate::rt::time::sleep(std::time::Duration::from_secs(*wait)).await;
// Another write may have carried it already.
if !load_pending().tombstones.iter().any(|t| t.community_id == pending.community_id) {
return;
}
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
match tombstone_community_list(&transport, &id, &relays, pending.removed_at, true).await {
Ok(()) => {
crate::log_net_info!(
"[CommunityList] leave tombstone for {} landed on retry #{}",
&pending.community_id[..8],
attempt + 1
);
return;
}
Err(e) => crate::log_warn!("[CommunityList] leave tombstone retry #{} failed: {}", attempt + 1, e),
}
}
crate::log_net_fail!(
"[CommunityList] leave tombstone for {} not landed after {} attempts — kept, retried on the next boot",
&pending.community_id[..8],
LIST_REPUBLISH_BACKOFF_SECS.len()
);
});
}
/// List writes that haven't landed yet, kept in the account's DB: a leave or a join whose
/// retries die with the app (closed, killed, offline) is otherwise lost for good, and the
/// other devices never hear of it.
#[derive(Default, serde::Serialize, serde::Deserialize)]
struct PendingListWrites {
#[serde(default)]
tombstones: Vec<PendingTombstone>,
#[serde(default)]
joins: Vec<PendingJoin>,
}
#[derive(Clone, serde::Serialize, serde::Deserialize)]
struct PendingTombstone {
community_id: String,
removed_at: u64,
}
#[derive(Clone, serde::Serialize, serde::Deserialize)]
struct PendingJoin {
community_id: String,
/// When the join happened: a retry days later must not out-date a leave made since.
joined_at: u64,
}
const LIST_PENDING_KEY: &str = "community_list_pending_writes";
fn load_pending() -> PendingListWrites {
let raw = crate::db::settings::get_sql_setting(LIST_PENDING_KEY.to_string()).ok().flatten();
raw.map_or_else(PendingListWrites::default, |s| {
serde_json::from_str(&s).unwrap_or_else(|e| {
// Kept aside rather than overwritten by the next edit: it may hold a leave.
crate::log_warn!("[CommunityList] pending list writes unreadable ({e}) — set aside");
let _ = crate::db::settings::set_sql_setting(format!("{LIST_PENDING_KEY}_unread"), s);
PendingListWrites::default()
})
})
}
fn edit_pending(f: impl FnOnce(&mut PendingListWrites)) {
// Process-wide: a task from an earlier session of the same account writes the same row.
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
let _held = LOCK.lock().unwrap_or_else(|e| e.into_inner());
let mut pending = load_pending();
f(&mut pending);
if let Ok(json) = serde_json::to_string(&pending) {
if let Err(e) = crate::db::settings::set_sql_setting(LIST_PENDING_KEY.to_string(), json) {
crate::log_warn!("[CommunityList] could not persist pending list writes: {e}");
}
}
}
/// Every removal this device has read from the List or written to it: `community_id` →
/// newest `removed_at` (ms). Merge-only, so an invite arriving between syncs still meets
/// the decision that answered it.
const LIST_TOMBSTONES_KEY: &str = "community_list_tombstones";
fn load_tombstone_mirror() -> Result<std::collections::HashMap<String, u64>, String> {
let raw = crate::db::settings::get_sql_setting_strict(LIST_TOMBSTONES_KEY)?;
Ok(raw.map_or_else(Default::default, |s| {
serde_json::from_str(&s).unwrap_or_else(|e| {
crate::log_warn!("[CommunityList] tombstone mirror unreadable ({e}) — set aside");
let _ = crate::db::settings::set_sql_setting(format!("{LIST_TOMBSTONES_KEY}_unread"), s);
Default::default()
})
}))
}
fn mirror_tombstones<'a>(tombstones: impl IntoIterator<Item = (&'a str, u64)>) {
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
let _held = LOCK.lock().unwrap_or_else(|e| e.into_inner());
// A failed read must not become an empty map that replaces the row.
let mut mirror = match load_tombstone_mirror() {
Ok(m) => m,
Err(e) => {
crate::log_warn!("[CommunityList] tombstone mirror not read ({e}) — removals not mirrored");
return;
}
};
let mut changed = false;
for (id, at) in tombstones {
let id = id.to_ascii_lowercase();
if mirror.get(&id).is_none_or(|&held| held < at) {
mirror.insert(id, at);
changed = true;
}
}
if !changed {
return;
}
if let Ok(json) = serde_json::to_string(&mirror) {
if let Err(e) = crate::db::settings::set_sql_setting(LIST_TOMBSTONES_KEY.to_string(), json) {
crate::log_warn!("[CommunityList] could not persist the tombstone mirror: {e}");
}
}
}
/// Record a removal this device made without a List write (a kick, a rekey exclusion), so a
/// re-delivered invite no newer than it stays answered.
pub fn note_local_removal(community_id: &str, removed_at: u64) {
mirror_tombstones([(community_id, removed_at)]);
}
/// Every removal this device has made or read: `community_id` → newest `removed_at` (ms).
fn known_removals() -> std::collections::HashMap<String, u64> {
let mut known = load_tombstone_mirror().unwrap_or_default();
for t in load_pending().tombstones {
let at = known.entry(t.community_id.to_ascii_lowercase()).or_insert(0);
*at = (*at).max(t.removed_at);
}
known
}
/// Whether a leave or decline at least as new as an invite (its inner rumor time,
/// in seconds) has already answered it, here or on a sibling device.
pub fn tombstone_suppresses(community_id: &str, invite_created_at_secs: u64) -> bool {
let invite_ms = invite_created_at_secs.saturating_mul(1000);
known_removals().get(&community_id.to_ascii_lowercase()).is_some_and(|&at| at >= invite_ms)
}
/// Resume every list write a previous run left unfinished. Once per session.
fn resume_pending_list_writes() {
struct Resumed;
if crate::state::nostr_client().is_none() {
return;
}
let flag = crate::db::current_session().scoped::<Resumed, std::sync::atomic::AtomicBool>();
if flag.swap(true, std::sync::atomic::Ordering::SeqCst) {
return;
}
let pending = load_pending();
if !pending.tombstones.is_empty() || !pending.joins.is_empty() {
crate::log_net_info!(
"[CommunityList] resuming {} unlanded leave(s) and {} unrecorded join(s)",
pending.tombstones.len(),
pending.joins.len()
);
}
for t in pending.tombstones {
retry_pending_tombstone(t, Vec::new());
}
for j in pending.joins {
if let Some(cid) = crate::simd::hex::hex_to_bytes_32_checked(&j.community_id) {
record_join_durable(crate::community::CommunityId(cid), j.joined_at);
}
}
}
/// Sync memberships from the Community List across devices: fetch this account's list from
/// `bootstrap_relays` (its held communities' relays plus any caller-supplied set for
/// a fresh device), and JOIN every live entry not already held — reconstructing the
/// community from its join material and re-verifying the owner root. Returns the
/// newly-rehydrated communities (so the caller can subscribe + notify).
/// What one Community-List sync changed locally.
pub struct ListSyncOutcome {
/// Communities newly adopted from the list (already persisted + chat-registered).
pub joined: Vec<CommunityV2>,
/// Communities a sibling device LEFT, as `(community_id_hex, channel_id_hexes)`.
///
/// The rows are already gone here, so the ids are captured BEFORE deletion: the caller
/// still has to finish the local teardown (chat rows, STATE, the live subscription),
/// and it can't look them up afterwards. Deleting the community while leaving its chat
/// row behind is what produces a ghost "0 Members" room pointing at nothing.
pub removed: Vec<(String, Vec<String>)>,
}
/// Marks that this account has written the fragmented list at least once.
const LIST_SEEDED_KEY: &str = "community_list_frag_seeded";
/// The join refusal for a VERIFIED dissolution — an owner-signed, identity-bound
/// tombstone (§9: no un-dissolve). A sentinel because the accept boundary matches
/// on it: this is the one join failure that is a verdict rather than a maybe, so
/// the parked invite is retired instead of kept for a retry that can never succeed.
pub const ERR_DISSOLVED: &str = "this community has been dissolved";
/// Retire a parked invite whose community is provably dead: drop the local row and
/// tombstone the §8 List so every sibling device purges its copy on the next sync.
/// ONLY for the dissolved verdict — ambiguous could-not-verify failures stay parked.
pub async fn retire_dead_invite<T: Transport + ?Sized>(transport: &T, community_id_hex: &str, relays: &[String]) {
let _ = crate::db::community::delete_pending_invite(community_id_hex);
if let Some(cid) = crate::simd::hex::hex_to_bytes_32_checked(community_id_hex) {
let id = crate::community::CommunityId(cid);
let at = now_ms();
record_leave(transport, &id, relays, at).await;
}
crate::emit_event("community_invites_purged", &serde_json::json!({}));
}
/// Every relay answered EOSE with zero fragments — the only reading of "empty"
/// strong enough to seed over. The aggregate fetch that precedes this cannot
/// distinguish "no fragments" from "the relay holding them never answered";
/// asked one at a time, an error is a FAILED read and a failed read never seeds.
async fn confirmed_no_fragments<T: Transport + ?Sized>(transport: &T, relays: &[String]) -> bool {
let Ok(my_pk) = me_pk() else { return false };
if relays.is_empty() {
return false;
}
let query = Query {
kinds: vec![super::kind::COMMUNITY_LIST_FRAG],
authors: vec![my_pk.to_hex()],
limit: Some(1),
..Default::default()
};
for relay in relays {
match transport.fetch(&query, std::slice::from_ref(relay)).await {
Ok(events) if events.is_empty() => {}
// Found one (the aggregate read raced a sibling's write) or the relay
// didn't answer — either way this account is not confirmed empty.
_ => return false,
}
}
true
}
/// First write of the §8 List for an account that has none: an account upgrading
/// from the retired single-event list arrives here with memberships that exist
/// only in local state, and nothing else in the stack publishes without a
/// membership change to record. Latched once it lands, so a boot-load read that
/// comes back empty can never republish local state over a sibling's tombstones.
async fn seed_community_list<T: Transport + ?Sized>(transport: &T) {
if crate::db::settings::get_sql_setting(LIST_SEEDED_KEY.to_string()).ok().flatten().is_some() {
return;
}
if held_v2_relays().is_empty() {
return;
}
// Seeding over a read that merely FAILED publishes fragment 0 over a sibling
// device's tombstones at a fresh created_at — confirm the emptiness per relay.
let own = own_list_relays().await;
let confirm = if own.is_empty() { held_v2_relays() } else { own };
if !confirmed_no_fragments(transport, &confirm).await {
crate::log_warn!("[CommunityList] seed DEFERRED — the empty read is unconfirmed; retrying on a later boot");
return;
}
crate::log_net_info!("[CommunityList] no fragments held anywhere (confirmed per relay) — seeding from local state");
match republish_community_list(transport, None).await {
Ok(true) => {
let _ = crate::db::settings::set_sql_setting(LIST_SEEDED_KEY.to_string(), "1".to_string());
}
Ok(false) => {}
Err(e) => crate::log_net_fail!("[CommunityList] seed failed: {e}"),
}
}
pub async fn sync_community_list<T: Transport + ?Sized>(transport: &T, bootstrap_relays: &[String]) -> Result<ListSyncOutcome, String> {
crate::db::scoped(async move {
resume_pending_list_writes();
let relays = list_read_relays(bootstrap_relays).await;
if relays.is_empty() {
return Ok(ListSyncOutcome { joined: vec![], removed: vec![] });
}
// A cross-device sync that finds nothing is indistinguishable from one that
// never ran, so every exit says why — this path is only ever debugged after
// the fact, from a user's log.
let list = match fetch_fragments(transport, &relays).await {
Ok(Some(set)) => {
crate::log_net_info!(
"[CommunityList] fetched: {} of {} fragment(s), {} entries, {} tombstones, across {} relays",
set.created_at.len(),
set.declared,
set.list.entries.len(),
set.list.tombstones.len(),
relays.len()
);
set.list
}
Ok(None) => {
// Transient by nature: boot runs many concurrent passes and a relay that
// times out under that load returns nothing. Only persistent absence
// matters, and that shows up as "adopted nothing" anyway.
crate::log_debug!("[CommunityList] no fragments across {} relays", relays.len());
seed_community_list(transport).await;
return Ok(ListSyncOutcome { joined: vec![], removed: vec![] });
}
Err(e) => {
crate::log_net_fail!("[CommunityList] fetch failed across {} relays: {e}", relays.len());
return Ok(ListSyncOutcome { joined: vec![], removed: vec![] });
}
};
// Every removal this device has made or read counts, whatever this copy says: one still
// on its way to the relays, or one a relay serving an older copy never got, would
// otherwise bring back a community already left.
let known: Vec<super::list::Tombstone> = known_removals()
.into_iter()
.map(|(community_id, removed_at)| super::list::Tombstone { community_id, removed_at, extra: Default::default() })
.collect();
let list = list.merge(&super::list::CommunityList { tombstones: known, ..Default::default() });
mirror_tombstones(list.tombstones.iter().map(|t| (t.community_id.as_str(), t.removed_at)));
// Receive-side teardown (the counterpart to the republish tombstone guard):
// a community this device still holds but the synced list shows TOMBSTONED (a
// sibling device left it) and NOT live gets torn down here, so a leave on one
// device propagates to the others. A re-join would have re-added it live
// (beating the tombstone), so is_live short-circuits the honest case.
let mut removed: Vec<(String, Vec<String>)> = Vec::new();
for t in &list.tombstones {
if list.is_live(&t.community_id) {
continue;
}
let Some(cid) = crate::simd::hex::hex_to_bytes_32_checked(&t.community_id) else { continue };
let id = crate::community::CommunityId(cid);
let Some(held) = crate::db::community::load_community_v2(&id).ok().flatten() else {
continue; // not held — nothing to tear down
};
// `is_live` above assumes a rejoin re-added an entry, but recording that entry is
// best-effort: a relay blip at join time leaves the tombstone unopposed forever, and
// this would then delete the community on every sync. So let the LOCAL hold break the
// tie too — a hold created after the removal IS the rejoin, whether or not its entry
// ever reached the list.
if hold_bound_ms(&held) > t.removed_at {
crate::log_warn!(
"[CommunityList] {} is tombstoned at {} but our hold ({}) post-dates it — treating as a rejoin, not tearing down",
&t.community_id[..8], t.removed_at, held.created_at_ms
);
continue;
}
let channel_ids: Vec<String> = held.channels.iter().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)).collect();
let _ = crate::db::community::delete_community(&t.community_id);
removed.push((t.community_id.clone(), channel_ids));
}
// A tombstone also retires any PARKED invite it post-dates — a decline or a
// dissolution-retire made on another device. Supersession, not a bare id
// match: only a removal NEWER than the invite's arrival is a verdict on it;
// an older tombstone is a past leave the re-invite already superseded
// (received_at is seconds, removed_at is ms).
let mut invites_purged = 0usize;
for t in &list.tombstones {
if list.is_live(&t.community_id) {
continue;
}
let Ok(Some(received_at)) = crate::db::community::pending_invite_received_at(&t.community_id) else { continue };
if (received_at.max(0) as u64).saturating_mul(1000) <= t.removed_at
&& crate::db::community::delete_pending_invite(&t.community_id).is_ok()
{
invites_purged += 1;
}
}
if invites_purged > 0 {
crate::emit_event("community_invites_purged", &serde_json::json!({}));
}
let mut joined = Vec::new();
for entry in list.live_entries() {
let Some(cid) = crate::simd::hex::hex_to_bytes_32_checked(&entry.community_id) else { continue };
// Held under ANY protocol, not just v2: a protocol-scoped check would re-adopt
// an id held under another protocol, fail verification (no v2 community at that
// coordinate), and retry on EVERY sync pass, a warning flood plus a relay walk.
if crate::db::community::community_exists(&crate::community::CommunityId(cid)).unwrap_or(false) {
continue; // already held
}
// The material IS a bundle; accept_bundle re-verifies the owner root, saves,
// and seeds floors. NO Guestbook Join: this device is receiving keys the
// account already holds elsewhere — the membership was announced when it
// actually joined, and a key sync is not a membership event.
let bundle = material_to_invite(&entry.current);
match accept_bundle(transport, &bundle, None, Some(entry.added_at)).await {
// A leave made while the adoption ran has already answered it.
Ok(community) if known_removals().get(&entry.community_id).is_some_and(|&at| at >= entry.added_at) => {
let channel_ids = community.channels.iter().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)).collect();
let _ = crate::db::community::delete_community(&entry.community_id);
removed.push((entry.community_id.clone(), channel_ids));
}
Ok(community) => {
// The staff write secret never rides a bundle shape — adopt it
// from the list entry directly, and only when it derives to the
// control_pk held for exactly this epoch (CORD-02 §5/§8). A
// stale secret fails closed to read-only; a 136-byte base blob
// or the Grant's control_wrap re-delivers on the walk forward.
if let (Some(pk), Some(root_hex)) = (community.control_pk, entry.current.control_root.as_deref()) {
if let Some(root) = crate::simd::hex::hex_to_bytes_32_checked(root_hex) {
if super::derive::control_signer_group_key(&root, community.id(), community.root_epoch).pk() == pk
{
let mut held = community.clone();
held.control_root = Some(root);
let _ = crate::db::community::save_community_v2(&held);
}
}
}
joined.push(community);
}
// A listed-but-unadoptable entry is the failure mode that reads as
// "cross-device sync is broken": the community never appears and any
// parked invite for it is never retired.
Err(e) => crate::log_net_fail!(
"[CommunityList] {} is listed but adoption failed: {e}",
&entry.community_id[..entry.community_id.len().min(8)]
),
}
}
Ok(ListSyncOutcome { joined, removed })
})
.await
}
// ── Control edition authoring (CORD-04 roles / CORD-02 §6 / CORD-03 §2) ──────
/// Publish one control edition (a role, grant, banlist, community-metadata, or
/// channel-metadata edit) at the next version for its entity, chaining `prev` from
/// our held head, and advance our local floor. Authority is enforced by every
/// reader's roster fold (CORD-04 §5: authority is rejection, not prevention), so this
/// requires only a valid local signer; a well-behaved client checks its own rank
/// first, but a reader drops an unauthorized edition regardless.
/// This actor's authority citation for a control edition (CORD-04 §5): the head
/// of their OWN Grant entity, pinned by coordinate + version + edition hash.
///
/// A SYNC FLOOR, not a verdict — a verifier refuses to act until it has synced
/// at least this Grant, then resolves rank against its CURRENT roster, so a
/// demoted admin is never grandfathered by an old-but-once-valid citation.
///
/// `None` for the owner (supreme, rank comes from the community id) and `None`
/// when no Grant head is held — an actor who cannot cite has no rank to claim,
/// and the edition is dropped by a conforming reader either way.
/// The verify half of [`my_authority_citation`] (CORD-04 §5): does the actor's
/// cited Grant prove authority we have actually SYNCED? The owner is supreme and
/// cites nothing. A non-owner MUST cite, and we must hold that Grant at ≥ the
/// cited version with the cited hash at the tip — else fail closed, because
/// honoring an action whose authority we can't confirm is exactly how a demoted
/// moderator keeps moderating.
///
/// Completeness only: the permission + outrank is the separate roster check, so a
/// since-demoted actor is refused there (refuse-superseded). An action citing a
/// version we haven't synced parks and is re-judged on the next roster sync — the
/// sync path can't escalate to a blocking fetch.
/// Whom a Kick is honored from (CORD-04 §6): a signer holding KICK, or BAN for the departure an
/// un-ban writes, who strictly outranks the target, is not banned, and cites a Grant we hold.
pub(super) fn kick_judge<'a>(
cid_hex: &'a str,
owner_hex: &'a str,
roles: &'a crate::community::roles::CommunityRoles,
) -> impl Fn(&PublicKey, &PublicKey, Option<&crate::community::edition::AuthorityCitation>) -> bool + 'a {
use crate::community::roles::Permissions;
move |actor, target, citation| {
let (actor_hex, target_hex) = (actor.to_hex(), target.to_hex());
// The roster check first: it is in memory, the other two read the database.
[Permissions::KICK, Permissions::BAN].into_iter().any(|bit| roles.can_act_on_member(&actor_hex, Some(owner_hex), &target_hex, bit))
// A banned member's Guestbook events count for nothing (CORD-04 §4).
&& !crate::db::community::is_author_banned(cid_hex, actor)
&& citation_is_synced(cid_hex, owner_hex, &actor_hex, citation)
}
}
pub(super) fn citation_is_synced(
cid_hex: &str,
owner_hex: &str,
actor_hex: &str,
citation: Option<&crate::community::edition::AuthorityCitation>,
) -> bool {
if owner_hex == actor_hex {
return true;
}
if citation.is_none() {
return false;
}
let cid_bytes = crate::simd::hex::hex_to_bytes_32(cid_hex);
let actor_bytes = crate::simd::hex::hex_to_bytes_32(actor_hex);
let grant_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(
&crate::community::CommunityId(cid_bytes),
&actor_bytes,
));
let head: Vec<crate::community::edition::EntityHead> =
crate::db::community::get_edition_head(cid_hex, &grant_hex)
.ok()
.flatten()
.map(|(version, self_hash)| crate::community::edition::EntityHead {
entity_hex: grant_hex.clone(),
version,
self_hash,
inner_id: [0u8; 32],
citation: None,
})
.into_iter()
.collect();
crate::community::edition::authority_citation_satisfied(&head, Some(owner_hex), actor_hex, &grant_hex, citation)
}
/// [`my_authority_citation`], but refusing to emit an action every reader will
/// drop (CORD-04 §5: which non-owner actions must cite).
///
/// The citation is built from PERSISTED heads, which only `follow_control` writes
/// — so an admin who hasn't folded yet (just promoted, or freshly restored) would
/// otherwise publish uncited and have the action silently vanish on every client,
/// with nothing shown locally. Failing here turns that into one retryable error.
fn required_authority_citation(
community: &CommunityV2,
actor: &PublicKey,
) -> Result<Option<crate::community::edition::AuthorityCitation>, String> {
if community.owner().ok().as_ref() == Some(actor) {
return Ok(None); // supreme, cites nothing
}
my_authority_citation(community, actor).map(Some).ok_or_else(|| {
"your admin rights aren't synced on this device yet — reopen the community and retry".to_string()
})
}
fn my_authority_citation(
community: &CommunityV2,
actor: &PublicKey,
) -> Option<crate::community::edition::AuthorityCitation> {
if community.owner().ok().as_ref() == Some(actor) {
return None;
}
let entity_id = super::derive::grant_locator(community.id(), &actor.to_bytes());
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
crate::db::community::get_edition_head(&cid_hex, &entity_hex)
.ok()
.flatten()
.map(|(version, edition_hash)| crate::community::edition::AuthorityCitation { entity_id, version, edition_hash })
}
/// The row as the Control Plane leaves it now, read again under the lock every whole-row
/// writer takes. Hold the guard while acting on it; drop it before anything that rotates.
async fn follow_fresh<T: Transport + ?Sized>(transport: &T, id: &crate::community::CommunityId) -> Result<(tokio::sync::OwnedMutexGuard<()>, CommunityV2), String> {
let guard = super::realtime::follow_lock(id).lock_owned().await;
let current = crate::db::community::load_community_v2(id)?.ok_or("v2 community not found")?;
follow_control(transport, ¤t).await?;
let fresh = crate::db::community::load_community_v2(id)?.ok_or("v2 community not found")?;
Ok((guard, fresh))
}
/// Refuse a root-derived write whose in-hand struct predates a rotation.
///
/// A Ban's refound buries the old root while the caller's `CommunityV2` still
/// points at it; publishing there lands on a plane nobody folds — the action
/// "succeeds" and silently never happened (an unban that doesn't unban, an
/// invite that strands its joiner on a dead epoch). Failing loudly instead lets
/// the caller reload and retry against the living root.
fn assert_current_root(community: &CommunityV2) -> Result<(), String> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
match crate::db::community::get_server_root_epoch(&cid_hex)? {
Some(held) if held != community.root_epoch.0 => Err(format!(
"the community re-founded mid-action (epoch {} -> {held}); retry",
community.root_epoch.0
)),
_ => Ok(()), // no row = a not-yet-persisted create; nothing newer to defer to
}
}
async fn publish_control_edition<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
vsk: &str,
entity_id: &[u8; 32],
content: &str,
) -> Result<(), String> {
publish_control_edition_at(transport, community, vsk, entity_id, content, now_ms() / 1000).await
}
/// [`publish_control_edition`] dated `at` (seconds).
async fn publish_control_edition_at<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
vsk: &str,
entity_id: &[u8; 32],
content: &str,
at: u64,
) -> Result<(), String> {
publish_control_edition_wrap_at(transport, community, vsk, entity_id, content, at).await.map(|_| ())
}
/// [`publish_control_edition_at`], handing back the wrap it published.
async fn publish_control_edition_wrap_at<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
vsk: &str,
entity_id: &[u8; 32],
content: &str,
at: u64,
) -> Result<Event, String> {
crate::db::scoped(async move {
assert_current_root(community)?;
let signer = crate::signer::active_signer()?;
let my_pk = me_pk()?;
// On a split epoch the signing secret is the staff-held control_root
// (CORD-02 §2) — a member without it fails HERE with a readable error
// instead of minting a wrap every reader and relay drops.
let view = control::ControlPlane::of(community);
let control = view.write_group()?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let entity_hex = crate::simd::hex::bytes_to_hex_32(entity_id);
let (version, prev) = match crate::db::community::get_edition_head(&cid_hex, &entity_hex)? {
Some((v, h)) => (v + 1, Some(h)),
None => (1, None),
};
// CORD-04 §5: a non-owner names the exact Grant edition it claims its rank
// under. Computed here rather than passed in — the citation is a property of
// WHO IS ACTING, identical for every entity kind, so deciding it per call
// site is nine chances to forget (and nine were, silently: every site passed
// None). The owner cites nothing; their rank is the community id itself.
let citation = required_authority_citation(community, &my_pk)?;
// On Roles v2 every edition is marked: its hash covers its signer and it names its
// Community (CORD-04 §1). A Roles v2 kind is marked even while the switch is under way.
let everyone_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::everyone_locator(community.id()));
let marked = [super::vsk::ROLE_V2, super::vsk::TENURE, super::vsk::CATEGORY, super::vsk::CHANNEL_ACL, super::vsk::CHANNEL_SYNC, super::vsk::WRITERS].contains(&vsk)
|| crate::db::community::get_edition_head(&cid_hex, &everyone_hex)?.is_some();
let binding = marked.then(|| super::derive::edition_binding(community.id()));
let rumor = control::build_edition_rumor_bound(my_pk, vsk, entity_id, version, prev.as_ref(), content, at, citation.as_ref(), binding);
// Readers judge the edition's own time; relays refuse a wrap dated ahead.
let (wrap, _) = control::seal_control_edition_signed(&signer, my_pk, &rumor, &control, Timestamp::from_secs(at.min(now_ms() / 1000))).await.map_err(|e| e.to_string())?;
// A Tenure is what keeps a removed member's decisions standing, so it goes to every relay.
if vsk == super::vsk::TENURE {
transport.publish_durable(&wrap, &community.relays).await?;
} else {
transport.publish(&wrap, &community.relays).await?;
}
// Advance our own floor so a follow-up edit chains from this head and refuse-
// downgrade holds; open our own wrap to recover the self_hash + inner_id.
// Re-check the session AFTER the publish await: a swap mid-publish means the
// pool now points at another account's DB — skipping is safe (the next own
// edit rebuilds the same head from the relay's copy).
hold_wrap(community, &wrap);
if let Ok((ed, _)) = control::open_control_edition(&wrap, &control) {
crate::db::community::set_family_head_at_epoch(&cid_hex, &entity_hex, ed.version, &ed.self_hash, &ed.inner_id, &ed.author.to_bytes(), community.root_epoch.0, floor_family(&ed.vsk))?;
hold_own(community, ed);
}
Ok(wrap)
})
.await
}
/// Merge our OWN just-published Role/Grant into the locally stored roster.
///
/// v2 persists the roster only inside `follow_control`, so a role or grant we
/// just published is invisible to every sync local read (entitlement, capability
/// gates, the next grant) until the next fold. This writes what we are already
/// authorized to have written; the next fold recomputes from the plane and
/// converges. Mirrors the fold's own write, so the stored `roles_at` is left
/// alone — a real edition always outranks this optimistic merge.
fn merge_local_roster(cid_hex: &str, role: Option<&crate::community::roles::Role>, grant: Option<&crate::community::roles::MemberGrant>) {
let mut roster = crate::db::community::get_community_roles(cid_hex).unwrap_or_default();
if let Some(r) = role {
match roster.roles.iter_mut().find(|x| x.role_id == r.role_id) {
Some(slot) => *slot = r.clone(),
None => roster.roles.push(r.clone()),
}
}
if let Some(g) = grant {
match roster.grants.iter_mut().find(|x| x.member == g.member) {
Some(slot) => *slot = g.clone(),
None => roster.grants.push(g.clone()),
}
}
let at = crate::db::community::get_community_roles_at(cid_hex).unwrap_or(0);
if let Err(e) = crate::db::community::set_community_roles(cid_hex, &roster, at) {
crate::log_warn!("v2: local roster merge failed (heals on the next control fold): {e}");
}
}
/// Create or edit a Role (vsk 1, CORD-04 §2). `role.role_id` is the coordinate; a
/// rename or permission change is a versioned edit of the same id. Gated on the
/// reader side by `MANAGE_ROLES` + outrank.
pub async fn set_role<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, role: &crate::community::roles::Role) -> Result<(), String> {
super::roles::validate_role(role)?;
let content = super::roles::role_content_json(role)?;
let role_id = crate::simd::hex::hex_to_bytes_32_checked(&role.role_id).ok_or("role_id must be 32-byte hex")?;
publish_control_edition(transport, community, vsk::ROLE, &role_id, &content).await
}
/// Grant or revoke a member's Roles (vsk 3, CORD-04 §2). Empty `role_ids` is a
/// revoke. Gated on the reader side by `MANAGE_ROLES` + outrank of every role + the
/// member. Staff-ness (whether the Grant must deliver the `control_root`,
/// CORD-04 §3) is judged from the persisted roster; internal callers holding a
/// fresher fetched view use `grant_roles_with_roster`.
pub async fn grant_roles<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, member: &PublicKey, role_ids: Vec<String>) -> Result<(), String> {
grant_roles_sealing(transport, community, member, role_ids, Seal::Strict).await
}
async fn grant_roles_sealing<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, member: &PublicKey, role_ids: Vec<String>, seal: Seal) -> Result<(), String> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
// A role this device hasn't folded is unjudgeable for staff-ness, and
// guessing "not staff" publishes a staff-making Grant with NO control_wrap
// — seating a staffer who cannot write, silently (CORD-04 §3 makes the wrap
// mandatory on such a Grant). Resolve it from the network first; only the
// definitions still missing after that fall back to the local view.
// Internal callers already holding a fetched roster use
// `grant_roles_with_roster` and skip this round trip.
let roster = if community.control_pk.is_some() && role_ids.iter().any(|rid| roster.role(rid).is_none()) {
let mut fetched = fetch_authority(transport, community).await.roles;
for r in roster.roles {
if !fetched.roles.iter().any(|x| x.role_id == r.role_id) {
fetched.roles.push(r);
}
}
fetched
} else {
roster
};
grant_roles_with_roster_sealing(transport, community, member, role_ids, &roster, seal).await
}
/// The `control_wrap` a Grant carries when its role set leaves `member` staff
/// (CORD-04 §3): the current epoch's `control_root`, NIP-44-encrypted under
/// the granter↔member pairwise key, `epoch_be[8] ‖ control_root[32]` inside.
/// `None` when nothing is owed — a legacy pre-split epoch, or a grant that
/// leaves the member non-staff. Attached on EVERY staff-leaving grant, not
/// just the first: a re-issue with a fresh wrap is the spec's own re-delivery
/// path (a lost key, a head superseded before its member fetched it), and the
/// marginal cost is one ECDH.
///
/// Errs when a wrap is owed but this granter cannot mint one: a staff-making
/// edition MUST carry a wrap fresh for the current epoch — publishing without
/// it would seat a staffer who cannot write, silently. (The publish itself
/// would fail on the same missing secret, but the promotion must never outrun
/// the delivery.)
async fn control_wrap_owed(community: &CommunityV2, makes_staff: bool, member: &PublicKey) -> Result<Option<String>, String> {
if !makes_staff {
return Ok(None);
}
let Some(pk) = community.control_pk else {
return Ok(None); // legacy epoch — the plane has no write key to deliver
};
let Some(cr) = community.control_root else {
return Err("you don't hold this community's staff write key, so you can't promote to staff yet".to_string());
};
// Never deliver a secret that doesn't derive to the held address — the
// recipient's fail-closed check would drop it anyway (CORD-04 §3).
if super::derive::control_signer_group_key(&cr, community.id(), community.root_epoch).pk() != pk {
return Err("this community's held staff write key is corrupt; re-sync before promoting".to_string());
}
use nostr_sdk::prelude::AsyncNip44;
let signer = crate::signer::active_signer()?;
let wrap = signer
.nip44_encrypt_async(member, &super::rekey::control_wrap_b64(community.root_epoch, &cr))
.await
.map_err(|e| format!("staff key delivery: {e}"))?;
Ok(Some(wrap))
}
/// [`grant_roles`] judging staff-ness against a caller-supplied roster — the
/// freshest view the caller holds (a fetched authority merge, or one carrying
/// a role minted moments ago that no fold has read back).
async fn grant_roles_with_roster<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
member: &PublicKey,
role_ids: Vec<String>,
roster: &crate::community::roles::CommunityRoles,
) -> Result<(), String> {
grant_roles_with_roster_sealing(transport, community, member, role_ids, roster, Seal::Strict).await
}
async fn grant_roles_with_roster_sealing<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
member: &PublicKey,
role_ids: Vec<String>,
roster: &crate::community::roles::CommunityRoles,
seal: Seal,
) -> Result<(), String> {
// Every Role a Grant takes away seals what the member decided with it first (CORD-04 §9).
// A strip to nothing seals whatever the plane says they held, stale roster or not.
if role_ids.is_empty() || roster.roles_of(&member.to_hex()).any(|r| !role_ids.contains(&r.role_id)) {
seal_standing(transport, community, std::slice::from_ref(member), seal).await?;
}
// A grant that leaves the member staff carries the staff write key in the
// edition itself (CORD-04 §3) — promotion and delivery are one signed
// edition: nothing separate to send, race, or watch an inbox for. The owner
// holds the key by right.
let owner_self = community.owner().is_ok_and(|o| o == *member);
let control_wrap = control_wrap_owed(community, !owner_self && roster.roles_make_staff(&role_ids), member).await?;
let grant = crate::community::roles::MemberGrant { member: member.to_hex(), role_ids };
let content = super::roles::grant_content_json_with_wrap(&grant, control_wrap)?;
let eid = super::derive::grant_locator(community.id(), &member.to_bytes());
publish_control_edition(transport, community, vsk::GRANT, &eid, &content).await
}
/// The community's @admin role id: the folded Server-scope ADMIN_ALL role when one
/// exists, else (with `create_if_missing`) a DETERMINISTIC mint — the same id on
/// every device, so concurrent grants converge as editions of ONE entity instead
/// of forking two Admin roles.
pub async fn ensure_admin_role<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
view: &AuthorityView,
create_if_missing: bool,
) -> Result<Option<String>, String> {
use crate::community::roles::{Permissions, Role, RoleScope};
// The finder tests the FROZEN founding mask, never ADMIN_ALL: published
// Admin roles predate later bits (PIN_MESSAGES...), and requiring a bit
// they can't have would orphan every one of them and mint a duplicate.
if let Some(r) = view
.roles
.roles
.iter()
.find(|r| matches!(r.scope, RoleScope::Server) && r.permissions.contains(Permissions::ADMIN_FOUNDING_MASK))
{
return Ok(Some(r.role_id.clone()));
}
if !create_if_missing {
return Ok(None);
}
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let role_id = crate::crypto::sha256_hex(format!("vector/v2/role/admin/{cid_hex}").as_bytes());
set_role(transport, community, &Role::admin(role_id.clone())).await?;
Ok(Some(role_id))
}
/// Grant the @admin role (minting it deterministically when absent), MERGED into
/// the member's existing grant — a grant entity replaces whole (CORD-04 §2), so a
/// blind push would erase their other roles. Owner-only: the position-1 Admin is
/// manageable only by position 0 (an equal never outranks it), and refusing
/// before any publish keeps an unauthorized edition of the DETERMINISTIC admin
/// entity from advancing this device's own floor onto a head readers reject.
pub async fn grant_admin<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, member: &PublicKey) -> Result<(), String> {
crate::db::scoped(async move {
// Guard spans the multi-page fetch below: a swap mid-fetch must not let the
// downstream publish's own (post-swap) guard write account A's floor into B.
let my_pk = me_pk()?;
if my_pk != community.owner()? {
return Err("only the community owner can grant @admin".to_string());
}
let view = fetch_authority(transport, community).await;
let member_hex = member.to_hex();
require_grant_head(community, &view, &member_hex)?;
let role_id = ensure_admin_role(transport, community, &view, true)
.await?
.expect("create_if_missing yields an id");
let mut role_ids = view
.roles
.grants
.iter()
.find(|g| g.member == member_hex)
.map(|g| g.role_ids.clone())
.unwrap_or_default();
if role_ids.contains(&role_id) {
return Ok(()); // already admin — don't bump the grant edition for nothing.
}
role_ids.push(role_id.clone());
// Judge staff-ness against a roster that HOLDS the admin definition: a
// just-minted role hasn't folded into the fetched view yet, and missing it
// would seat an admin without the write key (CORD-04 §3).
let mut roster = view.roles.clone();
if roster.role(&role_id).is_none() {
roster.roles.push(crate::community::roles::Role::admin(role_id));
}
grant_roles_with_roster(transport, community, member, role_ids, &roster).await
})
.await
}
/// Strip the @admin role from the member's grant, preserving their other roles.
/// A no-op when they don't hold it. Owner-only, like [`grant_admin`].
pub async fn revoke_admin<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, member: &PublicKey) -> Result<(), String> {
crate::db::scoped(async move {
let my_pk = me_pk()?;
if my_pk != community.owner()? {
return Err("only the community owner can revoke @admin".to_string());
}
let view = fetch_authority(transport, community).await;
let member_hex = member.to_hex();
require_grant_head(community, &view, &member_hex)?;
let Some(role_id) = ensure_admin_role(transport, community, &view, false).await? else {
return Ok(()); // no admin role exists — nothing to revoke.
};
let mut role_ids = view
.roles
.grants
.iter()
.find(|g| g.member == member_hex)
.map(|g| g.role_ids.clone())
.unwrap_or_default();
let before = role_ids.len();
role_ids.retain(|r| r != &role_id);
if role_ids.len() == before {
return Ok(());
}
// A demotion can still leave the member staff through a KEPT role — the
// fetched view holds every kept definition, so judge against it.
grant_roles_with_roster(transport, community, member, role_ids, &view.roles).await
})
.await
}
// ── Role authoring (CORD-04 §2/§3) ──────────────────────────────────────────
//
// Every check below is the rule a READER applies, run before publishing so this
// device never signs an edition the fold drops. That matters beyond wasted work:
// editions are version-chained, and a dropped head still advances the author's own
// floor onto a state nobody honours.
/// Who is authoring a role change, and from what standing.
struct RoleAuthor {
me_hex: String,
owner_hex: String,
is_owner: bool,
/// The owner is 0; otherwise the highest (lowest-numbered) role position held.
rank: u32,
/// The roster the author acts against, for downward support.
roles: crate::community::roles::CommunityRoles,
}
impl RoleAuthor {
/// Strictly above `position`: equal never acts on equal (CORD-04 §3).
fn outranks(&self, position: u32) -> bool {
self.is_owner || self.rank < position
}
/// Whether an edition touching everything down to `reach` and carrying `bits` is one
/// readers admit (CORD-04 §3): MANAGE_ROLES, and every bit, from the author's roles
/// positioned strictly above it. Judged on the edition alone, as readers judge it.
fn supports(&self, reach: u32, bits: u64) -> bool {
use crate::community::roles::Permissions;
if self.is_owner {
return true;
}
let support = self.roles.permissions_above(&self.me_hex, reach);
support.contains(Permissions::MANAGE_ROLES) && bits & !support.0 == 0
}
}
fn role_author(community: &CommunityV2, view: &AuthorityView) -> Result<RoleAuthor, String> {
use crate::community::roles::Permissions;
let me = me_pk()?;
let owner = community.owner()?;
let (me_hex, owner_hex) = (me.to_hex(), owner.to_hex());
let is_owner = me == owner;
if !is_owner {
if view.banned.contains(&me_hex) {
return Err("you are banned from this community".to_string());
}
if !view.roles.is_authorized(&me_hex, Some(&owner_hex), Permissions::MANAGE_ROLES) {
return Err("managing roles needs the Manage Roles permission".to_string());
}
}
let rank = if is_owner { 0 } else { view.roles.highest_position(&me_hex).unwrap_or(u32::MAX) };
Ok(RoleAuthor { me_hex, owner_hex, is_owner, rank, roles: view.roles.clone() })
}
/// A role's current head must be in hand before replacing it, or this edition could
/// chain from a stale version and lose to (or fork from) the one the relays hold.
fn require_role_head(view: &AuthorityView, role_id: &str) -> Result<(), String> {
let eid = role_id.to_ascii_lowercase();
if view.floored.contains(&eid) && !view.head_entities.contains(&eid) {
return Err("this role's current state could not be fetched; try again once relays serve the control plane".to_string());
}
Ok(())
}
/// Mint a Role beneath everything that exists, including its author: a new role
/// starts at the bottom, as in Discord, and no role may sit at or above its minter.
/// Returns the new `role_id`.
pub async fn create_role<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
name: &str,
color: u32,
permissions: u64,
scope: crate::community::roles::RoleScope,
) -> Result<String, String> {
crate::db::scoped(async move {
use crate::community::roles::{Permissions, Role};
let view = fetch_authority(transport, community).await;
let author = role_author(community, &view)?;
if view.roles.roles.len() >= super::roles::MAX_ROLES_PER_COMMUNITY {
return Err(format!("a community holds at most {} roles", super::roles::MAX_ROLES_PER_COMMUNITY));
}
let name = name.trim();
if name.is_empty() {
return Err("a role needs a name".to_string());
}
// Channel access roles are parked at the bottom band on purpose (see
// `channel_access_role`), so a new role lands just above that band rather than
// in the one slot left beneath it, where the next would saturate into a peer.
let floor = view
.roles
.roles
.iter()
.map(|r| r.position)
.filter(|p| *p < ACCESS_ROLE_POSITION)
.max()
.unwrap_or(0)
.max(author.rank);
if floor.saturating_add(1) >= ACCESS_ROLE_POSITION {
return Err("there's no room beneath your role for a new one; reorder the roles first".to_string());
}
if !author.supports(floor.saturating_add(1), permissions) {
return Err("you can't give a role permissions you don't hold".to_string());
}
let role = Role {
role_id: crate::simd::hex::bytes_to_hex_32(&super::super::random_32()),
name: name.to_string(),
position: floor.saturating_add(1),
permissions: Permissions(permissions),
scope,
color,
rank: None, display: false, mentionable: false,
extra: Default::default(),
};
set_role(transport, community, &role).await?;
Ok(role.role_id)
})
.await
}
/// Edit a Role's name, colour and permissions, keeping its position, its scope and
/// every field another client wrote. Both CORD-04 §3 gates hold: the author outranks the
/// role as it stands, and the edition claims nothing at or above them.
pub async fn edit_role<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
role_id: &str,
name: &str,
color: u32,
permissions: u64,
scope: crate::community::roles::RoleScope,
) -> Result<(), String> {
crate::db::scoped(async move {
use crate::community::roles::Permissions;
let view = fetch_authority(transport, community).await;
let author = role_author(community, &view)?;
let current = view.roles.role(role_id).cloned().ok_or("no such role")?;
require_role_head(&view, role_id)?;
if !author.outranks(current.position) {
return Err("you can only edit roles beneath your own".to_string());
}
if !author.supports(current.position, permissions) {
return Err("you can't give a role permissions you don't hold".to_string());
}
let name = name.trim();
if name.is_empty() {
return Err("a role needs a name".to_string());
}
// A scope is a channel's access list: moving it would re-entitle every holder at
// once, and keys follow grants, not role edits. It is fixed at creation.
if scope != current.scope {
return Err("a role's channel can't be changed once it's created".to_string());
}
let mut next = current.clone();
next.name = name.to_string();
next.color = color;
next.permissions = Permissions(permissions);
if next == current {
return Ok(());
}
set_role(transport, community, &next).await
})
.await
}
/// Reorder the roles beneath the author, top to bottom as `ordered` lists them.
///
/// Positions are the whole of CORD-04's ordering (no RoleOrder entity), so a reorder
/// republishes each role whose position moves, and nothing else. The author's own
/// rank and everything above it stay put: the moved set is renumbered from just
/// beneath them, which also resolves any ties into one definite order. Returns how
/// many roles were republished.
pub async fn reorder_roles<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
ordered: &[String],
) -> Result<usize, String> {
crate::db::scoped(async move {
let view = fetch_authority(transport, community).await;
let author = role_author(community, &view)?;
let mut movable: Vec<crate::community::roles::Role> = view
.roles
.roles
.iter()
.filter(|r| author.outranks(r.position))
.cloned()
.collect();
// The requested order first; anything it omits keeps its current relative place.
movable.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.role_id.cmp(&b.role_id)));
let rank_of = |id: &str| ordered.iter().position(|o| o.eq_ignore_ascii_case(id));
let mut keyed: Vec<(usize, usize, crate::community::roles::Role)> = movable
.into_iter()
.enumerate()
.map(|(i, r)| (rank_of(&r.role_id).unwrap_or(usize::MAX), i, r))
.collect();
keyed.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
let mut changed = Vec::new();
for (i, (_, _, role)) in keyed.into_iter().enumerate() {
let position = author.rank.saturating_add(1).saturating_add(i as u32);
if role.position != position {
if !author.supports(role.position.min(position), role.permissions.0) {
return Err(format!("you can't move \"{}\": it has permissions you don't hold", role.name));
}
require_role_head(&view, &role.role_id)?;
let mut next = role;
next.position = position;
changed.push(next);
}
}
for role in &changed {
set_role(transport, community, role).await?;
}
Ok(changed.len())
})
.await
}
/// Publish a Roles v2 edition of `role` (vsk 13, CORD-04 §2).
pub async fn set_role_v2<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, role: &crate::community::roles::Role) -> Result<(), String> {
if role.name.len() > super::roles::MAX_ROLE_NAME_BYTES {
return Err("role name over 64 bytes".to_string());
}
let content = super::roles::role_v2_content_json(role)?;
let role_id = crate::simd::hex::hex_to_bytes_32_checked(&role.role_id).ok_or("role_id must be 32-byte hex")?;
publish_control_edition(transport, community, vsk::ROLE_V2, &role_id, &content).await
}
/// Who holds `role_id`.
fn holders_of(view: &AuthorityView, role_id: &str) -> Vec<PublicKey> {
view.roles
.grants
.iter()
.filter(|g| g.role_ids.iter().any(|r| r == role_id))
.filter_map(|g| PublicKey::from_hex(&g.member).ok())
.collect()
}
/// The live Roles in rank order, top first, as the fold ordered them.
fn ranked(view: &AuthorityView) -> Vec<&crate::community::roles::Role> {
let mut roles: Vec<&crate::community::roles::Role> = view.roles.roles.iter().filter(|r| r.rank.is_some()).collect();
roles.sort_by(|a, b| a.rank.as_deref().unwrap_or("").as_bytes().cmp(b.rank.as_deref().unwrap_or("").as_bytes()).then_with(|| a.role_id.cmp(&b.role_id)));
roles
}
fn require_activated(view: &AuthorityView) -> Result<(), String> {
if !view.activated {
return Err("this community still uses the legacy roster".to_string());
}
// A read that lost @everyone would diff every member into or out of every channel.
if view.roles.everyone.is_none() || !view.everyone_served {
return Err("the community's roles couldn't be read; try again".to_string());
}
Ok(())
}
/// Mint a Roles v2 Role at the bottom, beneath everything, as in Discord. Returns its id.
pub async fn create_role_v2<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str, color: u32, permissions: u64) -> Result<String, String> {
crate::db::scoped(async move {
use crate::community::roles::{Permissions, Role, RoleScope};
let view = fetch_authority(transport, community).await;
require_activated(&view)?;
let author = role_author(community, &view)?;
if view.roles.roles.len() >= super::roles::MAX_ROLES_PER_COMMUNITY {
return Err(format!("a community holds at most {} roles", super::roles::MAX_ROLES_PER_COMMUNITY));
}
let name = name.trim();
if name.is_empty() {
return Err("a role needs a name".to_string());
}
let order = ranked(&view);
let bottom = order.iter().map(|r| r.position).max().unwrap_or(0).saturating_add(1);
if !author.supports(bottom, permissions) {
return Err("you can't give a role permissions you don't hold".to_string());
}
let rank = crate::community::rank::between(order.last().and_then(|r| r.rank.as_deref()), None).ok_or("no room left at the bottom; reorder the roles first")?;
let role = Role {
role_id: crate::simd::hex::bytes_to_hex_32(&super::super::random_32()),
name: name.to_string(),
position: bottom,
permissions: Permissions(permissions),
scope: RoleScope::Server,
color,
rank: Some(rank),
display: false,
mentionable: false,
extra: Default::default(),
};
set_role_v2(transport, community, &role).await?;
Ok(role.role_id)
})
.await
}
/// Edit a Roles v2 Role in place, keeping its rank and every field another client wrote.
#[allow(clippy::too_many_arguments)]
pub async fn edit_role_v2<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
role_id: &str,
name: &str,
color: u32,
permissions: u64,
display: bool,
mentionable: bool,
) -> Result<(), String> {
crate::db::scoped(async move {
use crate::community::roles::Permissions;
let view = fetch_authority(transport, community).await;
require_activated(&view)?;
let author = role_author(community, &view)?;
let current = view.roles.role(role_id).cloned().ok_or("no such role")?;
require_role_head(&view, role_id)?;
if !author.outranks(current.position) {
return Err("you can only edit roles beneath your own".to_string());
}
if !author.supports(current.position, permissions) {
return Err("you can't give a role permissions you don't hold".to_string());
}
let name = name.trim();
if name.is_empty() {
return Err("a role needs a name".to_string());
}
if current.permissions.0 & !permissions != 0 {
seal_standing(transport, community, &holders_of(&view, role_id), Seal::Strict).await?;
}
let mut next = current;
next.name = name.to_string();
next.color = color;
next.permissions = Permissions(permissions);
next.display = display;
next.mentionable = mentionable;
set_role_v2(transport, community, &next).await?;
let mut after = view.roles.clone();
if let Some(slot) = after.roles.iter_mut().find(|r| r.role_id == next.role_id) {
*slot = next;
}
settle_access(transport, community, &view.roles, &after).await
})
.await
}
/// Move a Roles v2 Role to `index` in the rank order (0 is the top): one edition, on the
/// moved Role alone, its key minted between its new neighbours.
pub async fn move_role_v2<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, role_id: &str, index: usize) -> Result<(), String> {
crate::db::scoped(async move {
let mut view = fetch_authority(transport, community).await;
let before = view.roles.clone();
move_role_in(transport, community, &mut view, role_id, index).await?;
let after = roster_after_moves(transport, community, &view, &before, &[role_id.to_string()]).await;
settle_access(transport, community, &before, &after).await
})
.await
}
/// Reorder the Roles to `ordered` (top first; Roles it leaves out keep their order after
/// it). The longest run already in order stays put and each other Role moves once, all
/// judged against one fold carried forward, so a relay slow to serve one move can't skew
/// the next.
pub async fn reorder_roles_v2<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, ordered: &[String]) -> Result<usize, String> {
crate::db::scoped(async move {
let mut view = fetch_authority(transport, community).await;
require_activated(&view)?;
let before = view.roles.clone();
let mut cur: Vec<String> = ranked(&view).into_iter().map(|r| r.role_id.clone()).collect();
let mut target: Vec<String> = ordered.iter().filter(|id| cur.contains(id)).cloned().collect();
target.extend(cur.iter().filter(|id| !ordered.contains(id)).cloned());
let seq: Vec<usize> = target.iter().map(|id| cur.iter().position(|c| c == id).expect("from cur")).collect();
let n = seq.len();
let (mut len, mut prev) = (vec![1usize; n], vec![usize::MAX; n]);
for i in 0..n {
for j in 0..i {
if seq[j] < seq[i] && len[j] + 1 > len[i] {
len[i] = len[j] + 1;
prev[i] = j;
}
}
}
let mut keep = vec![false; n];
let mut at = (0..n).max_by_key(|&i| (len[i], std::cmp::Reverse(i)));
while let Some(k) = at {
keep[k] = true;
at = (prev[k] != usize::MAX).then_some(prev[k]);
}
// Each moved Role lands just after its predecessor in the target order.
let mut moved = Vec::new();
for i in (0..n).filter(|&i| !keep[i]) {
let id = target[i].clone();
let index = match i.checked_sub(1) {
None => 0,
Some(p) => cur.iter().filter(|c| **c != id).position(|c| *c == target[p]).map_or(0, |at| at + 1),
};
move_role_in(transport, community, &mut view, &id, index).await?;
cur.retain(|c| *c != id);
cur.insert(index.min(cur.len()), id.clone());
moved.push(id);
}
if !moved.is_empty() {
let after = roster_after_moves(transport, community, &view, &before, &moved).await;
settle_access(transport, community, &before, &after).await?;
}
Ok(moved.len())
})
.await
}
/// The Roster to settle Role moves against. Readers re-judge every overwrite against the
/// new ranks, so their fold when a fresh read is whole and serves every move; else `local`,
/// carried forward from a whole read, which a failed read can't empty.
/// A local settle can't see which overwrites readers now drop, so the cut is owed against
/// `before` until a whole read lands.
async fn roster_after_moves<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, local: &AuthorityView, before: &crate::community::roles::CommunityRoles, moved: &[String]) -> crate::community::roles::CommunityRoles {
let fresh = fetch_authority(transport, community).await;
let serves = |id: &String| fresh.roles.role(id).is_some_and(|r| local.roles.role(id).is_some_and(|l| l.rank == r.rank));
if fresh.everyone_served && !fresh.gapped && moved.iter().all(serves) {
return fresh.roles;
}
crate::log_warn!("[Concord] role move settled against the local fold: the fresh read was partial");
owe_settle(&crate::simd::hex::bytes_to_hex_32(&community.id().0), before);
local.roles.clone()
}
/// Remember the Roster a change started from, when who lost access couldn't be read; kept
/// the earliest, so the owed settle covers every change since.
fn owe_settle(cid_hex: &str, before: &crate::community::roles::CommunityRoles) {
if owed_settle(cid_hex).is_some() {
return;
}
if let Ok(v) = serde_json::to_string(before) {
let _ = crate::db::settings::set_sql_setting(format!("v2_settle:{cid_hex}"), v);
}
}
fn owed_settle(cid_hex: &str) -> Option<crate::community::roles::CommunityRoles> {
crate::db::settings::get_sql_setting(format!("v2_settle:{cid_hex}")).ok().flatten().and_then(|v| serde_json::from_str(&v).ok())
}
pub(crate) fn has_owed_settle(cid_hex: &str) -> bool {
owed_settle(cid_hex).is_some()
}
/// Settle an owed change against a whole read: cut who lost access since, invite who gained.
async fn run_owed_settle<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<bool, String> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let Some(before) = owed_settle(&cid_hex) else { return Ok(false) };
let fresh = fetch_authority(transport, community).await;
if !fresh.everyone_served || fresh.gapped {
return Err("the roster couldn't be read whole; the settle stays owed".to_string());
}
settle_access(transport, community, &before, &fresh.roles).await?;
let _ = crate::db::settings::set_sql_setting(format!("v2_settle:{cid_hex}"), String::new());
Ok(true)
}
async fn move_role_in<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, view: &mut AuthorityView, role_id: &str, index: usize) -> Result<(), String> {
{
require_activated(view)?;
let author = role_author(community, view)?;
let current = view.roles.role(role_id).cloned().ok_or("no such role")?;
require_role_head(view, role_id)?;
let others: Vec<&crate::community::roles::Role> = ranked(view).into_iter().filter(|r| r.role_id != current.role_id).collect();
let index = index.min(others.len());
let (above, below) = (index.checked_sub(1).map(|i| others[i]), others.get(index).copied());
// The new spot sits just beneath `above`: the author must outrank it and the old one,
// and hold the Role's bits through Roles above both.
let spot = above.map_or(1, |a| a.position.saturating_add(1));
if !author.outranks(current.position) || !(author.is_owner || above.is_some_and(|a| author.rank <= a.position)) {
return Err("you can only move roles beneath your own, to a place beneath your own".to_string());
}
if !author.supports(current.position.min(spot), current.permissions.0) {
return Err(format!("you can't move \"{}\": it has permissions you don't hold", current.name));
}
let rank = crate::community::rank::between(above.and_then(|r| r.rank.as_deref()), below.and_then(|r| r.rank.as_deref()))
.ok_or("no room between those roles; move a neighbour first")?;
if current.rank.as_deref().is_some_and(|old| old.as_bytes() < rank.as_bytes()) {
seal_standing(transport, community, &holders_of(view, role_id), Seal::Strict).await?;
}
// A Grant is judged on the Role's rank as it stands, so moving the Role up past the
// Grant's signer would take it from the member: re-sign those Grants as the mover.
let resign: Vec<&crate::community::roles::MemberGrant> = view
.roles
.grants
.iter()
.filter(|g| g.role_ids.iter().any(|r| r == role_id))
.filter(|g| view.grant_authors.get(&g.member).is_some_and(|a| *a != author.owner_hex && view.roles.highest_position(a).is_none_or(|p| p >= spot)))
.collect();
for g in &resign {
let reach = g.role_ids.iter().filter_map(|r| view.roles.role(r).map(|x| x.position)).chain([spot, view.roles.highest_position(&g.member).unwrap_or(u32::MAX)]).min().unwrap_or(spot);
if !author.outranks(view.roles.highest_position(&g.member).unwrap_or(u32::MAX)) || !author.supports(reach.min(spot), 0) {
return Err(format!("moving \"{}\" there would take it from members you can't give it to", current.name));
}
}
let resign: Vec<crate::community::roles::MemberGrant> = resign.into_iter().cloned().collect();
let mut next = current;
next.rank = Some(rank.clone());
set_role_v2(transport, community, &next).await?;
for g in &resign {
let member = PublicKey::from_hex(&g.member).map_err(|e| e.to_string())?;
grant_roles_with_roster(transport, community, &member, g.role_ids.clone(), &view.roles).await?;
}
// Carry the move forward in the view, as the next fold will read it.
if let Some(r) = view.roles.roles.iter_mut().find(|r| r.role_id == role_id) {
r.rank = Some(rank);
}
let keys: Vec<String> = view.roles.roles.iter().filter_map(|r| r.rank.clone()).collect();
let ranks = crate::community::rank::dense_ranks(keys.iter().map(String::as_str));
for r in view.roles.roles.iter_mut() {
if let Some(p) = r.rank.as_deref().and_then(|k| ranks.get(k)) {
r.position = *p;
}
}
for g in &resign {
view.grant_authors.insert(g.member.clone(), author.me_hex.clone());
}
Ok(())
}
}
/// Delete a Roles v2 Role: terminal, it leaves every holder and frees its slot.
pub async fn delete_role_v2<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, role_id: &str) -> Result<(), String> {
crate::db::scoped(async move {
let view = fetch_authority(transport, community).await;
require_activated(&view)?;
let author = role_author(community, &view)?;
let current = view.roles.role(role_id).cloned().ok_or("no such role")?;
require_role_head(&view, role_id)?;
if !author.outranks(current.position) || !author.supports(current.position, 0) {
return Err("you can only delete roles beneath your own".to_string());
}
seal_standing(transport, community, &holders_of(&view, role_id), Seal::Strict).await?;
let eid = crate::simd::hex::hex_to_bytes_32_checked(role_id).ok_or("role_id must be 32-byte hex")?;
publish_control_edition(transport, community, vsk::ROLE_V2, &eid, &super::roles::role_v2_deleted_json(¤t.role_id)).await?;
let mut after = view.roles.clone();
after.roles.retain(|r| r.role_id != current.role_id);
settle_access(transport, community, &view.roles, &after).await
})
.await
}
/// Set what `@everyone` holds. Its editor holds every bit it carries through their Roles.
pub async fn set_everyone<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, permissions: u64) -> Result<(), String> {
crate::db::scoped(async move {
let view = fetch_authority(transport, community).await;
// The owner can always restate @everyone: it is how a refused head is repaired.
if me_pk()? != community.owner()? {
require_activated(&view)?;
} else if !view.activated {
return Err("this community still uses the legacy roster".to_string());
}
let author = role_author(community, &view)?;
if !author.supports(u32::MAX, permissions) {
return Err("you can't give everyone permissions you don't hold".to_string());
}
let eid = super::derive::everyone_locator(community.id());
let legacy = view.roles.legacy_channels.clone().or(crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0))?.legacy_channels);
publish_control_edition(transport, community, vsk::ROLE_V2, &eid, &super::roles::everyone_content_json_with(permissions, legacy.as_ref())).await?;
let mut after = view.roles.clone();
after.everyone = Some(crate::community::roles::Permissions(permissions));
settle_access(transport, community, &view.roles, &after).await
})
.await
}
/// Set, or with no bits clear, one overwrite on a Channel or Category (CORD-04 §8): judged
/// as readers judge it, on MANAGE_ROLES and every bit it touches held through Roles above
/// its target. Keys then follow View Channel in every Private Channel it reaches.
pub async fn set_overwrite<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
scope: [u8; 32],
target: crate::community::roles::OverwriteTarget,
allow: u64,
deny: u64,
) -> Result<(), String> {
use crate::community::roles::{Overwrite, OverwriteTarget, Permissions, OVERWRITABLE};
crate::db::scoped(async move {
let view = fetch_authority(transport, community).await;
require_activated(&view)?;
let author = role_author(community, &view)?;
if (allow | deny) & !OVERWRITABLE != 0 {
return Err("only channel permissions can be set per channel".to_string());
}
if !community.channels.iter().any(|c| c.id.0 == scope) && !community.categories.iter().any(|k| k.id == scope) {
return Err("no such channel or category".to_string());
}
// Keys follow the change: a private channel this device can't key can't be settled,
// whether the rule is its own or its Category's.
let scope_hex = crate::simd::hex::bytes_to_hex_32(&scope);
if community.channels.iter().any(|c| c.private && c.key.is_none() && (c.id.0 == scope || view.roles.syncs.get(&crate::simd::hex::bytes_to_hex_32(&c.id.0)) == Some(&scope_hex))) {
return Err(NO_KEY_TO_SHARE.to_string());
}
// Who might gain or lose a key must be readable before anything is published.
access_candidates(community, &view.roles)?;
let rank = match &target {
OverwriteTarget::Everyone => u32::MAX,
OverwriteTarget::Role(id) => view.roles.role(id).map(|r| r.position).ok_or("no such role")?,
OverwriteTarget::Member(m) if *m == author.owner_hex => return Err("the owner holds every permission everywhere".to_string()),
OverwriteTarget::Member(m) => view.roles.highest_position(m).unwrap_or(u32::MAX),
};
let current = view.roles.overwrites.iter().find(|o| o.scope == scope_hex && o.target == target);
let (was_allow, was_deny) = current.map_or((0, 0), |o| (o.allow.0, o.deny.0));
if !author.supports(rank, allow | deny | ((was_allow ^ allow) | (was_deny ^ deny))) {
return Err("you can only set permissions you hold, for roles and members beneath you".to_string());
}
let target_bytes = super::roles::overwrite_target_bytes(community.id(), &target).ok_or("malformed target")?;
let eid = super::derive::acl_locator(community.id(), &scope, &target_bytes);
if !author.is_owner {
require_role_head(&view, &crate::simd::hex::bytes_to_hex_32(&eid))?;
}
let o = Overwrite { scope: scope_hex.clone(), target: target.clone(), allow: Permissions(allow), deny: Permissions(deny) };
publish_control_edition(transport, community, vsk::CHANNEL_ACL, &eid, &super::roles::overwrite_content_json(&o)).await?;
let mut after = view.roles.clone();
after.overwrites.retain(|x| !(x.scope == scope_hex && x.target == target));
if allow != 0 || deny != 0 {
after.overwrites.push(o);
}
settle_access(transport, community, &view.roles, &after).await
})
.await
}
/// Sync a Channel to `category`'s overwrites, or (`None`) back to its own (CORD-04 §8).
/// Every rule on both sides swaps at once, so the writer must be able to write them all.
pub async fn set_channel_sync<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId, category: Option<[u8; 32]>) -> Result<(), String> {
crate::db::scoped(async move {
let view = fetch_authority(transport, community).await;
require_activated(&view)?;
let author = role_author(community, &view)?;
let channel = community.channel(channel_id).ok_or("no such channel")?;
if channel.private && channel.key.is_none() {
return Err(NO_KEY_TO_SHARE.to_string());
}
if category.is_some_and(|k| !community.categories.iter().any(|c| c.id == k)) {
return Err("no such category".to_string());
}
let chan = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
let cat = category.map(|k| crate::simd::hex::bytes_to_hex_32(&k));
let mut scopes = vec![chan.as_str()];
scopes.extend(cat.as_deref());
scopes.extend(view.roles.syncs.get(&chan).map(String::as_str));
if !may_swap_overwrites(&view.roles, Some(&author.owner_hex), &author.me_hex, &scopes, &|_| 0) {
return Err("syncing swaps permissions you can't set; ask someone who can".to_string());
}
access_candidates(community, &view.roles)?;
let eid = super::derive::sync_locator(community.id(), channel_id);
if !author.is_owner {
require_role_head(&view, &crate::simd::hex::bytes_to_hex_32(&eid))?;
}
publish_control_edition(transport, community, vsk::CHANNEL_SYNC, &eid, &super::roles::sync_content_json(&chan, cat.as_deref())).await?;
let mut after = view.roles.clone();
match cat {
Some(k) => after.syncs.insert(chan, k),
None => after.syncs.remove(&chan),
};
settle_access(transport, community, &view.roles, &after).await
})
.await
}
/// Why a change that opens a private channel this device can't key is refused (CORD-03 §5).
const NO_KEY_TO_SHARE: &str = "You can't change who can see this private channel: you don't have access to it yourself.";
/// Move Private Channel keys from what `before` entitled to what `after` does (CORD-03 §5):
/// the newly entitled get one Direct Invite carrying every key they gained, and a Channel
/// anyone lost is rekeyed without them. The roster this device holds is brought forward
/// first, so the invite and the rekey are built from `after`.
async fn settle_access<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
before: &crate::community::roles::CommunityRoles,
after: &crate::community::roles::CommunityRoles,
) -> Result<(), String> {
if after.everyone.is_none() {
return Ok(());
}
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let owner_hex = community.owner()?.to_hex();
let me = me_pk()?;
{
// Only what this change touched: anything else the stored roster holds stays, so a
// short read can't erase what the withholding defence is guarding.
let mut stored = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
if before.everyone != after.everyone {
stored.everyone = after.everyone;
}
for o in before.overwrites.iter().filter(|o| !after.overwrites.contains(o)) {
stored.overwrites.retain(|x| !(x.scope == o.scope && x.target == o.target));
}
for o in &after.overwrites {
if !stored.overwrites.contains(o) {
stored.overwrites.retain(|x| !(x.scope == o.scope && x.target == o.target));
stored.overwrites.push(o.clone());
}
}
for (ch, _) in before.syncs.iter().filter(|(c, k)| after.syncs.get(*c) != Some(*k)) {
stored.syncs.remove(ch);
}
for (ch, k) in &after.syncs {
stored.syncs.insert(ch.clone(), k.clone());
}
for r in before.roles.iter().filter(|r| after.role(&r.role_id).is_none()) {
stored.roles.retain(|x| x.role_id != r.role_id);
}
for r in &after.roles {
match stored.roles.iter_mut().find(|x| x.role_id == r.role_id) {
Some(slot) => *slot = r.clone(),
None => stored.roles.push(r.clone()),
}
}
for g in &after.grants {
if !stored.grants.contains(g) {
stored.grants.retain(|x| x.member != g.member);
stored.grants.push(g.clone());
}
}
let at = crate::db::community::get_community_roles_at(&cid_hex).unwrap_or(0);
if let Err(e) = crate::db::community::set_community_roles(&cid_hex, &stored, at) {
crate::log_warn!("v2: local roster merge failed (heals on the next control fold): {e}");
}
}
// Before's too: someone only a removed overwrite named still holds what it let them read.
let mut candidates = access_candidates(community, after)?;
for pk in access_candidates(community, before)? {
if !candidates.contains(&pk) {
candidates.push(pk);
}
}
let mut gained: std::collections::BTreeMap<PublicKey, ()> = Default::default();
// Readers take a Channel rotation only from its managers (CORD-06): without the
// standing, the cut waits for one of them rather than forking this device.
let may_rotate = me.to_hex() == owner_hex || after.is_authorized(&me.to_hex(), Some(&owner_hex), crate::community::roles::Permissions::MANAGE_CHANNELS);
// Per Channel: who lost it, how many come in without its history, and who reads it whole.
let mut rotating: Vec<(ChannelId, Vec<PublicKey>, Vec<PublicKey>)> = Vec::new();
let mut steady: Vec<(ChannelId, Vec<PublicKey>)> = Vec::new();
for ch in community.channels.iter().filter(|c| c.private && c.key.is_some()) {
let chan = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
let (mut lost, mut fresh, mut readers) = (Vec::new(), 0usize, Vec::new());
for pk in &candidates {
let hex = pk.to_hex();
if *pk == me || hex == owner_hex {
continue;
}
let (was, now) = (before.is_entitled(Some(&owner_hex), &hex, &chan, &[], &[]), after.is_entitled(Some(&owner_hex), &hex, &chan, &[], &[]));
if now && !was {
// Without history they come in at a fresh epoch, which the rotation below mints.
if after.reads_history(Some(&owner_hex), &hex, &chan, &[], &[]) {
gained.insert(*pk, ());
readers.push(*pk);
} else {
fresh += 1;
}
} else if was && !now {
lost.push(*pk);
}
}
// Readers adopt a delivery only from a deliverer their fold entitles.
if !(me.to_hex() == owner_hex || after.is_entitled(Some(&owner_hex), &me.to_hex(), &chan, &[], &[])) {
readers.clear();
}
if (!lost.is_empty() || fresh > 0) && !may_rotate {
crate::log_warn!("[v2:access] {} lost and {fresh} gained a channel's View; a channel manager's rotation will settle them", lost.len());
steady.push((ch.id, readers));
} else if !lost.is_empty() || fresh > 0 {
rotating.push((ch.id, lost, readers));
} else {
steady.push((ch.id, readers));
}
}
steady.retain(|(_, readers)| !readers.is_empty());
// A Channel that stays at its epoch is delivered before any other is rotated: its key is one
// round trip away, and must not wait out a rotation it has no part in.
deliver_gained(transport, community, &steady).await?;
let mut moved: Vec<(ChannelId, Vec<PublicKey>)> = Vec::new();
for (channel, lost, readers) in rotating {
let held = crate::db::community::load_community_v2(community.id())?.ok_or("v2 community not found")?;
rekey_channel_excluding(transport, &held, &channel, after, &[], &lost).await?;
if !readers.is_empty() {
moved.push((channel, readers));
}
}
// At the epoch each now holds.
deliver_gained(transport, community, &moved).await?;
if !gained.is_empty() {
let held = crate::db::community::load_community_v2(community.id())?.ok_or("v2 community not found")?;
let signer = crate::signer::active_signer()?;
for pk in gained.keys() {
let bundle = bundle_of_with_overlay(&held, BundleAudience::Member(*pk), Some(me), None, None, &[], &[]);
let wrap = invite::build_direct_invite_signed(&signer, me, pk, &bundle).await.map_err(|e| e.to_string())?;
transport.publish(&wrap, &held.relays).await?;
// The planes above already carry the key: the inbox copy only gets it there sooner,
// and resolving a stranger's inbox relays must not hold up the grant.
let pk = *pk;
crate::db::spawn_bound(async move { send_to_inbox(&wrap, &pk).await });
}
}
writing::settle_writers(transport, community, before, after).await
}
/// Deliver each Channel's key, and every past epoch this device reads, to the members who just
/// gained it with its history: on the Channel's access plane, which a member's client sweeps as
/// soon as its roster moves, rather than leaving them to another holder's duty. Every Channel in
/// one wave, so a Role that opens several keeps its member waiting one round trip, not one each.
/// One that fails is logged and left to that duty.
async fn deliver_gained<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, gained: &[(ChannelId, Vec<PublicKey>)]) -> Result<(), String> {
if gained.is_empty() {
return Ok(());
}
let held = crate::db::community::load_community_v2(community.id())?.ok_or("v2 community not found")?;
let ledger = crate::db::current_session().scoped::<AccessLedger, std::sync::Mutex<std::collections::HashSet<([u8; 32], u64, [u8; 32])>>>();
let delivered = in_one_wave(
gained
.iter()
.map(|(channel, readers)| {
let held = &held;
async move {
deliver_access(transport, held, channel, readers).await?;
deliver_history(transport, held, channel, readers).await
}
})
.collect(),
)
.await;
for ((channel, readers), delivered) in gained.iter().zip(delivered) {
let Some(epoch) = held.channel(channel).map(|c| c.epoch) else { continue };
match delivered {
Ok(_) => ledger.lock().unwrap_or_else(|e| e.into_inner()).extend(readers.iter().map(|pk| (channel.0, epoch.0, pk.to_bytes()))),
Err(e) => crate::log_warn!("[v2:access] delivering a gained channel's key failed (a holder's duty retries): {e}"),
}
}
Ok(())
}
/// A gift wrap to `recipient`'s DM inbox as well: their client reads gift wraps there, and a
/// Community's relays only for its planes.
async fn send_to_inbox(wrap: &Event, recipient: &PublicKey) {
let Some(client) = crate::state::nostr_client() else { return };
let targets = crate::inbox_relays::resolve_gift_wrap_targets(&client, recipient).await;
if let Err(e) = crate::inbox_relays::publish_gift_wrap_to_targets(&client, &targets, wrap).await {
crate::log_warn!("[v2:access] a Direct Invite didn't reach the recipient's inbox (the community relays carry it): {e}");
}
crate::inbox_relays::teardown_gift_wrap_targets(&client, &targets).await;
}
/// A Channel's access plane at the community's root epoch (CORD-03 §5).
fn access_group(community: &CommunityV2, channel: &ChannelId) -> super::derive::GroupKey {
super::derive::channel_access_group_key(&community.community_root, channel, community.root_epoch)
}
/// Every access delivery for a Channel on its plane, paged as the plane key: the address is
/// root-derived, so any root holder can bury the real deliveries under a single page.
async fn fetch_access_deliveries<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel: &ChannelId) -> Result<Vec<rekey::AccessDelivery>, String> {
fetch_plane_deliveries(transport, community, channel, rekey::RekeyScope::Channel(*channel)).await
}
tokio::task_local! {
/// The access planes one settling action has read, by address: `None` once the action wrote
/// to the plane itself, after which every read of it goes to the relays again.
static ACCESS_READS: std::cell::RefCell<std::collections::HashMap<[u8; 32], Option<std::sync::Arc<Vec<Event>>>>>;
}
/// Run `action` asking the relays for each access plane once, however many kinds of record it
/// takes from one: a plane holds the Channel's keys, its history, its writer keys and their
/// certifiers, and each is read by a step of its own. A plane the action writes to is read
/// afresh from then on, so it never judges on a copy from before its own delivery.
async fn reading_planes_once<F: std::future::Future>(action: F) -> F::Output {
if ACCESS_READS.try_with(|_| ()).is_ok() {
return action.await;
}
ACCESS_READS.scope(Default::default(), action).await
}
/// Every wrap on an access plane, from this action's earlier read of it when it has one.
async fn access_plane_wraps<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, group: &GroupKey) -> Result<std::sync::Arc<Vec<Event>>, String> {
let address = group.pk().to_bytes();
let read = ACCESS_READS.try_with(|reads| reads.borrow().get(&address).cloned()).ok().flatten();
if let Some(Some(wraps)) = read {
return Ok(wraps);
}
let wraps = std::sync::Arc::new(plane_wraps(transport, community, group).await?);
if read.is_none() {
let _ = ACCESS_READS.try_with(|reads| reads.borrow_mut().entry(address).or_insert_with(|| Some(wraps.clone())).is_some());
}
Ok(wraps)
}
/// This action is about to write to an access plane: what it read of it before no longer stands.
fn wrote_access_plane(group: &GroupKey) {
let _ = ACCESS_READS.try_with(|reads| reads.borrow_mut().insert(group.pk().to_bytes(), None));
}
/// The deliveries of `scope`'s keys on a Channel's access plane.
async fn fetch_plane_deliveries<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel: &ChannelId, scope: rekey::RekeyScope) -> Result<Vec<rekey::AccessDelivery>, String> {
let group = access_group(community, channel);
let wraps = access_plane_wraps(transport, community, &group).await?;
Ok(wraps
.iter()
.filter_map(|w| stream::open_wrap(w, &group).ok().and_then(|o| rekey::parse_access_delivery(&o).ok()))
.filter(|d| d.scope.id32() == scope.id32())
.collect())
}
/// Whether `member` holds a blob for `epoch` on the plane from a deliverer `trusted` admits:
/// anyone can put a blob at anyone's locator, so only a delivery a reader would take counts.
fn served_on_plane(deliveries: &[rekey::AccessDelivery], member: &PublicKey, channel: &ChannelId, epoch: Epoch, trusted: &dyn Fn(&PublicKey) -> bool) -> bool {
served_at(deliveries, member, rekey::RekeyScope::Channel(*channel), epoch, trusted)
}
fn served_at(deliveries: &[rekey::AccessDelivery], member: &PublicKey, scope: rekey::RekeyScope, epoch: Epoch, trusted: &dyn Fn(&PublicKey) -> bool) -> bool {
deliveries
.iter()
.filter(|d| d.epoch == epoch && trusted(&d.deliverer))
.any(|d| rekey::find_my_blob(&d.blobs, &d.deliverer.to_bytes(), &member.to_bytes(), scope, epoch).is_some())
}
struct MintedRotations;
type MintedMap = std::sync::Mutex<std::collections::HashMap<([u8; 32], u64), std::sync::Arc<Vec<(PublicKey, Vec<rekey::RekeyBlob>)>>>>;
/// The complete rotations that minted a Channel's `epoch`, each as its rotator and blobs.
/// A complete rotation never changes, so a found set is held for the session.
async fn minting_rotations<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel: &ChannelId, epoch: Epoch) -> Result<std::sync::Arc<Vec<(PublicKey, Vec<rekey::RekeyBlob>)>>, String> {
let cache = crate::db::current_session().scoped::<MintedRotations, MintedMap>();
if let Some(held) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(&(channel.0, epoch.0)) {
return Ok(held.clone());
}
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let mut out = Vec::new();
for root in channel_rekey_addressing_roots(community.community_root, &cid_hex) {
let group = channel_rekey_group_key(&root, channel, epoch);
for r in rekey::collect_rotations(&fetch_rekey_chunks(transport, &community, &group).await?) {
if r.is_complete() && r.new_epoch == epoch && matches!(r.scope, rekey::RekeyScope::Channel(c) if c.0 == channel.0) {
out.push((r.rotator, r.blobs));
}
}
}
let out = std::sync::Arc::new(out);
if !out.is_empty() {
cache.lock().unwrap_or_else(|e| e.into_inner()).insert((channel.0, epoch.0), out.clone());
}
Ok(out)
}
/// Whether an authorized one of `rotations` carried `member` a blob.
fn rotation_carries(rotations: &[(PublicKey, Vec<rekey::RekeyBlob>)], authorized: &dyn Fn(&PublicKey) -> bool, member: &PublicKey, channel: &ChannelId, epoch: Epoch) -> bool {
let scope = rekey::RekeyScope::Channel(*channel);
rotations
.iter()
.filter(|(rotator, _)| authorized(rotator))
.any(|(rotator, blobs)| rekey::find_my_blob(blobs, &rotator.to_bytes(), &member.to_bytes(), scope, epoch).is_some())
}
/// Deliver the key this device holds for `channel` to `recipients` on its access plane.
async fn deliver_access<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel: &ChannelId, recipients: &[PublicKey]) -> Result<(), String> {
let ch = community.channel(channel).ok_or("no such channel")?;
let key = ch.key.ok_or("this device doesn't hold that channel's key")?;
deliver_on_plane(transport, community, channel, rekey::RekeyScope::Channel(*channel), ch.epoch, None, &key, recipients).await
}
/// Deliver `key`, `scope`'s at `epoch`, to `recipients` on `channel`'s access plane; a writer key
/// names the address it derives to.
#[allow(clippy::too_many_arguments)]
async fn deliver_on_plane<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel: &ChannelId, scope: rekey::RekeyScope, epoch: Epoch, writer: Option<[u8; 32]>, key: &[u8; 32], recipients: &[PublicKey]) -> Result<(), String> {
deliver_certified(transport, community, channel, scope, epoch, writer, key, recipients, &Default::default()).await
}
/// [`deliver_on_plane`], each recipient's writer certificate riding the event that carries its blob.
#[allow(clippy::too_many_arguments)]
async fn deliver_certified<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel: &ChannelId,
scope: rekey::RekeyScope,
epoch: Epoch,
writer: Option<[u8; 32]>,
key: &[u8; 32],
recipients: &[PublicKey],
certs: &std::collections::HashMap<PublicKey, chat::WriterCert>,
) -> Result<(), String> {
for wrap in build_deliveries(community, channel, scope, epoch, writer, key, recipients, certs, false).await? {
transport.publish(&wrap, &community.relays).await?;
}
Ok(())
}
/// The sealed events of a delivery, built whole before any is sent: every blob is a signer
/// round trip. `mint` marks each as a part of a writer epoch's minting delivery.
#[allow(clippy::too_many_arguments)]
async fn build_deliveries(
community: &CommunityV2,
channel: &ChannelId,
scope: rekey::RekeyScope,
epoch: Epoch,
writer: Option<[u8; 32]>,
key: &[u8; 32],
recipients: &[PublicKey],
certs: &std::collections::HashMap<PublicKey, chat::WriterCert>,
mint: bool,
) -> Result<Vec<Event>, String> {
use nostr_sdk::prelude::AsyncGetPublicKey;
let signer = crate::signer::active_signer()?;
let me = me_pk()?;
// The signer is resolved process-wide; never let another account's sign for this one.
if signer.get_public_key_async().await.map_err(|e| e.to_string())? != me {
return Err("the active signer isn't this account".to_string());
}
let group = access_group(community, channel);
wrote_access_plane(&group);
let mut blobs = Vec::with_capacity(recipients.len());
for r in recipients {
blobs.push(rekey::build_blob(&signer, &me.to_bytes(), r, scope, epoch, key).await.map_err(|e| e.to_string())?);
}
let at = now_ms() / 1000;
let per_event = if certs.is_empty() { rekey::MAX_REKEY_BLOBS_PER_EVENT } else { rekey::MAX_CERTIFIED_BLOBS_PER_EVENT };
let parts = blobs.len().div_ceil(per_event).max(1);
let mut out = Vec::with_capacity(parts);
for (i, (part, who)) in blobs.chunks(per_event).zip(recipients.chunks(per_event)).enumerate() {
let mut whole: Vec<([u8; 32], [u8; 64])> = Vec::new();
let mut scoped: Vec<([u8; 32], [u8; 64], u64)> = Vec::new();
for r in who {
match certs.get(r) {
Some(chat::WriterCert::Full(c)) => whole.push((r.to_bytes(), *c)),
Some(chat::WriterCert::Scoped(c, rights)) => scoped.push((r.to_bytes(), *c, *rights)),
None => {}
}
}
let rumor = rekey::build_access_rumor_scoped(me, scope, epoch, writer, part, &whole, &scoped, at).map_err(|e| e.to_string())?;
let rumor = if mint { rekey::as_mint_part(rumor, i + 1, parts) } else { rumor };
let (wrap, _) = stream::seal_and_wrap_signed(&signer, me, &rumor, stream::SealForm::Encrypted, &group, stream::KIND_WRAP, Timestamp::from_secs(at), &[])
.await
.map_err(|e| e.to_string())?;
out.push(wrap);
}
Ok(out)
}
/// Deliver every past epoch of `channel` this device can read, read-only, to `recipients`:
/// one history event per epoch on the access plane (CORD-03 §5). Returns the epochs sent.
async fn deliver_history<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel: &ChannelId, recipients: &[PublicKey]) -> Result<usize, String> {
use nostr_sdk::prelude::AsyncGetPublicKey;
let ch = community.channel(channel).ok_or("no such channel")?;
let (cid_hex, ch_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&channel.0));
let mut views: std::collections::BTreeMap<u64, rekey::HistoryView> = crate::db::community::history_views(&cid_hex, &ch_hex)?
.into_iter()
.filter(|(e, _)| *e < ch.epoch)
.map(|(e, v)| (e.0, v))
.collect();
for (e, secret) in crate::db::community::held_epoch_keys(&cid_hex, &ch_hex)? {
if e < ch.epoch && secret != community.community_root {
views.insert(e.0, rekey::HistoryView::of(&channel_group_key(&secret, channel, e)));
}
}
if views.is_empty() || recipients.is_empty() {
return Ok(0);
}
let signer = crate::signer::active_signer()?;
let me = me_pk()?;
if signer.get_public_key_async().await.map_err(|e| e.to_string())? != me {
return Err("the active signer isn't this account".to_string());
}
let group = access_group(community, channel);
wrote_access_plane(&group);
let at = now_ms() / 1000;
for (epoch, view) in &views {
let epoch = Epoch(*epoch);
let mut blobs = Vec::with_capacity(recipients.len());
for r in recipients {
blobs.push(rekey::build_history_blob(&signer, &me.to_bytes(), r, channel, epoch, view).await.map_err(|e| e.to_string())?);
}
for part in blobs.chunks(rekey::MAX_WIDE_BLOBS_PER_EVENT) {
let rumor = rekey::build_history_rumor(me, channel, epoch, part, at).map_err(|e| e.to_string())?;
let (wrap, _) = stream::seal_and_wrap_signed(&signer, me, &rumor, stream::SealForm::Encrypted, &group, stream::KIND_WRAP, Timestamp::from_secs(at), &[])
.await
.map_err(|e| e.to_string())?;
transport.publish(&wrap, &community.relays).await?;
}
}
Ok(views.len())
}
/// Every history delivery for `channel` on its access plane.
async fn fetch_history_deliveries<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel: &ChannelId) -> Result<Vec<rekey::HistoryDelivery>, String> {
let group = access_group(community, channel);
let wraps = access_plane_wraps(transport, community, &group).await?;
Ok(wraps.iter().filter_map(|w| stream::open_wrap(w, &group).ok().and_then(|o| rekey::parse_history_delivery(&o, channel).ok())).collect())
}
struct OpenedHistory;
struct HistoryCollectClock;
/// How often a member re-reads history deliveries when nothing moved.
const HISTORY_COLLECT_PERIOD_MS: u64 = 10 * 60 * 1000;
/// Whether to read history deliveries for a community now: when the roster moved or a key was
/// just adopted, else once per period. Marks it read.
pub(crate) fn history_collect_due(id: &crate::community::CommunityId, moved: bool) -> bool {
let clock = crate::db::current_session().scoped::<HistoryCollectClock, std::sync::Mutex<std::collections::HashMap<[u8; 32], u64>>>();
let mut last = clock.lock().unwrap_or_else(|e| e.into_inner());
let now = now_ms();
let due = moved || last.get(&id.0).is_none_or(|t| now.saturating_sub(*t) > HISTORY_COLLECT_PERIOD_MS);
if due {
last.insert(id.0, now);
}
due
}
/// Read Message History, member side (CORD-03 §5): for each private channel this member reads
/// with READ_MESSAGE_HISTORY, archive every past epoch it lacks that a deliverer the channel
/// lets in sent it read-only. Returns how many epochs were archived.
pub async fn collect_history<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<usize, String> {
let mut archived = 0;
for (_, n) in collect_history_rooms(transport, community).await? {
archived += n;
}
Ok(archived)
}
/// [`collect_history`], by Channel: each that took a past epoch, and how many. What those epochs
/// hold is read by nothing yet.
pub async fn collect_history_rooms<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<Vec<(ChannelId, usize)>, String> {
use crate::community::roles::Permissions;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let roster = crate::db::community::get_community_roles(&cid_hex)?;
if roster.everyone.is_none() {
return Ok(Vec::new());
}
let owner_hex = community.owner()?.to_hex();
let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
let me = me_pk()?;
let signer = crate::signer::active_signer()?;
let opened = crate::db::current_session().scoped::<OpenedHistory, Opened>();
let mut archived: Vec<(ChannelId, usize)> = Vec::new();
let readable: Vec<_> = community
.channels
.iter()
.filter(|c| c.private && c.key.is_some())
.filter(|ch| roster.channel_permissions(Some(&owner_hex), &me.to_hex(), &crate::simd::hex::bytes_to_hex_32(&ch.id.0), true).contains(Permissions::READ_MESSAGE_HISTORY))
.collect();
let reads = in_one_wave(readable.iter().map(|ch| fetch_history_deliveries(transport, community, &ch.id)).collect()).await;
let mut unread = None;
for (ch, read) in readable.into_iter().zip(reads) {
let chan = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
let read = match read {
Ok(read) => read,
Err(e) => {
unread.get_or_insert(e);
continue;
}
};
let mut held: std::collections::HashSet<u64> = crate::db::community::held_epoch_keys(&cid_hex, &chan)?.into_iter().map(|(e, _)| e.0).collect();
held.extend(crate::db::community::history_views(&cid_hex, &chan)?.into_iter().map(|(e, _)| e.0));
held.insert(ch.epoch.0);
for d in read {
let h = d.deliverer.to_hex();
let trusted = h == owner_hex || (!banned.contains(&h) && roster.is_entitled(Some(&owner_hex), &h, &chan, &[], &[]));
if !trusted || d.epoch >= ch.epoch || held.contains(&d.epoch.0) {
continue;
}
let Some(blob) = d.blobs.iter().find(|b| b.locator == rekey::history_locator(&d.deliverer.to_bytes(), &me.to_bytes(), &ch.id, d.epoch)) else { continue };
if !opened.lock().unwrap_or_else(|e| e.into_inner()).insert((ch.id.0, d.deliverer.to_bytes(), me.to_bytes(), d.epoch.0)) {
continue;
}
if let Ok(view) = rekey::open_history_blob(&signer, &d.deliverer, &ch.id, d.epoch, blob).await {
crate::db::community::store_history_view(&cid_hex, &chan, d.epoch.0, &view)?;
held.insert(d.epoch.0);
match archived.last_mut() {
Some((last, n)) if *last == ch.id => *n += 1,
_ => archived.push((ch.id, 1)),
}
}
}
}
match unread {
Some(e) => Err(e),
None => Ok(archived),
}
}
struct AccessDutyClock;
/// How often a holder re-checks its channels' access planes when nothing in the roster moved.
const ACCESS_DUTY_PERIOD_MS: u64 = 10 * 60 * 1000;
/// Whether the access duty should run for a community now: whenever the roster moved, else
/// once per period. Marks it run.
pub(crate) fn access_duty_due(id: &crate::community::CommunityId, roster_moved: bool) -> bool {
let clock = crate::db::current_session().scoped::<AccessDutyClock, std::sync::Mutex<std::collections::HashMap<[u8; 32], u64>>>();
let mut last = clock.lock().unwrap_or_else(|e| e.into_inner());
let now = now_ms();
let due = roster_moved || last.get(&id.0).is_none_or(|t| now.saturating_sub(*t) > ACCESS_DUTY_PERIOD_MS);
if due {
last.insert(id.0, now);
}
due
}
struct AccessLedger;
struct OpenedDeliveries;
type Opened = std::sync::Mutex<std::collections::HashSet<([u8; 32], [u8; 32], [u8; 32], u64)>>;
/// Drop this session's marks of key, history and writer deliveries already opened.
fn forget_opened_deliveries() {
let session = crate::db::current_session();
*session.scoped::<OpenedDeliveries, Opened>().lock().unwrap_or_else(|e| e.into_inner()) = Default::default();
*session.scoped::<OpenedHistory, Opened>().lock().unwrap_or_else(|e| e.into_inner()) = Default::default();
writing::forget_opened_writer_blobs();
}
struct AccessCollectClock;
/// How often a keyless member re-reads its access planes when nothing in the roster moved.
const ACCESS_COLLECT_PERIOD_MS: u64 = 60 * 1000;
fn access_collect_clock() -> std::sync::Arc<std::sync::Mutex<std::collections::HashMap<[u8; 32], u64>>> {
crate::db::current_session().scoped::<AccessCollectClock, std::sync::Mutex<std::collections::HashMap<[u8; 32], u64>>>()
}
/// Make the next follow pass run the access duty.
pub(crate) fn access_duty_now(id: &crate::community::CommunityId) {
crate::db::current_session().scoped::<AccessDutyClock, std::sync::Mutex<std::collections::HashMap<[u8; 32], u64>>>().lock().unwrap_or_else(|e| e.into_inner()).remove(&id.0);
}
/// Let the next follow read a community's access planes whatever the period says.
pub(crate) fn access_collect_now(id: &crate::community::CommunityId) {
access_collect_clock().lock().unwrap_or_else(|e| e.into_inner()).remove(&id.0);
}
/// Whether to read the access planes for a community now: whenever the roster moved, else once
/// per period. Marks it read.
pub(crate) fn access_collect_due(id: &crate::community::CommunityId, roster_moved: bool) -> bool {
let clock = access_collect_clock();
let mut last = clock.lock().unwrap_or_else(|e| e.into_inner());
let now = now_ms();
let due = roster_moved || last.get(&id.0).is_none_or(|t| now.saturating_sub(*t) > ACCESS_COLLECT_PERIOD_MS);
if due {
last.insert(id.0, now);
}
due
}
/// Of `out`, whom a whole read of the Roster taken now still leaves out of `chan`. A read that
/// can't be taken whole cuts nobody: the duty runs again.
async fn still_left_out<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, chan: &str, owner_hex: &str, out: Vec<PublicKey>) -> Vec<PublicKey> {
let now = fetch_authority(transport, community).await;
if !now.everyone_served || now.gapped {
return Vec::new();
}
out.into_iter().filter(|pk| now.banned.contains(&pk.to_hex()) || !now.roles.is_entitled(Some(owner_hex), &pk.to_hex(), chan, &[], &[])).collect()
}
/// What one run of the access duty did.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct AccessDuty {
/// Keys delivered on access planes.
pub delivered: usize,
/// Holders cut by a rotation because the channel no longer lets them in.
pub cut: usize,
/// What the writer duty did for restricted Channels (CORD-03 §1).
pub writers: WriterDuty,
/// Private Channels whose metadata was sealed under their current key (CORD-03 §2).
pub resealed: usize,
/// Public Channels whose earlier planes this device published for every member (CORD-03 §2).
pub history: usize,
}
/// The holder's duty (CORD-03 §5): for every private Channel this device holds and may read,
/// deliver the key to each entitled member nobody has served at its epoch: not a reader-trusted
/// delivery on the plane, not the rotation that minted it, and not this device before. A member
/// who held the previous epoch and that rotation left out was cut, whatever the roster says.
/// As the revocation backstop, a manager who outranks a holder the channel no longer lets in
/// rotates them out.
pub async fn access_duty<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<AccessDuty, String> {
reading_planes_once(access_duty_once(transport, community)).await
}
async fn access_duty_once<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<AccessDuty, String> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
if crate::db::community::get_community_roles(&cid_hex)?.everyone.is_none() {
return Ok(AccessDuty::default());
}
// Judged on a whole read, never the stored roster: a stale entitlement would hand a new
// epoch's key to someone its rotation just cut.
let fresh = fetch_authority(transport, community).await;
if !fresh.everyone_served || fresh.gapped {
return Err("the roster couldn't be read whole; no key was delivered".to_string());
}
let (roster, banned) = (fresh.roles, fresh.banned);
let owner_hex = community.owner()?.to_hex();
let me = me_pk()?;
let candidates = access_candidates(community, &roster)?;
let rotator_ok = |r: &PublicKey| rotates_channels(&roster, &owner_hex, banned.iter(), &r.to_hex());
let ledger = crate::db::current_session().scoped::<AccessLedger, std::sync::Mutex<std::collections::HashSet<([u8; 32], u64, [u8; 32])>>>();
let me_hex = me.to_hex();
let may_rotate = me_hex == owner_hex || roster.is_authorized(&me_hex, Some(&owner_hex), crate::community::roles::Permissions::MANAGE_CHANNELS);
let banned_pks: Vec<PublicKey> = banned.iter().filter_map(|h| PublicKey::from_hex(h).ok()).collect();
let mut done = AccessDuty::default();
// One half's failure never stops the other: the writer duty runs whatever the keys did.
let keys: Result<(), String> = async {
for ch in community.channels.iter().filter(|c| c.private && c.key.is_some()) {
let chan = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
let entitled_here = |pk: &PublicKey| pk.to_hex() == owner_hex || (!banned.contains(&pk.to_hex()) && roster.is_entitled(Some(&owner_hex), &pk.to_hex(), &chan, &[], &[]));
// Readers adopt only from a deliverer their fold entitles.
if !entitled_here(&me) {
continue;
}
let epoch = ch.epoch;
let held = ledger.lock().unwrap_or_else(|e| e.into_inner()).clone();
let entitled: Vec<PublicKey> = candidates
.iter()
.filter(|pk| **pk != me && entitled_here(pk) && !held.contains(&(ch.id.0, epoch.0, pk.to_bytes())))
.copied()
.collect();
if entitled.is_empty() && !may_rotate {
continue;
}
let deliveries = fetch_access_deliveries(transport, community, &ch.id).await?;
let minted = minting_rotations(transport, community, &ch.id, epoch).await?;
let prior = match epoch.0.checked_sub(1) {
Some(p) if p > 0 => minting_rotations(transport, community, &ch.id, Epoch(p)).await?,
_ => Default::default(),
};
let prev = Epoch(epoch.0.saturating_sub(1));
if may_rotate {
let out: Vec<PublicKey> = candidates
.iter()
.chain(banned_pks.iter())
.filter(|pk| **pk != me && !entitled_here(pk))
.filter(|pk| rotation_carries(&minted, &rotator_ok, pk, &ch.id, epoch) || served_on_plane(&deliveries, pk, &ch.id, epoch, &entitled_here))
.filter(|pk| me_hex == owner_hex || roster.can_act_on_member(&me_hex, Some(&owner_hex), &pk.to_hex(), crate::community::roles::Permissions::MANAGE_CHANNELS))
.copied()
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
.collect();
// The Roster was read before the plane: someone let in between the two reads holds a
// delivery the read can't account for. Cut only who a fresh read still leaves out.
let out = match out.is_empty() {
true => out,
false => still_left_out(transport, community, &chan, &owner_hex, out).await,
};
if !out.is_empty() {
if rekey_channel_at(transport, community, &ch.id, &rotation_roster(roster.clone(), &cid_hex), &[], &out, Some(epoch)).await? {
done.cut += out.len();
}
// Whoever is owed this channel is owed its next epoch now; the next run serves them.
continue;
}
}
let unserved: Vec<PublicKey> = entitled
.into_iter()
.filter(|pk| {
let carried = rotation_carries(&minted, &rotator_ok, pk, &ch.id, epoch);
let cut = !carried
&& minted.iter().any(|(r, _)| rotator_ok(r))
&& (rotation_carries(&prior, &rotator_ok, pk, &ch.id, prev) || served_on_plane(&deliveries, pk, &ch.id, prev, &entitled_here));
!carried && !cut && !served_on_plane(&deliveries, pk, &ch.id, epoch, &entitled_here)
})
.collect();
// With Read Message History they take this epoch and every past one this device can
// read; without it, only a fresh epoch, so history starts where access did.
let (readers, fresh): (Vec<PublicKey>, Vec<PublicKey>) = unserved.into_iter().partition(|pk| roster.reads_history(Some(&owner_hex), &pk.to_hex(), &chan, &[], &[]));
if !readers.is_empty() {
deliver_access(transport, community, &ch.id, &readers).await?;
deliver_history(transport, community, &ch.id, &readers).await?;
ledger.lock().unwrap_or_else(|e| e.into_inner()).extend(readers.iter().map(|pk| (ch.id.0, epoch.0, pk.to_bytes())));
done.delivered += readers.len();
}
if !fresh.is_empty() && may_rotate && rekey_channel_at(transport, community, &ch.id, &rotation_roster(roster.clone(), &cid_hex), &[], &[], Some(epoch)).await? {
done.delivered += fresh.len();
}
}
Ok(())
}
.await;
let writers = writing::writer_duty(transport, community, &roster, &banned).await;
if may_rotate {
done.resealed = reseal_backstop(transport, community, &roster).await;
done.history = history_backstop(transport, community, &roster).await;
}
done.writers = writers?;
keys.map(|_| done)
}
/// Fetch the keys delivered to me for every private Channel I'm entitled to but can't read,
/// and park them for the vend judge to adopt (CORD-03 §5). Returns how many were parked.
pub async fn collect_access<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<usize, String> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let roster = crate::db::community::get_community_roles(&cid_hex)?;
if roster.everyone.is_none() {
return Ok(0);
}
let owner_hex = community.owner()?.to_hex();
let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
let me = me_pk()?;
let signer = crate::signer::active_signer()?;
let opened = crate::db::current_session().scoped::<OpenedDeliveries, Opened>();
let mut parked = 0;
let owed: Vec<_> = community
.channels
.iter()
.filter(|c| c.private && c.key.is_none())
.filter(|ch| roster.is_entitled(Some(&owner_hex), &me.to_hex(), &crate::simd::hex::bytes_to_hex_32(&ch.id.0), &[], &[]))
.collect();
// One wave for every plane: a member let into several channels waits one round trip, not
// one each. A plane that can't be read keeps nobody from the others.
let reads = in_one_wave(owed.iter().map(|ch| fetch_access_deliveries(transport, community, &ch.id)).collect()).await;
let mut unread = None;
for (ch, read) in owed.into_iter().zip(reads) {
let chan = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
let read = match read {
Ok(read) => read,
Err(e) => {
unread.get_or_insert(e);
continue;
}
};
let scope = rekey::RekeyScope::Channel(ch.id);
// Only deliverers the channel lets in, and only an epoch the keyless walk has reached
// or its next: a keyless channel seats whatever it adopts first, so neither a stale key
// nor one claimed far ahead may ever be on offer.
let window = ch.epoch.0..=ch.epoch.0.saturating_add(1);
let deliveries: Vec<rekey::AccessDelivery> = read
.into_iter()
.filter(|d| window.contains(&d.epoch.0))
.filter(|d| {
// A manager counts: the creator rule that may let them in is sealed from a keyless reader.
let h = d.deliverer.to_hex();
h == owner_hex
|| (!banned.contains(&h)
&& (roster.is_entitled(Some(&owner_hex), &h, &chan, &[], &[]) || roster.is_authorized(&h, Some(&owner_hex), crate::community::roles::Permissions::MANAGE_CHANNELS)))
})
.collect();
let Some(newest) = deliveries.iter().map(|d| d.epoch).max() else { continue };
for d in deliveries.iter().filter(|d| d.epoch == newest) {
let mine: Vec<&rekey::RekeyBlob> = rekey::find_my_blobs(&d.blobs, &d.deliverer.to_bytes(), &me.to_bytes(), scope, d.epoch).collect();
// Opened once a session: parking again would trim other candidates out of the cap.
if mine.is_empty() || !opened.lock().unwrap_or_else(|e| e.into_inner()).insert((ch.id.0, d.deliverer.to_bytes(), me.to_bytes(), d.epoch.0)) {
continue;
}
for blob in mine {
if let Ok(key) = rekey::open_blob(&signer, &d.deliverer, scope, d.epoch, blob).await {
crate::db::community::park_channel_key(&cid_hex, &chan, d.epoch.0, &key, &d.deliverer.to_hex())?;
parked += 1;
break;
}
}
}
}
match unread {
Some(e) => Err(e),
None => Ok(parked),
}
}
/// Run `reads` together, a few at a time, and hand back what each came to in the order given.
async fn in_one_wave<F: std::future::Future>(reads: Vec<F>) -> Vec<F::Output> {
use futures_util::stream::StreamExt;
futures_util::stream::iter(reads).buffered(CHANNEL_FAN_CONCURRENCY).collect().await
}
/// Whether `member` holds any Role here by the stored Roster.
pub(crate) fn holds_grant(community: &CommunityV2, member: &PublicKey) -> bool {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let hex = member.to_hex();
crate::db::community::get_community_roles(&cid_hex).is_ok_and(|r| r.grants.iter().any(|g| g.member == hex && !g.role_ids.is_empty()))
}
/// Whether the stored Roster still owes this member a key someone else must deliver: a Private
/// Channel's, or a restricted Channel's writer key.
pub(crate) fn owed_keys(community: &CommunityV2) -> bool {
owed_channel_keys(community) || writing::owed_writer_keys(community)
}
/// Whether a restricted Channel's writer key, certificate or certifier is still owed to this member.
pub(crate) fn owed_writer_keys(community: &CommunityV2) -> bool {
writing::owed_writer_keys(community)
}
/// Whether the stored Roster lets this member into a Private Channel it holds no key for, with
/// its history: the key is then delivered on the access plane. Without history it comes in the
/// rotation that mints the member a fresh epoch, which the rekey walk takes.
pub(crate) fn owed_channel_keys(community: &CommunityV2) -> bool {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let (Ok(roster), Ok(owner), Ok(me)) = (crate::db::community::get_community_roles(&cid_hex), community.owner(), me_pk()) else { return false };
if roster.everyone.is_none() {
return false;
}
let (owner_hex, me_hex) = (owner.to_hex(), me.to_hex());
community
.channels
.iter()
.filter(|c| c.private && c.key.is_none())
.map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0))
.any(|chan| roster.is_entitled(Some(&owner_hex), &me_hex, &chan, &[], &[]) && roster.reads_history(Some(&owner_hex), &me_hex, &chan, &[], &[]))
}
/// Everyone a Private Channel's key could be owed to: every Grant holder, every member an
/// overwrite names, and every member this device knows.
fn access_candidates(community: &CommunityV2, roster: &crate::community::roles::CommunityRoles) -> Result<Vec<PublicKey>, String> {
use crate::community::roles::OverwriteTarget;
// A memberlist we can't read would leave roleless entitled members off a rekey.
let mut out: std::collections::BTreeSet<PublicKey> = stored_memberlist(community)?.into_iter().collect();
out.extend(roster.grants.iter().filter_map(|g| PublicKey::from_hex(&g.member).ok()));
out.extend(roster.overwrites.iter().filter_map(|o| match &o.target {
OverwriteTarget::Member(m) => PublicKey::from_hex(m).ok(),
_ => None,
}));
let banned = crate::db::community::get_community_banlist(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap_or_default();
Ok(out.into_iter().filter(|pk| !banned.contains(&pk.to_hex())).collect())
}
/// Move a Community to Roles v2 (CORD-04 §2), owner only: each legacy Role is carried
/// across in the same order, names, colours and bits, continuing its own chain so its
/// Grants keep resolving, then `@everyone` is published, which is the switch itself.
pub async fn activate_roles_v2<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, everyone: u64) -> Result<usize, String> {
crate::db::scoped(async move {
if me_pk()? != community.owner()? {
return Err("only the owner moves a community to the new roles".to_string());
}
let view = fetch_authority(transport, community).await;
if view.activated {
return Err("this community already uses the new roles".to_string());
}
// The switch lists every Channel that stands; one it can't list would vanish for joiners.
let community = &follow_fresh(transport, community.id()).await?.1;
if community.channels.len() > super::roles::MAX_LEGACY_CHANNELS {
return Err(format!("a community moves to the new roles with at most {} channels", super::roles::MAX_LEGACY_CHANNELS));
}
let mut legacy: Vec<crate::community::roles::Role> = view.roles.roles.clone();
legacy.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.role_id.cmp(&b.role_id)));
let mut last: Option<String> = None;
let mut prev_position: Option<u32> = None;
for role in &legacy {
require_role_head(&view, &role.role_id)?;
// Legacy peers stay peers.
let rank = match (&last, prev_position) {
(Some(k), Some(p)) if p == role.position => k.clone(),
_ => crate::community::rank::between(last.as_deref(), None).ok_or("too many roles to carry across")?,
};
let mut next = role.clone();
next.rank = Some(rank.clone());
next.scope = crate::community::roles::RoleScope::Server;
// A managing Role predates the channel bits; it keeps managing channel access.
if next.permissions.contains(crate::community::roles::Permissions::MANAGE_ROLES) {
next.permissions = crate::community::roles::Permissions(next.permissions.0 | super::roles::EVERYONE_DEFAULT);
}
// The legacy member list set admins apart; they stay apart.
next.display |= role.permissions.is_management();
set_role_v2(transport, community, &next).await?;
last = Some(rank);
prev_position = Some(role.position);
}
// A channel access role becomes a Role its private Channel lets through, which is
// closed to everyone else by default. Who holds the key is unchanged.
use crate::community::roles::{Overwrite, OverwriteTarget, Permissions, RoleScope};
let view_bit = Permissions(Permissions::VIEW_CHANNEL);
let mut scoped: std::collections::BTreeMap<String, Vec<String>> = Default::default();
for role in &legacy {
if let RoleScope::Channel(c) = &role.scope {
scoped.entry(c.to_ascii_lowercase()).or_default().push(role.role_id.clone());
}
}
for (chan, role_ids) in &scoped {
let Some(scope) = crate::simd::hex::hex_to_bytes_32_checked(chan) else { continue };
let targets = role_ids.iter().map(|id| (OverwriteTarget::Role(id.clone()), view_bit, Permissions(0)));
for (target, allow, deny) in targets {
let bytes = super::roles::overwrite_target_bytes(community.id(), &target).ok_or("malformed target")?;
let o = Overwrite { scope: chan.clone(), target, allow, deny };
publish_control_edition(transport, community, vsk::CHANNEL_ACL, &super::derive::acl_locator(community.id(), &scope, &bytes), &super::roles::overwrite_content_json(&o)).await?;
}
}
let eid = super::derive::everyone_locator(community.id());
let standing: std::collections::BTreeSet<String> = community.channels.iter().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)).collect();
publish_control_edition(transport, community, vsk::ROLE_V2, &eid, &super::roles::everyone_content_json_with(everyone, Some(&standing))).await?;
Ok(legacy.len())
})
.await
}
/// The heads a Tenure seals for a member, in the order a budget keeps them: their deletions,
/// which are terminal, then their authority heads, then the rest of what they decided.
fn seal_order(authority: &[FoldedHead], control: &[FoldedHead], theirs: impl Fn(&FoldedHead) -> bool, deletes: impl Fn(&FoldedHead) -> bool) -> Vec<[u8; 32]> {
let mut out: Vec<[u8; 32]> = Vec::new();
let ordered = control
.iter()
.filter(|h| theirs(h) && deletes(h))
.chain(authority.iter().filter(|h| theirs(h)))
.chain(control.iter().filter(|h| theirs(h) && !deletes(h)));
for h in ordered {
if !out.contains(&h.self_hash) {
out.push(h.self_hash);
}
}
out
}
/// How a reduction treats a member whose standing its writer can't seal whole.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Seal {
/// Refuse the reduction: a role edit waits for someone who holds the member's bits.
Strict,
/// Seal what the writer can and go ahead: a removal is never held hostage.
BestEffort,
}
/// Before a reduction, publish each member's Tenure sealing their current heads at the
/// standing they hold now (CORD-04 §9), so what they decided outlives the change.
async fn seal_standing<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, members: &[PublicKey], mode: Seal) -> Result<(), String> {
// The owner's Roles are display alone, so no Tenure names the owner (CORD-04 §3).
let owner = community.owner().ok();
let members: Vec<PublicKey> = members.iter().filter(|m| Some(**m) != owner).copied().collect();
if members.is_empty() {
return Ok(());
}
let members = members.as_slice();
crate::db::scoped(async move {
let cid = community.id();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)?
.into_iter()
.filter(|(_, f)| f.0 == community.root_epoch.0)
.map(|(entity, f)| (entity, (f.1, f.2, f.3, f.4, f.5)))
.collect();
let Some(editions) = fetch_control_plane_whole(transport, community).await else {
// Nothing to seal before Roles v2, and a removal never waits on a read.
let everyone_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::everyone_locator(cid));
if floors.contains_key(&everyone_hex) && mode == Seal::Strict {
return Err("the control plane couldn't be read whole; nothing was changed".to_string());
}
if floors.contains_key(&everyone_hex) {
crate::log_warn!("[v2:tenure] the control plane couldn't be read whole; removing without sealing");
}
return Ok(());
};
let authority = fold_authority(community, &editions, &floors);
if !authority.activated {
return Ok(());
}
let control = apply_control_fold(community, &editions, &floors, &authority);
let me = me_pk()?;
let me_hex = me.to_hex();
let is_owner = me == community.owner()?;
for member in members {
let member_hex = member.to_hex();
// Then authority heads: a budget cut drops a channel edit before a Grant. A Tenure
// of theirs listing an edition nobody has seen is left out: sealing it would let
// whoever signed that edition publish it later on this standing.
// A decided head's predecessor was seen too, served or compacted away.
let decided: std::collections::HashSet<[u8; 32]> = authority.heads.iter().chain(control.heads.iter()).map(|h| h.inner_id).collect();
let served: std::collections::HashSet<[u8; 32]> = editions
.iter()
.map(|e| e.self_hash)
.chain(editions.iter().filter(|e| decided.contains(&e.inner_id)).filter_map(|e| e.prev_hash))
.collect();
let vouches_only_for_served = |h: &FoldedHead| {
editions
.iter()
.find(|e| e.inner_id == h.inner_id && e.vsk == vsk::TENURE)
.and_then(|e| super::roles::parse_tenure_content(&e.content))
.is_none_or(|t| t.sealed.iter().flat_map(|x| x.heads.iter()).all(|x| crate::simd::hex::hex_to_bytes_32_checked(x).is_some_and(|b| served.contains(&b))))
};
// Deletions first of all: they are terminal, so a budget cut must never take one.
let deletes = |h: &FoldedHead| {
editions.iter().find(|e| e.inner_id == h.inner_id).is_some_and(|e| {
(e.vsk == vsk::CHANNEL_METADATA || e.vsk == vsk::CATEGORY) && deletes_entity(e.vsk == vsk::CATEGORY, &e.content)
})
};
let theirs = |h: &FoldedHead| h.author == member.to_bytes() && vouches_only_for_served(h);
let mut mine = seal_order(&authority.heads, &control.heads, theirs, deletes);
if mine.is_empty() {
continue;
}
let roles: Vec<&crate::community::roles::Role> = authority.roles.roles_of(&member_hex).collect();
let Some(top) = roles.iter().filter(|r| r.rank.is_some()).min_by_key(|r| r.position) else { continue };
let mut bits = roles.iter().fold(0u64, |acc, r| acc | r.permissions.0);
if !is_owner {
let support = authority.roles.permissions_above(&me_hex, top.position);
let whole = support.contains(crate::community::roles::Permissions::MANAGE_ROLES) && bits & !support.0 == 0;
match (whole, mode) {
(true, _) => {}
(false, Seal::Strict) => {
return Err("this member holds permissions you don't, so their decisions can't be kept; ask someone who holds them".to_string());
}
(false, Seal::BestEffort) if !support.contains(crate::community::roles::Permissions::MANAGE_ROLES) => continue,
(false, Seal::BestEffort) => bits &= support.0,
}
}
if mine.len() > super::roles::TENURE_HEAD_BUDGET {
if mode == Seal::Strict {
return Err("this member decided more than one record can keep; nothing was changed".to_string());
}
mine.truncate(super::roles::TENURE_HEAD_BUDGET);
}
let eid = super::derive::tenure_locator(cid, &member.to_bytes(), &me.to_bytes());
let eid_hex = crate::simd::hex::bytes_to_hex_32(&eid);
let held = authority.heads.iter().find(|h| h.entity_hex == eid_hex).and_then(|h| editions.iter().find(|e| e.inner_id == h.inner_id));
// Replacing a Tenure this fold can't see would drop what it sealed.
if held.is_none() && floors.contains_key(&eid_hex) && !authority.refused.contains(&eid_hex) {
match mode {
Seal::Strict => return Err("this member's earlier record isn't being served; nothing was changed, try again shortly".to_string()),
Seal::BestEffort => continue,
}
}
let prior = held.and_then(|e| super::roles::parse_tenure_content(&e.content)).map(|t| t.sealed).unwrap_or_default();
let entry = super::roles::TenureEntry { rank: top.rank.clone().expect("a ranked role"), permissions: bits, heads: mine.iter().map(crate::simd::hex::bytes_to_hex_32).collect() };
let Some(sealed) = super::roles::tenure_with(prior, entry, &mine) else { continue };
let tenure = super::roles::TenureContent { member: member_hex, sealed };
publish_control_edition(transport, community, vsk::TENURE, &eid, &super::roles::tenure_content_json(&tenure)?).await?;
}
Ok(())
})
.await
}
/// Set exactly which Roles `member` holds. A Grant replaces the member's whole set
/// (CORD-04 §2), so this is the one place a set is written: every change is judged
/// against the author's rank, and ids this device can't resolve ride through
/// untouched rather than being stripped by the device that knows least.
pub async fn set_member_roles<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
member: &PublicKey,
role_ids: Vec<String>,
) -> Result<(), String> {
change_member_roles(transport, community, member, move |_| role_ids).await
}
/// [`set_member_roles`] to what `next` makes of the Roles the member holds by the freshest
/// view, so a Role granted or taken elsewhere meanwhile is kept as it now stands.
pub async fn change_member_roles<T: Transport + ?Sized, F: FnOnce(&[String]) -> Vec<String> + Send>(
transport: &T,
community: &CommunityV2,
member: &PublicKey,
next: F,
) -> Result<(), String> {
crate::db::scoped(async move {
let view = fetch_authority(transport, community).await;
let author = role_author(community, &view)?;
let member_hex = member.to_hex();
// The owner may hold Roles, for display alone, and only the owner sets them (CORD-04 §3).
let owner_self = member_hex == author.owner_hex;
if owner_self && author.me_hex != author.owner_hex {
return Err("only the owner sets the owner's roles".to_string());
}
if owner_self && view.roles.everyone.is_none() {
return Err("the owner holds roles only on the new roles".to_string());
}
require_grant_head(community, &view, &member_hex)?;
let member_rank = view.roles.highest_position(&member_hex).unwrap_or(u32::MAX);
if !owner_self && (author.me_hex == member_hex || !author.supports(member_rank, 0)) {
return Err("you can only change the roles of members beneath you".to_string());
}
let current: Vec<String> = view
.roles
.grants
.iter()
.find(|g| g.member == member_hex)
.map(|g| g.role_ids.clone())
.unwrap_or_default();
let role_ids = next(¤t);
let mut next: Vec<String> = Vec::new();
for id in role_ids.iter().map(|r| r.to_ascii_lowercase()) {
if !next.contains(&id) {
next.push(id);
}
}
for id in next.iter().filter(|id| !current.contains(id)) {
let role = view.roles.role(id).ok_or("no such role")?;
if !author.supports(role.position, 0) {
return Err(format!("you can't grant \"{}\": it isn't beneath your own role", role.name));
}
}
let dropped: Vec<String> = current.iter().filter(|id| !next.contains(id)).cloned().collect();
for id in dropped {
// An unresolvable id can't be judged, so it can't be removed either.
match view.roles.role(&id) {
Some(role) if !author.supports(role.position, 0) => {
return Err(format!("you can't remove \"{}\": it isn't beneath your own role", role.name));
}
Some(_) => {}
None => next.push(id),
}
}
if next.len() > super::roles::MAX_ROLES_PER_MEMBER {
return Err(format!("a member holds at most {} roles", super::roles::MAX_ROLES_PER_MEMBER));
}
let mut a = current.clone();
let mut b = next.clone();
a.sort();
b.sort();
if a == b {
return Ok(());
}
// Keys follow the grant: one that opens a private channel this device can't key leaves
// the member at its door (CORD-03 §5).
if view.roles.everyone.is_some() {
let mut after = view.roles.clone();
after.grants.retain(|g| g.member != member_hex);
after.grants.push(crate::community::roles::MemberGrant { member: member_hex.clone(), role_ids: next.clone() });
let owner = Some(author.owner_hex.as_str());
let opened = community
.channels
.iter()
.filter(|c| c.private && c.key.is_none())
.map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0))
.filter(|chan| !view.roles.is_entitled(owner, &member_hex, chan, &[], &[]) && after.is_entitled(owner, &member_hex, chan, &[], &[]))
.count();
if opened > 0 {
let what = if next.iter().filter(|id| !current.contains(id)).count() > 1 { "these roles" } else { "this role" };
let channels = if opened == 1 { "a private channel".to_string() } else { format!("{opened} private channels") };
return Err(format!("You can't give {what}: it opens {channels} you don't have access to. Someone with access has to, or get access first."));
}
}
grant_roles_with_roster(transport, community, member, next.clone(), &view.roles).await?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
merge_local_roster(&cid_hex, None, Some(&crate::community::roles::MemberGrant { member: member_hex.clone(), role_ids: next.clone() }));
if owner_self {
return Ok(()); // the owner already holds every channel's key
}
settle_channel_keys(transport, community, &view, member, ¤t, &next).await
})
.await
}
/// Move Private Channel keys to match a role change (CORD-03: a key is "delivered on
/// grant and rekeyed on removal"). A role scoped to a channel IS its access list, so
/// gaining one owes the member that channel's key, and losing the last one that
/// entitled them rotates the channel without them. Without this a Grant would move
/// entitlement while the keys stayed where they were.
async fn settle_channel_keys<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
view: &AuthorityView,
member: &PublicKey,
before: &[String],
after: &[String],
) -> Result<(), String> {
use crate::community::roles::RoleScope;
if view.roles.everyone.is_some() {
let mut next = view.roles.clone();
let member_hex = member.to_hex();
next.grants.retain(|g| g.member != member_hex);
next.grants.push(crate::community::roles::MemberGrant { member: member_hex, role_ids: after.to_vec() });
return settle_access(transport, community, &view.roles, &next).await;
}
let added: Vec<String> = after.iter().filter(|id| !before.contains(id)).cloned().collect();
let removed: Vec<String> = before.iter().filter(|id| !after.contains(id)).cloned().collect();
let owner_hex = community.owner()?.to_hex();
let member_hex = member.to_hex();
let channel_of = |id: &String| match view.roles.role(id).map(|r| &r.scope) {
Some(RoleScope::Channel(c)) => Some(c.to_ascii_lowercase()),
_ => None,
};
let held = |hex: &str| {
crate::simd::hex::hex_to_bytes_32_checked(hex)
.and_then(|b| community.channel(&ChannelId(b)).map(|c| (c.private, c.key.is_some(), ChannelId(b))))
};
// One Direct Invite carries every channel the new set entitles them to.
if added.iter().filter_map(channel_of).any(|c| matches!(held(&c), Some((true, true, _)))) {
let my_pk = me_pk()?;
let bundle = bundle_of_with_overlay(community, BundleAudience::Member(*member), Some(my_pk), None, None, &added, &removed);
let signer = crate::signer::active_signer()?;
let wrap = invite::build_direct_invite_signed(&signer, my_pk, member, &bundle).await.map_err(|e| e.to_string())?;
transport.publish(&wrap, &community.relays).await?;
}
let mut severed: Vec<String> = Vec::new();
for chan in removed.iter().filter_map(channel_of) {
if severed.contains(&chan) {
continue;
}
severed.push(chan.clone());
let Some((true, true, channel_id)) = held(&chan) else { continue };
if view.roles.is_entitled(Some(&owner_hex), &member_hex, &chan, &added, &removed) {
continue; // another role they keep still opens it
}
let access_ids = view.roles.channel_role_ids(&chan);
rekey_channel_excluding(transport, community, &channel_id, &view.roles, &access_ids, std::slice::from_ref(member)).await?;
}
Ok(())
}
/// A grant replaces whole — refuse the merge when this member's grant is FLOORED
/// locally but no head folded (withheld / evicted): a blind push at that point
/// would erase their other roles at a higher version.
fn require_grant_head(community: &CommunityV2, view: &AuthorityView, member_hex: &str) -> Result<(), String> {
let Some(member) = crate::simd::hex::hex_to_bytes_32_checked(member_hex) else {
return Err("malformed member key".to_string());
};
let eid_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(community.id(), &member));
if view.floored.contains(&eid_hex) && !view.head_entities.contains(&eid_hex) {
return Err("this member's current grant could not be fetched; try again once relays serve the control plane".to_string());
}
Ok(())
}
/// Replace the Banlist (vsk 4, CORD-04 §4) with `banned` (lowercase-hex npubs), the
/// whole list on every edit. Gated on the reader side by `BAN` per head plus strict
/// outrank per entry — mirrored here BEFORE the publish, so an unauthorized caller
/// (an SDK bot without the bit, a demoted moderator) fails loudly instead of
/// publishing an edition every reader silently rejects while its own local echo
/// caches the phantom ban.
pub async fn set_banlist<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, banned: &[String]) -> Result<(), String> {
crate::db::scoped(async move {
super::roles::validate_banlist(banned)?;
{
let my_pk = me_pk()?;
let owner = community.owner()?;
if my_pk != owner {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let me_hex = my_pk.to_hex();
let current = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
if current.contains(&me_hex) {
return Err("you are banned from this community".to_string());
}
let roster = crate::db::community::get_community_roles(&cid_hex)?;
let owner_hex = owner.to_hex();
if !roster.is_authorized(&me_hex, Some(&owner_hex), crate::community::roles::Permissions::BAN) {
return Err("editing the banlist needs the BAN permission".to_string());
}
// Only the entries this edit ADDS need the per-target outrank (the fold
// keeps prior authorized bans alive through its per-candidate history).
for target in banned.iter().filter(|t| !current.contains(*t)) {
if !roster.can_act_on_member(&me_hex, Some(&owner_hex), target, crate::community::roles::Permissions::BAN) {
return Err("you do not outrank a member this ban targets".to_string());
}
}
}
}
let content = super::roles::banlist_content_json(banned)?;
let eid = super::derive::banlist_locator(community.id());
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let entity_hex = crate::simd::hex::bytes_to_hex_32(&eid);
// The version this publish will chain to — mirrors publish_control_edition.
let version = match crate::db::community::get_edition_head(&cid_hex, &entity_hex)? {
Some((v, _)) => v + 1,
None => 1,
};
publish_control_edition(transport, community, vsk::BANLIST, &eid, &content).await?;
// ECHO the published list into the local cache at once. Without this, the
// cache only moves on a successful control-plane fold — and a caller
// composing ban steps (banlist → grant strip → refound) re-reads the STALE
// list if any later step trips before the fold, so each new banlist
// edition it builds ERASES every ban since the last fold. Nineteen bans in
// production each overwrote their predecessor exactly this way.
store_banlist(&cid_hex, banned, version as i64);
Ok(())
})
.await
}
/// Store a banlist, telling the UI when the set moved.
fn store_banlist(cid_hex: &str, banned: &[String], version: i64) {
if crate::db::community::set_community_banlist(cid_hex, banned, version).unwrap_or(false) {
announce_banlist(cid_hex);
}
}
/// A ban hides what its target already posted (in SQL), and an un-ban shows it again: a painted
/// timeline is stale only when the set moves, so this, not every control change, re-reads it.
fn announce_banlist(cid_hex: &str) {
crate::emit_event("community_banlist_changed", &serde_json::json!({ "community_id": cid_hex }));
}
/// Per-community moderation-unit locks. Session-scoped: an account swap drops the
/// map with its session, so no cross-account carry-over and nothing to clear.
struct ModerationLocks;
fn moderation_lock(cid: &crate::community::CommunityId) -> std::sync::Arc<tokio::sync::Mutex<()>> {
let map = crate::db::current_session()
.scoped::<ModerationLocks, std::sync::Mutex<std::collections::HashMap<[u8; 32], std::sync::Arc<tokio::sync::Mutex<()>>>>>();
let mut m = map.lock().unwrap_or_else(|e| e.into_inner());
if let Some(lock) = m.get(&cid.0) {
return std::sync::Arc::clone(lock);
}
// A lock only the map holds has no holder or waiter, so a left community's goes here.
m.retain(|_, lock| std::sync::Arc::strong_count(lock) > 1);
std::sync::Arc::clone(m.entry(cid.0).or_default())
}
/// Fold control + guestbook so a moderation unit composes over the freshest view
/// another moderator may have advanced. Best-effort: on a dead network the local
/// cache (kept fresh by `set_banlist`'s own echo) is still the best basis.
async fn converge_authority<T: Transport + ?Sized>(transport: &T, id: &crate::community::CommunityId) {
if let Ok(Some(fresh)) = crate::db::community::load_community_v2(id) {
let _ = follow_control(transport, &fresh).await;
// Membership is part of the converged view: a Join that legally raced a ban
// window may exist only on the relays, and our own just-published edition
// doesn't echo back to trigger a follow.
if let Ok(added) = sync_guestbook(transport, &fresh).await {
if !added.is_empty() {
crate::traits::emit_event_json(
"community_refreshed",
serde_json::json!({ "community_id": crate::simd::hex::bytes_to_hex_32(&id.0) }),
);
}
}
}
}
/// One queued ban/unban intent, answered on `done` when its batch completes.
struct ModIntent {
id: u64,
targets: Vec<PublicKey>,
banned: bool,
done: tokio::sync::oneshot::Sender<Result<(), String>>,
}
/// Per-community pending moderation intents — the coalescing queue behind
/// [`moderation_lock`]. Session-scoped for the same reason as the lock.
struct PendingModeration;
fn pending_moderation(cid: &crate::community::CommunityId) -> std::sync::Arc<std::sync::Mutex<std::collections::HashMap<[u8; 32], Vec<ModIntent>>>> {
let _ = cid;
crate::db::current_session()
.scoped::<PendingModeration, std::sync::Mutex<std::collections::HashMap<[u8; 32], Vec<ModIntent>>>>()
}
/// Ban or unban members as ONE moderation unit — the CORD-04 §6 three-removal
/// composition, once for the whole wave: one Banlist edition (instant silence),
/// one grant-strip pass (authority removal), and one read cut (a private
/// community re-founds ONCE with every target removed; a public one rotates each
/// reachable private channel ONCE excluding them all).
///
/// Serialized AND coalesced per community. Without the lock, concurrent bans
/// (the SDK spawns a handler task per message, so a spam wave is exactly this)
/// each build their edition from a pre-sibling banlist snapshot, and the fold
/// takes the HEAD's content — so the last racing head silently un-bans the
/// earlier target at every reader, and the refound then compacts that erasure
/// into the new epoch permanently.
///
/// The coalescing half: a unit's read cut holds the lock for a whole multi-
/// publish rotation, so serial single bans arriving meanwhile would each queue
/// up a rotation of their own. Instead every caller deposits an intent; whoever
/// next takes the lock drains ALL of them into one edition + one read cut,
/// applied in arrival order (ban-then-unban of one npub nets to unban). Each
/// intent is judged individually — a target the caller cannot outrank, or an
/// add past the 500-entry ceiling, fails only its own caller, never the batch.
pub async fn set_members_banned<T: Transport + ?Sized>(
transport: &T,
community_id: &crate::community::CommunityId,
members: &[PublicKey],
banned: bool,
) -> Result<(), String> {
crate::db::scoped(async move {
// Dedup — a doubled target must not strip or rotate twice.
let mut targets: Vec<PublicKey> = Vec::with_capacity(members.len());
for m in members {
if !targets.contains(m) {
targets.push(*m);
}
}
if targets.is_empty() {
return Ok(());
}
// Plain uniqueness source for intent ids — not per-account state.
static INTENT_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
let my_id = INTENT_IDS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let (tx, rx) = tokio::sync::oneshot::channel();
{
let map = pending_moderation(community_id);
let mut m = map.lock().unwrap_or_else(|e| e.into_inner());
m.entry(community_id.0).or_default().push(ModIntent { id: my_id, targets, banned, done: tx });
}
let unit = moderation_lock(community_id);
// `biased` so a verdict delivered by another leader wins over a lock we
// happen to also hold — a drained intent must never run twice.
tokio::select! {
biased;
res = rx => res.unwrap_or_else(|_| Err("moderation unit aborted before completing".to_string())),
_guard = unit.lock() => {
// Leader: drain EVERYTHING pending right now. Every ban/unban that
// stacked while the previous unit's rotation ran coalesces here.
let batch: Vec<ModIntent> = {
let map = pending_moderation(community_id);
let mut m = map.lock().unwrap_or_else(|e| e.into_inner());
m.remove(&community_id.0).unwrap_or_default()
};
run_moderation_batch(transport, community_id, batch, my_id).await
}
}
})
.await
}
/// Execute one drained batch of moderation intents under the held lock: judge
/// each intent in arrival order against the evolving list, publish the coalesced
/// edition, strip + read-cut the net newly-banned set once, then answer every
/// intent with its own verdict. Returns the LEADER's verdict.
async fn run_moderation_batch<T: Transport + ?Sized>(
transport: &T,
community_id: &crate::community::CommunityId,
batch: Vec<ModIntent>,
leader_id: u64,
) -> Result<(), String> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community_id.0);
// SYNC BEFORE COMPOSING: a banlist edition replaces the whole list on the
// wire, so the mutation must start from the freshest view — another
// moderator's ban this device hasn't folded yet would otherwise be
// silently erased by ours.
converge_authority(transport, community_id).await;
let original = crate::db::community::get_community_banlist(&cid_hex)?;
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let community0 = crate::db::community::load_community_v2(community_id)?
.ok_or_else(|| "v2 community not found".to_string())?;
let owner = community0.owner()?;
let my_pk = me_pk()?;
let my_hex = my_pk.to_hex();
let owner_hex = owner.to_hex();
// Judge intents in arrival order against the EVOLVING list, so the last
// intent naming an npub wins — exactly serial semantics, minus the churn.
let mut list = original.clone();
let mut pk_of: std::collections::HashMap<String, PublicKey> = std::collections::HashMap::new();
let mut verdicts: std::collections::HashMap<u64, Result<(), String>> = std::collections::HashMap::new();
for intent in &batch {
let hexes: Vec<String> = intent.targets.iter().map(|p| p.to_hex()).collect();
for (pk, hex) in intent.targets.iter().zip(&hexes) {
pk_of.insert(hex.clone(), *pk);
}
let verdict = (|| {
// Mirror of set_banlist's authority gate, per intent, so one refused
// intent cannot sink its batch-mates.
if my_pk != owner {
if original.contains(&my_hex) {
return Err("you are banned from this community".to_string());
}
if !roster.is_authorized(&my_hex, Some(&owner_hex), crate::community::roles::Permissions::BAN) {
return Err("editing the banlist needs the BAN permission".to_string());
}
if intent.banned {
for t in hexes.iter().filter(|t| !list.contains(*t)) {
if !roster.can_act_on_member(&my_hex, Some(&owner_hex), t, crate::community::roles::Permissions::BAN) {
return Err("you do not outrank a member this ban targets".to_string());
}
}
}
}
let mut next = list.clone();
next.retain(|h| !hexes.contains(h));
if intent.banned {
next.extend(hexes.iter().cloned());
}
super::roles::validate_banlist(&next)?;
list = next;
Ok(())
})();
verdicts.insert(intent.id, verdict);
}
let changed = {
let mut a = original.clone();
let mut b = list.clone();
a.sort();
b.sort();
a != b
};
let newly_banned: Vec<PublicKey> = list
.iter()
.filter(|h| !original.contains(*h))
.filter_map(|h| pk_of.get(h).copied())
.collect();
// Publish the coalesced edition + strips, then the single read cut.
let unit_result: Result<(), String> = async {
if !changed {
return Ok(());
}
// Rotation barrier: a sibling refound holds this lock for its whole
// multi-publish rotation while the row still names the OLD root. Dropped
// before `refound_community`, which re-acquires it (non-reentrant).
let (community, stripped) = {
let lock = super::realtime::follow_lock(community_id);
let _rotation = lock.lock().await;
let community = crate::db::community::load_community_v2(community_id)?
.ok_or_else(|| "v2 community not found".to_string())?;
// A ban drops what its target says, never what they decided (CORD-04 §9).
seal_standing(transport, &community, &newly_banned, Seal::BestEffort).await?;
// The departure goes first: between the two, the banlist still holds them out.
let unbanned: Vec<PublicKey> = original.iter().filter(|h| !list.contains(*h)).filter_map(|h| pk_of.get(h).copied()).collect();
if !unbanned.is_empty() {
publish_ban_departures(transport, &community, &unbanned).await;
}
set_banlist(transport, &community, &list).await?;
let mut stripped: Vec<(PublicKey, Vec<String>)> = Vec::new();
// Pre-strip role capture: the read-severance below judges which
// private channels each member could reach, and after the strip
// the fold may no longer show it.
for pk in &newly_banned {
let hex = pk.to_hex();
let roles: Vec<String> = roster.roles_of(&hex).map(|r| r.role_id.clone()).collect();
// Nothing granted = nothing to strip: a bulk ban of roleless
// spammers must not publish one empty Grant edition apiece.
let has_grant = roster.grants.iter().any(|g| g.member == hex && !g.role_ids.is_empty());
if has_grant {
// Strip on the kick doctrine (skip, not refuse): readers honor a
// grant strip only from MANAGE_ROLES + outrank, and a BAN-only
// moderator still bans — the banlist silences regardless, and
// publishing a strip readers reject would only poison our own
// floor for that grant entity.
let can_strip = my_pk == owner
|| roster.can_act_on_member(&my_hex, Some(&owner_hex), &hex, crate::community::roles::Permissions::MANAGE_ROLES);
if can_strip {
grant_roles_sealing(transport, &community, pk, vec![], Seal::BestEffort).await?;
} else {
crate::log_warn!("[Ban] grant strip skipped (no MANAGE_ROLES over the target); the banlist still silences");
}
}
stripped.push((*pk, roles));
}
(community, stripped)
};
if !newly_banned.is_empty() {
// CORD-05 §5 gate: a PUBLIC community — any live invite link — must NOT
// refound on ban. The link refresh re-posts the bundle with the new root
// behind the same URL, so the banned member re-fetches and reads on: the
// rotation severs nothing and can strand foreign-link joiners on a buried
// epoch. The Banlist does all the real work in Public mode.
if community_is_public(transport, &community).await {
crate::log_info!("[Ban] public community — banlist + grant strip, no refound (CORD-05 §5)");
// CORD-06 §1 still applies per channel: only rotation severs the
// private-channel reads their held keys still allow.
match sever_banned_private_reads(transport, &community, &stripped, Some(&roster)).await {
Ok(0) => {}
Ok(n) => crate::log_info!("[Ban] rotated {n} private channel(s) the banned member(s) could read"),
Err(e) => crate::log_warn!("[Ban] private-channel read severance incomplete: {e}"),
}
} else if let Err(e) = refound_community(transport, &community, &newly_banned).await {
// Best-effort escalation, NEVER the ban's verdict. The banlist
// edition (instant silence at every honest reader) and the grant
// strip ARE the ban; the refound's §3 coverage gate demands the
// relay serve back heads published milliseconds ago, so propagation
// lag makes it fail-closed — and propagating that error out of here
// once left every ban half-applied AND skipped the converge below,
// so each next ban rebuilt from a stale list and erased its
// predecessors.
crate::log_warn!("[Ban] refound deferred (banlist + grant strip landed): {e}");
}
}
Ok(())
}
.await;
converge_authority(transport, community_id).await;
// Answer every intent: its own judgment first, then the shared publish fate.
let mut my_verdict = Err("leader intent missing from its own batch".to_string());
for intent in batch {
let final_verdict = verdicts
.remove(&intent.id)
.unwrap_or_else(|| Err("intent was never judged".to_string()))
.and_then(|()| unit_result.clone());
if intent.id == leader_id {
my_verdict = final_verdict;
} else {
let _ = intent.done.send(final_verdict);
}
}
my_verdict
}
// ── Raid containment (CORD-06 Severing Refounding) ──────────────────────────
/// What a containment actually accomplished. Every field is an honest count —
/// a caller (Sentinel, a moderation console) reports these to a human, so a
/// half-done containment must never read as a closed door.
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct ContainmentReport {
/// Raiders added to the Banlist.
pub banned: usize,
/// Members cut for joining inside the raid window without being convicted.
pub window_cut: usize,
/// Root epoch before and after. Equal = the refound did NOT land.
pub epoch_before: u64,
pub epoch_after: u64,
/// True only if the severing refound published.
pub refound_ok: bool,
/// My own public links revoked here. Other creators' links die as their
/// clients adopt the severed rotation.
pub own_links_revoked: usize,
/// Creators whose links are still live pending their client's adoption.
pub foreign_link_creators: Vec<String>,
/// Non-fatal problems worth showing a human.
pub warnings: Vec<String>,
}
/// Contain a raid: ban the raiders, cut everyone who walked in through the door
/// during the raid window, then perform a SEVERING Refounding — the rotation
/// that revokes the invite links instead of carrying them into the new epoch.
///
/// This is the raid lane, not a general ban. An ordinary ban (even in a Public
/// community) keeps its shipped behaviour — [`set_members_banned`] decides
/// internally, and a public one deliberately does NOT roll the root. Here the
/// door itself is the vector, so it closes with the rotation.
///
/// `window_start_secs` is the raid's opening edge: unconvicted members who
/// joined at-or-after it are cut from the new epoch (NOT banned — an innocent
/// caught in the window rejoins through the owner's next link). Members already
/// present before the window are never cut, however quiet.
pub async fn contain_raid<T: Transport + ?Sized>(
transport: &T,
community_id: &crate::community::CommunityId,
raiders: &[PublicKey],
window_start_secs: u64,
cut_also: &[PublicKey],
) -> Result<ContainmentReport, String> {
crate::db::scoped(async move {
let mut report = ContainmentReport::default();
let community = crate::db::community::load_community_v2(community_id)?
.ok_or_else(|| "v2 community not found".to_string())?;
report.epoch_before = community.root_epoch.0;
report.epoch_after = community.root_epoch.0;
let owner = community.owner()?;
let my_pk = me_pk()?;
// 1. Ban the convicted. Goes through the coalescer: the banlist edition is
// a read-modify-write, and a concurrent single ban would otherwise
// rebuild from a stale list and erase this one. A FAILED ban (most
// plausibly the 500-entry banlist ceiling under a mega-raid) must not
// abort the containment: the refound below cuts the raiders
// cryptographically whether or not the list could name them.
if !raiders.is_empty() {
match set_members_banned(transport, community_id, raiders, true).await {
Ok(()) => report.banned = raiders.len(),
Err(e) => report.warnings.push(format!("banlist did not land ({e}) — the refound still cuts every named raider")),
}
}
// Re-read: the ban published a Banlist edition and stripped grants.
let community = crate::db::community::load_community_v2(community_id)?
.ok_or_else(|| "v2 community not found".to_string())?;
// 2. The window cut. A raid arrives THROUGH the link, so everyone who
// walked in during it is part of the wave for containment purposes —
// conviction only ever names the ones who spoke. Never the owner, never
// staff, never anyone whose earliest trace predates the window.
//
// `cut_also` first: Join timestamps are AUTHOR-claimed, so a quiet
// raider who backdated their Join slides under any window this fold
// can compute. A caller watching arrivals on its own clock (Sentinel's
// receive log) names them here and they are cut regardless.
let mut cut: Vec<PublicKey> = raiders.to_vec();
for pk in cut_also {
if !cut.contains(pk) {
cut.push(*pk);
report.window_cut += 1;
}
}
if window_start_secs > 0 {
let roster = crate::db::community::get_community_roles(
&crate::simd::hex::bytes_to_hex_32(&community.id().0),
)
.unwrap_or_default();
let owner_hex = owner.to_hex();
match fetch_guestbook_events(transport, &community, 0).await {
Ok((events, _, _)) => {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let (held, _) = crate::db::community::get_guestbook(&cid_hex).unwrap_or_default();
let watched = guestbook_observed_since(&cid_hex).is_some_and(|since| since < window_start_secs);
let first_seen = earliest_arrivals(&events, &held, watched, |pk| {
*pk == owner || roster.is_authorized(&pk.to_hex(), Some(&owner_hex), crate::community::roles::Permissions::BAN)
});
for (pk, joined) in first_seen {
if joined < window_start_secs || pk == owner || pk == my_pk || cut.contains(&pk) {
continue;
}
// Staff are never cut by a window: a moderator who joined
// moments before a raid is still a moderator.
if roster.is_staff(&pk.to_hex(), Some(&owner_hex)) {
continue;
}
cut.push(pk);
report.window_cut += 1;
}
}
Err(e) => report
.warnings
.push(format!("guestbook unreadable — no window cut applied, only convicted raiders are severed ({e})")),
}
}
// 3. The severing refound. Private channels are deliberately NOT rotated
// separately: the root roll re-keys every plane, and link-borne raiders
// were never entitled to a private channel in the first place.
//
// Under the MODERATION lock, exactly as `run_moderation_batch` holds it
// across ITS refound: an ordinary ban racing this rotation would publish
// a banlist edition the compaction fetch below has already read past,
// and the new epoch would carry it away — a ban silently erased at the
// moment bans matter most. Lock order (moderation → follow) matches the
// shipped path. Retried: the refound's coverage gate fails closed under
// exactly the relay lag a mid-raid flood produces.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let links_before = crate::db::community::list_public_invites(&cid_hex).map(|l| l.len()).unwrap_or(0);
let unit = moderation_lock(community_id);
let _guard = unit.lock().await;
let mut refound = Err("severing refound never attempted".to_string());
for attempt in 0..3u8 {
refound = refound_community_severing(transport, &community, &cut, window_start_secs).await;
if refound.is_ok() {
break;
}
if attempt < 2 {
crate::rt::time::sleep(std::time::Duration::from_millis(400 * (attempt as u64 + 1))).await;
}
}
match refound {
Ok(updated) => {
report.refound_ok = true;
report.epoch_after = updated.root_epoch.0;
let links_after = crate::db::community::list_public_invites(&cid_hex).map(|l| l.len()).unwrap_or(0);
report.own_links_revoked = links_before.saturating_sub(links_after);
if links_after > 0 {
report.warnings.push(format!(
"{links_after} of my own link(s) survived the sever — the mark retries them on the next follow"
));
}
report.foreign_link_creators = crate::db::community::invite_link_set_creators(&cid_hex)
.unwrap_or_default()
.into_iter()
.filter(|c| *c != my_pk.to_hex())
.collect();
}
Err(e) => {
// The banlist landed and silences the named raiders at every honest
// reader, but the DOOR IS STILL OPEN. Never dress this as success.
report.warnings.push(format!("SEVERING REFOUND FAILED — the invite door may still be open: {e}"));
}
}
Ok(report)
})
.await
}
/// Edit the community metadata (vsk 0, CORD-02 §6). Gated on the reader side by
/// `MANAGE_METADATA`.
pub async fn edit_community_metadata<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, meta: &control::CommunityMetadata) -> Result<(), String> {
ensure_folded_permission(community, &me_pk()?, crate::community::roles::Permissions::MANAGE_METADATA, "editing the community metadata")?;
control::validate_community_metadata(meta).map_err(|e| e.to_string())?;
let content = serde_json::to_string(meta).map_err(|e| e.to_string())?;
let lock = super::realtime::follow_lock(community.id());
let _guard = lock.lock().await;
publish_control_edition(transport, community, vsk::COMMUNITY_METADATA, &community.id().0, &content).await?;
// Applied locally too: the fold that would otherwise land it runs on a later control pass.
if let Ok(Some(mut held)) = crate::db::community::load_community_v2(community.id()) {
if apply_community_metadata(&mut held, meta.clone()) {
crate::db::community::save_community_v2(&held)?;
}
}
Ok(())
}
/// Persist a freshly-published icon/banner onto the held row and return the fresh
/// row. Reloads under the community's follow lock: `save_community_v2` is a
/// whole-row save that prunes channels absent from the passed struct, so writing
/// a stale pre-upload copy would drop rows a concurrent fold just landed.
pub async fn persist_community_image(
id: &crate::community::CommunityId,
img: Option<control::ImageRef>,
is_banner: bool,
) -> Option<CommunityV2> {
let lock = super::realtime::follow_lock(id);
let _guard = lock.lock().await;
let mut fresh = crate::db::community::load_community_v2(id).ok()??;
if is_banner {
fresh.banner = img;
} else {
fresh.icon = img;
}
crate::db::community::save_community_v2(&fresh).ok()?;
Some(fresh)
}
/// Add or edit a channel's metadata (vsk 2, CORD-03 §2). `channel_id` is the
/// coordinate. Gated on the reader side by `MANAGE_CHANNELS`.
pub async fn edit_channel_metadata<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId, meta: &control::ChannelMetadata) -> Result<(), String> {
crate::db::scoped(edit_channel_metadata_bound(transport, community, channel_id, meta)).await
}
async fn edit_channel_metadata_bound<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId, meta: &control::ChannelMetadata) -> Result<(), String> {
let my_pk = me_pk()?;
ensure_channel_manager(community, &my_pk)?;
let old_name = community.channel(channel_id).map(|c| c.name.clone());
let base = community.channel(channel_id).map(|c| c.metadata());
// Making a Channel private is a key rotation of its own (CORD-03 §2).
if meta.private && community.channel(channel_id).is_some_and(|c| !c.private) {
return Err("make a channel private with privatize_channel".to_string());
}
// The edition chains from the head this lock keeps still until it is published.
let lock = super::realtime::follow_lock(community.id());
let guard = lock.lock().await;
let fresh = crate::db::community::load_community_v2(community.id())?.unwrap_or_else(|| community.clone());
// A sealed rename goes under the newest key, never one a member just cut still holds.
let refreshed;
let community = if meta.private && roles_v2_held(&fresh) {
follow_rekeys(transport, &fresh, &crate::db::current_session()).await?;
refreshed = crate::db::community::load_community_v2(community.id())?.ok_or("v2 community not found")?;
&refreshed
} else {
&fresh
};
let held = community.channel(channel_id);
if held.is_some_and(|c| c.sealed.as_ref().is_some_and(|s| !s.open && !s.junk)) {
return Err("this private channel's details are sealed under a key this device lacks".to_string());
}
// Only what the caller changed goes over what folded since it read the Channel.
let merged = match (&base, held) {
(Some(base), Some(now)) => merge_channel_metadata(base, meta, &now.metadata()),
_ => meta.clone(),
};
let meta = &merged;
let prev = channel_head(community, channel_id)?;
let content = channel_edition_content(community, channel_id, meta, held.and_then(|c| c.key.map(|k| (k, c.epoch))), prev.as_ref())?;
publish_control_edition(transport, community, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
let sealed = sealed_held(&content, prev);
// Apply locally too. The fold is the authority but runs later, so without this
// an edit we just made reads back stale until some future control pass — the
// rename appears to have silently failed.
if let Ok(Some(mut held)) = crate::db::community::load_community_v2(community.id()) {
if let Some(ch) = held.channels.iter_mut().find(|c| c.id.0 == channel_id.0) {
ch.name = meta.name.clone();
ch.private = meta.private;
ch.voice = meta.voice;
ch.meta_custom = meta.custom.clone();
ch.meta_extra = meta.extra.clone();
ch.sealed = sealed;
crate::db::community::save_community_v2(&held)?;
}
}
drop(guard);
// Keep the companion access role's label in step with the channel it gates.
if meta.private {
if let Some(old) = old_name.filter(|o| *o != meta.name) {
rename_channel_access_role(transport, community, channel_id, &old, &meta.name).await;
}
}
Ok(())
}
/// `ours` as its writer meant it against the `base` they read: each field they changed, over
/// `theirs`, the Channel as it stands now.
fn merge_channel_metadata(base: &control::ChannelMetadata, ours: &control::ChannelMetadata, theirs: &control::ChannelMetadata) -> control::ChannelMetadata {
fn pick<T: Clone + PartialEq>(base: &T, ours: &T, theirs: &T) -> T {
if ours != base { ours.clone() } else { theirs.clone() }
}
let mut extra = theirs.extra.clone();
for key in base.extra.keys().chain(ours.extra.keys()) {
if base.extra.get(key) != ours.extra.get(key) {
match ours.extra.get(key) {
Some(v) => extra.insert(key.clone(), v.clone()),
None => extra.remove(key),
};
}
}
let custom = match (&base.custom, &ours.custom, &theirs.custom) {
(b, o, t) if o == b => t.clone(),
(b, Some(o), t) => {
let (b, mut out) = (b.clone().unwrap_or_default(), t.clone().unwrap_or_default());
for key in b.keys().chain(o.keys()) {
if b.get(key) != o.get(key) {
match o.get(key) {
Some(v) => out.insert(key.clone(), v.clone()),
None => out.remove(key),
};
}
}
Some(out)
}
(_, None, _) => None,
};
control::ChannelMetadata {
name: pick(&base.name, &ours.name, &theirs.name),
private: pick(&base.private, &ours.private, &theirs.private),
voice: pick(&base.voice, &ours.voice, &theirs.voice),
deleted: pick(&base.deleted, &ours.deleted, &theirs.deleted),
custom,
extra,
}
}
/// Rename a private channel's companion access role to follow the channel (CORD-04 §2).
/// Best-effort and never fatal: the channel rename has already published, and a role's
/// name is cosmetic — entitlement is carried by the scope, not the label.
///
/// Only renames a label still equal to the channel's OLD name, so a deliberately
/// customised role name survives a channel rename untouched.
async fn rename_channel_access_role<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
old_name: &str,
new_name: &str,
) {
crate::db::scoped(async move {
let (Ok(my_pk), Ok(owner)) = (me_pk(), community.owner()) else {
return;
};
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
// Fetched, not cached: `set_role` republishes the WHOLE role body, so a stale
// cache would clobber a permission edit this client has not folded yet.
let mut roster = fetch_authority(transport, community).await.roles;
let cached = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
for r in cached.roles {
if !roster.roles.iter().any(|x| x.role_id == r.role_id) {
roster.roles.push(r);
}
}
// MANAGE_CHANNELS got us the rename; the role edition needs MANAGE_ROLES + outrank
// of its own. Publishing one readers reject would wedge our later, legitimate role
// edits behind a rejected chain, so verify before publishing rather than after.
let (me_hex, owner_hex) = (my_pk.to_hex(), owner.to_hex());
if !roster.is_authorized_in(&me_hex, Some(&owner_hex), &chan_hex, crate::community::roles::Permissions::MANAGE_ROLES) {
return;
}
// Same selector `grant_channel_access` vends: the permission-less scoped role. A
// per-channel moderator role sharing the scope is NOT the access list.
let Some(mut role) = roster
.channel_roles(&chan_hex)
.into_iter()
.find(|r| r.permissions == crate::community::roles::Permissions::empty() && r.name == old_name)
.cloned()
else {
return;
};
if !roster.can_act_on_position(&me_hex, Some(&owner_hex), role.position, crate::community::roles::Permissions::MANAGE_ROLES) {
return;
}
role.name = new_name.to_string();
if let Err(e) = set_role(transport, community, &role).await {
crate::log_warn!("v2: channel renamed but its access role did not follow: {e}");
return;
}
merge_local_roster(&cid_hex, Some(&role), None);
})
.await
}
/// The local mirror of a reader-side permission fold gate: the owner, or a
/// roster-authorized holder of `needed` who isn't banned. Refusing BEFORE any
/// publish keeps an unauthorized device from advancing its own edition floor onto
/// a head every reader rejects (wedging its later, legitimately-authorized edits
/// behind a rejected chain). Fail-closed: an empty/unfolded roster collapses to
/// owner-only — it can over-restrict, never grant authority no one has.
fn ensure_folded_permission(
community: &CommunityV2,
me: &PublicKey,
needed: u64,
verb: &str,
) -> Result<(), String> {
let owner = community.owner()?;
if *me == owner {
return Ok(());
}
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let me_hex = me.to_hex();
if crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default().contains(&me_hex) {
return Err("you are banned from this community".to_string());
}
let roster = crate::db::community::get_community_roles(&cid_hex)?;
if roster.is_authorized(&me_hex, Some(&owner.to_hex()), needed) {
Ok(())
} else {
Err(format!("{verb} needs the {} permission", permission_label(needed)))
}
}
fn permission_label(bits: u64) -> &'static str {
use crate::community::roles::Permissions;
match bits {
Permissions::MANAGE_ROLES => "MANAGE_ROLES",
Permissions::MANAGE_CHANNELS => "MANAGE_CHANNELS",
Permissions::MANAGE_METADATA => "MANAGE_METADATA",
Permissions::BAN => "BAN",
Permissions::CREATE_INVITE => "CREATE_INVITE",
_ => "required",
}
}
/// [`ensure_folded_permission`] for `MANAGE_CHANNELS` (CORD-03 §2).
fn ensure_channel_manager(community: &CommunityV2, me: &PublicKey) -> Result<(), String> {
ensure_folded_permission(community, me, crate::community::roles::Permissions::MANAGE_CHANNELS, "managing channels here")
}
/// Create a new PUBLIC channel (CORD-03 §2): mint a fresh id, publish its metadata
/// edition (vsk 2), and add it to the held community. A Public channel derives its Chat
/// Plane from the `community_root` (no per-channel key), so other members fold it in on
/// their next control follow with nothing to distribute. Returns the new channel id.
/// Reader-gated by `MANAGE_CHANNELS`.
pub async fn create_public_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str) -> Result<ChannelId, String> {
let channel_id = ChannelId(super::super::random_32());
create_public_channel_with_id(transport, community, name, channel_id).await?;
Ok(channel_id)
}
/// [`create_public_channel`] with a CALLER-CHOSEN id — the migration-only entry point
/// (§migration) that reuses an existing channel's id so chat history stitches through.
/// Asserts the id isn't already live in a DIFFERENT held v2 community before minting.
pub async fn create_public_channel_with_id<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str, channel_id: ChannelId) -> Result<(), String> {
crate::db::scoped(async move {
// Serialize with the follow worker: the save below writes the WHOLE community
// row from this caller's struct, so an unserialized concurrent follow adopting
// a rotation would be rolled back to a stale root (a deaf community).
let lock = super::realtime::follow_lock(community.id());
let _guard = lock.lock().await;
let my_pk = me_pk()?;
ensure_channel_manager(community, &my_pk)?;
assert_channel_id_free(&channel_id, community.id())?;
let meta = control::ChannelMetadata { name: name.to_string(), private: false, voice: None, deleted: None, custom: None, extra: Default::default() };
control::validate_channel_metadata(&meta).map_err(|e| e.to_string())?;
let content = serde_json::to_string(&meta).map_err(|e| e.to_string())?;
publish_control_edition(transport, community, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
// Add locally + persist so the creator can post immediately (peers fold it in).
let mut updated = community.clone();
updated.channels.push(ChannelV2 { id: channel_id, name: name.to_string(), private: false, key: None, epoch: updated.root_epoch, voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed: None });
crate::db::community::save_community_v2(&updated)?;
Ok(())
})
.await
}
/// Refuse a channel id already live in a DIFFERENT held v2 community — the same
/// cross-community hijack the `save_community_v2` guard forecloses, checked up front so a
/// migration twin never adopts an id it doesn't own. Only a foreign v2 owner blocks; a
/// row under any other protocol is re-parented.
fn assert_channel_id_free(channel_id: &ChannelId, community_id: &crate::community::CommunityId) -> Result<(), String> {
let ch_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
if let Ok(Some(existing)) = crate::db::community::community_id_for_channel(&ch_hex) {
let mine = crate::simd::hex::bytes_to_hex_32(&community_id.0);
let existing_id = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&existing));
if existing != mine
&& matches!(crate::db::community::community_held(&existing_id), Ok(true))
{
return Err("channel id is already live in another v2 community".to_string());
}
}
Ok(())
}
/// Publish a Category edition and apply it locally, as a channel edit does: the fold
/// that would otherwise show it runs later.
async fn set_category<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, id: [u8; 32], meta: &control::CategoryMetadata) -> Result<(), String> {
if meta.deleted != Some(true) && meta.name.trim().is_empty() {
return Err("a category needs a name".to_string());
}
control::validate_category_metadata(meta).map_err(|e| e.to_string())?;
let content = serde_json::to_string(meta).map_err(|e| e.to_string())?;
publish_control_edition(transport, community, vsk::CATEGORY, &id, &content).await?;
let lock = super::realtime::follow_lock(community.id());
let _guard = lock.lock().await;
if let Ok(Some(mut held)) = crate::db::community::load_community_v2(community.id()) {
if apply_category_metadata(&mut held, id, meta.clone()) {
crate::db::community::save_community_v2(&held)?;
}
}
Ok(())
}
/// Create a Category at the bottom of the sidebar (CORD-03 §4).
pub async fn create_category<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str) -> Result<[u8; 32], String> {
crate::db::scoped(async move {
ensure_channel_manager(community, &me_pk()?)?;
if community.categories.len() >= super::community::MAX_CATEGORIES {
return Err(format!("a community holds at most {} categories", super::community::MAX_CATEGORIES));
}
let last = community.categories.iter().filter_map(|c| c.position.as_deref()).max_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
let position = crate::community::rank::between(last, None).ok_or("no room for another category")?;
let id = super::super::random_32();
set_category(transport, community, id, &control::CategoryMetadata { name: name.trim().to_string(), position: Some(position), deleted: None, extra: Default::default() }).await?;
Ok(id)
})
.await
}
pub async fn rename_category<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, id: [u8; 32], name: &str) -> Result<(), String> {
crate::db::scoped(async move {
ensure_channel_manager(community, &me_pk()?)?;
let current = community.categories.iter().find(|c| c.id == id).ok_or("no such category")?;
let meta = control::CategoryMetadata { name: name.trim().to_string(), position: current.position.clone(), deleted: None, extra: current.extra.clone() };
set_category(transport, community, id, &meta).await
})
.await
}
/// Delete a Category: terminal. Its Channels keep pointing at it and render uncategorized.
pub async fn delete_category<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, id: [u8; 32]) -> Result<(), String> {
crate::db::scoped(async move {
ensure_channel_manager(community, &me_pk()?)?;
community.categories.iter().find(|c| c.id == id).ok_or("no such category")?;
set_category(transport, community, id, &control::CategoryMetadata { deleted: Some(true), ..Default::default() }).await
})
.await
}
/// Move a Category to `index` among the Categories (0 is the top).
pub async fn move_category<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, id: [u8; 32], index: usize) -> Result<(), String> {
crate::db::scoped(async move {
ensure_channel_manager(community, &me_pk()?)?;
let current = community.categories.iter().find(|c| c.id == id).ok_or("no such category")?.clone();
let order: Vec<super::community::CategoryV2> = community.sidebar().into_iter().filter_map(|(c, _)| c.cloned()).filter(|c| c.id != id).collect();
let keys = keyed(transport, community, order.iter().map(|c| (c.position.clone(), Keyed::Category(c.clone()))).collect()).await?;
let index = index.min(keys.len());
let position = crate::community::rank::between(index.checked_sub(1).map(|i| keys[i].as_str()), keys.get(index).map(String::as_str))
.ok_or("no room between those categories")?;
let meta = control::CategoryMetadata { name: current.name, position: Some(position), deleted: None, extra: current.extra };
set_category(transport, community, id, &meta).await
})
.await
}
/// Move a Channel into `category` (`None` = uncategorized) at `index` among its
/// Channels: one edition, on the moved Channel (CORD-03 §2).
pub async fn move_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId, category: Option<[u8; 32]>, index: usize) -> Result<(), String> {
crate::db::scoped(async move {
ensure_channel_manager(community, &me_pk()?)?;
let ch = community.channel(channel_id).ok_or("no such channel")?.clone();
if category.is_some_and(|c| !community.categories.iter().any(|x| x.id == c)) {
return Err("no such category".to_string());
}
let sidebar = community.sidebar();
let group: Vec<ChannelV2> = sidebar
.iter()
.find(|(c, _)| c.map(|c| c.id) == category)
.map(|(_, v)| v.iter().filter(|c| c.id.0 != channel_id.0).map(|c| (*c).clone()).collect())
.unwrap_or_default();
let keys = keyed(transport, community, group.iter().map(|c| (c.position().map(String::from), Keyed::Channel(c.clone()))).collect()).await?;
let index = index.min(keys.len());
let position = crate::community::rank::between(index.checked_sub(1).map(|i| keys[i].as_str()), keys.get(index).map(String::as_str))
.ok_or("no room between those channels")?;
let mut meta = ch.metadata();
meta.extra.insert("position".into(), position.into());
match category {
Some(c) => meta.extra.insert("category".into(), crate::simd::hex::bytes_to_hex_32(&c).into()),
None => meta.extra.remove("category"),
};
edit_channel_metadata(transport, community, channel_id, &meta).await
})
.await
}
/// Edit a Channel's name, topic and view, keeping every field another client wrote.
pub async fn edit_channel_details<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
name: &str,
topic: Option<&str>,
view: super::community::ChannelView,
) -> Result<(), String> {
let ch = community.channel(channel_id).ok_or("no such channel")?;
let name = name.trim();
if name.is_empty() {
return Err("a channel needs a name".to_string());
}
let mut meta = ch.metadata();
meta.name = name.to_string();
match topic.map(str::trim).filter(|t| !t.is_empty()) {
Some(t) => meta.extra.insert("topic".into(), t.into()),
None => meta.extra.remove("topic"),
};
// An unchanged view a later revision defined stays as written.
match view {
_ if view == ch.view() && meta.extra.contains_key("view") => None,
super::community::ChannelView::Chat if ch.voice != Some(true) => meta.extra.remove("view"),
v => meta.extra.insert("view".into(), v.as_str().into()),
};
edit_channel_metadata(transport, community, channel_id, &meta).await
}
/// Create a Channel inside `category` (or uncategorized), at the end of its group.
pub async fn create_channel_in<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str, private: bool, category: Option<[u8; 32]>) -> Result<ChannelId, String> {
// Unsynced, a public Channel in a Category with its own rules would sit open to everyone.
if let Some(cat) = category.filter(|_| !private && roles_v2_held(community)) {
let roster = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0))?;
let cat_hex = crate::simd::hex::bytes_to_hex_32(&cat);
let owner = community.owner()?.to_hex();
if roster.overwrites.iter().any(|o| o.scope == cat_hex) && !may_swap_overwrites(&roster, Some(&owner), &me_pk()?.to_hex(), &[cat_hex.as_str()], &|_| 0) {
return Err("this category sets its own permissions, so a channel in it takes Manage Roles over them".to_string());
}
}
let id = if private { create_private_channel(transport, community, name).await? } else { create_public_channel(transport, community, name).await? };
// A keyless Channel already sorts last in its group.
if category.is_some() {
let held = crate::db::community::load_community_v2(community.id())?.ok_or("v2 community not found")?;
move_channel(transport, &held, &id, category, usize::MAX).await?;
// A public Channel made inside a Category takes its rules; a private one keeps its own.
if !private && roles_v2_held(&held) {
if let Err(e) = set_channel_sync(transport, &held, &id, category).await {
crate::log_warn!("[v2:sync] the new channel keeps its own rules: {e}");
}
}
}
Ok(id)
}
/// A sidebar entry a reorder may need to key first.
enum Keyed {
Channel(ChannelV2),
Category(super::community::CategoryV2),
}
/// The keys of an ordered group, minting them for keyless entries (a Channel from before
/// positions existed) so a move can land between any two. Each minted key is one edition.
async fn keyed<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, group: Vec<(Option<String>, Keyed)>) -> Result<Vec<String>, String> {
let mut keys: Vec<String> = Vec::with_capacity(group.len());
for (key, entry) in group {
let last = keys.last().map(String::as_str);
let key = match key {
Some(k) if last.is_none_or(|l| l.as_bytes() < k.as_bytes()) => k,
_ => {
let k = crate::community::rank::between(last, None).ok_or("no room to order these")?;
match entry {
Keyed::Channel(ch) => {
let mut meta = ch.metadata();
meta.extra.insert("position".into(), k.clone().into());
edit_channel_metadata(transport, community, &ch.id, &meta).await?;
}
Keyed::Category(c) => {
set_category(transport, community, c.id, &control::CategoryMetadata { name: c.name, position: Some(k.clone()), deleted: None, extra: c.extra }).await?;
}
}
k
}
};
keys.push(key);
}
Ok(keys)
}
/// Create a new PRIVATE channel (CORD-03 §2): mint a fresh id + an independent
/// random key at channel-epoch 1, mint a companion channel-scoped Role that is
/// the channel's access list (CORD-04 §2), deliver the key to the entitled over
/// the rekey plane (CORD-06 §1), then announce the channel (vsk 2, `private`).
/// Epoch 0 is the root generation ("the first privatisation is epoch 1"), so the
/// delivery commits its continuity to `(0, community_root)` — verifiable by every
/// member and bound to THIS community's root. The key ships BEFORE the
/// announcement: an aborted attempt leaves only an unannounced crate (invisible),
/// and a retry mints a fresh id, so there is no same-coordinate double-mint to
/// fork on. Live public links are refreshed; they carry no private key, so this
/// only re-states the public set.
pub async fn create_private_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str) -> Result<ChannelId, String> {
let channel_id = ChannelId(super::super::random_32());
create_private_channel_with_id(transport, community, name, channel_id).await?;
Ok(channel_id)
}
/// The companion Role minted alongside a Private channel — the channel's access
/// list (CORD-04 §2 `scope: {"kind":"channel"}`). Same name as the channel, and
/// **no permission bits**: it confers read access, which is key possession, never
/// authority. Position sits below every management role for the same reason.
/// Where channel access roles sit: the bottom, so anyone who can manage roles outranks
/// them and may hand out read access.
pub const ACCESS_ROLE_POSITION: u32 = u32::MAX - 1;
pub fn channel_access_role(channel_id: &ChannelId, name: &str) -> crate::community::roles::Role {
use crate::community::roles::{Permissions, Role, RoleScope};
Role {
role_id: crate::simd::hex::bytes_to_hex_32(&super::super::random_32()),
name: name.to_string(),
position: ACCESS_ROLE_POSITION,
permissions: Permissions::empty(),
scope: RoleScope::Channel(crate::simd::hex::bytes_to_hex_32(&channel_id.0)),
color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
}
}
/// Who a reader takes a Channel rotation from (CORD-06 §3): the owner, or an unbanned holder of
/// `MANAGE_CHANNELS`, or of `BAN`, which a Refounding rides on and which can cut a member anyway.
pub(crate) fn rotates_channels<'a>(roster: &crate::community::roles::CommunityRoles, owner_hex: &str, banned: impl IntoIterator<Item = &'a String>, rotator_hex: &str) -> bool {
use crate::community::roles::Permissions;
rotator_hex == owner_hex
|| (!banned.into_iter().any(|b| b == rotator_hex)
&& (roster.is_authorized(rotator_hex, Some(owner_hex), Permissions::MANAGE_CHANNELS) || roster.is_authorized(rotator_hex, Some(owner_hex), Permissions::BAN)))
}
/// The bit a Channel rotator acts on members under: `MANAGE_CHANNELS` when it holds it, else `BAN`.
pub(crate) fn channel_rotation_bit(roster: &crate::community::roles::CommunityRoles, owner_hex: &str, rotator_hex: &str) -> u64 {
use crate::community::roles::Permissions;
if roster.is_authorized(rotator_hex, Some(owner_hex), Permissions::MANAGE_CHANNELS) { Permissions::MANAGE_CHANNELS } else { Permissions::BAN }
}
/// Make a Public Channel private (CORD-03 §2), on Roles v2: mint its own key at the next channel
/// epoch, deliver it to everyone the Channel lets in once private, then publish its first sealed
/// edition, naming this member as its creator and when it stopped being public.
pub async fn privatize_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId) -> Result<(), String> {
crate::db::scoped(async move {
let lock = super::realtime::follow_lock(community.id());
let _guard = lock.lock().await;
let signer = crate::signer::active_signer()?;
let my_pk = me_pk()?;
ensure_channel_manager(community, &my_pk)?;
let community = &crate::db::community::load_community_v2(community.id())?.unwrap_or_else(|| community.clone());
if !roles_v2_held(community) {
return Err("making a channel private needs the community on the new roles".to_string());
}
let ch = community.channel(channel_id).ok_or("no such channel")?.clone();
if ch.private {
return Ok(());
}
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
// One epoch past any it was private at before, the same one again on a retry.
let pending_key = format!("v2_privatize:{cid_hex}:{chan_hex}");
let pending = crate::db::get_sql_setting(pending_key.clone()).ok().flatten().and_then(|v| v.parse::<u64>().ok());
let epoch = match pending {
Some(e) => Epoch(e),
None => {
let mut top = crate::db::community::held_epoch_keys(&cid_hex, &chan_hex)?.into_iter().map(|(e, _)| e.0).max().unwrap_or(0);
// An earlier private era may have rotated past what this device ever held. Only a
// complete rotation a reader would honor takes an epoch: junk at an address doesn't.
let roots = channel_rekey_addressing_roots(community.community_root, &cid_hex);
let owner_hex = community.owner()?.to_hex();
let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
let probe_roster = crate::db::community::get_community_roles(&cid_hex)?;
for _ in 0..MAX_VEND_EPOCH_LEAD {
let next = Epoch(top.checked_add(1).ok_or("channel epoch overflow")?);
let mut taken = false;
for root in &roots {
let chunks = fetch_rekey_chunks(transport, &community, &channel_rekey_group_key(root, channel_id, next)).await?;
taken = rekey::collect_rotations(&chunks).iter().any(|r| {
r.scope.id32() == RekeyScope::Channel(*channel_id).id32()
&& r.new_epoch == next
&& r.is_complete()
&& rotates_channels(&probe_roster, &owner_hex, banned.iter(), &r.rotator.to_hex())
});
if taken {
break;
}
}
if !taken {
break;
}
top = next.0;
}
let e = Epoch(top.checked_add(1).ok_or("channel epoch overflow")?);
crate::db::set_sql_setting(pending_key.clone(), e.0.to_string())?;
e
}
};
let channel_key = mint_or_reuse_rotation_key(&cid_hex, &chan_hex, epoch.0)?;
// Whom the Channel lets in once private: its rules as they stand, this member as creator.
let mut roster = crate::db::community::get_community_roles(&cid_hex)?;
roster.creators.insert(chan_hex.clone(), my_pk.to_hex());
let owner = community.owner()?;
let owner_hex = owner.to_hex();
let mut recipients = vec![my_pk];
if owner != my_pk {
recipients.push(owner);
}
for pk in access_candidates(community, &roster)? {
if !recipients.contains(&pk) && roster.is_entitled(Some(&owner_hex), &pk.to_hex(), &chan_hex, &[], &[]) {
recipients.push(pk);
}
}
let prev_epoch = Epoch(epoch.0 - 1);
let prev_commit = super::derive::epoch_key_commitment(prev_epoch, &community.community_root);
let mut blobs = Vec::with_capacity(recipients.len());
for r in &recipients {
blobs.push(rekey::build_blob(&signer, &my_pk.to_bytes(), r, RekeyScope::Channel(*channel_id), epoch, &channel_key).await.map_err(|e| e.to_string())?);
}
let group = channel_rekey_group_key(&community.community_root, channel_id, epoch);
let at_ms = now_ms();
let chunks = rekey::build_rekey_chunks(&signer, my_pk, &group, RekeyScope::Channel(*channel_id), epoch, prev_epoch, &prev_commit, &blobs, at_ms / 1000, my_authority_citation(community, &my_pk).as_ref(), false)
.await
.map_err(|e| e.to_string())?;
for c in &chunks {
transport.publish_durable(c, &community.relays).await?;
}
let mut meta = ch.metadata();
meta.private = true;
meta.extra.insert("creator".into(), my_pk.to_hex().into());
meta.extra.insert("public_until".into(), at_ms.into());
let prev = channel_head(community, channel_id)?;
let content = channel_edition_content(community, channel_id, &meta, Some((channel_key, epoch)), prev.as_ref())?;
publish_control_edition(transport, community, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
if !crate::db::community::community_held(community.id())? {
return Err("community removed while making the channel private".to_string());
}
let mut updated = crate::db::community::load_community_v2(community.id())?.unwrap_or_else(|| community.clone());
if let Some(held) = updated.channels.iter_mut().find(|c| c.id.0 == channel_id.0) {
held.private = true;
held.key = Some(channel_key);
held.epoch = epoch;
held.meta_extra = meta.extra.clone();
held.sealed = sealed_held(&content, prev);
}
crate::db::community::save_community_v2(&updated)?;
let at = crate::db::community::get_community_roles_at(&cid_hex).unwrap_or(0);
crate::db::community::set_community_roles(&cid_hex, &roster, at)?;
// Only once it's held: a retry before this reuses the epoch and key it minted.
let _ = crate::db::set_sql_setting(pending_key, String::new());
let _ = refresh_public_links(transport, &updated).await;
Ok(())
})
.await
}
/// [`create_private_channel`] with a CALLER-CHOSEN id — the migration-only entry point
/// (§migration) reusing an existing private channel's id so history stitches through.
pub async fn create_private_channel_with_id<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str, channel_id: ChannelId) -> Result<(), String> {
crate::db::scoped(async move {
// Serialize with the follow worker across the whole fetch→publish→save span
// (the memberlist fetch is seconds long; an unserialized follow adopting a
// rotation meanwhile would be rolled back by the whole-row save below).
let lock = super::realtime::follow_lock(community.id());
let _guard = lock.lock().await;
let signer = crate::signer::active_signer()?;
let my_pk = me_pk()?;
ensure_channel_manager(community, &my_pk)?;
assert_channel_id_free(&channel_id, community.id())?;
let v2 = roles_v2_held(community);
// On Roles v2 the sealed metadata names its creator, who is let in on that (CORD-04 §8).
let mut extra = serde_json::Map::new();
if v2 {
extra.insert("creator".into(), my_pk.to_hex().into());
}
let meta = control::ChannelMetadata { name: name.to_string(), private: true, voice: None, deleted: None, custom: None, extra };
let channel_key = super::super::random_32();
let epoch = Epoch(1);
let content = channel_edition_content(community, &channel_id, &meta, Some((channel_key, epoch)), None)?;
let sealed = control::parse_sealed_channel_meta(&content).map(|s| super::community::SealedMeta { epoch: s.epoch, raw: content.clone(), open: true, junk: false, prev: None });
// The channel's access list: a companion channel-scoped Role (CORD-04 §2),
// granted to me so the creator is entitled from the first edition.
let access_role = channel_access_role(&channel_id, name);
let access_role_ids = vec![access_role.role_id.clone()];
// Recipients are the ENTITLED, not the memberlist: CORD-03's private channel
// is "readable only by granted role-holders". At create that is me (plus the
// owner, who is always entitled) — everyone else keys up when granted.
let owner = community.owner()?;
let mut recipients = vec![my_pk];
if owner != my_pk {
recipients.push(owner);
}
let prev_commit = super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
let mut blobs = Vec::with_capacity(recipients.len());
for r in &recipients {
blobs.push(
rekey::build_blob(&signer, &my_pk.to_bytes(), r, RekeyScope::Channel(channel_id), epoch, &channel_key)
.await
.map_err(|e| e.to_string())?,
);
}
let group = channel_rekey_group_key(&community.community_root, &channel_id, epoch);
let at_secs = now_ms() / 1000;
let chunks = rekey::build_rekey_chunks(&signer, my_pk, &group, RekeyScope::Channel(channel_id), epoch, Epoch(0), &prev_commit, &blobs, at_secs, my_authority_citation(community, &my_pk).as_ref(), false)
.await
.map_err(|e| e.to_string())?;
for c in &chunks {
transport.publish_durable(c, &community.relays).await?;
}
publish_control_edition(transport, community, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
if v2 {
// On Roles v2 a Private Channel is closed to everyone but the owner and its creator
// until they let a Role or a member in, so it opens nothing before its rules exist.
let chan = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
if !crate::db::community::community_held(community.id())? {
return Err("community removed during channel create".to_string());
}
let mut updated = community.clone();
updated.channels.push(ChannelV2 { id: channel_id, name: name.to_string(), private: true, key: Some(channel_key), epoch, voice: None, meta_custom: None, meta_extra: meta.extra.clone(), writers: None, sealed: sealed.clone() });
crate::db::community::save_community_v2(&updated)?;
crate::db::community::store_epoch_key(&cid_hex, &chan, epoch.0, &channel_key)?;
// The fold reads the creator back later; until then the stored Roster must let them in.
let mut roster = crate::db::community::get_community_roles(&cid_hex)?;
roster.creators.insert(chan.clone(), my_pk.to_hex());
let at = crate::db::community::get_community_roles_at(&cid_hex).unwrap_or(0);
crate::db::community::set_community_roles(&cid_hex, &roster, at)?;
let _ = refresh_public_links(transport, &updated).await;
return Ok(());
}
// Publish the access list AFTER the channel exists, so a peer folding the
// Role always resolves the channel it scopes to. A failure here leaves a
// channel only its creator can read — recoverable by re-granting, never a
// leak.
set_role(transport, community, &access_role).await?;
// Judge staff-ness against a roster that HOLDS the role just minted above —
// no fold has read it back yet, and the access role is permission-less, so
// resolving it locally both skips a round trip and gets the right answer.
let mut roster_with_access = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap_or_default();
if roster_with_access.role(&access_role.role_id).is_none() {
roster_with_access.roles.push(access_role.clone());
}
grant_roles_with_roster(transport, community, &my_pk, access_role_ids.clone(), &roster_with_access).await?;
// The fold is the authority but runs later; without this the creator is not
// yet entitled to their own channel and the next grant finds no access role.
merge_local_roster(
&crate::simd::hex::bytes_to_hex_32(&community.id().0),
Some(&access_role),
Some(&crate::community::roles::MemberGrant { member: my_pk.to_hex(), role_ids: access_role_ids }),
);
// A leave/delete raced the create: saving would resurrect the community row.
if !crate::db::community::community_held(community.id())? {
return Err("community removed during channel create".to_string());
}
let mut updated = community.clone();
updated.channels.push(ChannelV2 { id: channel_id, name: name.to_string(), private: true, key: Some(channel_key), epoch, voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed: sealed.clone() });
crate::db::community::save_community_v2(&updated)?;
// Archive the epoch-1 key so this channel's history stays readable across its
// future rotations (CORD-03 §3).
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::store_epoch_key(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&channel_id.0), epoch.0, &channel_key)?;
// Re-state live links. They carry no private key (CORD-05 §2 — a link's
// audience holds no Role), so this only refreshes the public set.
let _ = refresh_public_links(transport, &updated).await;
Ok(())
})
.await
}
// ── Receiving a key vend (CORD-03 "delivered on grant") ──────────────────────
/// What a client should do with a vended Private-Channel key right now.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VendVerdict {
/// Every rule passed — adopt the key.
Accept,
/// Cannot judge YET: our fold lags the grant it delivers. Park quietly and
/// re-judge after the next control follow. NOT an anomaly — a lagging fold
/// is the normal case for a vend that races its own Grant.
Park(&'static str),
/// Judged invalid against evidence that cannot become true later. Alarm-worthy.
Refuse(&'static str),
}
/// Judge a vended Private-Channel key against our OWN folded state.
///
/// The Grant is the authority half and rides the owner-rooted control plane, so
/// it cannot be forged; the vend is only delivery. Acceptance therefore rests
/// entirely on what our own fold proves — a bundle can never introduce a channel
/// our control plane doesn't define, which is what closes the hidden-channel
/// injection class.
///
/// `community` must already be the held (self-certified) community: the caller
/// resolves it by `community_id`, so a bundle naming a community we're not in is
/// never judged here at all.
pub fn judge_channel_key_vend(
community: &CommunityV2,
roster: &crate::community::roles::CommunityRoles,
channel_id: &ChannelId,
epoch: Epoch,
sender_hex: &str,
) -> VendVerdict {
let me = match me_pk() {
Ok(pk) => pk.to_hex(),
Err(_) => return VendVerdict::Park("no active identity"),
};
let owner_hex = match community.owner() {
Ok(o) => o.to_hex(),
Err(_) => return VendVerdict::Refuse("community has no resolvable owner"),
};
let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
// (2) The channel must exist in OUR fold, and be private there. The bundle's
// own claims are ignored: a vend may deliver a key, never define a channel.
let Some(ch) = community.channel(channel_id) else {
return VendVerdict::Park("channel not in our fold yet");
};
if !ch.private {
// Never heals: our owner-rooted fold says this channel is public, so a
// "private key" for it is a spoof, not a lagging view.
return VendVerdict::Refuse("vend names a channel our fold says is public");
}
// (5) Epoch sanity, BOTH directions. Below is superseded by the rotation that
// produced our copy. Above matters more: the channel head is monotonic, so a
// wildly-ahead epoch is not merely wrong, it is PERMANENT — every genuine
// rotation afterwards lands at `head + 1`, is refused as stale, and the
// channel dies for us with no heal path at all (not a rekey, not a re-grant,
// not a refound). Rotations advance one epoch at a time, so a lead this large
// is never a delivery we could place.
if ch.key.is_some() && epoch.0 <= ch.epoch.0 {
return VendVerdict::Refuse("superseded: we already hold this epoch or newer");
}
if epoch.0 > ch.epoch.0.saturating_add(MAX_VEND_EPOCH_LEAD) {
return VendVerdict::Refuse("vend epoch is implausibly far ahead of the channel head");
}
// (3) OUR fold must show US granted a role scoped to this channel. This is
// the rule that kills the spoof class: an attacker cannot forge the Grant,
// so they cannot make us accept a key for a channel we were never granted.
if !roster.is_entitled(Some(&owner_hex), &me, &chan_hex, &[], &[]) {
return VendVerdict::Park("our grant for this channel has not folded yet");
}
// (4) The vendor must be entitled too — they hold the real key, so a wrong
// key from them costs isolation, never confidentiality. A channel manager may be
// let in by a creator rule only a holder can read, so they count as one. A banned
// vendor delivers nothing (CORD-03 §5).
if PublicKey::from_hex(sender_hex).is_ok_and(|pk| crate::db::community::is_author_banned_in(&community.id().0, &pk)) {
return VendVerdict::Refuse("vendor is banned");
}
let manages = roster.is_authorized(sender_hex, Some(&owner_hex), crate::community::roles::Permissions::MANAGE_CHANNELS);
if sender_hex != owner_hex && !manages && !roster.is_entitled(Some(&owner_hex), sender_hex, &chan_hex, &[], &[]) {
return VendVerdict::Park("vendor's entitlement has not folded yet");
}
VendVerdict::Accept
}
/// How long an unprovable parked vend is kept. Deliberately long: the fallback
/// heal is the channel's next rotation, which may never come.
const PARKED_VEND_TTL_SECS: u64 = 30 * 24 * 3600;
/// How far above our channel head a vend may claim to be. Generous — a keyless
/// cursor can lag a busy channel by many rotations — but bounded, because the
/// head is monotonic and an over-advance can never be walked back.
const MAX_VEND_EPOCH_LEAD: u64 = 1024;
/// Re-judge every parked key vend for this community and adopt the ones that now
/// pass. Runs after a control follow (the fold moved, so verdicts can change) and
/// on the boot sweep.
///
/// Returns the channels newly keyed up.
pub fn absorb_parked_channel_keys(community: &CommunityV2, session: &std::sync::Arc<crate::db::Session>) -> Vec<ChannelId> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let parked = match crate::db::community::get_pending_channel_keys(&cid_hex) {
Ok(p) if !p.is_empty() => p,
_ => return Vec::new(),
};
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let mut adopted = Vec::new();
let now = now_ms() / 1000;
for p in parked {
// Several candidates may name one channel (parking is open to any sender,
// so a stranger can never suppress the entitled vendor's key by holding a
// slot). Once one is seated the rest are moot.
if adopted.iter().any(|c: &ChannelId| crate::simd::hex::bytes_to_hex_32(&c.0) == p.channel_id) {
let _ = crate::db::community::drop_pending_channel_key(p.id);
continue;
}
// A vend we were never able to prove is not kept forever: an admin who
// adds then immediately removes someone leaves a row nothing will ever
// discharge. Generous by design — the alternative heal (the channel's
// next rotation) can be arbitrarily far away, so this is hygiene, not a
// deadline.
if now.saturating_sub(p.received_at.max(0) as u64) > PARKED_VEND_TTL_SECS {
let _ = crate::db::community::drop_pending_channel_key(p.id);
continue;
}
let Some(id_bytes) = crate::simd::hex::hex_to_bytes_32_checked(&p.channel_id) else {
let _ = crate::db::community::drop_pending_channel_key(p.id);
continue;
};
let channel_id = ChannelId(id_bytes);
match judge_channel_key_vend(community, &roster, &channel_id, Epoch(p.epoch), &p.sender) {
VendVerdict::Accept => {
if !session.is_live() {
return adopted;
}
// First delivery vs rotation. A keyless channel must bypass the
// monotonic guard: it sits at the epoch-0 cursor, and a peer that
// mints born-private channels at epoch 0 vends that same epoch, so
// `new > current` would refuse the only key on offer.
let keyless = community.channel(&channel_id).is_some_and(|c| c.key.is_none());
let seated = if keyless {
crate::db::community::seat_channel_key(&cid_hex, &p.channel_id, p.epoch, &p.key)
} else {
crate::db::community::advance_channel_epoch(&cid_hex, &p.channel_id, p.epoch, &p.key).map(|_| ())
};
if let Err(e) = seated {
crate::log_warn!("v2: adopting a vended channel key failed: {e}");
continue;
}
// The key landed — every other candidate for this channel is moot.
let _ = crate::db::community::drop_pending_channel_keys_for(&cid_hex, &p.channel_id);
adopted.push(channel_id);
}
VendVerdict::Refuse(why) => {
crate::log_warn!("v2: refused a vended channel key for {}: {why}", p.channel_id);
// Only THIS candidate — a sibling may still be the genuine vend.
let _ = crate::db::community::drop_pending_channel_key(p.id);
}
// Quiet by design: the fold simply hasn't caught up.
VendVerdict::Park(_) => {}
}
}
// A key that just landed may open the channel's sealed metadata.
if !adopted.is_empty() && session.is_live() {
if let Ok(Some(mut held)) = crate::db::community::load_community_v2(community.id()) {
if unseal_held(&mut held) {
let _ = crate::db::community::save_community_v2(&held);
}
}
}
adopted
}
/// Grant `member` read access to a Private channel (CORD-03 "delivered on
/// grant"): publish a Grant adding the channel's access role, then vend the key
/// as a CORD-05 §6 Direct Invite whose bundle carries exactly the channels they
/// are now entitled to.
///
/// The Grant is the authority half and rides the owner-rooted control plane, so
/// it cannot be forged; the vend is only delivery. A recipient accepts the key
/// solely on the strength of their OWN fold showing this grant — the bundle can
/// never introduce a channel their control plane doesn't define.
/// This device has folded the community onto Roles v2.
/// What a channel edition carries: on Roles v2 a Private Channel seals its metadata under its
/// key (CORD-03 §2), so only a key holder writes one.
fn channel_edition_content(community: &CommunityV2, channel_id: &ChannelId, meta: &control::ChannelMetadata, key: Option<([u8; 32], Epoch)>, prev: Option<&[u8; 32]>) -> Result<String, String> {
if !meta.private || !roles_v2_held(community) {
control::validate_channel_metadata(meta).map_err(|e| e.to_string())?;
return serde_json::to_string(meta).map_err(|e| e.to_string());
}
let (key, epoch) = key.ok_or("you can only edit a private channel you can read")?;
control::seal_channel_metadata(meta, channel_group_key(&key, channel_id, epoch).conv_key(), epoch.0, prev)
}
/// The head a Channel's next edition builds on, as this device holds it.
fn channel_head(community: &CommunityV2, channel_id: &ChannelId) -> Result<Option<[u8; 32]>, String> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
Ok(crate::db::community::get_edition_head(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&channel_id.0))?.map(|(_, h)| h))
}
/// What a just-published sealed edition, built on `prev`, leaves this device holding.
fn sealed_held(content: &str, prev: Option<[u8; 32]>) -> Option<super::community::SealedMeta> {
let s = control::parse_sealed_channel_meta(content)?;
Some(super::community::SealedMeta { epoch: s.epoch, raw: content.to_string(), open: true, junk: false, prev: prev.map(|p| crate::simd::hex::bytes_to_hex_32(&p)) })
}
/// Whether a Private Channel's metadata needs sealing under the key this device holds now: its
/// head is plain, or sealed under an earlier epoch this device could read.
fn needs_reseal(community: &CommunityV2, ch: &ChannelV2) -> bool {
ch.private
&& ch.key.is_some()
&& !ch.name.is_empty()
&& match &ch.sealed {
Some(s) => (s.open && s.epoch < ch.epoch.0) || s.junk,
None => true,
}
&& roles_v2_held(community)
}
/// Re-seal a Private Channel's metadata under its current key (CORD-03 §2): the rotator's duty
/// after a rekey, with any manager holding the key as backstop. Returns whether it published.
async fn reseal_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId) -> Result<bool, String> {
// Sealed from the Channel as this device holds it now, so a rename that folded since the
// caller read it is never written back over.
let fresh = crate::db::community::load_community_v2(community.id())?.unwrap_or_else(|| community.clone());
let Some(ch) = fresh.channel(channel_id).or_else(|| community.channel(channel_id)) else { return Ok(false) };
let ch = ch.clone();
if !needs_reseal(&fresh, &ch) {
return Ok(false);
}
let meta = control::sanitize_channel_metadata(ch.metadata());
let prev = channel_head(&fresh, channel_id)?;
let content = channel_edition_content(&fresh, channel_id, &meta, ch.key.map(|k| (k, ch.epoch)), prev.as_ref())?;
publish_control_edition(transport, &fresh, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
if let Ok(Some(mut held)) = crate::db::community::load_community_v2(community.id()) {
if let Some(slot) = held.channels.iter_mut().find(|c| c.id.0 == channel_id.0) {
slot.sealed = sealed_held(&content, prev);
crate::db::community::save_community_v2(&held)?;
}
}
Ok(true)
}
/// The reseal backstop (CORD-03 §2): after a rank-staggered wait, seal again what needs it.
/// One Channel's failure never stops the rest.
async fn reseal_backstop<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, roster: &crate::community::roles::CommunityRoles) -> usize {
let Ok(Some(held)) = crate::db::community::load_community_v2(community.id()) else { return 0 };
if !held.channels.iter().any(|ch| needs_reseal(&held, ch)) {
return 0;
}
let (Ok(owner), Ok(me)) = (held.owner(), me_pk()) else { return 0 };
let steps = if me == owner { 0 } else { roster.highest_position(&me.to_hex()).map_or(10, |p| p.saturating_add(1).min(10)) as u64 };
crate::rt::time::sleep(std::time::Duration::from_millis(2_000 * steps + rand::random::<u64>() % 2_000)).await;
if !crate::db::current_session().is_live() {
return 0;
}
// Sealed from what the Control Plane says now: another manager's reseal or rename may have landed.
let (_guard, held) = match follow_fresh(transport, held.id()).await {
Ok(fresh) => fresh,
Err(e) => {
crate::log_warn!("v2: the reseal backstop couldn't read the Control Plane: {e}");
return 0;
}
};
let mut resealed = 0;
for ch in held.channels.iter().filter(|c| c.private && c.key.is_some()) {
match reseal_channel(transport, &held, &ch.id).await {
Ok(true) => resealed += 1,
Ok(false) => {}
Err(e) => crate::log_warn!("v2: resealing a private channel's details failed: {e}"),
}
}
resealed
}
/// The earlier planes of a Channel's history `held` lists or `add` brings, each address once,
/// oldest dropped past the cap; `None` when `add` brings nothing new.
fn merged_history(held: Vec<(Epoch, GroupKey)>, add: Vec<(Epoch, GroupKey)>) -> Option<serde_json::Value> {
let mut all = held;
let before = all.len();
for (epoch, group) in add {
if !all.iter().any(|(_, g)| g.pk() == group.pk()) {
all.push((epoch, group));
}
}
if all.len() == before {
return None;
}
all.sort_by_key(|(e, _)| e.0);
let drop = all.len().saturating_sub(super::community::MAX_HISTORY);
Some(serde_json::Value::Array(
all.into_iter().skip(drop).map(|(e, g)| serde_json::json!([e.0, crate::simd::hex::bytes_to_hex_32(&g.secret())])).collect(),
))
}
/// The planes of a Private Channel's own epochs this device holds.
fn private_planes(community: &CommunityV2, ch: &ChannelV2) -> Vec<(Epoch, GroupKey)> {
let (cid_hex, ch_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&ch.id.0));
let mut keys = crate::db::community::held_epoch_keys(&cid_hex, &ch_hex).unwrap_or_default();
if let Some(key) = ch.key.filter(|_| ch.private && !keys.iter().any(|(e, _)| *e == ch.epoch)) {
keys.push((ch.epoch, key));
}
keys.into_iter().filter(|(_, k)| *k != community.community_root).map(|(e, k)| (e, channel_group_key(&k, &ch.id, e))).collect()
}
fn history_scan_key(community: &CommunityV2, ch: &ChannelV2) -> String {
format!("history_scan:{}:{}", crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&ch.id.0))
}
/// What of a public Channel's history this device can hand every member and its metadata doesn't
/// yet (CORD-03 §2): the private epochs it kept, and each past root epoch the Channel wrote
/// under, found from the oldest not yet looked at. With it, the root epoch looked at up to.
async fn owed_history<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, ch: &ChannelV2) -> (Vec<(Epoch, GroupKey)>, Option<u64>) {
let listed: std::collections::HashSet<PublicKey> = ch.published_history().into_iter().map(|(_, g)| g.pk()).collect();
let mut owed: Vec<(Epoch, GroupKey)> = private_planes(community, ch).into_iter().filter(|(_, g)| !listed.contains(&g.pk())).collect();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let from = crate::db::get_sql_setting(history_scan_key(community, ch)).ok().flatten().and_then(|v| v.parse::<u64>().ok()).map_or(0, |s| s + 1);
let mut roots: Vec<(Epoch, [u8; 32])> = crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX)
.unwrap_or_default()
.into_iter()
.filter(|(e, _)| e.0 >= from && *e < community.root_epoch)
.collect();
roots.sort_by_key(|(e, _)| e.0);
let written: std::collections::HashSet<u64> = ch.writers.iter().flat_map(|l| l.roots()).map(|e| e.0).collect();
let mut scanned = None;
for (epoch, root) in roots {
let group = channel_group_key(&root, &ch.id, epoch);
if !listed.contains(&group.pk()) {
let carries = written.contains(&epoch.0) || {
let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk().to_hex()], limit: Some(1), ..Default::default() };
match transport.fetch_plane(group.keys(), &q, &community.relays).await {
Ok(f) => !f.events.is_empty(),
Err(_) => break,
}
};
if carries {
owed.push((epoch, group));
}
}
scanned = Some(epoch.0);
}
(owed, scanned)
}
/// Add `add` to a public Channel's published history (CORD-03 §2), read from the Channel as this
/// device holds it now. Returns whether an edition went out.
async fn publish_history<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId, add: Vec<(Epoch, GroupKey)>) -> Result<bool, String> {
let fresh = crate::db::community::load_community_v2(community.id())?.unwrap_or_else(|| community.clone());
let Some(ch) = fresh.channel(channel_id).filter(|c| !c.private) else { return Ok(false) };
let Some(history) = merged_history(ch.published_history(), add) else { return Ok(false) };
let mut meta = ch.metadata();
meta.extra.insert(super::community::HISTORY_FIELD.to_string(), history);
edit_channel_metadata(transport, &fresh, channel_id, &meta).await?;
Ok(true)
}
/// Make a Private Channel public (CORD-03 §2). While `@everyone` there reads history, the edition
/// publishes the private epochs this device holds, so a member who never held the key reads what
/// was said while it was private.
pub async fn publicize_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId) -> Result<(), String> {
let ch = community.channel(channel_id).ok_or("unknown channel")?;
if !ch.private {
return Ok(());
}
let mut meta = ch.metadata();
meta.private = false;
meta.extra.remove("creator");
meta.extra.remove("public_until");
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
if roster.everyone_reads_history(&crate::simd::hex::bytes_to_hex_32(&channel_id.0)) {
if let Some(history) = merged_history(ch.published_history(), private_planes(community, ch)) {
meta.extra.insert(super::community::HISTORY_FIELD.to_string(), history);
}
}
edit_channel_metadata(transport, community, channel_id, &meta).await
}
type Planes = Vec<(Epoch, GroupKey)>;
/// How often one Channel's history is looked at again by the backstop.
const HISTORY_CHECK_PERIOD_MS: u64 = 60 * 60 * 1000;
/// The history backstop (CORD-03 §2): what this device holds of a public Channel's earlier planes,
/// where `@everyone` reads history and the Channel's metadata doesn't publish them yet, it
/// publishes after a rank-staggered wait. One Channel's failure never stops the rest.
async fn history_backstop<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, roster: &crate::community::roles::CommunityRoles) -> usize {
struct HistoryChecks;
type Checks = std::sync::Mutex<std::collections::HashMap<[u8; 32], (u64, Epoch)>>;
let Ok(Some(held)) = crate::db::community::load_community_v2(community.id()) else { return 0 };
let checks = crate::db::current_session().scoped::<HistoryChecks, Checks>();
let now = now_ms();
let due: Vec<ChannelV2> = {
let mut last = checks.lock().unwrap_or_else(|e| e.into_inner());
let due: Vec<ChannelV2> = held
.channels
.iter()
.filter(|ch| !ch.private && roster.everyone_reads_history(&crate::simd::hex::bytes_to_hex_32(&ch.id.0)))
// A rotation closes an epoch to publish: due at once.
.filter(|ch| last.get(&ch.id.0).is_none_or(|(t, e)| *e != held.root_epoch || now.saturating_sub(*t) > HISTORY_CHECK_PERIOD_MS))
.cloned()
.collect();
for ch in &due {
last.insert(ch.id.0, (now, held.root_epoch));
}
due
};
let mut owed: Vec<(ChannelV2, Planes, Option<u64>)> = Vec::new();
for ch in due {
let (add, scanned) = owed_history(transport, &held, &ch).await;
if add.is_empty() {
if let Some(s) = scanned {
let _ = crate::db::set_sql_setting(history_scan_key(&held, &ch), s.to_string());
}
} else {
owed.push((ch, add, scanned));
}
}
if owed.is_empty() {
return 0;
}
let (Ok(owner), Ok(me)) = (held.owner(), me_pk()) else { return 0 };
let steps = if me == owner { 0 } else { roster.highest_position(&me.to_hex()).map_or(10, |p| p.saturating_add(1).min(10)) as u64 };
crate::rt::time::sleep(std::time::Duration::from_millis(2_000 * steps + rand::random::<u64>() % 2_000)).await;
if !crate::db::current_session().is_live() {
return 0;
}
// Published against what the Control Plane says now: another manager may have done it. The
// edit takes the follow lock itself.
let fresh = match follow_fresh(transport, held.id()).await {
Ok((_guard, fresh)) => fresh,
Err(e) => {
crate::log_warn!("v2: the history backstop couldn't read the Control Plane: {e}");
return 0;
}
};
let mut published = 0;
for (ch, add, scanned) in owed {
match publish_history(transport, &fresh, &ch.id, add).await {
Ok(done) => {
published += done as usize;
if let Some(s) = scanned {
let _ = crate::db::set_sql_setting(history_scan_key(&fresh, &ch), s.to_string());
}
}
Err(e) => crate::log_warn!("v2: publishing a channel's history failed: {e}"),
}
}
published
}
fn roles_v2_held(community: &CommunityV2) -> bool {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let everyone = crate::simd::hex::bytes_to_hex_32(&super::derive::everyone_locator(community.id()));
crate::db::community::get_community_roles(&cid_hex).is_ok_and(|r| r.everyone.is_some())
|| crate::db::community::get_edition_head(&cid_hex, &everyone).ok().flatten().is_some()
}
/// On Roles v2 a member's access to one Private Channel is their own overwrite there:
/// View Channel allowed to let them in, denied to keep them out, other bits kept.
async fn member_view_overwrite<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId, member: &PublicKey, grant: bool) -> Result<(), String> {
use crate::community::roles::{OverwriteTarget, Permissions};
let ch = community.channel(channel_id).ok_or("unknown channel")?;
if !ch.private {
return Err("channel is public: every member already reads it".to_string());
}
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let chan = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
let target = OverwriteTarget::Member(member.to_hex());
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let (allow, deny) = roster.overwrites.iter().find(|o| o.scope == chan && o.target == target).map_or((0, 0), |o| (o.allow.0, o.deny.0));
let v = Permissions::VIEW_CHANNEL;
let (allow, deny) = if grant { (allow | v, deny & !v) } else { (allow & !v, deny | v) };
set_overwrite(transport, community, channel_id.0, target, allow, deny).await
}
pub async fn grant_channel_access<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
member: &PublicKey,
) -> Result<(), String> {
if roles_v2_held(community) {
return member_view_overwrite(transport, community, channel_id, member, true).await;
}
crate::db::scoped(async move {
let my_pk = me_pk()?;
let ch = community.channel(channel_id).ok_or("unknown channel")?;
if !ch.private {
return Err("channel is public — every member already reads it".to_string());
}
if ch.key.is_none() {
return Err("we hold no key for this channel, so we cannot vend it".to_string());
}
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
let owner_hex = community.owner()?.to_hex();
// A Grant REPLACES the member's role set, so the union it is built from must
// be CURRENT: a stale local roster would silently strip every role this
// client hasn't folded yet. Fetch the authority fresh rather than trusting
// the cache, and merge the local view on top so a role we just published
// ourselves (which the plane has but no fold has read back) survives too.
let view = fetch_authority(transport, community).await;
let mut roster = view.roles.clone();
let cached = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
for r in cached.roles {
if !roster.roles.iter().any(|x| x.role_id == r.role_id) {
roster.roles.push(r);
}
}
for g in cached.grants {
if !roster.grants.iter().any(|x| x.member == g.member) {
roster.grants.push(g);
}
}
let my_hex = my_pk.to_hex();
let member_hex = member.to_hex();
// Reader-gated by MANAGE_ROLES, like any Grant; narrowed to this channel so
// a channel-scoped manager can run its own access list.
if !roster.is_authorized_in(&my_hex, Some(&owner_hex), &chan_hex, crate::community::roles::Permissions::MANAGE_ROLES) {
return Err("not authorized to manage this channel's access".to_string());
}
// Rank as well as the bit: the fold drops a Grant aimed at a peer or superior
// (CORD-04 §2), so publishing one vends a key against a role set no reader
// will honour. The owner is the exception — never a valid rank target, but a
// legitimate recipient of a channel key an admin minted.
if member_hex != owner_hex {
if !roster.can_act_on_member(&my_hex, Some(&owner_hex), &member_hex, crate::community::roles::Permissions::MANAGE_ROLES) {
return Err("you do not outrank this member".to_string());
}
// A Grant replaces whole — a floored-but-unserved head would publish a
// wipe. The owner holds no Grant (their authority is implicit), so there
// is no head to insist on and nothing a first edition could erase.
require_grant_head(community, &view, &member_hex)?;
}
// The channel's roles are ordered by AUTHORITY, so `.first()` is the most
// privileged — granting read access must never hand out a per-channel
// moderator role that happens to share the scope. Pick the permission-less
// one: conferring read access is exactly what carries no authority.
let role_id = roster
.channel_roles(&chan_hex)
.into_iter()
.find(|r| r.permissions == crate::community::roles::Permissions::empty())
.map(|r| r.role_id.clone())
.ok_or("channel has no permission-less access role to grant")?;
let mut role_ids: Vec<String> = roster.roles_of(&member_hex).map(|r| r.role_id.clone()).collect();
if !role_ids.contains(&role_id) {
role_ids.push(role_id.clone());
}
// The access role is permission-less (never staff-making), but a KEPT role
// can be — the fetched roster judges (CORD-04 §3).
grant_roles_with_roster(transport, community, member, role_ids.clone(), &roster).await?;
merge_local_roster(&cid_hex, None, Some(&crate::community::roles::MemberGrant { member: member.to_hex(), role_ids }));
// Settle the vend against the Grant we JUST published — the fold lags it.
let bundle = bundle_of_with_overlay(
community,
BundleAudience::Member(*member),
Some(my_pk),
None,
None,
std::slice::from_ref(&role_id),
&[],
);
let signer = crate::signer::active_signer()?;
let wrap = invite::build_direct_invite_signed(&signer, my_pk, member, &bundle).await.map_err(|e| e.to_string())?;
transport.publish(&wrap, &community.relays).await?;
Ok(())
})
.await
}
/// Revoke `member`'s read access to a Private channel (CORD-03 "rekeyed on
/// removal"): drop the channel's access role from their Grant, then rotate the
/// channel to its next epoch delivering the fresh key to everyone still
/// entitled (CORD-06). The revoked member keeps whatever history they already
/// read — a rekey protects the future, never the past.
pub async fn revoke_channel_access<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
member: &PublicKey,
) -> Result<(), String> {
if roles_v2_held(community) {
return member_view_overwrite(transport, community, channel_id, member, false).await;
}
crate::db::scoped(async move {
let my_pk = me_pk()?;
let ch = community.channel(channel_id).ok_or("unknown channel")?;
if !ch.private {
return Err("channel is public — there is no access to revoke".to_string());
}
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
let owner_hex = community.owner()?.to_hex();
// Same replace-not-merge hazard as the grant: the retained set must be built
// from a CURRENT roster or this revoke strips roles we simply hadn't folded.
let view = fetch_authority(transport, community).await;
let mut roster = view.roles.clone();
let cached = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
for r in cached.roles {
if !roster.roles.iter().any(|x| x.role_id == r.role_id) {
roster.roles.push(r);
}
}
for g in cached.grants {
if !roster.grants.iter().any(|x| x.member == g.member) {
roster.grants.push(g);
}
}
let my_hex = my_pk.to_hex();
let member_hex = member.to_hex();
if !roster.is_authorized_in(&my_hex, Some(&owner_hex), &chan_hex, crate::community::roles::Permissions::MANAGE_ROLES) {
return Err("not authorized to manage this channel's access".to_string());
}
if *member == community.owner()? {
return Err("the owner is supreme and cannot be removed".to_string());
}
// Rank as well as the bit, and it matters more here than on the grant side:
// readers drop the Grant, but the channel rotation below is gated on the
// citation alone, so an unauthorized revoke still severs its target.
if !roster.can_act_on_member(&my_hex, Some(&owner_hex), &member_hex, crate::community::roles::Permissions::MANAGE_ROLES) {
return Err("you do not outrank this member".to_string());
}
// A Grant replaces whole — a floored-but-unserved head would publish a wipe.
require_grant_head(community, &view, &member_hex)?;
let access_ids = roster.channel_role_ids(&chan_hex);
// Without the access list this revoke is a no-op that still ROTATES, and the
// rotation's recipient filter would match nobody — cutting off every
// legitimately entitled member. Refuse rather than mass-evict.
if access_ids.is_empty() {
return Err("this channel's access role has not folded yet — retry once the control plane serves it".to_string());
}
let remaining: Vec<String> = roster
.roles_of(&member_hex)
.map(|r| r.role_id.clone())
.filter(|id| !access_ids.contains(id))
.collect();
grant_roles_with_roster(transport, community, member, remaining.clone(), &roster).await?;
merge_local_roster(&cid_hex, None, Some(&crate::community::roles::MemberGrant { member: member.to_hex(), role_ids: remaining }));
// Rotate so the removal actually severs them (CORD-06 §1). The revoked
// member is excluded from the recipient set by the overlay, since the fold
// has not yet caught the Grant we just published.
rekey_channel_excluding(transport, community, channel_id, &roster, &access_ids, std::slice::from_ref(member)).await
})
.await
}
/// Rotate one Private channel to its next epoch, delivering the fresh key to
/// everyone entitled EXCEPT `removed` (CORD-06 §1 single-channel rekey).
///
/// `roster` must be the caller's CURRENT view (fetched, not the local cache):
/// the recipient set is built from it, so a cached roster silently drops every
/// member granted since this client last folded — they keep a dead key with no
/// heal path. `access_ids` is that roster's access-role set for this channel;
/// `removed` is excluded explicitly, since the revoking Grant was published
/// moments ago and no fold has caught it. A batch ban excludes its whole wave
/// in ONE rotation — that is why this takes a slice.
async fn rekey_channel_excluding<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
roster: &crate::community::roles::CommunityRoles,
access_ids: &[String],
removed: &[PublicKey],
) -> Result<(), String> {
rekey_channel_at(transport, community, channel_id, roster, access_ids, removed, None).await.map(|_| ())
}
/// [`rekey_channel_excluding`] from the channel as held once the follow lock is ours. With `judged`,
/// only while it still stands at that epoch: false when it moved meanwhile, so the caller re-judges.
async fn rekey_channel_at<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
roster: &crate::community::roles::CommunityRoles,
access_ids: &[String],
removed: &[PublicKey],
judged: Option<Epoch>,
) -> Result<bool, String> {
crate::db::scoped(async move {
// Whole-row save below — serialize with the follow worker (see create_*_channel).
let lock = super::realtime::follow_lock(community.id());
let _guard = lock.lock().await;
// A rotation from a copy read before the wait would mint an epoch someone already has.
let held = crate::db::community::load_community_v2(community.id())?.ok_or("v2 community not found")?;
let community = &held;
if judged.is_some_and(|e| community.channel(channel_id).map(|c| c.epoch) != Some(e)) {
return Ok(false);
}
let signer = crate::signer::active_signer()?;
let my_pk = me_pk()?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
let ch = community.channel(channel_id).ok_or("unknown channel")?.clone();
let old_key = ch.key.ok_or("we hold no key for this channel, so we cannot rotate it")?;
let new_epoch = Epoch(ch.epoch.0.checked_add(1).ok_or("channel epoch overflow")?);
let owner = community.owner()?;
let owner_hex = owner.to_hex();
// Everyone still entitled: the owner (always), me (the rotator must be able
// to read what it rekeys), and every member the roster shows holding an
// access role — minus the removals.
let removed_hexes: std::collections::HashSet<String> = removed.iter().map(|p| p.to_hex()).collect();
let mut recipients: Vec<PublicKey> = vec![my_pk];
if owner != my_pk {
recipients.push(owner);
}
if roster.everyone.is_some() {
// On Roles v2, everyone the Channel resolves View Channel for.
for pk in access_candidates(community, roster)? {
let hex = pk.to_hex();
if removed_hexes.contains(&hex) || hex == owner_hex || recipients.contains(&pk) {
continue;
}
if roster.is_entitled(Some(&owner_hex), &hex, &chan_hex, &[], &[]) {
recipients.push(pk);
}
}
}
for g in roster.grants.iter().filter(|_| roster.everyone.is_none()) {
if removed_hexes.contains(&g.member) || g.member == owner_hex {
continue;
}
if !g.role_ids.iter().any(|id| access_ids.contains(id)) {
continue;
}
if let Ok(pk) = PublicKey::parse(&g.member) {
if !recipients.contains(&pk) {
recipients.push(pk);
}
}
}
// Mint-or-reuse keyed by (channel, next epoch) so a retry after a partial
// publish re-uses the same key instead of forking the epoch.
let new_key = mint_or_reuse_rotation_key(&cid_hex, &chan_hex, new_epoch.0)?;
let prev_commit = super::derive::epoch_key_commitment(ch.epoch, &old_key);
let mut blobs = Vec::with_capacity(recipients.len());
for r in &recipients {
blobs.push(
rekey::build_blob(&signer, &my_pk.to_bytes(), r, RekeyScope::Channel(*channel_id), new_epoch, &new_key)
.await
.map_err(|e| e.to_string())?,
);
}
let group = channel_rekey_group_key(&community.community_root, channel_id, new_epoch);
let at_secs = now_ms() / 1000;
let chunks = rekey::build_rekey_chunks(&signer, my_pk, &group, RekeyScope::Channel(*channel_id), new_epoch, ch.epoch, &prev_commit, &blobs, at_secs, my_authority_citation(community, &my_pk).as_ref(), false)
.await
.map_err(|e| e.to_string())?;
for c in &chunks {
transport.publish_durable(c, &community.relays).await?;
}
if !crate::db::community::community_held(community.id())? {
return Err("community removed during channel rekey".to_string());
}
// Adopt locally + archive, so our own history reads across the rotation.
crate::db::community::advance_channel_epoch(&cid_hex, &chan_hex, new_epoch.0, &new_key)?;
crate::db::community::store_epoch_key(&cid_hex, &chan_hex, new_epoch.0, &new_key)?;
let mut rotated = community.clone();
if let Some(c) = rotated.channels.iter_mut().find(|c| c.id == *channel_id) {
c.key = Some(new_key);
c.epoch = new_epoch;
}
reseal_rotated(transport, &rotated, channel_id).await;
// The live subscription is addressed by each Channel's epoch, and a rotation this device
// made itself folds no change a follow would notice: without this it goes deaf in the room.
if let Some(client) = crate::state::nostr_client() {
crate::db::spawn_bound(async move { super::realtime::refresh_subscription(&client).await });
}
super::realtime::reread_tails(*community.id(), vec![(*channel_id, ch.epoch)]);
Ok(true)
})
.await
}
/// The rotator's duty after minting a Private Channel's epoch (CORD-03 §2, CORD-04 §7): seal its
/// Pin List and metadata again under the new key, which members who join at it hold alone.
/// Best-effort: a failure never fails the rotation, and a manager's duty backs it up.
async fn reseal_rotated<T: Transport + ?Sized>(transport: &T, rotated: &CommunityV2, channel_id: &ChannelId) {
match read_channel_pins(rotated, channel_id) {
Ok(read) if !read.sealed && !read.pins.is_empty() => {
let entries: Vec<super::pins::PinEntry> = read.pins.iter().map(|p| p.entry.clone()).collect();
if let Some(ch) = rotated.channel(channel_id).cloned() {
match publish_pin_list(transport, rotated, &ch, &entries).await {
Err(e) => crate::log_warn!("[pins] rotation reseal failed (a curator's next edit heals): {e}"),
Ok(_) => crate::log_info!("[pins] resealed {} pin(s) under epoch {}", entries.len(), ch.epoch.0),
}
}
}
Ok(read) if read.sealed => crate::log_warn!("[pins] rotating a channel whose pin list we cannot read; reseal skipped"),
_ => {}
}
if let Err(e) = reseal_channel(transport, rotated, channel_id).await {
crate::log_warn!("v2: rotation reseal of channel metadata failed (the access duty retries): {e}");
}
}
/// Rotate every private channel a just-banned member could read (CORD-06 §1 applied
/// per channel). A Public-community Ban skips the Refounding (CORD-05 §5), but the
/// banlist and grant strip alone leave the member holding each private channel's
/// CURRENT epoch key — rotation is the only read severance.
///
/// Takes the whole banned wave: a channel several targets could read rotates ONCE,
/// excluding them all. Per-target rotation would mint N epochs for one ban wave and
/// churn every legitimate reader N times.
///
/// Each target carries its role set as captured before the strip: the fold may or
/// may not have caught the strip yet, and the `with` overlay makes the entitlement
/// judgment independent of that timing.
///
/// Offer-side mirror of the reader's `channel_rotator_ok`: a channel rotation is
/// honored only from `MANAGE_CHANNELS` holders, so a BAN-only moderator must not
/// publish one — locally adopting an epoch every reader rejects forks the channel.
///
/// Best-effort per channel (one failure must not leave the others unrotated);
/// returns how many channels rotated, or the joined failures.
pub async fn sever_banned_private_reads<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
targets: &[(PublicKey, Vec<String>)],
// The roster as it stood before the ban: on Roles v2 a ban drops its target's own
// overwrites, so who could read is only answerable from before it.
before_ban: Option<&crate::community::roles::CommunityRoles>,
) -> Result<usize, String> {
crate::db::scoped(async move {
let my_pk = me_pk()?;
// Readers take a Channel rotation from MANAGE_CHANNELS or BAN (CORD-06 §3).
ensure_folded_permission(community, &my_pk, crate::community::roles::Permissions::MANAGE_CHANNELS, "severing a banned member's channel reads")
.or_else(|_| ensure_folded_permission(community, &my_pk, crate::community::roles::Permissions::BAN, "severing a banned member's channel reads"))?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let owner_hex = community.owner().ok().map(|o| o.to_hex());
// On Roles v2 who could read is judged from before the ban, a local read: recorded
// first, so a rotation the network refuses now is retried until it lands.
if let Some(before) = before_ban.filter(|b| b.everyone.is_some()) {
let mut cuts: ReadCuts = Default::default();
for ch in community.channels.iter().filter(|c| c.private && c.key.is_some()) {
let chan_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
let out: std::collections::BTreeSet<String> = targets
.iter()
.filter(|(pk, stripped)| before.is_entitled(owner_hex.as_deref(), &pk.to_hex(), &chan_hex, stripped, &[]))
.map(|(pk, _)| pk.to_hex())
.collect();
if !out.is_empty() {
cuts.insert(chan_hex, out);
}
}
add_read_cuts(&cid_hex, cuts);
return run_read_cuts(transport, community).await;
}
// Recipients need the CURRENT entitlement view — fetched, then merged over the
// cache so entitlements we published ourselves survive a lagging fold (the same
// two-strand merge as `revoke_channel_access`).
let fresh = fetch_authority(transport, community).await;
let v2 = before_ban.is_some_and(|b| b.everyone.is_some()) || fresh.activated;
// On Roles v2 recipients are whoever the channel resolves View for: a partial read
// would leave out the very members a rotation must keep.
if v2 && !fresh.everyone_served {
return Err("the roster couldn't be read whole, so no channel was rotated yet".to_string());
}
let roster = rotation_roster(fresh.roles, &cid_hex);
let mut rotated = 0usize;
let mut failures: Vec<String> = Vec::new();
for ch in &community.channels {
if !ch.private || ch.key.is_none() {
continue;
}
let chan_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
// Everyone in the wave who could read this channel, cut in ONE rotation.
let judge = before_ban.filter(|_| v2).unwrap_or(&roster);
let excluded: Vec<PublicKey> = targets
.iter()
.filter(|(pk, stripped)| judge.is_entitled(owner_hex.as_deref(), &pk.to_hex(), &chan_hex, stripped, &[]))
.map(|(pk, _)| *pk)
.collect();
if excluded.is_empty() {
continue;
}
let access_ids = roster.channel_role_ids(&chan_hex);
// On the legacy roster entitlement without an access-role set can't happen for
// a non-owner, and an empty set would make the rotation's recipient filter
// mass-evict. On Roles v2 recipients are whoever the channel resolves View for.
if access_ids.is_empty() && !v2 {
continue;
}
// Reload per iteration: each rotation advances the held document, and a
// stale struct would mint a colliding channel epoch on the next pass.
let held = match crate::db::community::load_community_v2(community.id()) {
Ok(Some(c)) => c,
_ => return Err("community gone during ban severance".to_string()),
};
match rekey_channel_excluding(transport, &held, &ch.id, &roster, &access_ids, &excluded).await {
Ok(()) => rotated += 1,
Err(e) => failures.push(format!("{}: {e}", &chan_hex[..12])),
}
}
if failures.is_empty() {
Ok(rotated)
} else {
Err(format!("{rotated} rotated; failed: {}", failures.join("; ")))
}
})
.await
}
/// The fetched Roster with what this device holds and the fetch didn't serve merged under it,
/// so entitlements we published ourselves survive a lagging fold.
fn rotation_roster(mut roster: crate::community::roles::CommunityRoles, cid_hex: &str) -> crate::community::roles::CommunityRoles {
let cached = crate::db::community::get_community_roles(cid_hex).unwrap_or_default();
for r in cached.roles {
if !roster.roles.iter().any(|x| x.role_id == r.role_id) {
roster.roles.push(r);
}
}
for g in cached.grants {
if !roster.grants.iter().any(|x| x.member == g.member) {
roster.grants.push(g);
}
}
for o in cached.overwrites {
if !roster.overwrites.iter().any(|x| x.scope == o.scope && x.target == o.target) {
roster.overwrites.push(o);
}
}
for (channel, category) in cached.syncs {
roster.syncs.entry(channel).or_insert(category);
}
roster
}
/// Private channels a ban still has to rotate, each with the members to leave out (hex).
type ReadCuts = std::collections::BTreeMap<String, std::collections::BTreeSet<String>>;
fn read_cuts(cid_hex: &str) -> ReadCuts {
crate::db::settings::get_sql_setting(format!("v2_cut:{cid_hex}"))
.ok()
.flatten()
.and_then(|v| serde_json::from_str(&v).ok())
.unwrap_or_default()
}
fn store_read_cuts(cid_hex: &str, cuts: &ReadCuts) {
if let Ok(v) = serde_json::to_string(cuts) {
let _ = crate::db::settings::set_sql_setting(format!("v2_cut:{cid_hex}"), v);
}
}
fn add_read_cuts(cid_hex: &str, add: ReadCuts) {
if add.is_empty() {
return;
}
let mut cuts = read_cuts(cid_hex);
for (chan, members) in add {
cuts.entry(chan).or_default().extend(members);
}
store_read_cuts(cid_hex, &cuts);
}
pub(crate) fn has_read_cuts(cid_hex: &str) -> bool {
!read_cuts(cid_hex).is_empty()
}
/// Rotate each pending cut's channel without its members. A cut is dropped once its
/// rotation lands, or once there is nothing left this device could rotate.
async fn run_read_cuts<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<usize, String> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let cuts = read_cuts(&cid_hex);
if cuts.is_empty() {
return Ok(0);
}
let my_pk = me_pk()?;
if let Err(e) = ensure_folded_permission(community, &my_pk, crate::community::roles::Permissions::MANAGE_CHANNELS, "severing a banned member's channel reads")
.or_else(|_| ensure_folded_permission(community, &my_pk, crate::community::roles::Permissions::BAN, "severing a banned member's channel reads"))
{
store_read_cuts(&cid_hex, &ReadCuts::new());
return Err(e);
}
// Recipients are whoever the channel resolves View for: a partial read would leave out
// the very members the rotation must keep.
let fresh = fetch_authority(transport, community).await;
if !fresh.everyone_served {
return Err("the roster couldn't be read whole, so no channel was rotated yet; retrying on the next follow".to_string());
}
let roster = rotation_roster(fresh.roles, &cid_hex);
let (mut rotated, mut done, mut failures) = (0usize, Vec::new(), Vec::new());
for (chan, members) in &cuts {
let readable = community.channels.iter().any(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0) == *chan && c.private && c.key.is_some());
let Some(channel) = crate::simd::hex::hex_to_bytes_32_checked(chan).filter(|_| readable) else {
done.push(chan.clone());
continue;
};
let excluded: Vec<PublicKey> = members.iter().filter_map(|m| PublicKey::from_hex(m).ok()).collect();
// Reload per iteration: each rotation advances the held document.
let held = crate::db::community::load_community_v2(community.id())?.ok_or("community gone during ban severance")?;
match rekey_channel_excluding(transport, &held, &ChannelId(channel), &roster, &roster.channel_role_ids(chan), &excluded).await {
Ok(()) => {
rotated += 1;
done.push(chan.clone());
}
Err(e) => failures.push(format!("{}: {e}", &chan[..12])),
}
}
let mut left = read_cuts(&cid_hex);
for chan in done {
left.remove(&chan);
}
store_read_cuts(&cid_hex, &left);
if failures.is_empty() {
Ok(rotated)
} else {
Err(format!("{rotated} rotated; failed: {}", failures.join("; ")))
}
}
/// Retry the rotations this device still owes a community: a ban's cuts and a Role move's
/// settle. Runs outside the follow lock, which every rotation takes.
pub(crate) async fn retry_owed_rotations(id: &crate::community::CommunityId) {
let Ok(Some(community)) = crate::db::community::load_community_v2(id) else { return };
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
match run_read_cuts(&transport, &community).await {
Ok(0) => {}
Ok(n) => crate::log_info!("[Ban] rotated {n} private channel(s) a ban still owed"),
Err(e) => crate::log_warn!("[Ban] owed private-channel rotation still pending: {e}"),
}
let Ok(Some(community)) = crate::db::community::load_community_v2(id) else { return };
if let Err(e) = run_owed_settle(&transport, &community).await {
crate::log_warn!("[Roles] owed access settle still pending: {e}");
}
}
/// Tombstone a channel (CORD-03 §2, `deleted: true`) + drop it locally. Reader-gated by
/// `MANAGE_CHANNELS`; the coordinate stays folded as a grave so peers hide it.
pub async fn delete_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId, name: &str) -> Result<(), String> {
crate::db::scoped(async move {
// Whole-row save below — serialize with the follow worker (see create_*_channel).
let lock = super::realtime::follow_lock(community.id());
let _guard = lock.lock().await;
let my_pk = me_pk()?;
ensure_channel_manager(community, &my_pk)?;
// The tombstone carries the FULL held document (deleted flag set): a strict
// reader treats an edition as the entity, so even a deletion must not strip
// fields it didn't touch (CORD-02 §6).
let mut meta = community.channel(channel_id).map(|c| c.metadata()).unwrap_or_else(|| control::ChannelMetadata {
name: name.to_string(), private: false, voice: None, deleted: None, custom: None, extra: Default::default(),
});
meta.deleted = Some(true);
// A sealed channel goes with its seal carried verbatim: deleting takes only the bit.
let content = match community.channel(channel_id).and_then(|c| c.sealed.as_ref()) {
Some(s) => control::sealed_tombstone(&s.raw).ok_or("this channel's sealed details are malformed")?,
None => serde_json::to_string(&meta).map_err(|e| e.to_string())?,
};
publish_control_edition(transport, community, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
let mut updated = community.clone();
updated.channels.retain(|c| c.id.0 != channel_id.0);
crate::db::community::save_community_v2(&updated)?;
purge::purge_deleted_channel(community, channel_id, Some(my_pk)).await;
Ok(())
})
.await
}
// ── Live control-follow (CORD-02 §6 / CORD-03 §2) ────────────────────────────
/// Re-fold this community's Control Plane and apply the current metadata +
/// **public** channel set to the held community, persisting any change. Called
/// when a control-plane wrap arrives in realtime (a rename, a new channel, an
/// edited description) so a long-running bot tracks the community mid-session
/// instead of freezing at its join-time view.
///
/// **Authority (CORD-04 §5):** the roster (roles/grants/banlist) folds first into
/// the owner-seeded authorized set (`fold_authority`), then each metadata/channel
/// edition is eligible only if its signer CURRENTLY holds the entity's management
/// bit (`MANAGE_METADATA`/`MANAGE_CHANNELS`) — so an authorized admin's edits fold,
/// a demoted one's drop. The owner is supreme, proven by the self-certifying
/// community_id (no network trust).
///
/// **Private channels are skipped here:** a Private channel's Chat-Plane key is
/// delivered over the rekey plane (or an invite bundle), never derivable from a
/// control edition alone. A new Private channel therefore surfaces only once
/// [`follow_rekeys`] delivers its key. Public channels derive from the
/// community_root, so they fold in directly.
///
/// Returns the updated community iff something changed (so the caller can skip a
/// redundant re-subscribe + refresh notification).
/// What a control fold moved. `updated` is the community DOCUMENT (metadata,
/// channels, adopted control root); `authority_changed` is the roster/banlist/
/// registry — which live in their own columns and so are invisible in `updated`.
///
/// The distinction is load-bearing: the rekey walk's authority gates read exactly
/// the state `authority_changed` covers, so a caller that keys its retry off
/// `updated` alone will refuse a rotation on pass 1, silently fix the roster on
/// pass 2, and never look again. That is a permanent strand — and a strand is a
/// fork to everyone else.
#[derive(Debug, Default)]
pub struct ControlFollow {
pub updated: Option<CommunityV2>,
pub authority_changed: bool,
}
impl ControlFollow {
/// Did anything at all move? Either half warrants another rekey walk.
pub fn moved(&self) -> bool {
self.updated.is_some() || self.authority_changed
}
}
/// What a follow of the Control Plane reads and folds before it persists anything.
struct ControlRead {
floors: Floors,
editions: Vec<ParsedEdition>,
authority: AuthoritySet,
fold: ControlFold,
/// The read stopped with editions this device tracks still unread.
truncated: bool,
pages_read: usize,
/// Floors a build before marked editions wrote, now on the edition's real hash.
healed: Vec<HealedFloor>,
/// Why the last fold refused each role and grant it refused.
refusals: std::collections::BTreeMap<String, &'static str>,
}
/// A floor that held a marked edition under its unsigned hash, and the edition it names.
struct HealedFloor {
entity_hex: String,
version: u64,
unsigned: [u8; 32],
self_hash: [u8; 32],
inner_id: [u8; 32],
author: [u8; 32],
}
/// A floor written before marked editions (CORD-04 §1) holds the edition's unsigned hash, which
/// no served edition carries any more: its chain reads as a rival at the same version, and every
/// edition resting on its authority stops folding. Only the same edition takes the floor over: its
/// inner id, or its unsigned hash under the signer the floor recorded. A copy re-signed under
/// another key shares that hash, so a floor that recorded no signer heals only to the owner's.
fn heal_unsigned_floors(floors: &mut Floors, owner: Option<[u8; 32]>, editions: &[ParsedEdition], healed: &mut Vec<HealedFloor>) {
let mut at: crate::fasthash::FastMap<([u8; 32], u64), Vec<&ParsedEdition>> = Default::default();
for e in editions {
at.entry((e.entity_id, e.version)).or_default().push(e);
}
for (eid, f) in floors.iter_mut() {
let Some(entity) = crate::simd::hex::hex_to_bytes_32_checked(eid) else { continue };
let Some(served) = at.get(&(entity, f.0)) else { continue };
if served.iter().any(|e| held_is(f, e)) {
continue;
}
let same: Vec<&ParsedEdition> = match served.iter().find(|e| f.2 == Some(e.inner_id)) {
Some(e) => vec![*e],
None => {
let Some(signer) = f.3.or(owner) else { continue };
served
.iter()
.copied()
.filter(|e| e.binding.is_some() && e.author.to_bytes() == signer)
.filter(|e| f.4.is_none_or(|fam| fam == crate::db::community::FloorFamily::of(floor_family(&e.vsk))))
.filter(|e| crate::community::version::edition_hash(&e.entity_id, e.version, e.prev_hash.as_ref(), e.content.as_bytes()) == f.1)
.collect()
}
};
let Some(e) = same.iter().min_by_key(|e| e.inner_id) else { continue };
if same.iter().any(|o| o.self_hash != e.self_hash) {
continue;
}
let unsigned = f.1;
f.1 = e.self_hash;
f.2 = Some(e.inner_id);
f.3 = Some(e.author.to_bytes());
if !healed.iter().any(|h| h.entity_hex == *eid) {
healed.push(HealedFloor { entity_hex: eid.clone(), version: f.0, unsigned, self_hash: e.self_hash, inner_id: e.inner_id, author: e.author.to_bytes() });
}
}
}
/// Per-entity refuse-downgrade floors for the CURRENT epoch only. A head recorded under a prior
/// epoch is excluded, so that entity auto-bootstraps after a Refounding (Armada accepts a compacted
/// head across a dangling prev — matched). A read error FAILS CLOSED: an empty map would silently
/// re-open the rollback window the floor exists to shut.
fn held_floors(community: &CommunityV2) -> Result<Floors, String> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
Ok(crate::db::community::get_all_edition_heads_full(&cid_hex)?
.into_iter()
.filter(|(_, f)| f.0 == community.root_epoch.0)
.map(|(entity, f)| (entity, (f.1, f.2, f.3, f.4, f.5)))
.collect())
}
impl ControlRead {
/// A fold with one answer over a whole window: what a live edition may later fold against.
fn settled(&self) -> bool {
self.authority.converged && !self.truncated && !self.fold.gapped && !self.authority.gapped
}
}
/// The fold a follow runs, over editions already in hand. No network, and not truncated: the
/// window it extends was read whole.
fn fold_control_held(community: &CommunityV2, editions: Vec<ParsedEdition>) -> Result<ControlRead, String> {
let mut floors = held_floors(community)?;
let mut healed = Vec::new();
heal_unsigned_floors(&mut floors, community.owner().ok().map(|o| o.to_bytes()), &editions, &mut healed);
let authority = fold_authority(community, &editions, &floors);
let refusals = AUTHORITY_REFUSALS.with(|c| c.borrow().clone());
let fold = apply_control_fold(community, &editions, &floors, &authority);
Ok(ControlRead { floors, editions, authority, fold, truncated: false, pages_read: 0, healed, refusals })
}
/// A Control Plane window a settled follow read this session, which a live edition folds
/// against instead of re-reading the plane.
#[derive(Clone)]
struct Held {
epoch: u64,
/// [`super::realtime::link_generation`] when the read began.
link: u64,
editions: Vec<ParsedEdition>,
/// The owner and everyone the window's Roster grants a Role: nobody else's edition can fold
/// here, since it would need a grant this window doesn't hold.
staff: crate::fasthash::FastSet<[u8; 32]>,
/// Channels the window already deletes.
deleted: Vec<ChannelId>,
}
struct HeldControl;
type HeldControlMap = std::sync::Mutex<std::collections::HashMap<[u8; 32], Held>>;
fn held_control() -> std::sync::Arc<HeldControlMap> {
crate::db::current_session().scoped::<HeldControl, HeldControlMap>()
}
/// The most editions a held window keeps: past it, live editions wait for a follow's re-read.
const LIVE_WINDOW_MAX: usize = FOLLOW_PAGE * 2;
/// What a window needs beside its editions to be held: one answer over all of it, with every
/// floored role and grant served.
fn holdable(community: &CommunityV2, read: &ControlRead) -> Option<(crate::fasthash::FastSet<[u8; 32]>, Vec<ChannelId>)> {
if !read.settled() || !read.authority.complete {
return None;
}
let mut staff: crate::fasthash::FastSet<[u8; 32]> =
read.authority.roles.grants.iter().filter_map(|g| crate::simd::hex::hex_to_bytes_32_checked(&g.member)).collect();
staff.extend(community.owner().ok().map(|o| o.to_bytes()));
Some((staff, read.fold.deleted_channels.clone()))
}
/// Keep a window, or forget one a follow could not settle.
fn hold_control(community: &CommunityV2, window: Option<Held>) {
let held = held_control();
let mut held = held.lock().unwrap_or_else(|e| e.into_inner());
match window.filter(|w| w.editions.len() <= LIVE_WINDOW_MAX) {
Some(w) => held.insert(community.id().0, w),
None => held.remove(&community.id().0),
};
}
/// Our own published edition joins the held window, which its floor has already passed.
fn hold_own(community: &CommunityV2, edition: ParsedEdition) {
let held = held_control();
let mut held = held.lock().unwrap_or_else(|e| e.into_inner());
let Some(w) = held.get_mut(&community.id().0).filter(|w| w.epoch == community.root_epoch.0) else {
return;
};
if edition.vsk == vsk::GRANT {
let member = super::roles::parse_grant_content(&edition.content).and_then(|g| crate::simd::hex::hex_to_bytes_32_checked(&g.member));
w.staff.extend(member);
}
if !w.editions.iter().any(|e| e.inner_id == edition.inner_id) {
w.editions.push(edition);
}
if w.editions.len() > LIVE_WINDOW_MAX {
held.remove(&community.id().0);
}
}
/// Follows reading a community's plane right now, whoever called them: a live fold waits them
/// out, since one that persists after it would write a row from before it.
struct ControlReads;
type ControlReadCounts = std::sync::Mutex<std::collections::HashMap<[u8; 32], usize>>;
struct Reading(std::sync::Arc<ControlReadCounts>, [u8; 32]);
impl Drop for Reading {
fn drop(&mut self) {
let mut counts = self.0.lock().unwrap_or_else(|e| e.into_inner());
if let Some(n) = counts.get_mut(&self.1) {
*n -= 1;
if *n == 0 {
counts.remove(&self.1);
}
}
}
}
fn reading(id: &crate::community::CommunityId) -> Reading {
let counts = crate::db::current_session().scoped::<ControlReads, ControlReadCounts>();
*counts.lock().unwrap_or_else(|e| e.into_inner()).entry(id.0).or_default() += 1;
Reading(counts, id.0)
}
fn being_read(id: &crate::community::CommunityId) -> bool {
crate::db::current_session().scoped::<ControlReads, ControlReadCounts>().lock().unwrap_or_else(|e| e.into_inner()).contains_key(&id.0)
}
/// A live control wrap, folded in place: the window the last settled follow read plus this
/// edition, through the fold and persist a follow runs. `None` whenever the window may not
/// decide it as a full read would (none held, a read since that may have missed something, an
/// author or a refusal only a read can settle, a new deletion): a full follow then reads the plane.
pub(crate) async fn follow_control_live(community: &CommunityV2, wrap: &Event) -> Option<ControlFollow> {
crate::db::scoped(async move {
hold_wrap(community, wrap);
if being_read(community.id()) {
return None;
}
let held = held_control().lock().unwrap_or_else(|e| e.into_inner()).get(&community.id().0).cloned()?;
if held.epoch != community.root_epoch.0 || held.link != super::realtime::link_generation() {
return None;
}
let edition = control::ControlPlane::of(community).open_edition(wrap).ok()?;
if held.editions.iter().any(|e| e.inner_id == edition.inner_id) {
return Some(ControlFollow::default());
}
// A Grant of mine that carries the staff key takes a remote signer to open: not on this
// path. One that carries none folds here like anyone's, so a Role handed out is known at once.
let mine = me_pk().is_ok_and(|me| edition.entity_id == super::derive::grant_locator(community.id(), &me.to_bytes()));
let keyed = mine && super::roles::parse_grant_control_wrap(&edition.content).is_some();
if keyed || !held.staff.contains(&edition.author.to_bytes()) {
return None;
}
let id = edition.inner_id;
let Held { epoch, link, mut editions, deleted, .. } = held;
editions.push(edition);
let read = fold_control_held(community, editions).ok()?;
let admitted = read.fold.admitted.contains(&id) || read.authority.admitted.contains(&id) || read.authority.heads.iter().any(|h| h.inner_id == id);
// A deletion purges history for good: only a full read may decide one.
if !admitted || read.fold.deleted_channels.iter().any(|c| !deleted.contains(c)) {
return None;
}
let (staff, deleted) = holdable(community, &read)?;
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let Ok((follow, Some(editions))) = persist_control(&transport, community, read).await else {
hold_control(community, None);
return None;
};
hold_control(community, Some(Held { epoch, link, editions, staff, deleted }));
Some(follow)
})
.await
}
/// Keep a Control wrap that reached this device outside a read (live, or one it just published),
/// so no relay is asked for it again.
fn hold_wrap(community: &CommunityV2, wrap: &Event) {
if control_store::mode() == control_store::Mode::Off {
return;
}
if let Err(e) = control_store::View::of(community).absorb(std::slice::from_ref(wrap)) {
crate::log_warn!("[v2:control {}] a wrap was not kept: {e}", &community.id().to_hex()[..8]);
}
}
/// What a read decided, each part by name, for telling two reads of one plane apart.
fn read_outcome(read: &ControlRead) -> Vec<(&'static str, String)> {
let heads = |heads: &[FoldedHead]| {
let mut all: Vec<String> = heads.iter().map(|h| format!("{}@{}:{}", h.entity_hex, h.version, crate::simd::hex::bytes_to_hex_32(&h.inner_id))).collect();
all.sort();
all.join(",")
};
let mut deleted: Vec<String> = read.fold.deleted_channels.iter().map(|c| crate::simd::hex::bytes_to_hex_32(&c.0)).collect();
deleted.sort();
vec![
("control heads", heads(&read.fold.heads)),
("roster heads", heads(&read.authority.heads)),
("roster", format!("{:?}", read.authority.roles)),
("banned", format!("{:?}", read.authority.banned)),
("banlist", format!("{:?}", read.authority.banlist_persist)),
("gapped", format!("{}/{}", read.fold.gapped, read.authority.gapped)),
("settled", format!("{}/{}", read.authority.converged, read.authority.complete)),
("community", format!("{:?}", read.fold.updated)),
("pins", format!("{:?}", read.fold.pins_persist)),
("writers", format!("{:?}", read.fold.writers_persist)),
("deleted", deleted.join(",")),
]
}
/// Read through the wraps held beside the read by pages a follow just made, and say where the
/// two part. Decides nothing.
async fn shadow_control<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, paged: &ControlRead) {
let cid = community.id().to_hex();
let held = match read_control_held(transport, community).await {
Ok(held) => held,
Err(Unheld::Paged(why)) => {
crate::log_warn!("[v2:control {}] shadow: no read through the store ({why})", &cid[..8]);
return;
}
Err(Unheld::NoRelay(_)) => return,
};
let has: crate::fasthash::FastSet<[u8; 32]> = held.editions.iter().map(|e| e.inner_id).collect();
let lost = paged.editions.iter().filter(|e| !has.contains(&e.inner_id)).count();
let more = has.len().saturating_sub(paged.editions.len() - lost);
// Two reads owe each other one answer only over the same editions, each having reached one.
// The store holding more is the point of it: what a relay stops serving is still held.
let parted: Vec<&'static str> = if lost > 0 || more > 0 || paged.truncated || held.truncated {
Vec::new()
} else {
read_outcome(paged).into_iter().zip(read_outcome(&held)).filter(|(a, b)| a.1 != b.1).map(|(a, _)| a.0).collect()
};
if lost > 0 || !parted.is_empty() {
// The suite run under `VECTOR_CONTROL_SHADOW_STRICT` takes every fixture as an oracle.
#[cfg(test)]
if std::env::var_os("VECTOR_CONTROL_SHADOW_STRICT").is_some() {
let apart: Vec<_> = read_outcome(paged).into_iter().zip(read_outcome(&held)).filter(|(a, b)| a.1 != b.1).collect();
panic!("the store read differs from the paged read: {lost} edition(s) lost, apart {apart:#?}");
}
crate::log_warn!(
"[v2:control {}] shadow: the store read DIFFERS: {lost} edition(s) only the paged read holds, parts apart {parted:?} (paged {} editions truncated={}, held {} truncated={})",
&cid[..8], paged.editions.len(), paged.truncated, held.editions.len(), held.truncated
);
} else {
crate::log_warn!(
"[v2:control {}] shadow: the store read agrees ({} editions held, {more} more than paged, {} paged)",
&cid[..8], held.editions.len(), paged.editions.len()
);
}
}
/// A control read in progress: the editions read so far and the folds over them.
struct Window<'a> {
community: &'a CommunityV2,
control: control::ControlPlane,
cid_hex: String,
everyone_hex: String,
owner: Option<[u8; 32]>,
floors: Floors,
healed: Vec<HealedFloor>,
refusals: std::collections::BTreeMap<String, &'static str>,
editions: Vec<ParsedEdition>,
seen: crate::fasthash::FastSet<[u8; 32]>,
seen_wraps: crate::fasthash::FastSet<nostr_sdk::prelude::EventId>,
fold: ControlFold,
authority: AuthoritySet,
/// Every entity some edition in hand speaks for: a page that can't account for everything
/// tracked folds nothing, since a head needs an edition of its own entity.
entities: crate::fasthash::FastSet<[u8; 32]>,
/// How many editions the folds last saw.
folded: Option<usize>,
}
/// What one page added to a [`Window`].
struct Taken {
/// Wraps not seen before.
fresh: usize,
/// The oldest second among them.
oldest: Option<u64>,
/// Fresh wraps that did not open.
unopened: Vec<nostr_sdk::prelude::EventId>,
}
impl<'a> Window<'a> {
fn new(community: &'a CommunityV2) -> Result<Window<'a>, String> {
Ok(Window {
community,
control: control::ControlPlane::of(community),
cid_hex: crate::simd::hex::bytes_to_hex_32(&community.id().0),
everyone_hex: crate::simd::hex::bytes_to_hex_32(&super::derive::everyone_locator(community.id())),
owner: community.owner().ok().map(|o| o.to_bytes()),
floors: held_floors(community)?,
healed: Vec::new(),
refusals: Default::default(),
editions: Vec::new(),
seen: Default::default(),
seen_wraps: Default::default(),
fold: ControlFold::default(),
authority: AuthoritySet::owner_only(),
entities: Default::default(),
folded: None,
})
}
/// Open a page into the window. A wrap seen before is passed over, so a re-served boundary
/// costs nothing.
fn take(&mut self, wraps: &[Event]) -> Taken {
let mut taken = Taken { fresh: 0, oldest: None, unopened: Vec::new() };
let batch = self.control.check_page(&wraps.iter().filter(|w| !self.seen_wraps.contains(&w.id)).collect::<Vec<_>>());
for w in wraps {
if !self.seen_wraps.insert(w.id) {
continue;
}
taken.fresh += 1;
let at = w.created_at.as_secs();
if taken.oldest.is_none_or(|o| at < o) {
taken.oldest = Some(at);
}
// Open + seal-verify every edition; authority is resolved by the roster
// fold (CORD-04 §5), not by a signer filter here — an admin's edits fold.
match self.control.open_edition(w) {
Ok(ed) => {
if self.seen.insert(ed.inner_id) {
self.entities.insert(ed.entity_id);
self.editions.push(ed);
}
}
Err(_) => taken.unopened.push(w.id),
}
}
drop(batch);
taken
}
/// Roster first (roles/grants/banlist → authorized set), then the authority-gated
/// metadata/channel fold over the same edition set.
fn fold(&mut self) {
heal_unsigned_floors(&mut self.floors, self.owner, &self.editions, &mut self.healed);
if self.folded != Some(self.editions.len()) {
self.authority = fold_authority(self.community, &self.editions, &self.floors);
// Taken before any await: the thread-local is this thread's, and the task can move.
self.refusals = AUTHORITY_REFUSALS.with(|c| c.borrow().clone());
self.fold = apply_control_fold(self.community, &self.editions, &self.floors, &self.authority);
self.folded = Some(self.editions.len());
}
}
/// Whether what is in hand is coherent AND complete for everything this device tracks, so
/// the read may stop. Folds when every tracked entity has an edition here to fold.
fn enough(&mut self) -> bool {
let known = crate::db::community::get_community_roles(&self.cid_hex);
let everyone = super::derive::everyone_locator(self.community.id());
let reachable = known.as_ref().is_ok_and(|known| {
(!known.roles.is_empty() || !known.grants.is_empty())
&& (!self.floors.contains_key(&self.everyone_hex) || self.entities.contains(&everyone))
&& known.roles.iter().all(|r| crate::simd::hex::hex_to_bytes_32_checked(&r.role_id).is_some_and(|id| self.entities.contains(&id)))
&& known.grants.iter().all(|g| crate::simd::hex::hex_to_bytes_32_checked(&g.member).is_none_or(|m| self.entities.contains(&super::derive::grant_locator(self.community.id(), &m))))
});
if !reachable {
if let Err(e) = &known {
crate::log_warn!("[v2:control {}] roster read failed mid-page ({e}) — paging on rather than assuming nothing is tracked", &self.cid_hex[..8.min(self.cid_hex.len())]);
}
return false;
}
self.fold();
// "Nothing is gapped" is NOT "I have read enough".
//
// An entity we track whose editions are entirely absent from the window
// folds away silently — absence dangles no link, so it raises no gap. The
// loop therefore declared the very first page coherent and stopped, and a
// community whose grants sit older than one page could never re-derive its
// own roster: every fold offered zero grants, and only the completeness
// guard retaining the cache kept the admin list alive at all. That made the
// cache the sole surviving copy of the roster rather than a cache.
//
// So keep paging while anything we already know about is still unaccounted
// for. This only ever reads MORE; it cannot lose data, and it terminates on
// the page cap or an exhausted plane exactly as before.
let heads_now = self.authority.settled();
// A FAILED read must not read as "I track nothing" — that makes
// "everything is accounted for" trivially true and stops the walk at the
// first page, which is the exact failure this loop exists to prevent.
// Fail toward reading MORE.
let all_accounted = match crate::db::community::get_community_roles(&self.cid_hex) {
Ok(known) => {
// A roster we have not built yet accounts for nothing, so
// "everything I track is present" is vacuously TRUE and stops a
// COLD device at the first page — caching whatever the newest
// window happened to hold as its whole baseline, and losing every
// grant older than one page. The early break is an optimisation
// for a client that already knows what it is looking for.
(!known.roles.is_empty() || !known.grants.is_empty())
&& (!self.floors.contains_key(&self.everyone_hex) || heads_now.contains(self.everyone_hex.as_str()))
&& known.roles.iter().all(|r| heads_now.contains(r.role_id.as_str()))
&& known.grants.iter().all(|g| {
crate::simd::hex::hex_to_bytes_32_checked(&g.member).is_none_or(|m| {
let eid = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(self.community.id(), &m));
heads_now.contains(eid.as_str())
})
})
}
Err(e) => {
crate::log_warn!("[v2:control {}] roster read failed mid-page ({e}) — paging on rather than assuming nothing is tracked", &self.cid_hex[..8.min(self.cid_hex.len())]);
false
}
};
!(self.fold.gapped || self.authority.gapped) && all_accounted
}
/// Whether every stored, floored role and grant has a head in the fold as it stands.
fn accounted(&self) -> bool {
let stored = crate::db::community::get_community_roles(&self.cid_hex).unwrap_or_default();
let heads = self.authority.settled();
stored.roles.iter().all(|r| !self.floors.contains_key(&r.role_id) || heads.contains(r.role_id.as_str()))
&& stored.grants.iter().all(|g| {
crate::simd::hex::hex_to_bytes_32_checked(&g.member).is_none_or(|m| {
let eid = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(self.community.id(), &m));
!self.floors.contains_key(&eid) || heads.contains(eid.as_str())
})
})
}
fn finish(self, truncated: bool, pages_read: usize) -> ControlRead {
ControlRead { floors: self.floors, editions: self.editions, authority: self.authority, fold: self.fold, truncated, pages_read, healed: self.healed, refusals: self.refusals }
}
}
/// Read the Control Plane as deep as a follow does and fold it without persisting: through the
/// wraps held of it once the store is on, else page by page off the relays.
async fn read_control<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<ControlRead, String> {
if control_store::mode() == control_store::Mode::On {
match read_control_held(transport, community).await {
Ok(read) => return Ok(read),
Err(Unheld::NoRelay(e)) => return Err(e),
// The store is a saving, never a reason a follow fails.
Err(Unheld::Paged(why)) => {
crate::log_warn!("[v2:control {}] read by pages: {why}", &community.id().to_hex()[..8]);
}
}
}
read_control_paged(transport, community).await
}
/// [`read_control`] page by page off the relays, escalating to Full while anything this device
/// tracks is unaccounted for.
async fn read_control_paged<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<ControlRead, String> {
let began = crate::rt::time::Instant::now();
let mut window = Window::new(community)?;
let address = window.control.pk_hex();
// Whether this round gave up with editions still unread. The follow is
// procedural by design — process what arrives, converge with everyone else —
// so a short read never blocks reading, writing or epoch adoption. It only
// withholds the ROSTER cache below: caching a partial authority as this
// device's baseline is the one step that outlives the round.
let mut truncated = true;
let mut pages_read = 0usize;
// Newest window first; page OLDER only while a tracking entity is gapped (its
// floor link evicted from the window — H1/M8 refetch), bounded like the join
// verifier. A withholding relay still converges to fail-closed after the cap.
//
// Quorum answers as soon as a majority does, so a fast subset that happens not
// to hold an older edition is indistinguishable from that edition not existing —
// and the same subset answers every boot, so the retain never lifts and the
// roster cache freezes with no way back. This fold draws an ABSENCE verdict
// (`stored_complete`, `truncated`), and CORD-04 §5 makes a gap fail closed FOR
// THAT ENTITY and refetch. So escalate: read at Quorum, and if anything we
// already hold is still unaccounted for, read again at Full before concluding.
// Healthy folds never pay for the second tier.
for tier in [
crate::community::transport::Evidence::Quorum,
crate::community::transport::Evidence::Full,
] {
let mut until: Option<u64> = None;
let mut oldest: Option<u64> = None;
truncated = true;
for _ in 0..FOLLOW_MAX_PAGES {
pages_read += 1;
let query = Query { evidence: tier, ..plane_page(address.clone(), FOLLOW_PAGE, until) };
let wraps = transport.fetch(&query, &community.relays).await?;
// The `until` cursor is INCLUSIVE (a `-1` step can skip same-second siblings
// at a page boundary); the wrap-id dedup makes re-served boundary events
// free, and a page with nothing new means the relay is exhausted.
let taken = window.take(&wraps);
oldest = oldest.into_iter().chain(taken.oldest).min();
if window.enough() {
truncated = false; // coherent AND complete for everything we track
break;
}
if taken.fresh == 0 {
// A FULL page with nothing new is a same-second wall no `until` steps
// past, so older editions stay unreachable; a short page is the end
// of the plane, and a gap in THAT is the relay withholding, not us
// giving up early.
truncated = wraps.len() >= FOLLOW_PAGE;
break;
}
until = oldest;
}
window.fold();
if tier == crate::community::transport::Evidence::Full || window.accounted() {
break;
}
crate::log_debug!(
"[v2:control {}] stored entit(ies) unaccounted after a Quorum read — re-reading at Full before drawing an absence verdict",
&window.cid_hex[..8.min(window.cid_hex.len())]
);
}
let read = window.finish(truncated, pages_read);
crate::log_debug!("[v2:control {}] read by pages: {} edition(s), {pages_read} page(s), truncated={truncated} in {:?}", &community.id().to_hex()[..8], read.editions.len(), began.elapsed());
Ok(read)
}
/// Why a read did not come through the wraps held.
enum Unheld {
/// No relay answered: the read fails, as one by pages would.
NoRelay(String),
/// Read it by pages instead: the plane is flooded, or the store could not be used.
Paged(String),
}
/// From a staff device: give each relay the Control wraps it lacks that another relay still
/// holds. Re-publishing a signed wrap needs no key, so any device could; staff are few, so the
/// traffic stays bounded.
async fn heal_control<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, view: &control_store::View, sync: &control_sync::PlaneSync) {
use control_sync::Held;
if sync.lacks.values().all(|lack| lack.is_empty()) {
return;
}
let Ok(me) = me_pk() else { return };
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let owner_hex = community.owner().ok().map(|o| o.to_hex());
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
if !roster.is_staff(&me.to_hex(), owner_hex.as_deref()) {
return;
}
let plan = control_sync::plan_heal(community, view, sync).await;
let id = view.id();
let work: Vec<(String, Vec<Event>)> = plan
.into_iter()
.filter_map(|(relay, ids)| {
let ids: Vec<[u8; 32]> = ids.iter().map(|id| id.to_bytes()).collect();
let bodies = crate::db::community::control_wrap_bodies(&cid_hex, &id, &ids).ok()?;
let wraps: Vec<Event> = bodies.iter().filter_map(|body| std::str::from_utf8(body).ok().and_then(|json| crate::event_json::event(json).ok())).collect();
(!wraps.is_empty()).then_some((relay, wraps))
})
.collect();
if work.is_empty() {
return;
}
let cid8 = cid_hex[..8].to_string();
match transport.detached() {
Some(owned) => {
crate::db::spawn_bound(async move {
// Staff devices spread out, so one of them usually gives a relay what it lacks.
crate::rt::time::sleep(std::time::Duration::from_millis(rand::random::<u64>() % 20_000)).await;
give_relays(&*owned, &cid8, work).await;
});
}
None => give_relays(transport, &cid8, work).await,
}
}
async fn give_relays<T: Transport + ?Sized>(transport: &T, cid8: &str, work: Vec<(String, Vec<Event>)>) {
for (relay, wraps) in work {
let relays = [relay.clone()];
let mut kept = 0usize;
for wrap in &wraps {
if transport.publish(wrap, &relays).await.is_ok() {
kept += 1;
}
}
crate::log_info!("[v2:control {cid8}] healed {relay}: {kept} of {} wrap(s) it lacked", wraps.len());
}
}
/// A fold of the wraps held, and how far down them it read.
struct HeldFold {
read: ControlRead,
/// Every stored, floored role and grant has its head.
accounted: bool,
/// It read to the end of what is held.
ended: bool,
oldest: Option<u64>,
}
/// Fold the wraps held of `view`, newest first, as deep as a follow reads.
fn fold_held(community: &CommunityV2, view: &control_store::View) -> Result<HeldFold, String> {
let mut window = Window::new(community)?;
let mut truncated = true;
let mut pages_read = 0usize;
let mut below: Option<(u64, nostr_sdk::prelude::EventId)> = None;
let (mut oldest, mut ended): (Option<u64>, bool) = (None, false);
for _ in 0..FOLLOW_MAX_PAGES {
pages_read += 1;
let wraps = view.page(below, FOLLOW_PAGE)?;
let taken = window.take(&wraps);
oldest = oldest.into_iter().chain(taken.oldest).min();
// Held as an edition that opens: one that no longer does is asked for again.
for id in &taken.unopened {
view.forget(id);
}
if window.enough() {
truncated = false;
break;
}
let Some(last) = wraps.last() else {
(truncated, ended) = (false, true);
break;
};
below = Some((last.created_at.as_secs(), last.id));
}
window.fold();
let accounted = window.accounted();
Ok(HeldFold { read: window.finish(truncated, pages_read), accounted, ended, oldest })
}
/// [`read_control`] through the wraps held: bring them up to what the relays hold, then fold them.
/// What the relays are asked for grows only while the fold says something is missing.
async fn read_control_held<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<ControlRead, Unheld> {
use control_sync::{read_whole, sync_plane, Relayed, Wait};
// Bound before the first await: the floors and the wraps folded after it are this account's.
crate::db::scoped(async move {
let view = control_store::View::of(community);
// Wraps are kept for a community this device holds, and go with it when it is left.
let kept = || match crate::db::community::community_held(community.id()) {
Ok(true) => Ok(()),
_ => Err(Unheld::Paged("the community is not held".into())),
};
kept()?;
if control_sync::flooded(community, &view) {
return Err(Unheld::Paged("more wraps than a pass reads".into()));
}
let synced = |sync: Result<control_sync::PlaneSync, control_sync::Unsynced>| match sync {
Ok(sync) if sync.flooded => Err(Unheld::Paged("more wraps than a pass reads".into())),
Ok(sync) => Ok(sync),
Err(control_sync::Unsynced::NoRelay(e)) => Err(Unheld::NoRelay(e)),
Err(control_sync::Unsynced::Store(e)) => Err(Unheld::Paged(e)),
};
let began = crate::rt::time::Instant::now();
let mut sync = synced(sync_plane(transport, community, &view, Wait::Quorum).await)?;
let mut held = fold_held(community, &view).map_err(Unheld::Paged)?;
let missing = |held: &HeldFold| !held.accounted || held.read.fold.gapped || held.read.authority.gapped;
if !held.accounted {
// An absence verdict is next: hear every relay before drawing it.
let all = synced(sync_plane(transport, community, &view, Wait::All).await)?;
// What a relay left unread stays unread when it is not there to be asked again.
let lost = sync.unread && sync.relays.iter().any(|(relay, ended)| *ended == Relayed::Partial && all.relays.get(relay) == Some(&Relayed::Unreached));
sync = all;
sync.unread |= lost;
held = fold_held(community, &view).map_err(Unheld::Paged)?;
}
if missing(&held) {
// A relay's "in sync" is its word, and the fold says something is missing: read them.
if let Ok(whole) = read_whole(transport, community, &view).await {
sync.unread |= whole.unread;
if whole.opened > 0 {
held = fold_held(community, &view).map_err(Unheld::Paged)?;
}
}
}
kept()?;
heal_control(transport, community, &view, &sync).await;
let HeldFold { mut read, ended, oldest, .. } = held;
// A fold that read to the end, or past a second no read can get whole, stands on a partial plane.
let walled = control_sync::wall(community, &view, Some(&sync)).is_some_and(|wall| ended || oldest.is_some_and(|o| o < wall));
read.truncated |= sync.unread || walled;
crate::log_debug!(
"[v2:control {}] read through {} wrap(s) held, {} new, {} of {} relay(s) answered, truncated={} in {:?}",
&community.id().to_hex()[..8],
read.editions.len(),
sync.opened,
sync.answered(),
sync.relays.len(),
read.truncated,
began.elapsed()
);
Ok(read)
})
.await
}
pub async fn follow_control<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
) -> Result<ControlFollow, String> {
crate::db::scoped(async move {
community.owner()?; // fail fast if the community is somehow unproven.
let _reading = reading(community.id());
let link = super::realtime::link_generation();
let read = match read_control(transport, community).await {
Ok(read) => read,
Err(e) => {
hold_control(community, None);
return Err(e);
}
};
if control_store::mode() == control_store::Mode::Shadow {
shadow_control(transport, community, &read).await;
}
let keep = holdable(community, &read);
match persist_control(transport, community, read).await {
Ok((follow, editions)) => {
let window = keep.zip(editions).map(|((staff, deleted), editions)| Held { epoch: community.root_epoch.0, link, editions, staff, deleted });
hold_control(community, window);
Ok(follow)
}
Err(e) => {
hold_control(community, None);
Err(e)
}
}
})
.await
}
/// Persist what a control fold decided: floors, Roster, banlist, registry, pins, writers and
/// the community row. Shared by the follow and the live fold, so both decide alike. Hands the
/// window back when it persisted.
async fn persist_control<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, read: ControlRead) -> Result<(ControlFollow, Option<Vec<ParsedEdition>>), String> {
{
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let ControlRead { floors, editions, authority, fold, truncated, pages_read, healed, .. } = read;
// The change feed waits for this fold's own look, after the community row lands.
let _persisting = super::changes::persist_guard(community.id());
// The fetches straddled awaits; a swap since the guard was captured must not
// write account A's control state into B.
// A leave/delete raced this follow: writing now would resurrect the community
// row and orphan floor rows past delete_community's wipe.
if !crate::db::community::community_held(community.id())? {
return Ok((ControlFollow::default(), None));
}
// A floor moved since this read loaded them: its fold is behind the row, so fold again.
let now = held_floors(community)?;
if now.iter().any(|(entity, f)| floors.get(entity).is_none_or(|r| f.0 > r.0)) {
crate::log_info!("[v2:control {}] floors moved during the read; following again", &cid_hex[..8.min(cid_hex.len())]);
super::realtime::enqueue_follow(community.id());
return Ok((ControlFollow::default(), None));
}
// A healed floor is the same edition under its real hash, whatever this fold makes of it:
// everything reading the row (sends, citations, the Audit Log) needs that hash too.
for h in &healed {
crate::db::community::heal_edition_head(&cid_hex, &h.entity_hex, community.root_epoch.0, h.version, &h.unsigned, &h.self_hash, &h.inner_id, &h.author)?;
}
if !healed.is_empty() {
crate::log_info!("[v2:control {}] {} floor(s) written before marked editions moved to their real hash", &cid_hex[..8.min(cid_hex.len())], healed.len());
}
// A Roster fold that ran out its bound has no single answer (CORD-04 §1): every verdict
// below rests on its last round's guess, so none of it is kept, and the next follow folds again.
if !authority.converged {
return Ok((ControlFollow::default(), None));
}
// Persist advanced floors BEFORE the state save (a failed floor write must not
// let saved state outrun its floor), stamping the epoch this fold ran under —
// not the row's write-time value, which a concurrent re-founding can bump. Both
// the metadata/channel heads and the roster/banlist heads advance their floors;
// run the advance (v+1) and same-version convergence (fork tiebreak) paths.
let families = fold.heads.iter().map(|h| (h, crate::db::community::FLOOR_CONTROL)).chain(authority.heads.iter().map(|h| (h, crate::db::community::FLOOR_AUTHORITY)));
crate::db::community::write_folded_heads(&cid_hex, |w| {
for (h, family) in families {
if h.rebased {
w.rebase(&h.entity_hex, h.version, &h.self_hash, &h.inner_id, &h.author, community.root_epoch.0, family)?;
continue;
}
w.set(&h.entity_hex, h.version, &h.self_hash, &h.inner_id, &h.author, community.root_epoch.0, family)?;
// The same edition content can arrive under another author's signature (the hash
// covers content, not signer): it must not re-key a floor that records its author,
// or a weaker copy lowers the bar a later rival has to beat.
let rekey = floors.get(&h.entity_hex).is_some_and(|f| f.0 == h.version && f.1 == h.self_hash && f.3.is_some());
if !rekey {
w.converge(&h.entity_hex, h.version, &h.self_hash, &h.inner_id, &h.author, community.root_epoch.0, family)?;
}
}
Ok(())
})?;
if super::changes::wanted() {
let admitted = |id: &[u8; 32]| fold.admitted.contains(id) || authority.admitted.contains(id);
note_folded_chains(community, &floors, fold.heads.iter().chain(authority.heads.iter()), &editions, admitted);
}
// Adopt the staff write key a promotion delivered inside MY OWN Grant
// (CORD-04 §3): decrypt the control_wrap under the granter↔me pairwise key
// and record the secret. Verified fail-closed inside — the epoch must be
// the one I'm on and the secret must derive to exactly the control_pk I
// hold — so a stale wrap (compaction re-wraps a Grant head verbatim across
// Refoundings) or a forged one is dropped, never adopted.
let adopted_control_root = adopt_my_control_wrap(community, &editions).await;
// The adopt can await a remote signer (bunker NIP-44 round-trip) — re-validate
// before the per-account writes below.
// Persist the authorized banlist content (retained/withholding folds carry None,
// so the stored banlist is left intact — an anti-roster never silently un-bans).
let mut authority_changed = false;
// Ban marks MERGE (never replace): they must outlive both the ban and this window,
// so a later un-ban can't resurrect a pre-ban Join. Persisted even when the banlist
// itself was retained — the history is what the suppression reads.
let _ = crate::db::community::merge_community_ban_marks(&cid_hex, &authority.banned_at);
if let Some((banned, version)) = &authority.banlist_persist {
let mut before = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
if crate::db::community::set_community_banlist(&cid_hex, banned, *version as i64)? {
announce_banlist(&cid_hex);
}
let mut after = banned.clone();
before.sort();
after.sort();
authority_changed |= before != after;
}
// Persist the authorized roster so capabilities/roles stay sync LOCAL reads
// (the passive follow folds, reads never fetch). Guarded: only an aggregate
// built from roster editions at least as new as
// the stored one may replace it — a withholding relay serving NO roster
// editions folds an empty-but-ungapped aggregate (absence raises no gap flag),
// and that must RETAIN the stored roster, never wipe standing.
let newest_roster_at = roster_stamp(&editions, &authority.heads);
// Completeness gate: the `gapped` flag only covers entities present in the window.
// A role/grant floored on this device but with ZERO editions fetched (aged out of
// the paging reach) folds absent yet raises no gap — persisting would silently drop
// it. So if any CURRENTLY-STORED entity is floored but folded no head this round,
// RETAIN. A real revoke still folds a head (see select_authorized), so it persists.
let stored = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let head_ents = authority.settled();
let stored_complete = stored.roles.iter().all(|r| !floors.contains_key(&r.role_id) || head_ents.contains(r.role_id.as_str()))
&& stored.grants.iter().all(|g| {
crate::simd::hex::hex_to_bytes_32_checked(&g.member).is_none_or(|m| {
let eid = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(community.id(), &m));
!floors.contains_key(&eid) || head_ents.contains(eid.as_str())
})
});
// `truncated` covers the case the other three can't: a COLD device (no floors,
// no stored roster) folding under a plane a member has inflated past the pager.
// `stored_complete` is trivially true with nothing stored, so without this the
// first sync would cache a partial authority as its own baseline.
let stored_at = crate::db::community::get_community_roles_at(&cid_hex)?;
// `stored_at == 0` is a roster with NO plane provenance: the optimistic local
// merge every creator writes (`merge_local_roster`) so a just-made role works
// before its edition folds. It is a guess about the plane, not evidence about
// it, so it must never out-vote a coherent fold — and it was: the seed names
// entities the plane no longer heads, `stored_complete` goes false forever, and
// the roster can never be replaced. A community's OWNER is the likeliest holder
// of such a seed, so the wedge lands on exactly the account whose rotations
// everyone else is waiting to adopt.
let seed_only = stored_at == 0;
// `stored_complete` retains the cache when a stored entity is floored but folded no
// head, because a withholding relay looks exactly like that. An entity can also stop
// producing a head for good (its author demoted, or compacted away), and then the veto
// holds: a frozen roster refuses rotations from admins promoted since. That is a known
// fork risk, accepted over the alternative below.
// NO FLOOR PRUNING. An attempt at it evicted thirteen real admins from a live
// community: their grant editions were merely outside the fetched window, and
// "the plane is serving newer editions than mine" is not evidence that a
// specific entity is gone. A frozen roster is a fork risk; a WRONG roster is a
// fork plus silent loss of everyone's standing, which is strictly worse. Until
// there is per-entity proof of absence, absence stays unproven.
// NOT gated on `authority.gapped`. That flag is a global OR across every
// entity — its own declaration calls it the per-entity flag that "drives
// older-paging" — so one unresolvable entity anywhere vetoed the whole roster
// cache, permanently once the plane is exhausted and more paging cannot help.
// CORD-04 §5 says a gap fails closed FOR THAT ENTITY, suspending and refetching
// it, and that already happens: a gapped entity produces no head and so is
// simply absent from the fold. Freezing every other entity behind it is the
// over-reach, and it is what left live communities unable to re-derive rosters
// they could otherwise read perfectly.
//
// The downgrade defence is `stored_complete`, which is untouched: nothing we
// already know can silently vanish. An entity we have never held cannot be
// stripped from us by its absence.
// A fold that ran out its bound has no settled answer to cache.
// A stamp past any clock is an older build's, taken from an unauthorized edition.
let stamp_ok = newest_roster_at >= stored_at || stored_at > roster_stamp_ceiling();
if !truncated && authority.converged && (stored_complete || seed_only) && stamp_ok {
authority_changed |= stored != authority.roles;
crate::db::community::set_community_roles(&cid_hex, &authority.roles, newest_roster_at)?;
} else {
// Loud, because the failure mode is silent and total: the roster is what
// authorizes every rotation, so a client that can never re-cache it is
// permanently deaf to that admin's re-foundings — and the only symptom is
// an epoch that never advances.
// Name the BLOCKERS and what the fold actually found. Without these the
// warning says a decision was made but not on what evidence, which is how
// a wrong roster stays indistinguishable from a cautious one.
let mut blockers: Vec<String> = Vec::new();
for r in &stored.roles {
if floors.contains_key(&r.role_id) && !head_ents.contains(r.role_id.as_str()) {
blockers.push(format!("role:{}", &r.role_id[..8.min(r.role_id.len())]));
}
}
for g in &stored.grants {
if let Some(m) = crate::simd::hex::hex_to_bytes_32_checked(&g.member) {
let eid = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(community.id(), &m));
if floors.contains_key(&eid) && !head_ents.contains(eid.as_str()) {
blockers.push(format!("grant:{}", &g.member[..8.min(g.member.len())]));
}
}
}
// Per-entity fate of every roster edition in the window. "Blocked" only
// says which stored entity produced no head; this says WHY — whether its
// editions were absent, or present and dropped, and by whom they were
// authored. Guessing between those three cost a day.
{
use std::collections::BTreeMap;
let mut fate: BTreeMap<String, (u64, u64, String, &str)> = BTreeMap::new();
for e in &editions {
if e.vsk != vsk::ROLE && e.vsk != vsk::GRANT {
continue;
}
let kind = if e.vsk == vsk::ROLE { "role" } else { "grant" };
let eid = crate::simd::hex::bytes_to_hex_32(&e.entity_id);
let slot = fate.entry(eid).or_insert((0, 0, String::new(), kind));
slot.0 += 1;
if e.version > slot.1 {
slot.1 = e.version;
slot.2 = e.author.to_hex()[..8].to_string();
slot.3 = kind;
}
}
let head_now: std::collections::HashSet<&str> =
authority.heads.iter().map(|h| h.entity_hex.as_str()).collect();
let rows: Vec<String> = fate
.iter()
.map(|(eid, (n, v, author, kind))| {
format!(
"{}[{kind}]:{}ed/v{}/by{}{}{}",
&eid[..8], n, v, author,
if authority.carried.contains(eid.as_str()) {
"/HEAD(kept: refused, nothing to fall back to)".to_string()
} else if head_now.contains(eid.as_str()) {
"/HEAD".to_string()
} else {
AUTHORITY_REFUSALS
.with(|c| c.borrow().get(eid.as_str()).copied())
.map(|r| format!("/DROPPED({r})"))
.unwrap_or_else(|| "/dropped(no candidate survived the fold)".into())
},
floors.get(eid).map(|f| format!("/floor@v{}", f.0)).unwrap_or_default(),
)
})
.collect();
// The OWNER is the root of all authority: every other author needs a
// grant that traces back to them. If no edition here is owner-authored
// the chain cannot bootstrap at all, and that is a different bug from
// any individual entity being rejected.
crate::log_warn!(
"[v2:control {}] fold accepted roles: [{}]",
&cid_hex[..8.min(cid_hex.len())],
authority.roles.roles.iter().map(|r| format!("{}@pos{}", &r.role_id[..8.min(r.role_id.len())], r.position)).collect::<Vec<_>>().join(" ")
);
crate::log_warn!(
"[v2:control {}] owner={} — roster editions in window: [{}]",
&cid_hex[..8.min(cid_hex.len())],
community.owner().map(|o| o.to_hex()[..8].to_string()).unwrap_or_else(|_| "UNPROVEN".into()),
rows.join(" ")
);
}
crate::log_warn!(
"[v2:control {}] roster NOT cached (truncated={} authority_gapped={} doc_gapped={} stored_complete={} newest_roster_at={} stored_at={}) — stored {}r/{}g, fold offers {}r/{}g from {} edition(s) over {} page(s), blocked by [{}]",
&cid_hex[..8.min(cid_hex.len())], truncated, authority.gapped, fold.gapped, stored_complete, newest_roster_at, stored_at,
stored.roles.len(), stored.grants.len(), authority.roles.roles.len(), authority.roles.grants.len(),
editions.len(), pages_read,
blockers.join(", ")
);
}
// Cache the folded invite Registry so Public/Private stays a sync LOCAL read
// (`invite_registry` is the column every caller reads). Gated like
// the roster: a truncated or gapped window folds an empty registry out of mere
// absence, and persisting that under-states Public — the unsafe direction, since
// it leaves a live link open behind a ban.
if !truncated && !authority.gapped && !fold.gapped {
if let Ok(owner) = community.owner() {
let sets = live_invite_link_sets(community.id(), &owner.to_hex(), &editions, &authority, &floors);
let live = flatten_link_sets(&sets);
let mut before = crate::db::community::get_community_invite_registry(&cid_hex).unwrap_or_default();
before.sort();
if before != live {
crate::db::community::set_community_invite_registry(&cid_hex, &live)?;
authority_changed = true;
}
// The per-creator split drives "X has N active invite links" and the
// first-link-flips-Public confirm; it lives in its own table.
crate::db::community::replace_invite_link_sets(&cid_hex, &sets)?;
}
}
// Folded Pin List heads (CORD-04 §7): raw content per channel. The write
// itself is monotonic on version (atomic in the statement), so a stale
// window racing a publish echo can never regress a newer held head.
for (channel_hex, content, version, rebased) in &fold.writers_persist {
persist_writers(&cid_hex, channel_hex, content, *version, *rebased);
}
for (channel_hex, content, version, author_npub, created_at) in &fold.pins_persist {
match crate::db::community::set_community_pins(&cid_hex, channel_hex, content, *version as i64) {
Ok(true) => {
crate::log_info!("[pins] fold adopted v{} for channel {}", version, &channel_hex[..12]);
crate::emit_event(
"community_pins_updated",
&serde_json::json!({ "community_id": cid_hex, "channel_id": channel_hex }),
);
note_pins_modified(channel_hex, *version, author_npub, *created_at).await;
}
Ok(false) => {}
Err(e) => crate::log_warn!("[pins] fold persist failed: {e}"),
}
}
// Roster/banlist moves are invisible in the returned community (they live in
// their own columns), so callers that key a refresh off `updated` would never
// repaint a promote/demote/ban. Announce from the single fold point — it covers
// realtime, boot catch-up and manual sync alike.
if authority_changed {
crate::emit_event("community_refreshed", &serde_json::json!({ "community_id": cid_hex }));
}
// Owner-side silent Admin widening (PIN_MESSAGES): after the roster has
// folded, so the check reads the settled roles. Once per community per
// session — the fold runs constantly and the upgrade is a one-shot.
if first_admin_pin_upgrade(community.id()) {
let _ = upgrade_admin_role_pin_bit(transport, community).await;
}
// The pins/upgrade tail awaited network I/O — re-validate before the vault save.
// An adopted staff key rides whatever gets saved (the fold's update, or the
// otherwise-unchanged community) — the vault write that makes it durable.
// Kicks and snapshots are judged on the Roster, citations and minter this fold may have moved.
crate::db::community::bump_membership_generation();
let mut updated = fold.updated;
if let Some(cr) = adopted_control_root {
let mut u = updated.take().unwrap_or_else(|| community.clone());
u.control_root = Some(cr);
updated = Some(u);
}
resume_relay_copy(community);
crate::community::message_delete::resume_scrubs();
let follow = match updated {
Some(u) => {
crate::db::community::save_community_v2(&u)?;
if u.relays != community.relays {
relays_moved(community, &u);
}
ControlFollow { updated: Some(u), authority_changed }
}
None => ControlFollow { updated: None, authority_changed },
};
for channel_id in &fold.deleted_channels {
purge::purge_deleted_channel(community, channel_id, None).await;
}
Ok((follow, Some(editions)))
}
}
/// Tell the change feed which editions each advanced head moved through, walking its chain back
/// to the floor this fold started from, so a change several people made credits each of them.
fn note_folded_chains<'a>(community: &CommunityV2, floors: &Floors, heads: impl Iterator<Item = &'a FoldedHead>, editions: &[ParsedEdition], admitted: impl Fn(&[u8; 32]) -> bool) {
// Only what the fold authorized: the same content can arrive re-signed by someone else.
let by_hash: std::collections::HashMap<[u8; 32], &ParsedEdition> = editions.iter().filter(|e| admitted(&e.inner_id)).map(|e| (e.self_hash, e)).collect();
let by_id: std::collections::HashMap<[u8; 32], &ParsedEdition> = editions.iter().map(|e| (e.inner_id, e)).collect();
for h in heads.filter(|h| !h.rebased) {
let floor = floors.get(&h.entity_hex).map_or(0, |f| f.0);
if h.version <= floor {
continue;
}
let mut chain = Vec::new();
// The head is the edition the fold chose, by its own id; what it cites is walked by hash.
let mut next = by_id.get(&h.inner_id).copied();
while let Some(ed) = next {
if ed.version <= floor || chain.len() > 64 {
break;
}
chain.push((ed.version, ed.author, ed.created_at));
next = ed.prev_hash.and_then(|hash| by_hash.get(&hash).copied());
}
chain.reverse();
super::changes::note_folded(community.id(), &h.entity_hex, chain);
}
}
/// Adopt the `control_root` a staff-making Grant delivered to ME (CORD-04 §3).
///
/// Nothing to adopt on a legacy epoch (no write key exists) or when the secret
/// is already held. Candidate editions are MY grant coordinate's, newest
/// version first; authority-gating them is unnecessary for adoption — the
/// derive check IS the gate (only the true secret derives to the held
/// `control_pk`, so the worst a forged edition can do is fail it). The epoch
/// rides inside the ciphertext because staleness is structural: compaction
/// re-wraps a Grant head verbatim across Refoundings, and staff crossing a
/// rotation get the new secret in their 136-byte base blob instead.
async fn adopt_my_control_wrap(community: &CommunityV2, editions: &[ParsedEdition]) -> Option<[u8; 32]> {
use nostr_sdk::prelude::AsyncNip44;
let held_pk = community.control_pk?;
if community.control_root.is_some() {
return None;
}
let my_pk = me_pk().ok()?;
let signer = crate::signer::active_signer().ok()?;
let my_eid = super::derive::grant_locator(community.id(), &my_pk.to_bytes());
let mut candidates: Vec<&ParsedEdition> = editions
.iter()
.filter(|e| e.vsk == vsk::GRANT && e.entity_id == my_eid)
.collect();
candidates.sort_by_key(|e| std::cmp::Reverse(e.version));
for ed in candidates {
let Some(wrap_b64) = super::roles::parse_grant_control_wrap(&ed.content) else { continue };
// The granter is the edition's sealed author — the pairwise key's other
// half (one ECDH either side can compute; bunker accounts included).
let Ok(plain_b64) = signer.nip44_decrypt_async(&ed.author, &wrap_b64).await else { continue };
let Ok(plain) = crate::simd::base64::STANDARD.decode_to_vec(plain_b64.as_bytes()) else { continue };
let Ok((epoch, root)) = super::rekey::parse_control_wrap(&plain) else { continue };
if epoch != community.root_epoch {
continue;
}
if super::derive::control_signer_group_key(&root, community.id(), epoch).pk() != held_pk {
continue;
}
crate::log_info!("[v2] adopted the staff write key from my Grant (epoch {})", epoch.0);
return Some(root);
}
None
}
/// Control-follow paging bounds: enough depth to re-anchor a long-offline floor
/// (H1/M8 refetch) without letting a flooding relay stall the follow queue.
///
/// Nearly free to raise: both follow loops exit the moment the fold stops being
/// gapped, so the cap only binds when something is genuinely missing — exactly
/// when paging further is what's wanted. The old ceiling of 4 (~2k editions) sat
/// under a plane that 100 roles + 400 grants already outgrows before counting
/// superseded versions, which accumulate until a compaction retires them.
/// One walk's hop bound. A backlog deeper than this converges across passes,
/// because every adopted hop is checkpointed before the next is attempted.
const MAX_WALK_STEPS: usize = 128;
const FOLLOW_MAX_PAGES: usize = 32;
const FOLLOW_PAGE: usize = 500;
/// One page of a plane walked from its newest wrap down, `until` inclusive. Every such walk asks
/// through here: a page read from several relays is only whole down to where the shallowest of
/// them stopped, and `paged` has the transport cut it there.
fn plane_page(address: String, limit: usize, until: Option<u64>) -> Query {
Query { kinds: vec![stream::KIND_WRAP], authors: vec![address], until, limit: Some(limit), paged: true, ..Default::default() }
}
/// Page ceiling for a COMPACTION read (CORD-06 §3: a Refounder that cannot fold
/// every Control Event must abort). Far above any real plane, but plane depth is
/// attacker-controlled — any member holds the key that mints wraps — so the read
/// is bounded and reports coming up short rather than compacting a partial view.
const COMPACT_MAX_PAGES: usize = 512;
/// A folded control head to persist as the per-entity refuse-downgrade floor.
#[derive(Clone)]
struct FoldedHead {
entity_hex: String,
version: u64,
self_hash: [u8; 32],
inner_id: [u8; 32],
author: [u8; 32],
/// The held floor's head is served and the Roster now refuses it: this is the newest
/// edition it does admit, below the floor, and the floor moves down to it.
rebased: bool,
}
/// The outcome of a floor-aware control fold: the updated community (if content
/// changed), the heads to persist as the new floor (returned even when content is
/// unchanged, so the floor still seeds/advances), and whether any TRACKING entity
/// hit an unresolvable gap — the caller's signal to page older history and re-fold
/// (CORD-04 H1/M8's refetch).
#[derive(Default)]
struct ControlFold {
updated: Option<CommunityV2>,
heads: Vec<FoldedHead>,
gapped: bool,
/// Folded Pin List heads to persist:
/// `(channel_hex, raw content, version, author_npub, created_at)`.
/// Raw carried bytes on purpose — republishing must not re-serialize.
pins_persist: Vec<(String, String, u64, String, u64)>,
/// Folded Writers ledger heads to persist: `(channel_hex, raw content, version, rebased)`.
writers_persist: Vec<(String, String, u64, bool)>,
/// Channels a standing deletion took out, whose history every device drops.
deleted_channels: Vec<ChannelId>,
/// Entities whose held edition the Roster now refuses with no authorized edition to step
/// down to: this device keeps it as its head, but nobody new would fold it.
kept: std::collections::HashSet<String>,
/// Every edition this fold found authorized, by inner id.
admitted: crate::fasthash::FastSet<[u8; 32]>,
}
/// Per-entity floor: `(version, self_hash, inner_id, author, family)` of the committed head. The id
/// and author are its fork tiebreak key; either is `None` on a row written before it was recorded,
/// as the family is on a row that records none.
type Floor = (u64, [u8; 32], Option<[u8; 32]>, Option<[u8; 32]>, Option<crate::db::community::FloorFamily>);
/// An author's authority in an equal-version fork (CORD-04 §1), lower outranking: the owner, then
/// the lowest role position, then the roleless.
fn fork_rank(roles: &crate::community::roles::CommunityRoles, owner_hex: Option<&str>, author_hex: &str) -> u32 {
if owner_hex == Some(author_hex) {
return 0;
}
roles.highest_position(author_hex).unwrap_or(u32::MAX)
}
/// [`fork_rank`] over an index of the roster.
fn fork_rank_in(roles: &crate::community::roles::RoleIndex<'_>, owner_hex: Option<&str>, author_hex: &str) -> u32 {
if owner_hex == Some(author_hex) {
return 0;
}
roles.highest_position(author_hex).unwrap_or(u32::MAX)
}
/// The held floor's fork key, ranked against the roster the caller folds with.
enum HeldKey {
/// No tiebreak was recorded for the held head: any same-version rival may replace it.
Replaceable,
/// Recorded before authors were: rivals compare by id alone.
Id([u8; 32]),
Ranked(u32, [u8; 32]),
}
impl HeldKey {
fn of(floor: &Floor, rank_of: &dyn Fn(&[u8; 32]) -> u32) -> Self {
match (floor.2, floor.3) {
(None, _) => HeldKey::Replaceable,
(Some(id), None) => HeldKey::Id(id),
(Some(id), Some(author)) => HeldKey::Ranked(rank_of(&author), id),
}
}
/// Whether a same-version rival takes the floor from the held head.
fn beaten_by(&self, rank: u32, id: &[u8; 32]) -> bool {
match self {
HeldKey::Replaceable => true,
HeldKey::Id(held) => id < held,
HeldKey::Ranked(held_rank, held) => (rank, id) < (*held_rank, held),
}
}
}
type Floors = crate::fasthash::FastMap<String, Floor>;
/// Which fold an edition kind's floor belongs to.
fn floor_family(vsk_code: &str) -> &'static str {
use crate::db::community::{FLOOR_AUTHORITY, FLOOR_CONTROL};
match vsk_code {
vsk::ROLE | vsk::ROLE_V2 | vsk::GRANT | vsk::BANLIST | vsk::TENURE | vsk::CHANNEL_ACL | vsk::CHANNEL_SYNC => FLOOR_AUTHORITY,
_ => FLOOR_CONTROL,
}
}
/// `floors` without the rows another fold recorded: a row's coordinate can be squatted by
/// an edition of another kind, whose floor means nothing to this one.
fn floors_of_family(floors: &Floors, family: &str) -> Floors {
let family = crate::db::community::FloorFamily::of(family);
floors.iter().filter(|(_, f)| f.4.is_none_or(|f| f == family)).map(|(k, f)| (k.clone(), *f)).collect()
}
/// Fold owner-authored control editions into an updated community using the
/// PERSISTED per-entity version floor (refuse-downgrade). Per entity, fold with
/// [`version::fold`]`(floor, floor_hash)`:
/// - ANCHORED: adopt the chain-verified head. A `gap` ABOVE it (withheld middles)
/// doesn't block the verified prefix — refuse-downgrade holds for everything
/// applied — but flags `gapped` so the caller pages for the rest.
/// - UNANCHORED under a held floor: one legitimate cause is a same-version owner
/// fork AT the floor whose deterministic winner (lower inner id; a NULL held id
/// is always replaceable) isn't our held edition —
/// the floor CONVERGES to the winner and the chain re-anchors on it, so every
/// client lands on the same head where a hash-strict floor would wedge forever.
/// Anything else is withholding → fail closed + `gapped`.
/// - BOOTSTRAPPING (`floor == 0` — a fresh joiner, or a fresh epoch after a
/// Refounding, since the caller epoch-filters the floor) takes the highest
/// signed head (author already owner-filtered).
///
/// This matches CORD-04 §1. Epoch-filtering makes a
/// compaction at a new epoch auto-bootstrap, converging with Armada's acceptance of
/// a compacted head across a dangling `prev` (Armada doesn't persist a floor, so a
/// Vector floor only makes Vector STRICTER locally — no wire change, honest-case
/// convergence preserved).
fn apply_control_fold(community: &CommunityV2, editions: &[ParsedEdition], floors: &Floors, authority: &AuthoritySet) -> ControlFold {
use crate::community::roles::Permissions;
use std::collections::BTreeMap;
let floors = &floors_of_family(floors, crate::db::community::FLOOR_CONTROL);
let owner_hex = community.owner().ok().map(|o| o.to_hex());
let standing = crate::community::roles::RoleIndex::of(&authority.roles);
let head_index = HeadIndex::of(&authority.heads);
let mut groups: BTreeMap<(String, [u8; 32]), Vec<&ParsedEdition>> = BTreeMap::new();
for e in editions {
groups.entry((e.vsk.clone(), e.entity_id)).or_default().push(e);
}
let mut out = community.clone();
let mut changed = false;
let mut heads = Vec::new();
let mut gapped = false;
let mut pins_persist = Vec::new();
let mut deleted_channels = Vec::new();
let mut writers_persist = Vec::new();
let (mut kept, mut admitted) = (std::collections::HashSet::new(), crate::fasthash::FastSet::default());
// Pin List eids are one-way HKDF locators, so attribution runs the other
// direction: precompute every known channel's locator. An eid matching no
// channel folds nothing this round — once the channel's metadata lands, the
// next fold attributes it (editions re-fold from the window each sync).
let pins_by_eid: std::collections::HashMap<[u8; 32], String> = community
.channels
.iter()
.map(|ch| (super::derive::pins_locator(community.id(), &ch.id), crate::simd::hex::bytes_to_hex_32(&ch.id.0)))
.collect();
let writers_by_eid: std::collections::HashMap<[u8; 32], String> = community
.channels
.iter()
.map(|ch| (super::derive::writers_locator(community.id(), &ch.id), crate::simd::hex::bytes_to_hex_32(&ch.id.0)))
.collect();
// A channel id is minted at random, so one shared with another entity's coordinate is aimed
// at that entity: floor rows key on the coordinate alone. Only an edition its kind's bit
// backs claims a coordinate, so nobody without that bit can hide a Channel behind one.
let banlist_eid = super::derive::banlist_locator(community.id());
let claims = |kind: &str, author: &PublicKey| {
let bit = match kind {
vsk::COMMUNITY_METADATA => Permissions::MANAGE_METADATA,
vsk::CHANNEL_METADATA | vsk::CATEGORY | vsk::WRITERS => Permissions::MANAGE_CHANNELS,
vsk::ROLE | vsk::GRANT | vsk::ROLE_V2 | vsk::CHANNEL_ACL | vsk::TENURE | vsk::CHANNEL_SYNC => Permissions::MANAGE_ROLES,
vsk::BANLIST => Permissions::BAN,
vsk::INVITE_LINKS => Permissions::CREATE_INVITE,
vsk::PINS => Permissions::PIN_MESSAGES,
_ => return false,
};
standing.is_authorized(&author.to_hex(), owner_hex.as_deref(), bit)
};
let taken_by = |kind: &str| -> std::collections::HashSet<[u8; 32]> {
groups
.iter()
.filter(|((v, _), g)| v != kind && g.iter().any(|e| claims(v, &e.author)))
.map(|((_, e), _)| *e)
.chain([banlist_eid, super::derive::everyone_locator(community.id())])
.collect()
};
let (taken, taken_cat) = (taken_by(vsk::CHANNEL_METADATA), taken_by(vsk::CATEGORY));
for ((vsk_code, eid), group) in &groups {
// This fold applies three entities: community metadata (eid ==
// community_id), channel metadata, and per-channel Pin Lists. A vsk-2
// whose eid equals the community id is excluded — the floor row keys on
// the entity alone, so it would share (and corrupt) the metadata
// chain's floor.
let is_meta = vsk_code == vsk::COMMUNITY_METADATA && *eid == community.id().0;
let is_channel = vsk_code == vsk::CHANNEL_METADATA && *eid != community.id().0 && !taken.contains(eid);
let pins_channel = (vsk_code == vsk::PINS).then(|| pins_by_eid.get(eid)).flatten();
let is_category = vsk_code == vsk::CATEGORY && *eid != community.id().0 && !taken_cat.contains(eid);
let writers_channel = (vsk_code == vsk::WRITERS).then(|| writers_by_eid.get(eid)).flatten();
// One aimed at another entity folds as none, so a reader holding it agrees with a fresh one.
if vsk_code == vsk::CHANNEL_METADATA && !is_channel && *eid != community.id().0 {
let before = out.channels.len();
out.channels.retain(|c| c.id.0 != *eid);
changed |= out.channels.len() != before;
}
if vsk_code == vsk::CATEGORY && !is_category && *eid != community.id().0 {
let before = out.categories.len();
out.categories.retain(|c| c.id != *eid);
changed |= out.categories.len() != before;
}
if !is_meta && !is_channel && !is_category && pins_channel.is_none() && writers_channel.is_none() {
continue;
}
// A new kind is read marked only (CORD-04 §1): nothing older ever wrote one.
let group: Vec<&ParsedEdition> = group.iter().copied().filter(|e| !(is_category || writers_channel.is_some()) || e.binding.is_some()).collect();
if group.is_empty() {
continue;
}
let group = &group;
// Authority gate (CORD-04 §5): only editions whose author CURRENTLY holds the
// entity's management bit are eligible. Pre-filtering before the fold means a
// demoted admin's (possibly higher-version) edition can't be the head; the
// highest AUTHORIZED head wins. The owner is supreme.
let required = if is_meta {
Permissions::MANAGE_METADATA
} else if is_channel || is_category || writers_channel.is_some() {
Permissions::MANAGE_CHANNELS
} else {
Permissions::PIN_MESSAGES
};
let authorized: Vec<bool> = group
.iter()
.map(|e| {
let author = e.author.to_hex();
// A banned npub's edits are dropped (CORD-04 §4), even if they still
// held a bit via a not-yet-stripped grant, unless a Tenure sealed them.
let sealed = seal_of(&authority.sealed, &author, &e.self_hash, u32::MAX) & required == required;
(sealed || !authority.banned.contains(&author))
&& (sealed || standing.is_authorized(&author, owner_hex.as_deref(), required))
// …and the CORD-04 §5 sync floor. Resolved against the Grant heads
// this same fold settled, so it works on a bootstrap where no
// persisted head exists yet.
&& (sealed || citation_ok_in_fold(community.id(), &head_index, owner_hex.as_deref(), &e.author, e.authority.as_ref()))
})
.collect();
// A Writers ledger settles a tie on what never changes: a later change of rank can't move it.
let rank = |author_hex: &str| if writers_channel.is_some() { 0 } else { fork_rank_in(&standing, owner_hex.as_deref(), author_hex) };
let ledger_ok = writers_channel
.map(|ch| {
// What this reader already holds anchors what builds on it.
let anchor = floors.get(&crate::simd::hex::bytes_to_hex_32(eid)).and_then(|f| {
let (content, v) = crate::db::community::get_community_writers(&crate::simd::hex::bytes_to_hex_32(&community.id().0), ch).ok().flatten()?;
(v as u64 == f.0).then(|| super::writers::Ledger::parse(&content)).flatten().map(|l| (f.1, l))
});
ledger_chain_ok(group, &authorized, ch, &|e| (rank(&e.author.to_hex()), e.inner_id), anchor.as_ref())
})
.unwrap_or_default();
// An unmarked Channel edition describes only a Channel that stood before the switch.
let unlisted = is_channel && authority.roles.legacy_channels.as_ref().is_some_and(|l| !l.contains(&crate::simd::hex::bytes_to_hex_32(eid)));
let ok: Vec<bool> = group
.iter()
.zip(&authorized)
.map(|(e, &authorized)| authorized && writers_channel.is_none_or(|_| ledger_ok.get(&e.self_hash).copied().unwrap_or(false)) && !(unlisted && e.binding.is_none()))
.collect();
let entity_hex = crate::simd::hex::bytes_to_hex_32(eid);
admitted.extend(group.iter().zip(&ok).filter(|(_, &a)| a).map(|(e, _)| e.inner_id));
// Refuse-downgrade holds for the newest AUTHORIZED edition: when the edition this
// device holds (that very one, not a re-signed copy) is served yet no copy of it is
// authorized, the floor steps down to the predecessor it names, if an authorized
// copy of that is served. Only on a complete authority fold, so withholding can't
// manufacture the refusal.
let floor = floors.get(&entity_hex);
let held = floor.and_then(|f| group.iter().find(|e| held_is(f, e)));
// A floor recorded without the signer's id can't tell its edition from a copy.
let refused = authority.complete
&& floor.is_some_and(|f| f.2.is_some())
&& held.is_some_and(|h| !group.iter().zip(&ok).any(|(e, &a)| a && e.self_hash == h.self_hash));
if !ok.contains(&true) {
if refused && writers_channel.is_none() {
// Only an older build lists a Channel made after the switch by unmarked editions alone.
if unlisted && group.iter().all(|e| e.binding.is_none()) {
let before = out.channels.len();
out.channels.retain(|c| c.id.0 != *eid);
changed |= out.channels.len() != before;
}
kept.insert(entity_hex);
}
continue;
}
// Every served edition links the chain; only an authorized one can be the head.
let fold_eds: Vec<version::Edition> = group.iter().map(|p| p.to_fold_edition_ranked(rank(&p.author.to_hex()))).collect();
// An authorized edition built on the held one moves the entity on, refused or not.
let (linked, entity_gapped) = fold_head_among(&fold_eds, floor, &|a| rank(&crate::simd::hex::bytes_to_hex_32(a)), &|i| ok[i]);
gapped |= entity_gapped;
// A Channel's or Category's deletion is terminal over every authorized edition, not the head alone.
let deletion = (0..group.len())
.filter(|&i| (is_category || is_channel) && ok[i])
.filter(|&i| deletes_entity(is_category, &group[i].content))
.max_by_key(|&i| (group[i].version, std::cmp::Reverse(group[i].inner_id)));
if is_channel && deletion.is_some() {
deleted_channels.push(ChannelId(*eid));
}
let (hi, rebased) = match deletion.or(linked) {
Some(hi) => (hi, false),
// A ledger records what already happened: a head its Roster now refuses is kept, not
// stepped back from, or the posts its entry admitted would vanish.
None if refused && writers_channel.is_none() => {
let prev = held.and_then(|h| h.prev_hash);
// A build before marked editions names its predecessor by the unsigned hash.
let names = |e: &ParsedEdition| {
prev == Some(e.self_hash) || (e.binding.is_some() && prev == Some(crate::community::version::edition_hash(&e.entity_id, e.version, e.prev_hash.as_ref(), e.content.as_bytes())))
};
let target = (0..group.len()).filter(|&i| ok[i] && names(group[i])).min_by_key(|&i| (rank(&group[i].author.to_hex()), group[i].inner_id));
let Some(hi) = target else {
kept.insert(entity_hex);
continue;
};
(hi, true)
}
None => continue,
};
let head = group[hi];
heads.push(FoldedHead { entity_hex, version: head.version, self_hash: head.self_hash, inner_id: head.inner_id, author: head.author.to_bytes(), rebased });
if is_meta {
if let Ok(meta) = serde_json::from_str::<control::CommunityMetadata>(&head.content) {
changed |= apply_community_metadata(&mut out, meta);
}
} else if is_channel {
if let Some(sealed) = control::parse_sealed_channel_meta(&head.content) {
changed |= apply_sealed_channel_metadata(&mut out, ChannelId(*eid), &sealed, &head.content, head.prev_hash);
} else if let Ok(meta) = serde_json::from_str::<control::ChannelMetadata>(&head.content) {
// vsk-2 carries no community binding; a same-owner
// cross-community replay can inject a phantom PUBLIC channel (bounded:
// root-scoped key, eids don't collide). Binding is a deferred wire change.
changed |= apply_channel_metadata(&mut out, ChannelId(*eid), control::sanitize_channel_metadata(meta));
}
} else if is_category {
if let Ok(meta) = serde_json::from_str::<control::CategoryMetadata>(&head.content) {
changed |= apply_category_metadata(&mut out, *eid, meta);
}
} else if let Some(channel_hex) = pins_channel {
// The RAW carried content, cap-violations included: readers judge
// those (read as empty), and a re-serialization here would break the
// byte cap's meaning and every republish's fidelity.
use nostr_sdk::prelude::ToBech32;
let author_npub = head
.author
.to_bech32()
.unwrap_or_else(|_| head.author.to_hex());
pins_persist.push((channel_hex.clone(), head.content.clone(), head.version, author_npub, head.created_at));
} else if let Some(channel_hex) = writers_channel {
let ledger = super::writers::Ledger::parse(&head.content).filter(|l| crate::simd::hex::bytes_to_hex_32(&l.channel) == *channel_hex);
if let Some(ch) = out.channels.iter_mut().find(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0) == *channel_hex) {
if ch.writers != ledger {
ch.writers = ledger;
changed = true;
}
}
writers_persist.push((channel_hex.clone(), head.content.clone(), head.version, rebased));
}
}
changed |= unseal_held(&mut out);
ControlFold { updated: changed.then_some(out), heads, gapped, pins_persist, writers_persist, deleted_channels, kept, admitted }
}
/// Whether a Channel (or, with `category`, a Category) edition's content deletes it.
fn deletes_entity(category: bool, content: &str) -> bool {
if category {
serde_json::from_str::<control::CategoryMetadata>(content).is_ok_and(|m| m.deleted == Some(true))
} else {
control::parse_sealed_channel_meta(content)
.map(|s| s.deleted)
.or_else(|| serde_json::from_str::<control::ChannelMetadata>(content).ok().map(|m| m.deleted == Some(true)))
.unwrap_or(false)
}
}
/// Where a folded `@everyone` Role keeps the Channels that stood before the switch.
const EVERYONE_LEGACY: &str = "legacy";
/// Store a folded Writers ledger head. A rebased head, the fold stepping down from one it
/// refused, replaces whatever was held; when the live writer moves, writers look for its key.
fn persist_writers(cid_hex: &str, channel_hex: &str, content: &str, version: u64, rebased: bool) {
let held = crate::db::community::get_community_writers(cid_hex, channel_hex).ok().flatten();
if held.as_ref().is_some_and(|(c, v)| c == content && *v as u64 == version) {
return;
}
let live = |raw: &str| super::writers::Ledger::parse(raw).and_then(|l| l.current_writer());
let moved = held.as_ref().map(|(c, _)| live(c)) != Some(live(content));
match crate::db::community::set_community_writers(cid_hex, channel_hex, content, version as i64, rebased) {
Ok(true) if moved => {
if let Some(id) = crate::community::id32_from_hex(cid_hex) {
let id = crate::community::CommunityId(id);
access_collect_now(&id);
// A writer still on the epoch just left posts there a moment longer: read it again.
let read_at = crate::db::community::load_community_v2(&id).ok().flatten().and_then(|c| {
let ch = c.channels.iter().find(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0) == channel_hex)?;
(!(ch.private && ch.key.is_none())).then(|| (ch.id, c.channel_secret(ch).1))
});
if let Some((channel, epoch)) = read_at {
super::realtime::reread_tails(id, vec![(channel, epoch)]);
}
}
// The live subscription is addressed by the live writer: a move this device made itself
// folds no change a follow would notice.
if let Some(client) = crate::state::nostr_client() {
crate::db::spawn_bound(async move { super::realtime::refresh_subscription(&client).await });
}
}
Ok(_) => {}
Err(e) => crate::log_warn!("[writers] fold persist failed: {e}"),
}
}
/// Which of a Writers ledger's editions stand on their content (CORD-03 §1), judged along the
/// whole chain: each well formed for its Channel, its one new entry its signer's own, dated with
/// the edition and not past this reader's horizon, and extending a predecessor that itself
/// stands. Chains grow from the head this reader holds (`anchor`) and from one root: of those an
/// `authorized` edition builds on (a first edition, version 1 with one entry, or the head a
/// Refounding carried, whose predecessor isn't served), the one with the longest history.
fn ledger_chain_ok<'a>(
group: &[&'a ParsedEdition],
authorized: &[bool],
channel_hex: &str,
key: &dyn Fn(&ParsedEdition) -> (u32, [u8; 32]),
anchor: Option<&([u8; 32], super::writers::Ledger)>,
) -> std::collections::HashMap<[u8; 32], bool> {
use std::collections::HashMap;
let mut keys = super::writers::KeyCheck::default();
let parsed: HashMap<[u8; 32], super::writers::Ledger> = group
.iter()
.filter_map(|e| super::writers::Ledger::parse_with(&e.content, &mut keys).filter(|l| crate::simd::hex::bytes_to_hex_32(&l.channel) == channel_hex).map(|l| (e.self_hash, l)))
.collect();
let by_hash: HashMap<[u8; 32], &ParsedEdition> = group.iter().map(|e| (e.self_hash, *e)).collect();
let now = now_ms();
let own = |e: &ParsedEdition| parsed.get(&e.self_hash).is_some_and(|l| l.tail_fits(e.created_at, &e.author.to_bytes()) && l.not_ahead(now));
// Built on the held head, which isn't served: judged against what this reader holds.
let anchored = |e: &ParsedEdition| anchor.is_some_and(|(h, _)| e.prev_hash == Some(*h) && !by_hash.contains_key(h));
let root = |e: &ParsedEdition| match e.prev_hash {
None => own(e) && e.version == 1 && parsed.get(&e.self_hash).is_some_and(|l| l.is_first()),
Some(p) => !by_hash.contains_key(&p) && !anchored(e) && own(e),
};
// Each edition's children, in the group's order, so a walk down visits each edition once.
let mut children: HashMap<[u8; 32], Vec<&ParsedEdition>> = HashMap::new();
for e in group {
if let Some(p) = e.prev_hash {
children.entry(p).or_default().push(*e);
}
}
// Down each chain from what is judged so far: an edition stands on its predecessor's verdict.
let grow = |mut ok: HashMap<[u8; 32], bool>| {
let mut down: Vec<[u8; 32]> = ok.keys().copied().collect();
while let Some(p) = down.pop() {
let before = ok[&p];
for e in children.get(&p).into_iter().flatten() {
if ok.contains_key(&e.self_hash) {
continue;
}
let extends = parsed.get(&e.self_hash).zip(parsed.get(&p)).is_some_and(|(l, b)| l.extends(b));
ok.insert(e.self_hash, before && own(e) && extends);
down.push(e.self_hash);
}
}
ok
};
// Where an edition's chain starts in the group. An edition with no predecessor here is its
// own start; above it, each predecessor's start is found once.
let mut top_of: HashMap<[u8; 32], &ParsedEdition> = HashMap::new();
let mut top = |e: &'a ParsedEdition| -> &'a ParsedEdition {
let Some(mut at) = e.prev_hash.and_then(|p| by_hash.get(&p)).copied() else { return e };
let mut path = Vec::new();
let found = loop {
if let Some(t) = top_of.get(&at.self_hash) {
break *t;
}
path.push(at.self_hash);
match at.prev_hash.and_then(|p| by_hash.get(&p)) {
// A chain of distinct hashes is no longer than the group.
Some(up) if path.len() < group.len() => at = up,
_ => break at,
}
};
for h in path {
top_of.insert(h, found);
}
found
};
// The roots an authorized edition builds on.
let mut endorsed: Vec<&ParsedEdition> = Vec::new();
for (e, _) in group.iter().zip(authorized).filter(|(_, &a)| a) {
let at = top(e);
if root(at) && !endorsed.iter().any(|r| r.self_hash == at.self_hash) {
endorsed.push(at);
}
}
// The longest history wins, as for every Control entity: the highest version an authorized
// edition that stands reaches from each root. The fork key settles a tie.
let chosen = endorsed
.iter()
.map(|r| {
let ok = grow(HashMap::from([(r.self_hash, true)]));
let tip = group.iter().zip(authorized).filter(|(e, &a)| a && ok.get(&e.self_hash) == Some(&true)).map(|(e, _)| e.version).max().unwrap_or(0);
(tip, *r)
})
.min_by_key(|(tip, r)| (std::cmp::Reverse(*tip), key(r)))
.map(|(_, r)| r.self_hash);
let mut ok: HashMap<[u8; 32], bool> = HashMap::new();
if let Some((h, _)) = anchor.filter(|(h, _)| by_hash.contains_key(h)) {
ok.insert(*h, true);
}
for e in group {
if ok.contains_key(&e.self_hash) {
continue;
}
if let Some((_, held)) = anchor.filter(|_| anchored(e)) {
ok.insert(e.self_hash, own(e) && parsed.get(&e.self_hash).is_some_and(|l| l.extends(held)));
} else if e.prev_hash.is_none_or(|p| !by_hash.contains_key(&p)) {
ok.insert(e.self_hash, Some(e.self_hash) == chosen);
}
}
grow(ok)
}
/// [`ledger_chain_ok`] as it was first written, kept to check the faster one against.
#[cfg(test)]
fn ledger_chain_ok_reference(
group: &[&ParsedEdition],
authorized: &[bool],
channel_hex: &str,
key: &dyn Fn(&ParsedEdition) -> (u32, [u8; 32]),
anchor: Option<&([u8; 32], super::writers::Ledger)>,
) -> std::collections::HashMap<[u8; 32], bool> {
use std::collections::HashMap;
let parsed: HashMap<[u8; 32], super::writers::Ledger> = group
.iter()
.filter_map(|e| super::writers::Ledger::parse(&e.content).filter(|l| crate::simd::hex::bytes_to_hex_32(&l.channel) == channel_hex).map(|l| (e.self_hash, l)))
.collect();
let by_hash: HashMap<[u8; 32], &ParsedEdition> = group.iter().map(|e| (e.self_hash, *e)).collect();
let now = now_ms();
let own = |e: &ParsedEdition| parsed.get(&e.self_hash).is_some_and(|l| l.tail_fits(e.created_at, &e.author.to_bytes()) && l.not_ahead(now));
// Built on the held head, which isn't served: judged against what this reader holds.
let anchored = |e: &ParsedEdition| anchor.is_some_and(|(h, _)| e.prev_hash == Some(*h) && !by_hash.contains_key(h));
let root = |e: &ParsedEdition| match e.prev_hash {
None => own(e) && e.version == 1 && parsed.get(&e.self_hash).is_some_and(|l| l.is_first()),
Some(p) => !by_hash.contains_key(&p) && !anchored(e) && own(e),
};
// Down each chain from what is judged so far; one is at most as long as the group.
let grow = |mut ok: HashMap<[u8; 32], bool>| {
for _ in 0..group.len() {
let mut moved = false;
for e in group {
if ok.contains_key(&e.self_hash) {
continue;
}
let Some(p) = e.prev_hash else { continue };
if let Some(&before) = ok.get(&p) {
let extends = parsed.get(&e.self_hash).zip(parsed.get(&p)).is_some_and(|(l, b)| l.extends(b));
ok.insert(e.self_hash, before && own(e) && extends);
moved = true;
}
}
if !moved {
break;
}
}
ok
};
// The roots an authorized edition builds on.
let mut endorsed: Vec<&ParsedEdition> = Vec::new();
for (e, _) in group.iter().zip(authorized).filter(|(_, &a)| a) {
let mut at = *e;
for _ in 0..group.len() {
match at.prev_hash.and_then(|p| by_hash.get(&p)) {
Some(up) => at = up,
None => break,
}
}
if root(at) && !endorsed.iter().any(|r| r.self_hash == at.self_hash) {
endorsed.push(at);
}
}
// The longest history wins, as for every Control entity: the highest version an authorized
// edition that stands reaches from each root. The fork key settles a tie.
let chosen = endorsed
.iter()
.map(|r| {
let ok = grow(HashMap::from([(r.self_hash, true)]));
let tip = group.iter().zip(authorized).filter(|(e, &a)| a && ok.get(&e.self_hash) == Some(&true)).map(|(e, _)| e.version).max().unwrap_or(0);
(tip, *r)
})
.min_by_key(|(tip, r)| (std::cmp::Reverse(*tip), key(r)))
.map(|(_, r)| r.self_hash);
let mut ok: HashMap<[u8; 32], bool> = HashMap::new();
if let Some((h, _)) = anchor.filter(|(h, _)| by_hash.contains_key(h)) {
ok.insert(*h, true);
}
for e in group {
if ok.contains_key(&e.self_hash) {
continue;
}
if let Some((_, held)) = anchor.filter(|_| anchored(e)) {
ok.insert(e.self_hash, own(e) && parsed.get(&e.self_hash).is_some_and(|l| l.extends(held)));
} else if e.prev_hash.is_none_or(|p| !by_hash.contains_key(&p)) {
ok.insert(e.self_hash, Some(e.self_hash) == chosen);
}
}
grow(ok)
}
/// Fold one entity's editions against its persisted floor into a head index (into the
/// input slice) plus whether a TRACKING gap was hit (the caller pages older history).
/// Encapsulates the W2 refuse-downgrade policy: bootstrap at floor 0 (highest signed
/// head, what Armada shows across a compaction's dangling prev); adopt the chain-
/// anchored head, paging on an upper gap; converge a same-version fork at the floor to
/// the lower-inner-id winner; and fail closed otherwise.
fn fold_head(fold_eds: &[version::Edition], floor: Option<&Floor>, rank_of: &dyn Fn(&[u8; 32]) -> u32) -> (Option<usize>, bool) {
fold_head_among(fold_eds, floor, rank_of, &|_| true)
}
/// [`fold_head`] with the head taken only among the editions `eligible` admits, while
/// every served edition carries the chain.
fn fold_head_among(fold_eds: &[version::Edition], floor: Option<&Floor>, rank_of: &dyn Fn(&[u8; 32]) -> u32, eligible: &dyn Fn(usize) -> bool) -> (Option<usize>, bool) {
let Some(floor) = floor.filter(|f| f.0 > 0) else {
let ok: Vec<usize> = (0..fold_eds.len()).filter(|&i| eligible(i)).collect();
let sub: Vec<version::Edition> = ok.iter().map(|&i| fold_eds[i].clone()).collect();
return (version::bootstrap_head(&sub, 0).map(|k| ok[k]), false);
};
// A same-version rival of a withheld held head may stand in for it only by beating
// the key the floor recorded; while the held edition is served, the tiebreak decides.
let held = HeldKey::of(floor, rank_of);
let result = version::fold_linked(fold_eds, floor.0, Some(&floor.1), &|e| held.beaten_by(e.rank, &e.tiebreak_id), eligible);
if result.anchored {
return (result.head, result.gap); // verified prefix; page any upper gap.
}
// Nothing at or above the floor is a stale relay (no paging); anything else that
// fails to link is withholding, so fail closed.
(None, result.gap)
}
/// The folded, delegation-AUTHORIZED control-plane authority (CORD-04): the roster
/// (roles + grants, owner-seeded fixpoint), the enforced banlist, and the
/// role/grant/banlist heads to persist as refuse-downgrade floors. The owner is
/// recomputed from the self-certifying community_id at each use.
struct AuthoritySet {
roles: crate::community::roles::CommunityRoles,
banned: std::collections::BTreeSet<String>,
heads: Vec<FoldedHead>,
gapped: bool,
/// The authorized banlist `(content, version)` to persist when an authorized head
/// advanced the floor. `None` when the banlist was retained (no new authorized
/// head) or is empty — the caller then leaves the stored banlist untouched.
banlist_persist: Option<(Vec<String>, u64)>,
/// Ban HISTORY: npub hex → `created_at` (secs) of the newest authorized edition that
/// named them, across every edition in the window rather than just the head. Outlives
/// the ban itself so an un-ban can't resurrect a phantom (see [`fold_members`]).
banned_at: std::collections::BTreeMap<String, u64>,
/// Every floored role and grant served its held head this fold: data enough that a
/// held head the Roster refuses is refused on the evidence, not on a withholding.
complete: bool,
/// Role and grant entities refused whole on that evidence: settled absent, so no
/// completeness check waits on them.
refused: std::collections::BTreeSet<String>,
/// Role and grant entities whose held head is refused with nothing to fall back to.
carried: std::collections::BTreeSet<String>,
/// Every role and grant edition the fold admitted.
admitted: crate::fasthash::FastSet<[u8; 32]>,
/// Roles v2 is active (CORD-04 §2).
activated: bool,
/// Each member's sealed standings (CORD-04 §9).
sealed: SealedBy,
/// The authority fixpoint converged.
converged: bool,
}
impl AuthoritySet {
/// Every role/grant/banlist entity this fold settled: a head, or refused on evidence.
fn settled(&self) -> std::collections::HashSet<&str> {
self.heads.iter().map(|h| h.entity_hex.as_str()).chain(self.refused.iter().map(String::as_str)).collect()
}
}
impl AuthoritySet {
/// Bootstrap authority for a community with no roster editions folded yet: only
/// the owner is authorized (supreme), nobody banned.
fn owner_only() -> Self {
AuthoritySet {
roles: Default::default(),
banned: Default::default(),
heads: vec![],
gapped: false,
banlist_persist: None,
banned_at: Default::default(),
complete: false,
refused: Default::default(),
carried: Default::default(),
admitted: Default::default(),
activated: false,
sealed: Default::default(),
converged: true,
}
}
}
/// The stamp a roster cache carries: the newest of its authorized heads' times, clamped,
/// since a signer picks its own `created_at` and a future one would freeze every later
/// fold behind it.
fn roster_stamp(editions: &[ParsedEdition], heads: &[FoldedHead]) -> i64 {
let ids: std::collections::HashSet<[u8; 32]> = heads.iter().map(|h| h.inner_id).collect();
let ceiling = roster_stamp_ceiling();
editions
.iter()
.filter(|e| [vsk::ROLE, vsk::ROLE_V2, vsk::GRANT, vsk::BANLIST, vsk::TENURE, vsk::CHANNEL_ACL, vsk::CHANNEL_SYNC].contains(&e.vsk.as_str()) && ids.contains(&e.inner_id))
.map(|e| (e.created_at as i64).min(ceiling))
.max()
.unwrap_or(0)
}
fn roster_stamp_ceiling() -> i64 {
(now_ms() / 1000) as i64 + 600
}
/// Whether `e` is the very edition `floor` records (see [`AuthorityCand::is_held`]).
fn held_is(floor: &Floor, e: &ParsedEdition) -> bool {
e.version == floor.0 && e.self_hash == floor.1 && floor.2.is_none_or(|id| id == e.inner_id)
}
/// Fold the roster/banlist entities (vsk 1/3/4) from the control editions into the
/// delegation-AUTHORIZED roster + enforced banlist (CORD-04 §2-§5). Each entity binds
/// to its coordinate (role at role_id, grant at grant_locator(cid, member), banlist at
/// banlist_locator(cid)); a content whose coordinate doesn't match is dropped. Roles
/// cap at the 100 lowest role_ids, a member at 64 roles, the banlist at 500. The
/// banlist is enforced only if its head's signer held BAN in the authorized roster.
fn fold_authority(community: &CommunityV2, editions: &[ParsedEdition], floors: &Floors) -> AuthoritySet {
use crate::community::roles::{Permissions, Role};
use std::collections::BTreeMap;
let cid = community.id();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
let floors = &floors_of_family(floors, crate::db::community::FLOOR_AUTHORITY);
let owner = community.owner().ok();
let owner_hex = owner.map(|o| o.to_hex());
let banlist_eid = super::derive::banlist_locator(cid);
let banlist_hex = crate::simd::hex::bytes_to_hex_32(&banlist_eid);
let mut groups: BTreeMap<[u8; 32], Vec<&ParsedEdition>> = BTreeMap::new();
for e in editions {
if e.vsk == vsk::ROLE || e.vsk == vsk::ROLE_V2 || e.vsk == vsk::GRANT || e.vsk == vsk::BANLIST || e.vsk == vsk::TENURE {
groups.entry(e.entity_id).or_default().push(e);
}
}
// Per-entity CANDIDATE lists — every ≥floor edition of a role/grant, highest
// version first (lowest inner-id as the deterministic tiebreak). CORD-04 §1: an
// edition whose signer isn't authorized is SIMPLY DROPPED and the fold continues
// to the next candidate, so a forged higher-version edition can't suppress the
// authorized head beneath it (the author-blind collapse-to-one-head it replaces
// let any member vanish a role or a member's grant). `gapped` (drives older-
// paging) stays fold_head's per-entity flag.
// Roles v2 (CORD-04 §2): Roles fold from vsk 13 alone once @everyone stands there, judged
// in a vsk-13 fold, which traces to the owner because a vsk-1 Role confers nothing in it.
// So an admin's later edit of @everyone keeps the Community on Roles v2 across a
// Refounding, and once floored it stays. A vsk-1 edition then links the chain a migrated
// Role continues, and stands for nothing. Rank keys map to dense positions.
let everyone_eid = super::derive::everyone_locator(cid);
let everyone_hex = crate::simd::hex::bytes_to_hex_32(&everyone_eid);
let build = |activated: bool| {
let mut role_cands: BTreeMap<String, Vec<AuthorityCand>> = BTreeMap::new();
let mut grant_cands: BTreeMap<String, Vec<AuthorityCand>> = BTreeMap::new();
let mut tenure_cands: BTreeMap<String, Vec<AuthorityCand>> = BTreeMap::new();
let mut gapped = false;
let ranks: crate::fasthash::FastMap<String, u32> = if activated {
let mut keys: Vec<String> = editions
.iter()
.filter(|e| e.vsk == vsk::ROLE_V2 && e.binding.is_some())
.filter_map(|e| match super::roles::parse_role_v2_content(&e.content) {
Some(super::roles::RoleV2::Live(r)) => r.rank,
_ => None,
})
.collect();
// A Tenure's ranks sit in the same order as the Roles'.
keys.extend(
editions
.iter()
.filter(|e| e.vsk == vsk::TENURE && e.binding.is_some())
.filter_map(|e| super::roles::parse_tenure_content(&e.content))
.flat_map(|t| t.sealed.into_iter().map(|e| e.rank)),
);
crate::community::rank::dense_ranks(keys.iter().map(String::as_str)).into_iter().map(|(k, v)| (k.to_string(), v)).collect()
} else {
Default::default()
};
for (eid, group) in &groups {
// The banlist is folded author-aware AFTER the roster is known (below).
if *eid == banlist_eid {
continue;
}
let entity_hex = crate::simd::hex::bytes_to_hex_32(eid);
let floor = floors.get(&entity_hex).copied();
let held_served = floor.is_some_and(|f| group.iter().any(|p| held_is(&f, p)));
// Nothing above a withheld held head can be judged on the rank it acts on: page for it.
gapped |= floor.is_some_and(|f| !held_served && group.iter().any(|p| p.version > f.0));
for p in group {
let head = FoldedHead { entity_hex: entity_hex.clone(), version: p.version, self_hash: p.self_hash, inner_id: p.inner_id, author: p.author.to_bytes(), rebased: false };
let author_hex = p.author.to_hex();
let grant_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(cid, &p.author.to_bytes()));
let cand = |role: Role, kind: RoleKind| AuthorityCand { role: Some(role), grant: None, tenure: None, kind, author: p.author, author_hex: author_hex.clone(), grant_hex: grant_hex.clone(), head: head.clone(), citation: p.authority.clone(), prev: p.prev_hash, floor, held_served };
match p.vsk.as_str() {
// The @everyone coordinate holds @everyone alone.
vsk::ROLE if *eid == everyone_eid => {}
vsk::ROLE => {
// Bind: the content's role_id IS the coordinate; position 0 is the owner's.
if let Some(role) = super::roles::parse_role_content(&p.content) {
if role.role_id == entity_hex && role.position != 0 {
let kind = if activated { RoleKind::History } else { RoleKind::Live };
role_cands.entry(entity_hex.clone()).or_default().push(cand(role, kind));
}
}
}
vsk::ROLE_V2 if p.binding.is_none() => {}
vsk::ROLE_V2 if activated && *eid == everyone_eid => {
if let Some((bits, legacy)) = super::roles::parse_everyone_content(&p.content) {
let mut extra = serde_json::Map::new();
if let Some(l) = legacy {
extra.insert(EVERYONE_LEGACY.into(), serde_json::json!(l));
}
let role = Role { role_id: everyone_hex.clone(), name: "@everyone".into(), position: u32::MAX, permissions: Permissions(bits), scope: crate::community::roles::RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra };
role_cands.entry(entity_hex.clone()).or_default().push(cand(role, RoleKind::Everyone));
}
}
vsk::ROLE_V2 if activated => match super::roles::parse_role_v2_content(&p.content) {
Some(super::roles::RoleV2::Live(mut role)) if role.role_id == entity_hex => {
role.position = role.rank.as_ref().and_then(|k| ranks.get(k)).copied().unwrap_or(u32::MAX);
role_cands.entry(entity_hex.clone()).or_default().push(cand(role, RoleKind::Live));
}
Some(super::roles::RoleV2::Deleted { role_id }) if role_id == entity_hex => {
let role = Role { role_id, name: String::new(), position: u32::MAX, permissions: Permissions(0), scope: crate::community::roles::RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() };
role_cands.entry(entity_hex.clone()).or_default().push(cand(role, RoleKind::Deleted));
}
_ => {}
},
vsk::TENURE if activated && p.binding.is_some() => {
if let Some(t) = super::roles::parse_tenure_content(&p.content) {
let bound = crate::simd::hex::hex_to_bytes_32_checked(&t.member).is_some_and(|m| super::derive::tenure_locator(cid, &m, &p.author.to_bytes()) == *eid);
if bound {
let entries = t
.sealed
.iter()
.filter_map(|e| {
let position = ranks.get(&e.rank).copied()?;
let heads = e.heads.iter().filter_map(|h| crate::simd::hex::hex_to_bytes_32_checked(h)).collect();
Some(Sealed { position, bits: e.permissions, heads })
})
.collect();
tenure_cands.entry(entity_hex.clone()).or_default().push(AuthorityCand { role: None, grant: None, tenure: Some((t.member.clone(), entries)), kind: RoleKind::Live, author: p.author, author_hex: author_hex.clone(), grant_hex: grant_hex.clone(), head, citation: p.authority.clone(), prev: p.prev_hash, floor, held_served });
}
}
}
vsk::GRANT => {
if let Some(mut grant) = super::roles::parse_grant_content(&p.content) {
if let Some(member) = crate::simd::hex::hex_to_bytes_32_checked(&grant.member) {
if super::derive::grant_locator(cid, &member) == *eid {
grant.role_ids.truncate(super::roles::MAX_ROLES_PER_MEMBER);
grant_cands.entry(entity_hex.clone()).or_default().push(AuthorityCand { role: None, grant: Some(grant), tenure: None, kind: RoleKind::Live, author: p.author, author_hex: author_hex.clone(), grant_hex: grant_hex.clone(), head, citation: p.authority.clone(), prev: p.prev_hash, floor, held_served });
}
}
}
}
_ => {}
}
}
}
for cands in role_cands.values_mut().chain(grant_cands.values_mut()).chain(tenure_cands.values_mut()) {
cands.sort_by(|a, b| b.head.version.cmp(&a.head.version).then(a.head.inner_id.cmp(&b.head.inner_id)));
}
(role_cands, grant_cands, tenure_cands, gapped)
};
// Complete: every role and grant this device floors served its held head, so a held
// head the Roster refuses is refused on the evidence. The stored roster names the
// floored entities a plane might have stopped serving entirely.
let stored = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
// A Tenure this device floors is tracked too, or withholding it would refuse what it
// seals "on evidence". Its coordinate names member and writer, so the candidates are the
// authors of floored heads, each against everyone who could have reduced them.
let tenure_floors: Vec<String> = {
let mut writers: std::collections::BTreeSet<[u8; 32]> = owner.iter().map(|o| o.to_bytes()).collect();
let managers = stored.authorized_grantees(owner_hex.as_deref(), Permissions::MANAGE_ROLES);
writers.extend(stored.grants.iter().filter(|g| managers.contains(g.member.as_str())).filter_map(|g| crate::simd::hex::hex_to_bytes_32_checked(&g.member)));
let authors: std::collections::BTreeSet<[u8; 32]> = floors.values().filter_map(|f| f.3).collect();
authors
.iter()
.flat_map(|a| writers.iter().map(move |w| crate::simd::hex::bytes_to_hex_32(&super::derive::tenure_locator(cid, a, w))))
.filter(|eid| floors.contains_key(eid))
.collect()
};
// What `held_is` matches on, for every edition in hand: by version and hash, and with the id.
let served: crate::fasthash::FastSet<(u64, [u8; 32])> = editions.iter().map(|e| (e.version, e.self_hash)).collect();
let served_as: crate::fasthash::FastSet<(u64, [u8; 32], [u8; 32])> = editions.iter().map(|e| (e.version, e.self_hash, e.inner_id)).collect();
let held_served = |f: &Floor| match f.2 {
None => served.contains(&(f.0, f.1)),
Some(id) => served_as.contains(&(f.0, f.1, id)),
};
let complete_of = |role_cands: &BTreeMap<String, Vec<AuthorityCand>>, grant_cands: &BTreeMap<String, Vec<AuthorityCand>>, tenure_cands: &BTreeMap<String, Vec<AuthorityCand>>| {
let mut tracked: std::collections::BTreeSet<String> = role_cands.keys().chain(grant_cands.keys()).chain(tenure_cands.keys()).cloned().collect();
tracked.extend(tenure_floors.iter().cloned());
tracked.extend(stored.roles.iter().map(|r| r.role_id.clone()));
tracked.extend(stored.grants.iter().filter_map(|g| {
crate::simd::hex::hex_to_bytes_32_checked(&g.member)
.map(|m| crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(cid, &m)))
}));
tracked.iter().all(|eid| floors.get(eid).is_none_or(&held_served))
};
let some_v2 = groups.get(&everyone_eid).is_some_and(|g| g.iter().any(|e| e.vsk == vsk::ROLE_V2 && e.binding.is_some()));
let activated = floors.contains_key(&everyone_hex)
|| (some_v2 && {
let (rc, gc, tc, _) = build(true);
let none: std::collections::BTreeSet<String> = Default::default();
select_authorized(cid, &rc, &gc, &tc, owner_hex.as_deref(), &none, complete_of(&rc, &gc, &tc), None).heads.iter().any(|h| h.entity_hex == everyone_hex)
});
let (role_cands, grant_cands, tenure_cands, withheld) = build(activated);
let mut gapped = withheld;
let complete = complete_of(&role_cands, &grant_cands, &tenure_cands);
let empty: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
// Preliminary roster (bans not yet applied) — the authority view the banlist head
// is judged against.
let prelim_sel = select_authorized(cid, &role_cands, &grant_cands, &tenure_cands, owner_hex.as_deref(), &empty, complete, None);
let (prelim, prelim_heads, prelim_sealed) = (prelim_sel.roles, prelim_sel.heads, prelim_sel.sealed);
let prelim_rank = |author_hex: &str| fork_rank(&prelim, owner_hex.as_deref(), author_hex);
let prelim_rank_bytes = |a: &[u8; 32]| prelim_rank(&crate::simd::hex::bytes_to_hex_32(a));
// Whether a tracking role/grant chain gapped (drives older-paging), its forks ranked by
// the authority this pass resolved.
// Banlist (CORD-04 §4), folded AUTHORITY-aware so its two anti-roster hazards are
// both closed:
// - head selection: the head is the highest version whose author CURRENTLY holds
// BAN — an unauthorized higher-version edition can't erase existing bans
// (fail-open), and the floor never advances to one;
// - per-target: each entry is kept only if the author STRICTLY OUTRANKS that
// target (`can_act_on_member` — an admin can't ban a peer/superior, and the
// owner is unbannable);
// - withholding: when no authorized head is served, the persisted banlist is
// RETAINED (an anti-roster must not un-ban on a relay withholding the ban).
let persisted_banned: Vec<String> = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
// An ALREADY-banned npub can't author the banlist (a banned member vanishes, §4), or
// a BAN-holder whose grant-strip hasn't yet folded could publish a list omitting their
// OWN ban to un-ban themselves (removals aren't outrank-checked). Exclude them from
// head eligibility, not just from the roster.
let banned_authors: crate::fasthash::FastSet<&str> = persisted_banned.iter().map(String::as_str).collect();
let prelim_index = HeadIndex::of(&prelim_heads);
let banlist_authored: Vec<&ParsedEdition> = groups
.get(&banlist_eid)
.map(|g| {
g.iter()
.copied()
.filter(|e| {
let ah = e.author.to_hex();
let sealed_ban = seal_of(&prelim_sealed, &ah, &e.self_hash, u32::MAX) & Permissions::BAN != 0;
(!banned_authors.contains(ah.as_str()) || sealed_ban)
// From the author's Roles: @everyone's bits author no banlist.
&& (owner_hex.as_deref() == Some(ah.as_str()) || sealed_ban || prelim.permissions_above(&ah, u32::MAX).contains(Permissions::BAN))
&& (sealed_ban || citation_ok_in_fold(cid, &prelim_index, owner_hex.as_deref(), &e.author, e.authority.as_ref()))
// A malformed list is no Banlist edition: read as empty it would unban everyone.
&& super::roles::parse_banlist_content(&e.content).is_some()
})
.collect()
})
.unwrap_or_default();
// Ban history for phantom suppression: the newest AUTHORIZED edition naming each npub,
// over EVERY candidate rather than only the head — an un-ban replaces the head, so the
// head alone forgets the ban that the suppression exists to remember. The owner is
// skipped: they are never bannable, and a moderator listing them must not durably
// suppress them past the un-ban.
let mut banned_at: std::collections::BTreeMap<String, u64> = std::collections::BTreeMap::new();
for p in &banlist_authored {
for t in super::roles::parse_banlist_content(&p.content).unwrap_or_default() {
if owner_hex.as_deref() == Some(t.as_str()) {
continue;
}
let slot = banned_at.entry(t).or_insert(0);
*slot = (*slot).max(p.created_at);
}
}
let mut banlist_persist: Option<(Vec<String>, u64)> = None;
let mut banlist_head: Option<FoldedHead> = None;
let banned: std::collections::BTreeSet<String> = if banlist_authored.is_empty() {
persisted_banned.into_iter().collect()
} else {
// Every served edition links the chain; only an authored one can be the head.
let all: Vec<&ParsedEdition> = groups.get(&banlist_eid).map(|g| g.to_vec()).unwrap_or_default();
let authored: std::collections::HashSet<[u8; 32]> = banlist_authored.iter().map(|e| e.inner_id).collect();
let fold_eds: Vec<version::Edition> = all.iter().map(|p| p.to_fold_edition_ranked(prelim_rank(&p.author.to_hex()))).collect();
let (hi, g) = fold_head_among(&fold_eds, floors.get(&banlist_hex), &prelim_rank_bytes, &|i| authored.contains(&all[i].inner_id));
gapped |= g;
match hi {
Some(hi) => {
let head = all[hi];
let ah = head.author.to_hex();
let list: Vec<String> = super::roles::parse_banlist_content(&head.content)
.unwrap_or_default()
.into_iter()
.filter(|t| {
prelim.can_act_on_member(&ah, owner_hex.as_deref(), t, Permissions::BAN)
|| (owner_hex.as_deref() != Some(t.as_str())
&& seal_of(&prelim_sealed, &ah, &head.self_hash, prelim.highest_position(t).unwrap_or(u32::MAX)) & Permissions::BAN != 0)
})
.take(super::roles::MAX_BANLIST)
.collect();
banlist_head = Some(FoldedHead { entity_hex: banlist_hex.clone(), version: head.version, self_hash: head.self_hash, inner_id: head.inner_id, author: head.author.to_bytes(), rebased: false });
banlist_persist = Some((list.clone(), head.version));
list.into_iter().collect()
}
None => persisted_banned.into_iter().collect(),
}
};
// Final roster (CORD-04 §4: a banned npub vanishes — every edition it authored is
// dropped, and a grant TO a banned member carries no rank). Re-run selection with
// the banned set excluded so a banned admin loses authority.
let mut refusals: std::collections::BTreeMap<String, &'static str> = Default::default();
let selected = select_authorized(cid, &role_cands, &grant_cands, &tenure_cands, owner_hex.as_deref(), &banned, complete, Some(&mut refusals));
let (mut authorized, mut heads, refused, carried, admitted, sealed, converged) = (selected.roles, selected.heads, selected.refused, selected.carried, selected.admitted, selected.sealed, selected.converged);
gapped |= selected.gapped;
if !converged {
crate::log_warn!("[v2:authority {}] the roster fold did not settle within its bound; the last round stands", &cid_hex[..8.min(cid_hex.len())]);
}
AUTHORITY_REFUSALS.with(|c| *c.borrow_mut() = refusals);
if let Some(bh) = banlist_head {
heads.push(bh);
}
// Cap the AUTHORIZED community at the 100 lowest role_ids — applied AFTER
// authorization, so an attacker's unauthorized roles can't consume cap slots and
// evict a legitimate one (the pre-authorize cap they replace let 100 forged low-id
// roles empty the roster).
if authorized.roles.len() > super::roles::MAX_ROLES_PER_COMMUNITY {
authorized.roles.sort_by(|a, b| a.role_id.cmp(&b.role_id));
authorized.roles.truncate(super::roles::MAX_ROLES_PER_COMMUNITY);
let kept: std::collections::HashSet<&str> = authorized.roles.iter().map(|r| r.role_id.as_str()).collect();
authorized.grants.iter_mut().for_each(|g| g.role_ids.retain(|rid| kept.contains(rid.as_str())));
authorized.grants.retain(|g| !g.role_ids.is_empty());
}
if activated && authorized.everyone.is_none() {
authorized.everyone = stored.everyone;
}
if activated {
// The switch fixes the list (CORD-04 §2): an @everyone edition after it can't change it.
let switched = role_cands
.get(&everyone_hex)
.and_then(|cands| cands.iter().filter(|c| c.kind == RoleKind::Everyone && Some(c.author) == owner && c.prev.is_none()).min_by_key(|c| (c.head.version, c.head.inner_id)))
.and_then(|c| c.role.as_ref())
.and_then(|r| r.extra.get(EVERYONE_LEGACY))
.and_then(|l| serde_json::from_value(l.clone()).ok());
authorized.legacy_channels = switched.or(stored.legacy_channels.clone()).or(authorized.legacy_channels.take());
}
if activated {
authorized.overwrites = fold_overwrites(community, editions, floors, &authorized, &banned, &sealed, &mut heads, &mut gapped);
authorized.syncs = fold_syncs(community, editions, floors, &authorized, &banned, &sealed, &mut heads, &mut gapped);
authorized.creators = community.channels.iter().filter_map(|c| Some((crate::simd::hex::bytes_to_hex_32(&c.id.0), c.creator()?.to_string()))).collect();
}
AuthoritySet { roles: authorized, banned, heads, gapped, banlist_persist, banned_at, complete, refused, carried, admitted, activated, sealed, converged }
}
/// Whether `author_hex` could write every overwrite in `scopes` as it stands: what a sync
/// swaps all at once (CORD-04 §8). `sealed_over` lends a Tenure's standing to one edition.
fn may_swap_overwrites(roles: &crate::community::roles::CommunityRoles, owner_hex: Option<&str>, author_hex: &str, scopes: &[&str], sealed_over: &dyn Fn(u32) -> u64) -> bool {
use crate::community::roles::{OverwriteTarget, Permissions};
if owner_hex == Some(author_hex) {
return true;
}
let held = |rank: u32| roles.permissions_above(author_hex, rank).0 | sealed_over(rank);
if held(u32::MAX) & Permissions::MANAGE_ROLES == 0 {
return false;
}
roles.overwrites.iter().filter(|o| scopes.contains(&o.scope.as_str())).all(|o| {
let rank = match &o.target {
OverwriteTarget::Everyone => u32::MAX,
OverwriteTarget::Role(id) => roles.role(id).map_or(u32::MAX, |r| r.position),
OverwriteTarget::Member(m) => roles.highest_position(m).unwrap_or(u32::MAX),
};
let support = held(rank);
support & Permissions::MANAGE_ROLES != 0 && (o.allow.0 | o.deny.0) & !support == 0
})
}
/// Fold each Channel's sync (vsk 17): judged against the settled overwrites, since a sync
/// swaps every rule on both sides at once, so its signer must be able to write them all.
#[allow(clippy::too_many_arguments)]
fn fold_syncs(
community: &CommunityV2,
editions: &[ParsedEdition],
floors: &Floors,
roles: &crate::community::roles::CommunityRoles,
banned: &std::collections::BTreeSet<String>,
sealed: &SealedBy,
heads: &mut Vec<FoldedHead>,
gapped: &mut bool,
) -> std::collections::BTreeMap<String, String> {
let cid = community.id();
let owner_hex = community.owner().ok().map(|o| o.to_hex());
let mut groups: std::collections::BTreeMap<[u8; 32], Vec<(&ParsedEdition, String, Option<String>)>> = Default::default();
for e in editions.iter().filter(|e| e.vsk == vsk::CHANNEL_SYNC && e.binding.is_some()) {
let Some((channel, category)) = super::roles::parse_sync_content(&e.content) else { continue };
let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(&channel));
if super::derive::sync_locator(cid, &ch) == e.entity_id {
groups.entry(e.entity_id).or_default().push((e, channel, category));
}
}
let mut out = std::collections::BTreeMap::new();
let mut withheld: std::collections::BTreeSet<[u8; 32]> = Default::default();
let served: std::collections::BTreeSet<[u8; 32]> = groups.keys().copied().collect();
for (eid, group) in groups {
let ok: Vec<bool> = group
.iter()
.map(|(e, channel, category)| {
let ah = e.author.to_hex();
if banned.contains(&ah) && !is_listed(sealed, &ah, &e.self_hash) && owner_hex.as_deref() != Some(ah.as_str()) {
return false;
}
// The Category it leaves is the one its predecessor named: judged too, and
// unknowable while that predecessor isn't served.
let left = match e.prev_hash {
None => None,
Some(p) => match group.iter().find(|(x, _, _)| x.self_hash == p) {
Some((_, _, k)) => k.clone(),
None => return false,
},
};
let mut scopes = vec![channel.as_str()];
scopes.extend(category.as_deref());
scopes.extend(left.as_deref());
may_swap_overwrites(roles, owner_hex.as_deref(), &ah, &scopes, &|rank| seal_of(sealed, &ah, &e.self_hash, rank))
})
.collect();
if !ok.contains(&true) {
continue;
}
let entity_hex = crate::simd::hex::bytes_to_hex_32(&eid);
let rank = |a: &str| fork_rank(roles, owner_hex.as_deref(), a);
let fold_eds: Vec<version::Edition> = group.iter().map(|(p, _, _)| p.to_fold_edition_ranked(rank(&p.author.to_hex()))).collect();
let floor = floors.get(&entity_hex);
let (hi, gap) = fold_head_among(&fold_eds, floor, &|a| rank(&crate::simd::hex::bytes_to_hex_32(a)), &|i| ok[i]);
*gapped |= gap;
let held_served = floor.is_some_and(|f| group.iter().any(|(e, _, _)| held_is(f, e)));
let (hi, rebased) = match hi {
Some(hi) => (hi, false),
None if held_served => match fold_head_among(&fold_eds, None, &|a| rank(&crate::simd::hex::bytes_to_hex_32(a)), &|i| ok[i]).0 {
Some(hi) => (hi, true),
None => continue,
},
None => {
withheld.insert(eid);
continue;
}
};
let (head, channel, category) = &group[hi];
heads.push(FoldedHead { entity_hex, version: head.version, self_hash: head.self_hash, inner_id: head.inner_id, author: head.author.to_bytes(), rebased });
if let Some(k) = category {
out.insert(channel.clone(), k.clone());
}
}
let stored = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&cid.0)).unwrap_or_default();
for (channel, category) in stored.syncs {
let Some(ch) = crate::simd::hex::hex_to_bytes_32_checked(&channel) else { continue };
let eid = super::derive::sync_locator(cid, &ChannelId(ch));
if floors.contains_key(&crate::simd::hex::bytes_to_hex_32(&eid)) && (withheld.contains(&eid) || !served.contains(&eid)) {
out.entry(channel).or_insert(category);
}
}
out
}
/// Fold the Channel and Category overwrites (vsk 14, CORD-04 §8) against the settled
/// Roster. Each is judged on itself: its signer holds MANAGE_ROLES and every bit it allows
/// or denies through Roles ranked strictly above its target (a Role's rank, a member's,
/// beneath every Role for `@everyone`). The head is the newest admitted edition, chained
/// from the floor like any Control entity.
#[allow(clippy::too_many_arguments)]
fn fold_overwrites(
community: &CommunityV2,
editions: &[ParsedEdition],
floors: &Floors,
roles: &crate::community::roles::CommunityRoles,
banned: &std::collections::BTreeSet<String>,
sealed: &SealedBy,
heads: &mut Vec<FoldedHead>,
gapped: &mut bool,
) -> Vec<crate::community::roles::Overwrite> {
use crate::community::roles::{OverwriteTarget, Permissions};
let cid = community.id();
let owner_hex = community.owner().ok().map(|o| o.to_hex());
let mut groups: std::collections::BTreeMap<[u8; 32], Vec<(&ParsedEdition, crate::community::roles::Overwrite)>> = Default::default();
for e in editions.iter().filter(|e| e.vsk == vsk::CHANNEL_ACL && e.binding.is_some()) {
let Some(o) = super::roles::parse_overwrite_content(&e.content) else { continue };
let scope = crate::simd::hex::hex_to_bytes_32_checked(&o.scope).expect("parsed");
let Some(target) = super::roles::overwrite_target_bytes(cid, &o.target) else { continue };
if super::derive::acl_locator(cid, &scope, &target) == e.entity_id {
groups.entry(e.entity_id).or_default().push((e, o));
}
}
let mut out = Vec::new();
let mut withheld: std::collections::BTreeSet<[u8; 32]> = Default::default();
// A floored overwrite with no edition served at all is withheld too.
let served: std::collections::BTreeSet<[u8; 32]> = groups.keys().copied().collect();
for (eid, group) in groups {
let ok: Vec<bool> = group
.iter()
.map(|(e, o)| {
let ah = e.author.to_hex();
let rank = match &o.target {
OverwriteTarget::Everyone => u32::MAX,
// An overwrite names a Role that stands, or nothing.
OverwriteTarget::Role(id) => match roles.role(id) {
Some(r) => r.position,
None => return false,
},
// The owner holds everything, in every Channel: nothing to overwrite.
OverwriteTarget::Member(m) if owner_hex.as_deref() == Some(m.as_str()) => return false,
// A banned member holds nothing anywhere (CORD-04 §4).
OverwriteTarget::Member(m) if banned.contains(m) => return false,
OverwriteTarget::Member(m) => roles.highest_position(m).unwrap_or(u32::MAX),
};
if owner_hex.as_deref() == Some(ah.as_str()) {
return true;
}
if banned.contains(&ah) && !is_listed(sealed, &ah, &e.self_hash) {
return false;
}
let support = roles.permissions_above(&ah, rank).0 | seal_of(sealed, &ah, &e.self_hash, rank);
support & Permissions::MANAGE_ROLES != 0 && (o.allow.0 | o.deny.0) & !support == 0
})
.collect();
if !ok.contains(&true) {
continue;
}
let entity_hex = crate::simd::hex::bytes_to_hex_32(&eid);
let rank = |a: &str| fork_rank(roles, owner_hex.as_deref(), a);
let fold_eds: Vec<version::Edition> = group.iter().map(|(p, _)| p.to_fold_edition_ranked(rank(&p.author.to_hex()))).collect();
let floor = floors.get(&entity_hex);
let (hi, gap) = fold_head_among(&fold_eds, floor, &|a| rank(&crate::simd::hex::bytes_to_hex_32(a)), &|i| ok[i]);
*gapped |= gap;
// A held edition that is served but now refused falls back as a reader holding no
// floor would; only one that isn't served at all is kept as held.
let held_served = floor.is_some_and(|f| group.iter().any(|(e, _)| held_is(f, e)));
let (hi, rebased) = match hi {
Some(hi) => (hi, false),
None if held_served => match fold_head_among(&fold_eds, None, &|a| rank(&crate::simd::hex::bytes_to_hex_32(a)), &|i| ok[i]).0 {
Some(hi) => (hi, true),
None => continue,
},
None => {
withheld.insert(eid);
continue;
}
};
let (head, o) = &group[hi];
heads.push(FoldedHead { entity_hex, version: head.version, self_hash: head.self_hash, inner_id: head.inner_id, author: head.author.to_bytes(), rebased });
if o.allow.0 != 0 || o.deny.0 != 0 {
out.push(o.clone());
}
}
// What this device held for an overwrite a relay isn't serving stays as it was: absence
// proves nothing, and the stored roster is what the floor committed to.
let stored = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&cid.0)).unwrap_or_default();
for o in stored.overwrites {
let (Some(scope), Some(target)) = (crate::simd::hex::hex_to_bytes_32_checked(&o.scope), super::roles::overwrite_target_bytes(cid, &o.target)) else { continue };
let eid = super::derive::acl_locator(cid, &scope, &target);
let floored = floors.contains_key(&crate::simd::hex::bytes_to_hex_32(&eid));
if floored && (withheld.contains(&eid) || !served.contains(&eid)) && !out.iter().any(|x| x.scope == o.scope && x.target == o.target) {
out.push(o);
}
}
out
}
/// One candidate edition of a role/grant entity — the pool [`select_authorized`]
/// draws the highest AUTHORIZED head from (exactly one of `role`/`grant` is set).
struct AuthorityCand {
role: Option<crate::community::roles::Role>,
grant: Option<crate::community::roles::MemberGrant>,
/// A Tenure (CORD-04 §9): the member it seals, and each standing at its fold position.
tenure: Option<(String, Vec<Sealed>)>,
/// What a role candidate stands for (grants are always `Live`).
kind: RoleKind,
author: PublicKey,
/// `author` as hex, and the coordinate of their own Grant, which their citation names.
author_hex: String,
grant_hex: String,
head: FoldedHead,
/// The `vac` this edition carried (CORD-04 §5). `None` for an owner edition
/// (supreme, cites nothing) or an uncited one — the latter is refused.
citation: Option<crate::community::edition::AuthorityCitation>,
/// The edition this one names as its predecessor.
prev: Option<[u8; 32]>,
/// Its entity's persisted floor.
floor: Option<Floor>,
/// The entity's held floor edition is among the served candidates.
held_served: bool,
}
/// One sealed standing from a Tenure: editions whose hash it lists are judged as if their
/// author held `bits` through a Role at `position`.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Sealed {
position: u32,
bits: u64,
heads: std::collections::BTreeSet<[u8; 32]>,
}
/// Each member's sealed standings, from the Tenures the fold admits.
type SealedBy = std::collections::BTreeMap<String, Vec<Sealed>>;
/// The bits sealed for `author` over `hash` by every standing ranked above `reach`, as
/// Roles above it would lend them.
fn seal_of(sealed: &SealedBy, author_hex: &str, hash: &[u8; 32], reach: u32) -> u64 {
sealed.get(author_hex).into_iter().flatten().filter(|e| e.position < reach && e.heads.contains(hash)).fold(0, |acc, e| acc | e.bits)
}
/// Some Tenure lists `hash` as `author`'s, at whatever standing.
fn is_listed(sealed: &SealedBy, author_hex: &str, hash: &[u8; 32]) -> bool {
sealed.get(author_hex).is_some_and(|es| es.iter().any(|e| e.heads.contains(hash)))
}
/// What a role-entity edition is, in a Community that folds Roles v2 or doesn't.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum RoleKind {
Live,
/// A Role's terminal deletion: it acts on the Role at the rank it stood at.
Deleted,
/// `@everyone`, beneath every Role.
Everyone,
/// A vsk-1 edition after activation: it links what was built on it, and confers nothing.
History,
}
impl AuthorityCand {
/// The very edition its entity's floor records: version and hash, and the signer's
/// rumor id where the floor has one, since the hash alone admits a re-signed copy.
fn is_held(&self) -> bool {
self.floor.is_some_and(|f| self.head.version == f.0 && self.head.self_hash == f.1 && f.2.is_none_or(|id| id == self.head.inner_id))
}
/// A same-version rival of a withheld held edition that does not beat the key its
/// floor recorded (CORD-04 §1). Taking it would let a relay withholding the better
/// held edition swap in a worse one; a served held edition competes on the tiebreak.
fn loses_to_floor(&self, roles: &crate::community::roles::RoleIndex<'_>, owner_hex: Option<&str>) -> bool {
let Some(floor) = self.floor.as_ref().filter(|_| !self.held_served) else { return false };
if self.head.version != floor.0 || self.head.self_hash == floor.1 {
return false;
}
// Without the held edition its claims are unknown, so no rival can be judged against
// them: only the owner, who acts whatever the rank, stands in for it.
if owner_hex != Some(self.author_hex.as_str()) {
return true;
}
let rank_of = |a: &[u8; 32]| fork_rank_in(roles, owner_hex, &crate::simd::hex::bytes_to_hex_32(a));
let mine = fork_rank_in(roles, owner_hex, &self.author_hex);
!HeldKey::of(floor, &rank_of).beaten_by(mine, &self.head.inner_id)
}
}
/// CORD-04 §5 sync floor, resolved against the heads THIS fold pass has accepted.
///
/// Deliberately not the persisted-head helper the kick/hide paths use: this IS the
/// pass that establishes those heads, so an external floor would refuse every
/// non-owner edition on a bootstrap and the roster could never fold. Same rule the
/// spec gives for a dangling `prev` across a Refounding — a fresh joiner takes the
/// authority-verified head as its baseline, a tracking client fails closed per
/// entity — applied to the citation instead of the chain link.
fn citation_ok_in_fold(
cid: &crate::community::CommunityId,
heads: &HeadIndex<'_>,
owner_hex: Option<&str>,
author: &PublicKey,
citation: Option<&crate::community::edition::AuthorityCitation>,
) -> bool {
citation_ok_against(cid, heads, owner_hex, author, citation)
}
/// A fold's heads by entity, for the citation checks it makes per candidate: the first head held
/// for each entity, as a scan of the list would find it.
struct HeadIndex<'a>(crate::fasthash::FastMap<&'a str, (u64, [u8; 32])>);
impl<'a> HeadIndex<'a> {
fn of(heads: &'a [FoldedHead]) -> Self {
let mut index = crate::fasthash::FastMap::with_capacity_and_hasher(heads.len(), Default::default());
for h in heads {
index.entry(h.entity_hex.as_str()).or_insert((h.version, h.self_hash));
}
HeadIndex(index)
}
}
/// [`citation_ok_against`] for a candidate, whose author's hex and Grant coordinate it carries.
fn citation_ok_of(heads: &HeadIndex<'_>, owner_hex: Option<&str>, c: &AuthorityCand) -> bool {
if owner_hex == Some(c.author_hex.as_str()) {
return true;
}
crate::community::edition::authority_citation_satisfied_by(|e| heads.0.get(e).copied(), owner_hex, &c.author_hex, &c.grant_hex, c.citation.as_ref())
}
/// Whether `citation` holds against a fold's heads (the CORD-04 §5 sync floor).
fn citation_ok_against(
cid: &crate::community::CommunityId,
heads: &HeadIndex<'_>,
owner_hex: Option<&str>,
author: &PublicKey,
citation: Option<&crate::community::edition::AuthorityCitation>,
) -> bool {
let actor_hex = author.to_hex();
if owner_hex == Some(actor_hex.as_str()) {
return true;
}
let grant_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(cid, &author.to_bytes()));
crate::community::edition::authority_citation_satisfied_by(|e| heads.0.get(e).copied(), owner_hex, &actor_hex, &grant_hex, citation)
}
thread_local! {
/// Refusal reasons from the most recent authority fold on this thread — read by
/// the roster diagnostic. Diagnostic only; nothing branches on it.
static AUTHORITY_REFUSALS: std::cell::RefCell<std::collections::BTreeMap<String, &'static str>> =
const { std::cell::RefCell::new(std::collections::BTreeMap::new()) };
}
/// The authorized roster one fold settles on.
struct Selected {
roles: crate::community::roles::CommunityRoles,
heads: Vec<FoldedHead>,
/// Entities whose whole served chain the Roster refuses, judged on a complete fold:
/// settled as absent, not missing, so nothing waits on them.
refused: std::collections::BTreeSet<String>,
/// Entities whose held head is refused with nothing decided to fall back to: kept.
carried: std::collections::BTreeSet<String>,
/// An admitted edition sits above a head out of reach: a link withheld.
gapped: bool,
/// Every role and grant edition the last round admitted.
admitted: crate::fasthash::FastSet<[u8; 32]>,
/// Each member's sealed standings, from the Tenures admitted.
sealed: SealedBy,
/// The fixpoint was reached within its bound.
converged: bool,
}
type Refusals<'w> = Option<&'w mut std::collections::BTreeMap<String, &'static str>>;
fn refuse(why: &mut Refusals<'_>, c: &AuthorityCand, reason: &'static str) -> Option<Option<u32>> {
if let Some(m) = why.as_mut() {
m.insert(c.head.entity_hex.clone(), reason);
}
None
}
/// The owner-seeded delegation fixpoint (CORD-04 §1-§3). Per entity it takes the highest
/// edition its author is authorized to write under the roster resolved so far, dropping
/// an unauthorized higher version rather than vanishing the entity. Every edition is
/// judged only on roles ranked strictly above everything it touches (downward support),
/// so each decision rests on decisions above it, the fold has exactly one answer, and
/// this Jacobi iteration reaches it within one round per level. The heads it returns are
/// the floors to advance: an unauthorized forgery never poisons one.
#[allow(clippy::too_many_arguments)]
fn select_authorized(
cid: &crate::community::CommunityId,
role_cands: &std::collections::BTreeMap<String, Vec<AuthorityCand>>,
grant_cands: &std::collections::BTreeMap<String, Vec<AuthorityCand>>,
tenure_cands: &std::collections::BTreeMap<String, Vec<AuthorityCand>>,
owner_hex: Option<&str>,
excluded: &std::collections::BTreeSet<String>,
// The authority fold is complete (see `fold_authority`): a served held head the Roster
// refuses may then fall back below its floor, or settle as refused.
complete: bool,
// Why each entity was refused, for diagnosis: every gate is otherwise silent.
mut why: Refusals<'_>,
) -> Selected {
use crate::community::roles::{CommunityRoles, Permissions};
let mut accepted = CommunityRoles::default();
let mut heads: Vec<FoldedHead> = Vec::new();
let mut refused: std::collections::BTreeSet<String> = Default::default();
let mut carried: std::collections::BTreeSet<String> = Default::default();
let mut gapped = false;
let mut admitted: crate::fasthash::FastSet<[u8; 32]> = Default::default();
let mut sealed: SealedBy = Default::default();
let mut converged = false;
let everyone_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::everyone_locator(cid));
let bound = 2 * (role_cands.len() + grant_cands.len() + tenure_cands.len()) + 8;
#[cfg(test)]
let bound = tests::FOLD_BOUND.with(|b| b.get()).unwrap_or(bound);
let mut scratch = ReplayScratch::default();
for _ in 0..bound {
let mut next = CommunityRoles::default();
let mut next_heads: Vec<FoldedHead> = Vec::new();
let mut next_refused: std::collections::BTreeSet<String> = Default::default();
let mut next_carried: std::collections::BTreeSet<String> = Default::default();
let mut next_gapped = false;
let mut next_admitted: crate::fasthash::FastSet<[u8; 32]> = crate::fasthash::FastSet::with_capacity_and_hasher(admitted.len(), Default::default());
let mut next_sealed: SealedBy = Default::default();
let cite_heads = HeadIndex::of(&heads);
let standing = crate::community::roles::RoleIndex::of(&accepted);
// A ban takes what its target wrote, but not what a Tenure sealed (CORD-04 §9).
let voided = |cands: &[AuthorityCand]| {
held_banned(cands, excluded) && !cands.first().and_then(|c| c.floor).is_some_and(|f| f.3.is_some_and(|a| is_listed(&sealed, &crate::simd::hex::bytes_to_hex_32(&a), &f.1)))
};
// What an author holds above `reach` for this edition: their Roles, and the standing a
// Tenure sealed it at.
let support_for = |ah: &str, c: &AuthorityCand, reach: u32| -> Permissions {
Permissions(standing.permissions_above(ah, reach).0 | seal_of(&sealed, ah, &c.head.self_hash, reach))
};
for (entity, cands) in tenure_cands {
let claims = |c: &AuthorityCand| c.tenure.iter().flat_map(|(_, es)| es.iter().map(|e| e.position)).min();
let mut judge = |c: &AuthorityCand, _reach: u32| -> Option<Option<u32>> {
let (member, entries) = c.tenure.as_ref()?;
let ah = c.author_hex.as_str();
let is_sealed = is_listed(&sealed, ah, &c.head.self_hash);
if excluded.contains(ah) && !is_sealed {
return refuse(&mut why, c, "tenure: author banned");
}
// Written by whoever reduces the member: never by the member, and the owner
// needs none.
if member == ah || owner_hex == Some(member.as_str()) {
return refuse(&mut why, c, "tenure: written by its own member, or for the owner");
}
if owner_hex != Some(ah) {
// Each standing is one the writer could grant: beneath them, with bits
// they hold above it.
let can = entries.iter().all(|e| {
let support = support_for(ah, c, e.position);
support.contains(Permissions::MANAGE_ROLES) && e.bits & !support.0 == 0
});
if !can {
return refuse(&mut why, c, "tenure: seals a standing its writer couldn't grant");
}
}
// A sealed edition stands on its Tenure, not on the Grant it cited.
if !is_sealed && !citation_ok_of(&cite_heads, owner_hex, c) && c.citation.is_some() {
return refuse(&mut why, c, "tenure: cited a grant we cannot resolve");
}
Some(None)
};
let (picked, gap) = replay(cands, &standing, owner_hex, complete, voided(cands), &claims, &mut judge, &mut next_admitted, &mut scratch);
next_gapped |= gap;
let j = match picked {
Picked::Head(j, rebased) => {
next_heads.push(FoldedHead { rebased, ..cands[j].head.clone() });
j
}
Picked::Carried(j) => {
next_heads.push(cands[j].head.clone());
next_carried.insert(entity.clone());
j
}
Picked::Refused => {
next_refused.insert(entity.clone());
continue;
}
Picked::Nothing => continue,
};
if let Some((member, entries)) = cands[j].tenure.clone() {
next_sealed.entry(member).or_default().extend(entries);
}
}
for (entity, cands) in role_cands {
// A deletion and a legacy edition claim no rank: they act at the one the Role stood at.
let claims = |c: &AuthorityCand| match c.kind {
RoleKind::Deleted | RoleKind::History => None,
_ => c.role.iter().map(|r| r.position).min(),
};
let mut judge = |c: &AuthorityCand, reach: u32| -> Option<Option<u32>> {
let role = c.role.as_ref()?;
let ah = c.author_hex.as_str();
if c.kind == RoleKind::History {
return refuse(&mut why, c, "role: a vsk-1 edition after Roles v2 activated");
}
let is_sealed = is_listed(&sealed, ah, &c.head.self_hash);
if (excluded.contains(ah) && !is_sealed) || role.position == 0 {
return refuse(&mut why, c, "role: author banned or position 0");
}
if owner_hex != Some(ah) {
// MANAGE_ROLES and every carried bit from roles above the reach: both
// rank gates at once (the rank claimed and the rank replaced).
let support = support_for(ah, c, reach);
if !support.contains(Permissions::MANAGE_ROLES) {
return refuse(&mut why, c, "role: author holds no MANAGE_ROLES above what it touches");
}
// Judged on this edition alone, so a compacted head folds the same for
// every reader.
if role.permissions.0 & !support.0 != 0 {
return refuse(&mut why, c, "role: carries a permission its author lacks");
}
}
// A `vac` is a sync floor, not the verdict (CORD-04 §5): a citation we
// can't resolve parks, while an uncited edition declared no floor to wait
// for. The rank gates above already passed either way.
if !is_sealed && !citation_ok_of(&cite_heads, owner_hex, c) && c.citation.is_some() {
return refuse(&mut why, c, "role: cited a grant we cannot resolve");
}
Some((c.kind != RoleKind::Deleted).then_some(role.position))
};
let (picked, gap) = replay(cands, &standing, owner_hex, complete, voided(cands), &claims, &mut judge, &mut next_admitted, &mut scratch);
next_gapped |= gap;
// Deletion is terminal over the authorized chain, not the head alone (CORD-04 §2):
// once one stands, the Role is gone whatever was written after it.
// A deletion acts on the Role at every rank it holds from the deletion on, so one
// backdated beneath a Role's later life can't reach above its signer.
let deletion = cands
.iter()
.enumerate()
.filter(|(_, c)| c.kind == RoleKind::Deleted && next_admitted.contains(&c.head.inner_id))
.filter(|(_, d)| {
let later = cands
.iter()
.filter(|c| c.kind == RoleKind::Live && c.head.version >= d.head.version && next_admitted.contains(&c.head.inner_id))
.filter_map(|c| c.role.as_ref().map(|r| r.position))
.min();
later.is_none_or(|reach| judge(d, reach).is_some())
})
.max_by_key(|(_, c)| (c.head.version, std::cmp::Reverse(c.head.inner_id)))
.map(|(j, _)| j);
if let Some(j) = deletion {
let below = cands[j].floor.is_some_and(|f| cands[j].head.version < f.0 || (cands[j].head.version == f.0 && !cands[j].is_held()));
next_heads.push(FoldedHead { rebased: below, ..cands[j].head.clone() });
continue;
}
let keep = |j: usize, next: &mut CommunityRoles| {
let role = cands[j].role.clone().expect("a role candidate");
match cands[j].kind {
RoleKind::Everyone => {
next.everyone = Some(role.permissions);
next.legacy_channels = role.extra.get(EVERYONE_LEGACY).and_then(|l| serde_json::from_value(l.clone()).ok());
}
RoleKind::Live => next.roles.push(role),
// Kept as the head, standing for nothing.
RoleKind::Deleted | RoleKind::History => {}
}
};
match picked {
Picked::Head(j, rebased) => {
keep(j, &mut next);
next_heads.push(FoldedHead { rebased, ..cands[j].head.clone() });
}
Picked::Carried(j) => {
keep(j, &mut next);
next_heads.push(cands[j].head.clone());
next_carried.insert(entity.clone());
}
Picked::Refused => {
next_refused.insert(entity.clone());
}
Picked::Nothing => {}
}
}
for (entity, cands) in grant_cands {
// A grant confers the roles it names that resolve. It is judged on what it
// names, never on whether those resolve, so no role can hinge on its absence.
let claims = |c: &AuthorityCand| {
c.grant.iter().flat_map(|g| g.role_ids.iter()).filter(|rid| **rid != everyone_hex).filter_map(|rid| standing.role(rid).map(|r| r.position)).min()
};
let mut judge = |c: &AuthorityCand, reach: u32| -> Option<Option<u32>> {
let grant = c.grant.as_ref()?;
let ah = c.author_hex.as_str();
let is_sealed = is_listed(&sealed, ah, &c.head.self_hash);
if (excluded.contains(ah) && !is_sealed) || excluded.contains(&grant.member) {
return refuse(&mut why, c, "grant: author or member banned");
}
// An uncited edition may add authority, fully rank-checked, but one that
// names no Role anyone has published is a strip, and a strip must cite.
if !is_sealed && !citation_ok_of(&cite_heads, owner_hex, c) {
if c.citation.is_some() {
return refuse(&mut why, c, "grant: cited a grant we cannot resolve");
}
if grant.role_ids.iter().all(|rid| *rid == everyone_hex || !role_cands.contains_key(rid)) {
return refuse(&mut why, c, "grant: UNCITED revocation — a strip must cite its authority");
}
}
// MANAGE_ROLES from roles above the reach. That also rules out a
// self-grant: nothing of yours sits above your own standing. The owner
// is never a target.
let ok = owner_hex == Some(ah)
|| (owner_hex != Some(grant.member.as_str()) && support_for(ah, c, reach).contains(Permissions::MANAGE_ROLES));
if !ok {
return refuse(&mut why, c, "grant: author holds no MANAGE_ROLES above the roles or the member");
}
Some(claims(c))
};
// A banned member holds nothing, whatever their grant's history (CORD-04 §4).
if cands.first().and_then(|c| c.grant.as_ref()).is_some_and(|g| excluded.contains(&g.member)) {
next_refused.insert(entity.clone());
continue;
}
let (picked, gap) = replay(cands, &standing, owner_hex, complete, voided(cands), &claims, &mut judge, &mut next_admitted, &mut scratch);
next_gapped |= gap;
let (j, rebased) = match picked {
Picked::Head(j, rebased) => (j, rebased),
Picked::Carried(j) => {
next_carried.insert(entity.clone());
(j, false)
}
Picked::Refused => {
next_refused.insert(entity.clone());
continue;
}
Picked::Nothing => continue,
};
// A revoke still records its head: it is a real chain advance.
next_heads.push(FoldedHead { rebased, ..cands[j].head.clone() });
if let Some(grant) = &cands[j].grant {
let ids: Vec<String> = grant.role_ids.iter().filter(|rid| **rid != everyone_hex && standing.role(rid).is_some()).cloned().collect();
if !ids.is_empty() {
next.grants.push(crate::community::roles::MemberGrant { member: grant.member.clone(), role_ids: ids });
}
}
}
// Heads count too: a citation is judged against the heads of the round before.
let same_heads = next_heads.len() == heads.len()
&& next_heads.iter().zip(&heads).all(|(a, b)| (&a.entity_hex, a.self_hash, a.inner_id, a.rebased) == (&b.entity_hex, b.self_hash, b.inner_id, b.rebased));
let settled = same_heads && next.roles == accepted.roles && next.grants == accepted.grants && next.everyone == accepted.everyone && next.legacy_channels == accepted.legacy_channels && next_sealed == sealed;
accepted = next;
sealed = next_sealed;
heads = next_heads;
refused = next_refused;
carried = next_carried;
gapped = next_gapped;
admitted = next_admitted;
if settled {
converged = true;
break;
}
}
Selected { roles: accepted, heads, refused, carried, gapped, admitted, sealed, converged }
}
/// The signer the entity's floor records is banned: the held edition is gone with
/// everything else they wrote, served or not.
fn held_banned(cands: &[AuthorityCand], excluded: &std::collections::BTreeSet<String>) -> bool {
cands.first().and_then(|c| c.floor).and_then(|f| f.3).is_some_and(|a| excluded.contains(&crate::simd::hex::bytes_to_hex_32(&a)))
}
/// An author's authority for ordering a version's siblings, read only from roles ranked
/// above `reach`: the same standing the sibling is judged on, so the order can't lean on
/// authority the decision itself creates.
fn fork_rank_above(roles: &crate::community::roles::RoleIndex<'_>, owner_hex: Option<&str>, author_hex: &str, reach: u32) -> u32 {
if owner_hex == Some(author_hex) {
return 0;
}
roles.highest_position_above(author_hex, reach).unwrap_or(u32::MAX)
}
enum Picked {
/// The head's index, and whether it sits below the floor because the held head was refused.
Head(usize, bool),
/// The held head is the genesis, served, and refused on a complete fold.
Refused,
/// The held head, refused on what is served but with nothing decided to fall back to.
Carried(usize),
Nothing,
}
/// What an edition's successor stands on: the rank its nearest admitted ancestor confers,
/// and whether that is known on evidence.
#[derive(Clone, Copy)]
struct Stand {
standing: Option<u32>,
proven: bool,
}
/// An entity's editions by hash, each hash's in `cands` order.
#[derive(Default)]
struct HashGroups {
at: crate::fasthash::FastMap<[u8; 32], (u32, u32)>,
order: Vec<usize>,
}
impl HashGroups {
fn build(&mut self, n: usize, hash: impl Fn(usize) -> [u8; 32]) {
self.at.clear();
self.order.clear();
self.order.extend(0..n);
// Stable, so a hash's indices keep their order.
self.order.sort_by_key(|&j| hash(j));
let mut i = 0;
while i < self.order.len() {
let h = hash(self.order[i]);
let run = self.order[i..].iter().take_while(|&&j| hash(j) == h).count();
self.at.insert(h, (i as u32, run as u32));
i += run;
}
}
fn get(&self, h: &[u8; 32]) -> Option<&[usize]> {
self.at.get(h).map(|&(start, len)| &self.order[start as usize..(start + len) as usize])
}
}
/// What [`replay`] works in, kept across the entities and rounds of one fold: it is filled
/// afresh on every call, so only its allocations carry over.
#[derive(Default)]
struct ReplayScratch {
by_hash: HashGroups,
admitted: Vec<bool>,
sure: Vec<bool>,
conf: Vec<Option<Option<u32>>>,
stand: Vec<Stand>,
key: Vec<(u32, [u8; 32])>,
viable: Vec<bool>,
runs: crate::fasthash::FastMap<([u8; 32], u64), (Option<u32>, bool)>,
reachable: Vec<bool>,
}
fn refill<T: Clone>(v: &mut Vec<T>, n: usize, value: T) {
v.clear();
v.resize(n, value);
}
/// One entity's chain, replayed ascending (CORD-04 §1/§3), and its head. Each version acts
/// on what the newest admitted version below it left: never on what its own `prev` names,
/// which its author chooses and so could point at a branch where nothing stood. A link
/// adds to that only when it reaches evidence in hand: through editions the Roster
/// refuses (each perhaps a copy of one that stands, so the stricter rank counts) down to
/// an admitted one, or to the genesis below this device's own held edition. A link names
/// the version directly beneath. `judge` returns the rank an admitted edition confers.
/// Candidates arrive version-DESC. Also returns whether an admitted edition above the
/// head is out of reach, which is a link withheld and worth paging for.
#[allow(clippy::too_many_arguments)]
fn replay(
cands: &[AuthorityCand],
accepted: &crate::community::roles::RoleIndex<'_>,
owner_hex: Option<&str>,
complete: bool,
// The held edition's signer is banned: everything they wrote is gone, the floor with it.
voided: bool,
// The strictest rank an edition claims.
claims: &dyn Fn(&AuthorityCand) -> Option<u32>,
judge: &mut dyn FnMut(&AuthorityCand, u32) -> Option<Option<u32>>,
// Every edition this replay admits, collected for the caller.
admitted_out: &mut crate::fasthash::FastSet<[u8; 32]>,
scratch: &mut ReplayScratch,
) -> (Picked, bool) {
#[cfg(test)]
let mut fresh = ReplayScratch::default();
#[cfg(test)]
let scratch = if tests::FRESH_SCRATCH.with(|f| f.get()) { &mut fresh } else { scratch };
let n = cands.len();
let Some(first) = cands.first() else { return (Picked::Nothing, false) };
let floor = first.floor;
let is_owner = |c: &AuthorityCand| owner_hex == Some(c.author_hex.as_str());
let ReplayScratch { by_hash, admitted, sure, conf, stand, key, viable, runs, reachable } = scratch;
by_hash.build(n, |j| cands[j].head.self_hash);
let by_hash = &*by_hash;
// Copies of one hash share version, predecessor and content; any admitted one stands.
let node = |h: &[u8; 32], at: u64| by_hash.get(h).filter(|js| cands[js[0]].head.version == at);
refill(admitted, n, false);
refill(sure, n, false);
refill(conf, n, None);
refill(stand, n, Stand { standing: None, proven: false });
refill(key, n, (u32::MAX, [0u8; 32]));
refill(viable, n, false);
runs.clear();
// What the newest admitted version left.
let mut base: Option<u32> = None;
let mut i = n;
while i > 0 {
let hi = i;
let ver = cands[i - 1].head.version;
while i > 0 && cands[i - 1].head.version == ver {
i -= 1;
}
for j in i..hi {
let (constraint, proven) = match cands[j].prev {
None => (None, ver == 1),
Some(h) => *runs.entry((h, ver)).or_insert_with(|| link_run(cands, h, ver, by_hash, sure, conf, claims)),
};
stand[j] = Stand { standing: stricter(base, constraint), proven };
}
let own = |j: usize| claims(&cands[j]).into_iter().chain(stand[j].standing).min().unwrap_or(u32::MAX);
// A sibling that fails even on its own is out of the running: it can't make the
// version stricter for the rest.
for j in i..hi {
viable[j] = !cands[j].loses_to_floor(accepted, owner_hex) && (hi - i == 1 || judge(&cands[j], own(j)).is_some());
}
// One reach for the version: the strictest rank any viable sibling claims or stands
// on, so a low claim can't lean on authority its own sibling's acceptance creates.
let reach = (i..hi).filter(|&j| viable[j]).map(own).min().unwrap_or(u32::MAX);
for j in i..hi {
let c = &cands[j];
key[j] = (fork_rank_above(accepted, owner_hex, &c.author_hex, reach), c.head.inner_id);
conf[j] = if viable[j] { judge(c, reach) } else { None };
admitted[j] = conf[j].is_some();
// Decided on evidence: judged with what stood beneath it in hand, signed by the owner,
// or the version this device settled on.
sure[j] = admitted[j] && (stand[j].proven || is_owner(c) || floor.is_some_and(|f| f.0 == ver));
if admitted[j] {
admitted_out.insert(c.head.inner_id);
}
}
if let Some(w) = (i..hi).filter(|&j| admitted[j]).min_by_key(|&j| key[j]) {
base = conf[w].flatten();
}
}
let best = |ok: &dyn Fn(usize) -> bool| -> Option<usize> {
let top = (0..n).filter(|&j| ok(j)).map(|j| cands[j].head.version).max()?;
(0..n).filter(|&j| ok(j) && cands[j].head.version == top).min_by_key(|&j| key[j])
};
let Some(f) = floor.filter(|_| !voided) else {
if let Some(j) = best(&|j| admitted[j]) {
return (Picked::Head(j, voided && !cands[j].is_held()), false);
}
if !voided {
return (Picked::Nothing, false);
}
// Nothing stands once the banned signer's editions are gone, which is what a reader
// holding no floor folds too. Page for what stood before them unless the held chain
// already reads down to its genesis; a chain ending at a compaction pages in vain,
// but nothing waits on it.
let mut at = (0..n).find(|&j| cands[j].is_held());
for _ in 0..HELD_CHAIN_CAP {
let Some(j) = at else { break };
let Some(p) = cands[j].prev else { return (Picked::Refused, false) };
at = cands[j].head.version.checked_sub(1).and_then(|v| node(&p, v)).map(|js| js[0]);
}
return (Picked::Refused, true);
};
// Reachable from the floor along served links: its version (bar a rival that doesn't
// beat the held key), then whatever names the held hash or a reachable edition.
refill(reachable, n, false);
// Ascending, so a link's target one version down is decided before what names it.
for j in (0..n).rev() {
let c = &cands[j];
reachable[j] = match c.head.version.cmp(&f.0) {
std::cmp::Ordering::Less => false,
std::cmp::Ordering::Equal => !c.loses_to_floor(accepted, owner_hex),
std::cmp::Ordering::Greater => c.prev.is_some_and(|h| {
(Some(c.head.version) == f.0.checked_add(1) && h == f.1) || node(&h, c.head.version - 1).is_some_and(|js| js.iter().any(|&k| reachable[k]))
}),
};
}
let gap_above = |v: u64| (0..n).any(|j| admitted[j] && !reachable[j] && cands[j].head.version > v);
// Above the floor an edition stands on evidence: a withheld link leaves the rank it
// acts on unknown, and only the owner acts regardless of rank.
let advance = |j: usize| reachable[j] && admitted[j] && (cands[j].head.version == f.0 || stand[j].proven || is_owner(&cands[j]));
if let Some(j) = best(&advance) {
return (Picked::Head(j, false), gap_above(cands[j].head.version));
}
// The held edition itself is refused. On a complete fold it falls back to the
// predecessor it names, when a served copy of that stands on evidence; a genesis has
// none. A floor recorded without the signer's id can't tell its edition from a copy.
if !first.held_served {
return (Picked::Nothing, false);
}
let Some(held) = (0..n).find(|&j| cands[j].is_held()) else { return (Picked::Nothing, false) };
let gap = gap_above(f.0);
if complete && f.2.is_some() {
let Some(p) = cands[held].prev else { return (Picked::Refused, gap) };
let own = |j: usize| claims(&cands[j]).into_iter().chain(stand[j].standing).min().unwrap_or(u32::MAX);
// Stepping down is judged no lower than the held edition reached, so the choice
// between keeping it and its predecessor rests only on authority above both.
let floor_reach = own(held);
let target = node(&p, f.0.wrapping_sub(1)).and_then(|js| {
js.iter()
.copied()
.filter(|&k| sure[k])
.filter(|&k| judge(&cands[k], own(k).min(floor_reach)).is_some())
.min_by_key(|&k| key[k])
});
if let Some(k) = target {
return (Picked::Head(k, true), gap);
}
}
// Refused on what is served, with nothing decided to fall back to: it stays as held.
(Picked::Carried(held), gap)
}
/// How far a link walk goes before it counts as unresolved.
const LINK_RUN_CAP: usize = 64;
/// How far a voided floor's chain is read for its genesis before it counts as unresolved.
const HELD_CHAIN_CAP: usize = 4096;
/// What naming `h` at version `ver` adds to the rank an edition acts on, and whether that
/// rests on evidence in hand: the walk passes editions the Roster refuses, keeping the
/// strictest rank each could confer, and ends at an admitted copy (proving only as much as
/// that copy was itself decided on evidence), at the genesis below this device's held
/// edition, or unresolved. A walk of refused copies down to a genesis this device never
/// held proves nothing: anyone can serve one.
fn link_run(
cands: &[AuthorityCand],
mut h: [u8; 32],
ver: u64,
by_hash: &HashGroups,
sure: &[bool],
conf: &[Option<Option<u32>>],
claims: &dyn Fn(&AuthorityCand) -> Option<u32>,
) -> (Option<u32>, bool) {
let (mut acc, mut through_held, mut at) = (None, false, ver);
for _ in 0..LINK_RUN_CAP {
let Some(js) = by_hash.get(&h).filter(|js| cands[js[0]].head.version.checked_add(1) == Some(at)) else { return (None, false) };
if let Some(&k) = js.iter().find(|&&k| conf[k].is_some()) {
return (stricter(acc, conf[k].flatten()), js.iter().any(|&k| sure[k]));
}
through_held |= js.iter().any(|&k| cands[k].is_held());
acc = stricter(acc, claims(&cands[js[0]]).into_iter().min());
at = cands[js[0]].head.version;
match cands[js[0]].prev {
Some(p) => h = p,
None => return if through_held { (acc, true) } else { (None, false) },
}
}
(None, false)
}
/// The stricter of two ranks a successor could stand on; `None` binds nothing.
fn stricter(a: Option<u32>, b: Option<u32>) -> Option<u32> {
match (a, b) {
(Some(x), Some(y)) => Some(x.min(y)),
(x, None) => x,
(None, y) => y,
}
}
/// Apply a folded community-metadata head. Relays only overwrite when the edition
/// carries a non-empty list (a metadata edition that omits relays must not blank
/// the working set). Returns whether anything changed.
fn apply_community_metadata(out: &mut CommunityV2, meta: control::CommunityMetadata) -> bool {
let mut changed = false;
if out.name != meta.name {
out.name = meta.name;
changed = true;
}
if out.description != meta.description {
out.description = meta.description;
changed = true;
}
// Icon/banner apply verbatim, None included — an edition is the full
// document, so an absent image IS a removal (editors preserve via
// `CommunityV2::metadata()`).
if out.icon != meta.icon {
out.icon = meta.icon;
changed = true;
}
if out.banner != meta.banner {
out.banner = meta.banner;
changed = true;
}
// Client-extensible + unknown fields ride the fold verbatim so our own
// editions can carry them forward (CORD-02 §6).
if out.meta_custom != meta.custom {
out.meta_custom = meta.custom;
changed = true;
}
if out.meta_extra != meta.extra {
out.meta_extra = meta.extra;
changed = true;
}
// CAP on the way in. `cap_relays` is the truncate-on-read invariant for every
// other construction boundary, and the fold is a boundary like any other: an
// authorized editor is not a trusted one, and an oversize list costs every
// member a fan-out on each publish and the slowest of N on each fetch
// (CORD-02 §6 makes trimming explicitly a client's call). Compare against the
// CAPPED list too — against the raw one, an oversize edition never compares
// equal, so every fold would report a change and re-save forever.
let relays = crate::community::cap_relays(meta.relays);
if !relays.is_empty() && out.relays != relays {
out.relays = relays;
changed = true;
}
changed
}
/// Apply a folded channel-metadata head: delete removes the channel, a rename
/// updates an existing one, a brand-new PUBLIC channel is added, and a brand-new
/// PRIVATE one is recorded KEYLESS (unreadable until its key arrives over the
/// rekey plane or a fresh bundle). Returns whether anything changed.
fn apply_category_metadata(out: &mut CommunityV2, id: [u8; 32], meta: control::CategoryMetadata) -> bool {
if meta.deleted == Some(true) {
let before = out.categories.len();
out.categories.retain(|c| c.id != id);
return out.categories.len() != before;
}
let mut name = meta.name;
control::cut_name(&mut name);
let position = meta.position.filter(|k| crate::community::rank::is_rank_key(k));
let next = super::community::CategoryV2 { id, name, position, extra: meta.extra };
let changed = match out.categories.iter_mut().find(|c| c.id == id) {
Some(c) if *c == next => false,
Some(c) => {
*c = next;
true
}
None => {
out.categories.push(next);
true
}
};
// Past the cap, the lowest ids stand: the same set however the heads arrived.
if out.categories.len() > super::community::MAX_CATEGORIES {
out.categories.sort_by(|a, b| a.id.cmp(&b.id));
let dropped = out.categories.split_off(super::community::MAX_CATEGORIES);
return !dropped.iter().any(|c| c.id == id);
}
changed
}
/// Fold a sealed head (CORD-03 §2): the Channel stands as private, and its fields come once
/// this device opens the seal ([`unseal_held`]).
fn apply_sealed_channel_metadata(out: &mut CommunityV2, id: ChannelId, s: &control::SealedChannelMeta, raw: &str, prev: Option<[u8; 32]>) -> bool {
if s.deleted {
let before = out.channels.len();
out.channels.retain(|c| c.id.0 != id.0);
return out.channels.len() != before;
}
let sealed = Some(super::community::SealedMeta { epoch: s.epoch, raw: raw.to_string(), open: false, junk: false, prev: prev.map(|p| crate::simd::hex::bytes_to_hex_32(&p)) });
match out.channels.iter_mut().find(|c| c.id.0 == id.0) {
// Public → private (CORD-03 §2): keyless until a rotation delivers its key, which the
// rekey walk looks for from the first channel epoch, as for a Channel met fresh.
// Public → private (CORD-03 §2): keyless until the rotation that minted its key, which the
// rekey walk looks for at the sealed edition's own epoch.
Some(existing) if !existing.private => {
existing.private = true;
existing.key = None;
existing.epoch = Epoch(s.epoch.saturating_sub(1));
existing.sealed = sealed;
true
}
Some(existing) if existing.sealed.as_ref().is_some_and(|h| h.raw == raw) => false,
Some(existing) => {
existing.sealed = sealed;
true
}
None => {
out.channels.push(ChannelV2 { id, name: String::new(), private: true, key: None, epoch: Epoch(0), voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed });
true
}
}
}
/// Open what this device can of its Private Channels' sealed metadata, with the key of the
/// epoch each is sealed under. A seal that key can't open is junk: the details last read stay.
/// Returns whether anything changed.
pub(crate) fn unseal_held(community: &mut CommunityV2) -> bool {
let held = community.clone();
let mut changed = false;
for ch in community.channels.iter_mut() {
// Junk is tried again each time: the key held for its epoch may have changed.
let Some(s) = ch.sealed.clone().filter(|s| !s.open) else { continue };
let Some(conv) = held.channel(&ch.id).and_then(|c| channel_conv_key_at(&held, c, s.epoch)) else { continue };
let prev = s.prev.as_deref().and_then(crate::simd::hex::hex_to_bytes_32_checked);
let opened = control::parse_sealed_channel_meta(&s.raw).and_then(|parsed| control::open_sealed_channel_meta(&parsed, &conv, prev.as_ref()));
match opened.map(control::sanitize_channel_metadata) {
Some(meta) => {
ch.name = meta.name;
ch.voice = meta.voice;
ch.meta_custom = meta.custom;
ch.meta_extra = meta.extra;
ch.sealed = Some(super::community::SealedMeta { open: true, junk: false, ..s });
}
None if s.junk => continue,
None => ch.sealed = Some(super::community::SealedMeta { junk: true, ..s }),
}
changed = true;
}
changed
}
fn apply_channel_metadata(out: &mut CommunityV2, id: ChannelId, meta: control::ChannelMetadata) -> bool {
let deleted = meta.deleted.unwrap_or(false);
if deleted {
let before = out.channels.len();
out.channels.retain(|c| c.id.0 != id.0);
return out.channels.len() != before;
}
match out.channels.iter_mut().find(|c| c.id.0 == id.0) {
Some(existing) => {
let mut changed = false;
if existing.name != meta.name {
existing.name = meta.name;
changed = true;
}
// vsk-2 fields Vector doesn't drive still fold + persist, so a later
// local edit republishes them instead of wiping (CORD-02 §6).
if existing.voice != meta.voice {
existing.voice = meta.voice;
changed = true;
}
if existing.meta_custom != meta.custom {
existing.meta_custom = meta.custom;
changed = true;
}
if existing.meta_extra != meta.extra {
existing.meta_extra = meta.extra;
changed = true;
}
if existing.sealed.take().is_some() {
changed = true;
}
// The owner's edition authoritatively declares visibility. A channel the
// owner marks PUBLIC must derive from the root (key = None) — this heals a
// bundle-time misclassification where an attacker set a public channel's
// grant key to their own, silently addressing it at a plane only they read.
// A plain edition never makes a Channel private: that takes the sealed form and its
// key rotation (CORD-03 §2).
if !meta.private && (existing.private || existing.key.is_some()) {
existing.private = false;
existing.key = None;
changed = true;
}
changed
}
None if !meta.private => {
// A public channel derives its Chat Plane from the community_root at the
// current root epoch (key = None); its stored epoch mirrors the root.
out.channels.push(ChannelV2 {
id,
name: meta.name,
private: false,
key: None,
epoch: out.root_epoch,
voice: meta.voice,
meta_custom: meta.custom,
meta_extra: meta.extra,
writers: None,
sealed: None,
});
true
}
None => {
// A brand-new PRIVATE channel: record it KEYLESS at epoch 0 (the root
// generation — CORD-03 §2 numbers the first private key epoch 1). The
// epoch then doubles as [`follow_rekeys`]' scan cursor. Until a rotation
// delivers a key, every read/send/subscribe path skips the channel; the
// root-fallback in `channel_secret` is never taken for it.
out.channels.push(ChannelV2 {
id,
name: meta.name,
private: true,
key: None,
epoch: Epoch(0),
voice: meta.voice,
meta_custom: meta.custom,
meta_extra: meta.extra,
writers: None,
sealed: None,
});
true
}
}
}
// ── Live rekey-follow (CORD-06 §2/§3) ────────────────────────────────────────
/// The outcome of a rekey-follow pass.
pub struct RekeyFollow {
/// The community after adopting every rotation it could catch up on, or `None`
/// if nothing advanced.
pub updated: Option<CommunityV2>,
/// A base rotation removed us — the caller tears the local hold down (the
/// updated community is not persisted in that case).
pub self_removed: bool,
/// When that rotation was sent, in ms: the eviction's own time.
pub removed_at: Option<u64>,
/// An owner tombstone sits on the dissolved plane (CORD-02 §9) — the local
/// flag is already set; the caller surfaces the death and stops following.
pub dissolved: bool,
/// A complete authorized rotation carried a blob AT OUR LOCATOR that would
/// not open (a width this build predates, a rotator bug, or a deliberately
/// undecryptable blob planted to pass an admissibility check while severing
/// us). Never a removal (CORD-06 §2: removal is the ABSENCE of a blob), so
/// the walk parks — but the park is otherwise indistinguishable from "no
/// rotation happened", which is exactly what makes it abusable. Surfaced so
/// the user learns their key delivery is broken while the prior root still
/// reaches everyone.
pub wedged: bool,
}
/// The most archived base roots a channel-rekey lookup fans across per step. A
/// standalone rekey rides the minter's then-current root and a removal's rides the
/// PRIOR root (CORD-06 §3), so a follower whose base already advanced must look
/// back. A channel stranded DEEPER than this (its next-epoch crate addressed under
/// an older root than the fan reaches) only heals via a fresh invite bundle — the
/// walk is strictly sequential, so a later rotation can't be reached either.
const MAX_ADDRESSING_ROOTS: usize = 8;
/// The base roots a channel rekey may be addressed under, freshest first: the
/// current root plus the archived priors, capped at [`MAX_ADDRESSING_ROOTS`].
/// CORD-06 D2: a removal-forced channel rekey rides the PRIOR root — so the
/// follower's fetch fan ([`follow_rekeys`]) and the stream-auth registration
/// (`streamauth::register_community`) MUST cover the SAME set. A plane the
/// fetch addresses but auth never registered is invisible on an AUTH-gating
/// relay: the REQ is CLOSED, the rotation crate never arrives, and the channel
/// wedges at its old epoch while the base advances.
pub(crate) fn channel_rekey_addressing_roots(cur_root: [u8; 32], cid_hex: &str) -> Vec<[u8; 32]> {
let mut roots: Vec<[u8; 32]> = vec![cur_root];
let mut archived = crate::db::community::held_epoch_keys(cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX)
.unwrap_or_default();
archived.sort_by_key(|a| std::cmp::Reverse(a.0 .0));
for (_, r) in archived {
if !roots.contains(&r) {
roots.push(r);
}
}
roots.truncate(MAX_ADDRESSING_ROOTS);
roots
}
/// Follow rekeys for a held community: advance the base (root) epoch and each
/// Private channel's epoch as far as authorized rotations allow, adopting the
/// fresh key we're still a recipient of at each step and dropping a scope we've
/// been removed from. Persists the result. Called when a rekey wrap arrives in
/// realtime so a long-running bot keeps decrypting after a rotation instead of
/// going silent.
///
/// **Authority (CORD-06 §Authority):** a BASE rotation is honored from the owner
/// or any `BAN` holder, and a CHANNEL rotation from the owner or a
/// `MANAGE_CHANNELS` holder — both under the PERSISTED roster (folded by
/// `follow_control`), minus the banlist, so an admin-created private channel
/// keys up on every member. Concluding OUR OWN removal takes more than the bit:
/// the rotator must strictly outrank us (`*_outranks_me`), so an equal-rank
/// admin can never evict a peer by minting a rotation that skips their blob.
///
/// **Addressing fans across held base roots:** each channel step queries its
/// next-epoch rekey address under the current root AND the archived prior roots,
/// so a base adopt landing before a Refounding's prior-root-addressed channel
/// rekeys (or before a creation delivery minted under an older root) can't
/// strand the channel.
///
/// **Continuity + fork resolution are spec-strict:** a rotation must extend the
/// exact `(epoch, key)` I hold, one epoch at a time; a same-epoch fork resolves
/// by the lexicographically lowest new key ([`rekey::lowest_key_winner`]), so
/// every follower converges. An incomplete rotation (a missing chunk) never
/// concludes removal — it just waits. A KEYLESS channel (announced by vsk-2, key
/// not yet delivered) holds no chain, so continuity is vacuous for it (CORD-06
/// §2: "a convergence check, not a secrecy mechanism") — authority is its
/// boundary; its epoch is the scan cursor, advancing past complete rotations
/// that exclude us so the walk converges on the channel's current epoch.
/// Explain this client's epoch state: what we hold, what the next-epoch base plane
/// offers, and — per rotation found there — exactly which `advance_scope` gate
/// decided we did or did not adopt it.
///
/// **Ships in release builds deliberately.** A strand is silent by construction: a
/// client parked on a dead epoch is subscribed at its own addresses and simply sees
/// nothing, which is indistinguishable from a quiet community. Answering "why is
/// this client stuck" without this meant reading sqlite by hand. It is also the
/// instrument for comparing two clients' views of one community — the local half
/// (`held`) is what diverges first.
///
/// Read-only, and safe to surface: every rotator/owner is a PUBLIC key, and no key
/// material, blob plaintext or roster secret is returned.
pub async fn explain_epoch_state<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
) -> Result<serde_json::Value, String> {
let my_xonly = me_pk()?.to_bytes();
let owner = community.owner()?;
let owner_hex = owner.to_hex();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
let held_epoch = community.root_epoch;
let held_key = community.community_root;
let next = Epoch(held_epoch.0.saturating_add(1));
let group = base_rekey_group_key(&held_key, community.id(), next);
let chunks = fetch_rekey_chunks(transport, &community, &group).await?;
let rotations = rekey::collect_rotations(&chunks);
let reports: Vec<serde_json::Value> = rotations
.iter()
.map(|r| {
let rotator_is_owner = r.rotator == owner;
// CORD-06 §Authority: a Refounding is authorized by BAN in the folded
// Roster, not owner-identity — report that gate, not just owner-equality.
let rotator_authorized = rotator_is_owner
|| (!banned.contains(&r.rotator.to_hex())
&& roster.is_authorized(&r.rotator.to_hex(), Some(&owner_hex), crate::community::roles::Permissions::BAN));
let scope_ok = r.scope.id32() == rekey::RekeyScope::Root.id32();
let epoch_ok = r.new_epoch.0 == next.0;
let complete = r.is_complete();
let continuity = format!("{:?}", r.continuity(held_epoch, &held_key));
let has_my_blob = rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), &my_xonly, r.scope, r.new_epoch).is_some();
// Is the OWNER a recipient? A non-owner Refounding that drops the owner
// is a takeover attempt — this tells whether an "owner must be kept"
// adopt-block would be safe here (it would falsely reject a legitimate
// rotation that happened to exclude the owner).
let owner_kept = r.rotator == owner
|| rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), &owner.to_bytes(), r.scope, r.new_epoch).is_some();
// The exact reason follow_rekeys skipped/rejected this rotation, in gate order.
let verdict = if !rotator_authorized {
"REJECTED: rotator holds no BAN authority in the folded roster"
} else if !scope_ok {
"REJECTED: scope is not Root"
} else if !epoch_ok {
"REJECTED: new_epoch != held+1"
} else if !complete {
"WAIT: rotation incomplete (missing chunk) — never concludes removal"
} else if continuity != "Extends" {
"REJECTED: continuity does not extend my held root (FORK/GAP)"
} else if has_my_blob {
"ADOPT: authorized + complete + continuous + my blob present"
} else {
"REMOVED: complete authorized rotation with no blob for me"
};
serde_json::json!({
"rotator": r.rotator.to_hex(),
"rotator_is_recorded_owner": rotator_is_owner,
"rotator_authorized_ban": rotator_authorized,
"scope_is_root": scope_ok,
"new_epoch": r.new_epoch.0,
"prev_epoch": r.prev_epoch.0,
"declared_chunks": r.declared_chunks,
"held_chunks": r.held_chunks.iter().copied().collect::<Vec<_>>(),
"is_complete": complete,
"continuity_vs_held_root": continuity,
"my_blob_present": has_my_blob,
"owner_kept": owner_kept,
"blob_count": r.blobs.len(),
"severing": r.severed,
"verdict": verdict,
})
})
.collect();
// The LOCAL half. Two clients on one community diverge here first, and every
// field is a thing that has silently frozen a client in the field: the roster
// is what authorizes a rotator, its provenance is what the freeze-guard reads,
// and the invite registry is what Public/Private hangs off.
let roster_at = crate::db::community::get_community_roles_at(&cid_hex).unwrap_or(0);
let admin_count = roster.grants.iter().filter(|g| roster.is_admin(&g.member)).count();
let control_wraps = {
let view = control_store::View::of(community);
let (bodies, refusals, bytes) = view.counts().unwrap_or_default();
serde_json::json!({ "mode": format!("{:?}", control_store::mode()), "held": bodies, "refused": refusals, "bytes": bytes, "sync": control_sync::report(community, &view) })
};
let held = serde_json::json!({
"root_epoch": held_epoch.0,
"roster_roles": roster.roles.len(),
"roster_grants": roster.grants.len(),
"roster_admins": admin_count,
// 0 = a locally-seeded roster that never folded from the plane. A client
// whose roster never gains provenance can never authorize a non-owner
// admin, so it refuses their rotations forever.
"roster_provenance_at": roster_at,
"banlist_entries": banned.len(),
"sever_marks": sever_marks(&cid_hex).keys().copied().collect::<Vec<_>>(),
"control_plane_split": community.control_pk.is_some(),
"private_channels": community.channels.iter().filter(|c| c.private).count(),
"channels_awaiting_key": community.channels.iter().filter(|c| c.private && c.key.is_none()).count(),
// What is held of the Control Plane, and how each relay's last pass against it ended.
"control_wraps": control_wraps,
});
// The one-line answer. `probing_next_epoch` existing at all proves the community
// moved without us; what we did about it is the `rotations` verdicts.
let summary = if rotations.is_empty() {
"UP TO DATE (or the plane is unreachable): no rotation offered at held+1"
} else if reports.iter().any(|r| r["verdict"].as_str().is_some_and(|v| v.starts_with("ADOPT"))) {
"BEHIND: an adoptable rotation is waiting — run a sync"
} else {
"WEDGED: a rotation exists at held+1 and every one was refused (see verdicts)"
};
Ok(serde_json::json!({
"summary": summary,
"recorded_owner": owner.to_hex(),
"held": held,
"held_root_epoch": held_epoch.0,
"probing_next_epoch": next.0,
"base_plane_pk": group.pk_hex(),
"raw_chunks_parsed": chunks.len(),
"rotations_found": rotations.len(),
"rotations": reports,
}))
}
/// Wide enough to collapse a large community's channel fan into one wave, narrow enough that a
/// catch-up does not present as a burst to every relay.
const CHANNEL_FAN_CONCURRENCY: usize = 8;
/// What one hop of a rekey walk reads, before any of it is judged.
struct RekeyHop {
/// The roots a channel rekey may be addressed under: #0 the current one, then archived
/// priors. Shared with streamauth, so the auth registration covers exactly this fan.
roots: Vec<[u8; 32]>,
/// Each private Channel as held: its key, its epoch, and the epoch read for.
fan: Vec<(ChannelId, Option<[u8; 32]>, Epoch, Epoch)>,
/// A Channel's next-epoch chunks by `(channel, root index)`, where any were found.
channels: std::collections::HashMap<([u8; 32], usize), Vec<rekey::RekeyChunk>>,
/// The base plane's next-epoch chunks.
base: Vec<rekey::RekeyChunk>,
}
/// Read one hop in a single concurrent wave: every private Channel's next epoch under each
/// addressing root, and the base plane's. Serially this is `channels x roots + 1` round trips
/// before a hop can be decided, a week's absence walks dozens of hops, and every follow pays
/// one hop even when nothing rotated. Only the reads overlap: the walk still judges channels
/// first (a removal-forced channel rekey rides the PRIOR root, CORD-06 D2), then the base.
async fn read_rekey_hop<T: Transport + ?Sized>(transport: &T, cur: &CommunityV2, cid_hex: &str) -> Result<RekeyHop, String> {
use futures_util::stream::StreamExt;
let roots = channel_rekey_addressing_roots(cur.community_root, cid_hex);
let fan: Vec<(ChannelId, Option<[u8; 32]>, Epoch, Epoch)> =
cur.channels.iter().filter(|c| c.private).map(|ch| (ch.id, ch.key, ch.epoch, Epoch(ch.epoch.0.saturating_add(1)))).collect();
// root #0 = current, #1.. = archived priors (indices only: root bytes are key material
// and must never reach a log).
let jobs: Vec<(ChannelId, usize, GroupKey, Epoch)> = fan
.iter()
.flat_map(|(cid, _, _, next)| roots.iter().enumerate().map(move |(ri, root)| (*cid, ri, channel_rekey_group_key(root, cid, *next), *next)))
.collect();
let channels = async {
let mut found = std::collections::HashMap::new();
let mut results = futures_util::stream::iter(jobs)
.map(|(cid, ri, group, next)| async move { (cid, ri, next, fetch_rekey_chunks(transport, cur, &group).await) })
.buffer_unordered(CHANNEL_FAN_CONCURRENCY);
while let Some((cid, ri, next, out)) = results.next().await {
let ch_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
match out {
Ok(chunks) if chunks.is_empty() => {}
Ok(chunks) => {
crate::log_debug!("[v2:follow {}] ch {} next e{} root#{}/{}: {} rekey chunk(s)", &cid_hex[..8], &ch_hex[..8], next.0, ri, roots.len(), chunks.len());
found.insert((cid.0, ri), chunks);
}
Err(e) => {
crate::log_warn!("[v2:follow {}] ch {} next e{} root#{}/{}: rekey plane fetch failed: {}", &cid_hex[..8], &ch_hex[..8], next.0, ri, roots.len(), e);
return Err(e);
}
}
}
Ok(found)
};
let base_group = base_rekey_group_key(&cur.community_root, cur.id(), Epoch(cur.root_epoch.0.saturating_add(1)));
let (channels, base) = futures_util::future::join(channels, fetch_rekey_chunks(transport, cur, &base_group)).await;
let (channels, base) = (channels?, base?);
Ok(RekeyHop { roots, fan, channels, base })
}
pub async fn follow_rekeys<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
session: &std::sync::Arc<crate::db::Session>,
) -> Result<RekeyFollow, String> {
crate::db::scoped(async move {
// Death wins every race (CORD-02 §9): a dissolved community honors no epoch advance
// past its tombstone — don't adopt a rotation into a grave.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
return Ok(RekeyFollow { updated: None, self_removed: false, removed_at: None, dissolved: true, wedged: false });
}
// An offline member must also LEARN of a death: the tombstone rides its own
// public plane, which the live sub watches but no catch-up fetch touched —
// without this, a member who slept through a dissolution follows (and posts
// into) a grave forever. Fail-open on transport failure: availability is
// never death.
//
// The first hop's planes are read alongside: nothing is decided until both are in.
let (dead, first_hop) = futures_util::future::join(is_dissolved(transport, community), read_rekey_hop(transport, community, &cid_hex)).await;
if dead {
if session.is_live() {
let _ = crate::db::community::set_community_dissolved(&cid_hex);
}
return Ok(RekeyFollow { updated: None, self_removed: false, removed_at: None, dissolved: true, wedged: false });
}
let mut first_hop = Some(first_hop);
let signer = crate::signer::active_signer()?;
let my_pk = me_pk()?;
let my_xonly = my_pk.to_bytes();
let owner = community.owner()?;
let owner_hex = owner.to_hex();
let mut cur = community.clone();
let mut changed = false;
// A rotation delivered us a blob we could not open (see RekeyFollow::wedged).
let mut wedged = false;
// The rotator/admissibility gates read the PERSISTED roster (folded by a prior
// follow_control; the worker folds control right after this rekey pass). This
// is "one pass late" for the rotator-AUTHORIZATION direction (a newly-granted
// admin's rotation adopts a pass late, never early — safe). It is fail-OPEN for
// the base-admissibility protected-set: a superior whose grant this receiver
// has not yet folded is not in `roster.grants`, so a non-owner Refounding
// excluding them can be adopted within that propagation window. Bounded — the
// owner is ALWAYS hard-protected below (independent of the roster) and can
// counter-refound; and it is inherent to eventual consistency (one cannot gate
// on a grant never seen). Tightening this (fold control before the first rekey,
// or gate non-owner adoption on roster freshness) is a follow-on.
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
let me_hex = my_pk.to_hex();
// CORD-06 §Authority: "a rotation cites the Grant it acts under like any
// authority action (CORD-04's `vac`), so a just-demoted admin's rotation is
// never honored by a lagging client." Persisted heads ARE the right floor
// here (unlike the roster fold, which must resolve in-pass): a rotation is
// judged against a roster we already folded, and `follow_control` — v2's only
// roster writer — persists the heads in the same pass it writes the roster.
// A joiner who sees a rotation before folding control simply parks it and
// heals on the next follow, which runs control first.
let cited_ok = |rot: &rekey::Rotation| -> bool {
citation_is_synced(&cid_hex, &owner_hex, &rot.rotator.to_hex(), rot.citation.as_ref())
};
let channel_rotator_ok = |rotator: &PublicKey| -> bool { rotates_channels(&roster, &owner_hex, banned.iter(), &rotator.to_hex()) };
// Concluding MY removal takes more than the bit: the rotator must strictly
// outrank ME (CORD-06 §Authority — "the Rotator must strictly outrank every
// removed target"), so an equal-rank admin can never silently evict a peer
// (or the owner) by minting a complete rotation that skips their blob.
let channel_rotator_outranks_me = |rotator: &PublicKey| -> bool {
if *rotator == owner {
return true;
}
let rh = rotator.to_hex();
rotates_channels(&roster, &owner_hex, banned.iter(), &rh) && roster.can_act_on_member(&rh, Some(&owner_hex), &me_hex, channel_rotation_bit(&roster, &owner_hex, &rh))
};
// CORD-06 §Authority: a Refounding requires the BAN permission in the folded
// Roster (NOT owner-identity) — any admin holding BAN may perform it, checked
// against the Roster exactly like a channel rekey checks MANAGE_CHANNELS. The
// owner is always authorized. (Owner-only here silently wedged every member
// whose community was refounded by a non-owner admin.)
let base_rotator_ok = |rotator: &PublicKey| -> bool {
if *rotator == owner {
return true;
}
let rh = rotator.to_hex();
!banned.contains(&rh) && roster.is_authorized(&rh, Some(&owner_hex), crate::community::roles::Permissions::BAN)
};
// Concluding MY removal via a base rotation takes more than the bit: the
// rotator must strictly outrank ME with BAN (CORD-06 §Authority — "the
// Rotator must strictly outrank every removed target"), so an equal-rank
// admin can never evict a peer (or the owner) by minting a rotation that
// skips their blob. Adoption (I hold a blob) only needs `base_rotator_ok`.
let base_rotator_outranks_me = |rotator: &PublicKey| -> bool {
if *rotator == owner {
return true;
}
let rh = rotator.to_hex();
!banned.contains(&rh) && roster.can_act_on_member(&rh, Some(&owner_hex), &me_hex, crate::community::roles::Permissions::BAN)
};
// A non-owner Refounding may only remove members the rotator strictly
// OUTRANKS. The protected set is the owner plus every grant-holder the
// rotator can't act on with BAN (a peer or superior) — excluding one is
// an authority-escalation takeover, so its rotation is inadmissible.
// Plain members hold no grant and are always outranked by a BAN-holder,
// so removing them is legitimate and needs no memberlist.
let base_admissible = |r: &rekey::Rotation| -> bool {
if r.rotator == owner {
return true; // the owner is supreme.
}
// Uncited (or citing a Grant we haven't synced) → skip entirely:
// neither adopt nor conclude a removal, exactly like an
// unauthorized rotation. It parks and heals on the next follow.
if !cited_ok(r) {
return false;
}
let rotator_hex = r.rotator.to_hex();
let has_blob = |xonly: &[u8; 32]| {
rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), xonly, r.scope, r.new_epoch).is_some()
};
// The owner is never a valid removed target.
if !has_blob(&owner.to_bytes()) {
return false;
}
for g in &roster.grants {
if g.member == rotator_hex || g.member == owner_hex || banned.contains(&g.member) {
continue; // self, owner (checked), or an already-authorized removal.
}
// A grant-holder the rotator can't act on is a peer/superior.
if !roster.can_act_on_member(&rotator_hex, Some(&owner_hex), &g.member, crate::community::roles::Permissions::BAN) {
if let Ok(pk) = PublicKey::from_hex(&g.member) {
if !has_blob(&pk.to_bytes()) {
return false; // a peer/superior was excluded.
}
}
}
}
true
};
// Containment hops adopted in this walk (B2: any one of them condemns —
// a later ordinary hop in the same walk must not relaunder links open).
let mut severed_hops: Vec<u64> = Vec::new();
// ── Same-epoch convergence, BEFORE walking forward (CORD-06 §3) ─────────
//
// Two authorized rotators can mint the same epoch concurrently. The spec's
// tiebreak is deterministic — the lexicographically lowest new base key wins
// — but it was only ever applied among rotations seen in ONE fetch. A client
// that saw only the higher sibling adopted it and then looked exclusively
// for its successor, so the lower sibling became permanently unreachable:
// two halves of a community, both at the same epoch number, different keys,
// unable to read each other, forever. Nobody was misbehaving.
//
// So re-check the epoch we ALREADY hold on every follow, and step sideways
// onto a strictly lower sibling. Down-only, exactly as the spec requires: a
// held epoch converges only downward, so a flaky fetch that returns just the
// higher sibling can never re-fork a settled epoch, and the walk terminates
// because each convergence strictly decreases the held key.
//
// The losing branch's key is simply dropped. Messages already ingested from
// it stay readable — they are stored decrypted under the account vault, not
// re-derived from the epoch key — so converging costs only the fork-window
// messages this client never fetched, which live on a branch nobody reads.
if cur.root_epoch.0 > 0 {
let prior = crate::db::community::held_epoch_key(
&cid_hex,
crate::community::SERVER_ROOT_SCOPE_HEX,
cur.root_epoch.0 - 1,
)
.ok()
.flatten();
if let Some(prior_root) = prior {
let group = base_rekey_group_key(&prior_root, cur.id(), cur.root_epoch);
match fetch_rekey_chunks(transport, &cur, &group).await {
Ok(siblings) if !siblings.is_empty() => {
let held_before = cur.community_root;
match advance_scope(
&[(siblings, Some((Epoch(cur.root_epoch.0 - 1), prior_root)))],
RekeyScope::Root,
cur.id(),
&base_rotator_ok,
&base_rotator_outranks_me,
&base_admissible,
&signer,
&my_xonly,
cur.root_epoch,
)
.await
{
// Strictly lower only. Equal = the branch we already hold.
Advance::Adopt { new_key, control_pk, control_root, severed, rotator } if new_key < held_before => {
crate::log_warn!(
"[v2:follow {}] same-epoch fork at epoch {} — converging DOWN onto the canonical sibling",
&cid_hex[..8.min(cid_hex.len())], cur.root_epoch.0
);
cur.community_root = new_key;
cur.control_pk = control_pk.and_then(|pk| PublicKey::from_slice(&pk).ok());
cur.control_root = control_root;
// Everything the sibling carries, as if it had been adopted first.
record_epoch_minter(&cid_hex, cur.root_epoch.0, &rotator.to_hex());
if severed {
severed_hops.push(cur.root_epoch.0);
// Recorded now: a walk that fails later must not forget it.
add_sever_mark(&cid_hex, cur.root_epoch.0, now_ms() / 1000);
}
if let Err(e) = crate::db::community::store_epoch_key(
&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, cur.root_epoch.0, &new_key,
) {
crate::log_warn!("v2: converged epoch-key archive failed: {e}");
}
if matches!(crate::db::community::community_held(community.id()), Ok(true)) {
let _ = crate::db::community::save_community_v2(&cur);
}
changed = true;
}
// A sibling we cannot open is NOT a removal: refusing to
// converge parks us on a branch that still works, where
// concluding removal here would delete the community over
// a fork we merely could not read.
_ => {}
}
}
Ok(_) => {}
Err(e) => crate::log_warn!(
"[v2:follow {}] same-epoch fork check failed (will retry): {}",
&cid_hex[..8.min(cid_hex.len())], e
),
}
}
}
// Bound the catch-up: each real step consumes a valid authorized rotation, so a
// finite chain terminates naturally; the cap defends against a relay feeding a
// pathological set.
const MAX_STEPS: usize = MAX_WALK_STEPS;
for _ in 0..MAX_STEPS {
let mut advanced = false;
// Read against the state this hop decides on: the one read ahead stands only while
// the convergence above left the root where it was.
let hop = match first_hop.take().filter(|_| !changed) {
Some(read) => read?,
None => read_rekey_hop(transport, &cur, &cid_hex).await?,
};
let RekeyHop { roots: addressing_roots, fan, channels: mut prefetched, base } = hop;
for (cid, held_key, held_epoch, next) in fan {
let ch_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
let mut batches: Vec<RekeyBatch> = Vec::new();
for ri in 0..addressing_roots.len() {
if let Some(chunks) = prefetched.remove(&(cid.0, ri)) {
// A rotation committing to the root it is addressed under is a Public Channel
// made private (CORD-03 §2), from someone who could make it public: it extends
// an earlier private era's key too.
if held_key.is_some() {
let converts: Vec<rekey::RekeyChunk> = chunks
.iter()
.filter(|c| c.rotator == owner || roster.is_authorized(&c.rotator.to_hex(), Some(&owner_hex), crate::community::roles::Permissions::MANAGE_CHANNELS))
.cloned()
.collect();
if !converts.is_empty() {
batches.push((converts, Some((held_epoch, addressing_roots[ri]))));
}
}
batches.push((chunks, held_key.map(|k| (held_epoch, k))));
}
}
// Keyless-adopt residual (documented, deferred hardening): a malicious
// AUTHORIZED admin can fork a keyless member onto an orphan low-key
// rotation nothing extends (keyed members' continuity filters it out).
// Recoverable via a fresh bundle; an insider with MANAGE_CHANNELS can
// exclude the member outright anyway, so the marginal harm is the wedge
// outliving their demotion.
match advance_scope(&batches, RekeyScope::Channel(cid), cur.id(), &channel_rotator_ok, &channel_rotator_outranks_me, &cited_ok, &signer, &my_xonly, next).await {
Advance::Adopt { new_key, .. } => {
if let Some(ch) = cur.channels.iter_mut().find(|c| c.id.0 == cid.0) {
ch.key = Some(new_key);
ch.epoch = next;
}
crate::log_debug!("[v2:follow {}] ch {} ADOPTED e{}", &cid_hex[..8], &ch_hex[..8], next.0);
// The adopter's own multi-epoch archive (the minter archived at
// mint) — this channel's history stays readable across rotations.
// fetch_channel compensates for the CURRENT epoch, so a failed
// archive only bites after the NEXT rotation — surface it.
if let Err(e) = crate::db::community::store_epoch_key(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&cid.0), next.0, &new_key) {
crate::log_warn!("v2: channel epoch-key archive failed (history across this rotation may not read back): {e}");
}
advanced = true;
changed = true;
}
// A complete rotation without me: cut, or still keyless. Either way the
// channel stays known at that epoch, so the walk goes on to the CURRENT one,
// where a later rotation that names me again (a re-grant) lets me back in.
Advance::Removed { .. } => {
if held_key.is_some() {
crate::log_debug!("[v2:follow {}] ch {} cut at e{}", &cid_hex[..8], &ch_hex[..8], next.0);
}
if let Some(ch) = cur.channels.iter_mut().find(|c| c.id.0 == cid.0) {
ch.key = None;
ch.epoch = next;
}
advanced = true;
changed = true;
}
Advance::Stay => {}
Advance::StayWedged => {
// A blob at our locator that will not open: park, never
// remove, and make the park legible (a silent park is
// indistinguishable from "no rotation happened").
wedged = true;
}
}
}
// Base rotation (Refounding): advances the root + root_epoch, re-addressing
// every public channel, the guestbook, and the control plane by derivation
// (refresh_subscription recomputes the author-set from the new root).
{
let held_epoch = cur.root_epoch;
let held_key = cur.community_root;
let next = Epoch(held_epoch.0.saturating_add(1));
let batches = vec![(base, Some((held_epoch, held_key)))];
match advance_scope(&batches, RekeyScope::Root, cur.id(), &base_rotator_ok, &base_rotator_outranks_me, &base_admissible, &signer, &my_xonly, next).await {
Advance::Adopt { new_key, control_pk, control_root, severed, rotator } => {
// CORD-02 §5: this npub's snapshot — and only this npub's —
// seeds the new epoch's Guestbook. Recorded from the rotation
// this device just VERIFIED and adopted, so a snapshot can
// never nominate its own author.
record_epoch_minter(&cid_hex, next.0, &rotator.to_hex());
// Record the HOP that was severed, not the walk's final head:
// the mark drives both the link condemnation line and the
// rescue re-stamp, and a multi-step walk would otherwise
// present the containment at the wrong epoch.
if severed {
severed_hops.push(next.0);
add_sever_mark(&cid_hex, next.0, now_ms() / 1000);
}
cur.community_root = new_key;
cur.root_epoch = next;
// The control pair is the blob's, never inherited: the
// secret rolls with the root at every Refounding
// (CORD-02 §2), so a stale pair carried forward would sign
// (or subscribe) at a dead address.
//
// A legacy 72-byte blob therefore DOWNGRADES a split
// community back to the member-writable plane — the exact
// flooding surface the split closes. The width stays
// accepted (transition compat, CORD-06 §3), but once a
// community has been split this is either an outdated
// rotator or an attack, so it is never silent.
if cur.control_pk.is_some() && control_pk.is_none() {
crate::log_warn!(
"[v2:follow {}] rotation to epoch {} carried a LEGACY base blob — this community's control plane reverts to the member-writable address",
&cid_hex[..8.min(cid_hex.len())], next.0
);
}
archive_control_address(&cid_hex, held_epoch.0, cur.control_pk.as_ref());
cur.control_pk = control_pk.and_then(|pk| PublicKey::from_slice(&pk).ok());
archive_control_address(&cid_hex, next.0, cur.control_pk.as_ref());
cur.control_root = control_root;
// Archive on adopt: without this, a member who lived through TWO
// Refoundings loses the middle epoch's public history (only the
// minter archived it).
if let Err(e) = crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, next.0, &new_key) {
crate::log_warn!("v2: base epoch-key archive failed (this epoch's history may not read back after the next rotation): {e}");
}
// CHECKPOINT THE HOP. A client back from a long absence walks
// many epochs in one pass, and the row used to be written only
// after the whole loop — so a fetch failure on the last hop
// discarded every hop already taken. The next attempt started
// from scratch, cost the same again, and on a flaky link could
// never converge at all. Banking here makes the walk resumable:
// progress is monotonic, and an interrupted catch-up picks up
// where it stopped.
//
// The FULL row, never just root+epoch: `control_pk`/
// `control_root` roll with the root, so a narrow write would
// leave the control pair an epoch behind and fold the control
// plane at a dead address. Archive first, then the head — a
// stray archive is harmless, a missing one is permanent.
//
// A leave/delete racing the walk must not be resurrected by an
// upsert, so re-check the row still exists before each write.
match crate::db::community::community_held(community.id()) {
Ok(true) => {
if let Err(e) = crate::db::community::save_community_v2(&cur) {
crate::log_warn!("v2: hop checkpoint failed at epoch {} (the walk will redo it): {e}", next.0);
}
}
// Gone mid-walk: stop rather than resurrect it.
Ok(false) => return Ok(RekeyFollow { updated: None, self_removed: false, removed_at: None, dissolved: false, wedged }),
Err(e) => crate::log_warn!("v2: hop checkpoint skipped at epoch {}: {e}", next.0),
}
advanced = true;
changed = true;
}
Advance::Removed { at_ms } => {
return Ok(RekeyFollow { updated: None, self_removed: true, removed_at: Some(at_ms), dissolved: false, wedged: false });
}
Advance::Stay => {}
Advance::StayWedged => {
// A blob at our locator that will not open: park, never
// remove, and make the park legible (a silent park is
// indistinguishable from "no rotation happened").
wedged = true;
}
}
}
if !advanced {
break;
}
}
if wedged {
// Legible, and actionable: the prior root still reaches every member,
// so an owner/admin seeing this can counter-rotate before the honest
// chain moves on.
crate::log_warn!(
"[v2:follow {}] a complete rotation delivered a key blob this client cannot open — parked at epoch {} (never treated as a removal)",
&cid_hex[..8.min(cid_hex.len())], cur.root_epoch.0
);
crate::emit_event(
"community_rekey_wedged",
&serde_json::json!({ "community_id": cid_hex, "held_epoch": cur.root_epoch.0 }),
);
}
if !changed {
// A pending severance whose revoke was interrupted must heal on QUIET
// passes too — waiting for the next rotation means a one-shot transport
// blip leaves the community reading Public (and every future ban
// refound-less) until someone happens to rotate again.
retry_pending_severance(transport, &cur).await;
return Ok(RekeyFollow { updated: None, self_removed: false, removed_at: None, dissolved: false, wedged });
}
// A leave/delete raced this follow: saving would resurrect the community row
// (the save is an upsert) with no floor rows behind it.
if !crate::db::community::community_held(community.id())? {
return Ok(RekeyFollow { updated: None, self_removed: false, removed_at: None, dissolved: false, wedged });
}
unseal_held(&mut cur);
crate::db::community::save_community_v2(&cur)?;
// Mark every containment hop FIRST: the marks are what condemn links, and
// both the severance below and the refresh consult them — so the order of
// those two stops mattering (a condemned link is skipped by the refresh
// and buried by the severance, in either order, on any pass).
for hop in &severed_hops {
add_sever_mark(&cid_hex, *hop, now_ms() / 1000);
}
if !severed_hops.is_empty() {
// Someone ELSE ran a Severing Refounding: my links minted below the
// severed epoch are the raid's door — bury them instead of carrying
// them forward. A fresh link minted at-or-after it survives every
// device's adopt, however late (the epoch is the same on all of them).
if let Err(e) = sever_own_links(transport, &cur).await {
crate::log_warn!("[Sever] own-link revocation on adopt failed (retries next follow): {e}");
}
}
// Carry my SURVIVING links across the rotation someone ELSE performed
// (CORD-05 §2). The refounder refreshes only the bundles they can reach —
// their own — so without this every other creator's links keep vending the
// superseded root and drop new joiners onto a dead epoch, which is exactly
// the stranding the stable-URL refresh exists to prevent. Condemned links
// are skipped inside (see the guard there). Best-effort and idempotent.
let _ = refresh_public_links(transport, &cur).await;
// A pending sever mark (mine or adopted) whose revoke never completed
// keeps retrying while condemned links remain (B4).
retry_pending_severance(transport, &cur).await;
Ok(RekeyFollow { updated: Some(cur), self_removed: false, removed_at: None, dissolved: false, wedged })
})
.await
}
/// One scope's catch-up decision from the rekey chunks fetched at its next-epoch
/// address.
enum Advance {
/// Adopt this fresh key for `next_epoch`. A BASE adoption also carries the
/// next epoch's Control Plane pair from the blob (CORD-06 §1) — the pk in
/// every 104/136-byte blob, the secret only in a staff recipient's 136. The
/// pair is the BLOB's, never inherited: a legacy 72-byte blob carries
/// neither (that epoch's Control folds at the legacy address), and channel
/// rotations never carry any.
Adopt { new_key: [u8; 32], control_pk: Option<[u8; 32]>, control_root: Option<[u8; 32]>, severed: bool, rotator: PublicKey },
/// A complete owner rotation at `next_epoch` dropped my blob — I'm removed, as of `at_ms`.
Removed { at_ms: u64 },
/// No owner rotation extends my held epoch (yet) — keep the current key.
Stay,
/// A complete authorized rotation carried a blob at MY locator that would
/// not open. Never a removal (CORD-06 §2), but never silent either — the
/// caller surfaces it (see [`RekeyFollow::wedged`]).
StayWedged,
}
/// Fetch + parse every seal-verified 3303 chunk at a rekey plane address.
async fn fetch_rekey_chunks<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, group: &GroupKey) -> Result<Vec<rekey::RekeyChunk>, String> {
// A rekey plane address is community_root-derived, so ANY member can seal junk 3303s
// there: a flood, or a large community's own multi-chunk rotation, could bury the genuine
// rotation past one page. The seal + authority filter downstream drops the junk.
let wraps = plane_wraps(transport, community, group).await?;
let _batch = stream::check_page(&wraps.iter().collect::<Vec<_>>(), group);
Ok(wraps.iter().filter_map(|w| stream::open_wrap(w, group).ok()).filter_map(|opened| rekey::parse_rekey_chunk(&opened).ok()).collect())
}
/// Every wrap on a rekey or access plane: through the wraps held once the store is on, else
/// page by page off the relays.
async fn plane_wraps<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, group: &GroupKey) -> Result<Vec<Event>, String> {
match control_store::mode() {
control_store::Mode::Off => plane_wraps_paged(transport, &community.relays, group).await,
control_store::Mode::On => match plane_wraps_held(transport, community, group).await {
Some(wraps) => Ok(wraps),
None => plane_wraps_paged(transport, &community.relays, group).await,
},
control_store::Mode::Shadow => {
let paged = plane_wraps_paged(transport, &community.relays, group).await?;
if let Some(held) = plane_wraps_held(transport, community, group).await {
let held: std::collections::HashSet<nostr_sdk::prelude::EventId> = held.iter().map(|w| w.id).collect();
// A wrap that opens as nothing is held as refused, and read as nothing either way.
let pages: std::collections::HashSet<nostr_sdk::prelude::EventId> = paged.iter().filter(|w| stream::open_wrap(w, group).is_ok()).map(|w| w.id).collect();
let (lost, more) = (pages.difference(&held).count(), held.difference(&pages).count());
if lost > 0 || more > 0 {
#[cfg(test)]
if std::env::var("VECTOR_CONTROL_SHADOW_STRICT").is_ok() {
panic!("the plane read through the store differs from the paged one: {lost} wrap(s) lost, {more} more");
}
crate::log_warn!("[v2:plane {}] shadow: the read through the store differs: {lost} lost, {more} more", &community.id().to_hex()[..8]);
}
}
Ok(paged)
}
}
}
/// [`plane_wraps`] through the wraps held, the relays asked first: what the relays hold now, as a
/// read by pages finds it, since a delivery only this device still holds is one nobody else can
/// fetch. `None` when the store cannot serve it (no relay answered, the plane is flooded, a store
/// error, a relay that could not say what it lacks): the caller reads by pages.
async fn plane_wraps_held<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, group: &GroupKey) -> Option<Vec<Event>> {
crate::db::scoped(async move {
if !crate::db::community::community_held(community.id()).unwrap_or(false) {
return None;
}
let view = plane_store::PlaneView::of(community, group);
if control_sync::flooded(community, &view) {
return None;
}
let began = web_time::Instant::now();
let sync = control_sync::sync_plane(transport, community, &view, control_sync::Wait::Quorum).await.ok().filter(|sync| !sync.flooded && !sync.unread)?;
let synced = began.elapsed();
let unserved = control_sync::unserved_by_all(transport, &view, &sync).await?;
crate::log_debug!("[v2:plane {}] {} read in {:?} ({:?} to sync)", &community.id().to_hex()[..8], &group.pk_hex()[..8], began.elapsed(), synced);
Some(view.all().ok()?.into_iter().filter(|w| !unserved.contains(&w.id)).collect())
})
.await
}
/// [`plane_wraps`] off the relays, newest first, page by page to the end of the plane.
async fn plane_wraps_paged<T: Transport + ?Sized>(transport: &T, relays: &[String], group: &GroupKey) -> Result<Vec<Event>, String> {
// Bounded: a sustained flood past this depth degrades to "adopt one pass late", never a
// false state.
const PAGE: usize = 200;
const MAX_PAGES: usize = 6;
let mut out = Vec::new();
let mut seen: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
let (mut until, mut oldest): (Option<u64>, Option<u64>) = (None, None);
for _ in 0..MAX_PAGES {
let query = plane_page(group.pk_hex(), PAGE, until);
// Authenticate AS the plane key: on AUTH-gating relays (Ditto) the shared user-authed
// client's REQ for a plane's events is CLOSED.
let page = transport.fetch_plane(group.keys(), &query, relays).await?;
// A page nobody fully answered must not read as "the plane ends here".
let complete = page.is_complete();
let wraps = page.events;
let mut fresh = 0usize;
for w in wraps.iter() {
if !seen.insert(w.id) {
continue;
}
fresh += 1;
oldest = Some(oldest.map_or(w.created_at.as_secs(), |o| o.min(w.created_at.as_secs())));
out.push(w.clone());
}
if fresh == 0 || (wraps.len() < PAGE && complete) {
break;
}
match oldest {
Some(o) if o > 0 => until = Some(o),
_ => break,
}
}
Ok(out)
}
/// One addressing root's chunks, with the key held at that scope as `(epoch, key)`.
type RekeyBatch = (Vec<rekey::RekeyChunk>, Option<(Epoch, [u8; 32])>);
/// Decide how a scope advances from per-addressing-root chunk batches (pure). Each
/// batch pairs the chunks fetched under one root with the continuity to demand of
/// them: a rotation qualifies when it's rotator-authorized (`rotator_ok`),
/// complete, targets the immediate `next_epoch`, and — when I hold a chain —
/// extends my exact `(epoch, key)`. A KEYLESS batch (`held` = None) has no chain
/// to extend, so it qualifies on authority + completeness alone (CORD-06 §2:
/// continuity is "a convergence check, not a secrecy mechanism"; the rotator's
/// seal authority is the boundary). Among qualifying rotations carrying my blob
/// the lexicographically lowest new key wins (convergent). All complete
/// candidates without my blob conclude Removed for a KEYED holder only when one
/// came from a rotator who may remove ME (`rotator_may_remove_me`, the CORD-06
/// strict-outrank rule) — else Stay; for a keyless holder they merely advance the
/// scan cursor (any bit-holder's real rotation is scan progress, never a loss).
#[allow(clippy::too_many_arguments)]
async fn advance_scope<S: crate::signer::VectorSigner + ?Sized>(
batches: &[RekeyBatch],
scope: RekeyScope,
community_id: &crate::community::CommunityId,
rotator_ok: &(dyn Fn(&PublicKey) -> bool + Sync),
rotator_may_remove_me: &(dyn Fn(&PublicKey) -> bool + Sync),
admissible: &(dyn Fn(&rekey::Rotation) -> bool + Sync),
signer: &S,
my_xonly: &[u8; 32],
next_epoch: Epoch,
) -> Advance {
let mut winners: Vec<rekey::BaseKeyDelivery> = Vec::new();
// Parallel to `winners`: whether each delivery's rotation is a containment
// (Root scope only). Selected by the same lowest-key index, so a same-epoch
// fork adopts the winner's flag and never a loser's.
let mut winner_severed: Vec<bool> = Vec::new();
// Parallel to `winner_severed`: whose Refounding this delivery came from. The
// snapshot authority for the adopted epoch (CORD-02 §5) is exactly this npub.
let mut winner_rotator: Vec<PublicKey> = Vec::new();
let mut saw_complete_candidate = false;
// The latest complete rotation considered: a removal dates from it.
let mut removed_at: u64 = 0;
// Did any qualifying rotation actually carry recipients? See the removal gate.
let mut saw_nonempty_candidate = false;
let mut saw_outranking_candidate = false;
let mut my_blob_unopenable = false;
let keyed = batches.iter().any(|(_, held)| held.is_some());
for (chunks, held) in batches {
let rotations = rekey::collect_rotations(chunks);
for r in &rotations {
if !rotator_ok(&r.rotator) || r.scope.id32() != scope.id32() || r.new_epoch.0 != next_epoch.0 {
continue;
}
if let Some((held_epoch, held_key)) = held {
if r.continuity(*held_epoch, held_key) != Continuity::Extends {
continue;
}
}
// CORD-06 §Authority: a rotator must strictly OUTRANK every removed
// target. An authorized-but-inadmissible rotation (one that excludes
// the owner or a peer/superior the rotator can't act on) is a takeover
// attempt — skip it entirely, so it neither adopts nor concludes a
// removal (it forks; the honest chain wins).
if !admissible(r) {
continue;
}
// Completeness gates the DESTRUCTIVE direction only. Concluding removal
// means "no blob for me anywhere in this rotation", which is only
// knowable with every chunk in hand — so `saw_complete_candidate`, and
// everything downstream of it, still demands the whole set.
//
// ADOPTION does not need it. The blob binds its own (scope, epoch)
// inside the ciphertext, so a key that opens is this rotation's key
// whatever else is unreachable; and admissibility is monotonic in the
// blob set — chunks we have not seen can only ADD recipients, so a
// rotation that looks admissible on the blobs we hold cannot become a
// takeover once the rest arrive. Requiring the full set to adopt made a
// large community's rotation as fragile as its least reachable chunk,
// and the walk is sequential, so that strand blocked every epoch above
// it too. (A rotation that fails admissibility on partial data is still
// skipped, never adopted — the unsafe direction stays closed.)
if r.is_complete() {
removed_at = removed_at.max(r.at_ms);
saw_complete_candidate = true;
saw_nonempty_candidate |= !r.blobs.is_empty();
saw_outranking_candidate |= rotator_may_remove_me(&r.rotator);
}
// EVERY blob at my locator, not just the first. A locator is a public
// index that proves nothing, so anyone may publish a blob at mine;
// taking only the first would let a junk one shadow the real key and
// park a client that actually holds it. First that opens wins.
let mut mine = rekey::find_my_blobs(&r.blobs, &r.rotator.to_bytes(), my_xonly, r.scope, r.new_epoch).peekable();
let had_candidate = mine.peek().is_some();
let mut opened_one = false;
for blob in mine {
let opened = match scope {
// Base blobs are width-declared forms (CORD-06 §1).
RekeyScope::Root => rekey::open_base_blob(signer, &r.rotator, community_id, r.new_epoch, blob).await,
RekeyScope::Channel(_) => rekey::open_blob(signer, &r.rotator, r.scope, r.new_epoch, blob)
.await
.map(|k| rekey::BaseKeyDelivery { new_root: k, control_pk: None, control_root: None }),
};
if let Ok(d) = opened {
winners.push(d);
winner_severed.push(scope.id32() == RekeyScope::Root.id32() && r.severed);
winner_rotator.push(r.rotator);
opened_one = true;
break;
}
}
// A blob AT my locator that won't open is not an exclusion (CORD-06 §2:
// removal = NO blob across all chunks). It must never conclude Removed
// below — that is exactly how a pre-split client turned an unreadable
// width into a false self-removal. Stay and keep recovering instead.
if had_candidate && !opened_one {
my_blob_unopenable = true;
}
}
}
if !winners.is_empty() {
// `collect_rotations` correlates on `(rotator, scope, new_epoch, prev_commit)`,
// so a single rotator's blobs merge into ONE rotation (and a retried Refounding
// MINT-OR-REUSES its root, so it never emits two distinct roots to fork on).
// The lowest-key tiebreak engages only for CONCURRENT DISTINCT rotators racing
// the same epoch (separate rotations): every follower converges on the same
// lowest new BASE key — the control pair rides the winner's blobs, never
// compared (CORD-06 §3). A wrap served under two addressing roots can't
// double-count: each rekey wrap opens under exactly one root's group key.
let keys: Vec<[u8; 32]> = winners.iter().map(|d| d.new_root).collect();
let idx = rekey::lowest_key_winner(&keys).expect("winners is non-empty");
let w = &winners[idx];
return Advance::Adopt {
new_key: w.new_root,
control_pk: w.control_pk,
control_root: w.control_root,
severed: winner_severed[idx],
rotator: winner_rotator[idx],
};
}
// A rotation that delivered NO blob to anyone removed nobody. Read literally it
// is "complete, authorized, and contains no blob for me" — which is the removal
// shape — but removal DELETES the community locally, so one empty rotation from
// an authorized rotator would evict the entire membership at once, irreversibly.
// An empty recipient set is a malformed or aborted rotation, never a verdict
// about any individual. Nobody is removed by a rotation that removed everybody.
if saw_complete_candidate && !saw_nonempty_candidate {
return Advance::Stay;
}
if saw_complete_candidate && !my_blob_unopenable && (!keyed || saw_outranking_candidate) {
Advance::Removed { at_ms: removed_at.min(now_ms()) }
} else if my_blob_unopenable {
Advance::StayWedged
} else {
Advance::Stay
}
}
// ── Pins (CORD-04 §7) ────────────────────────────────────────────────────────
/// A channel's pin list, read from the locally folded head.
#[derive(Debug, serde::Serialize)]
pub struct ChannelPins {
/// Entries that passed the full §7 verification, wire order (curator's).
pub pins: Vec<super::pins::VerifiedPin>,
/// The head is sealed under a key epoch this client does not hold: the
/// pins exist but are unreadable. Render as unavailable, NEVER as empty —
/// and a writer seeing this MUST NOT publish (it would drop every entry).
pub sealed: bool,
/// Folded head version (0 = no edition has ever folded).
pub version: u64,
}
/// The channel's stream conversation key at `epoch`, if this client holds the
/// deriving secret: a private channel's held per-epoch key, a public channel's
/// held base root at that epoch.
fn channel_conv_key_at(community: &CommunityV2, ch: &ChannelV2, epoch: u64) -> Option<[u8; 32]> {
let ikm = channel_conv_ikm(community, ch, epoch).ok()?;
// A private plane is never derived from the root value (that would address
// the public plane) — mirrors fetch_channel_history's invariant.
if ch.private && ikm == community.community_root {
return None;
}
let group = channel_group_key(&ikm, &ch.id, Epoch(epoch));
group.conv_key().as_bytes().try_into().ok()
}
/// Read a channel's pins from the locally folded head: unseal (private form),
/// verify every entry, keep wire order. Local-only — the control follow is what
/// moves the head.
pub fn read_channel_pins(community: &CommunityV2, channel_id: &ChannelId) -> Result<ChannelPins, String> {
let ch = community.channel(channel_id).ok_or("no such channel in this community")?;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let ch_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
let Some((content, version)) = crate::db::community::get_community_pins(&cid_hex, &ch_hex)? else {
return Ok(ChannelPins { pins: Vec::new(), sealed: false, version: 0 });
};
let read = super::pins::read_pin_list(&content, |epoch| channel_conv_key_at(community, ch, epoch));
let pins = read
.entries
.iter()
.filter_map(|e| super::pins::verify_pin_entry(e, &ch_hex))
.collect();
Ok(ChannelPins { pins, sealed: read.sealed, version: version.max(0) as u64 })
}
/// Publish `entries` as the channel's next Pin List edition, in the form the
/// channel's folded type mandates, and echo it locally so a follow-up edit
/// builds on this write rather than the pre-write fold.
async fn publish_pin_list<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
ch: &ChannelV2,
entries: &[super::pins::PinEntry],
) -> Result<(), String> {
crate::db::scoped(async move {
let content = if ch.private {
let key = ch.key.ok_or("this private channel's key has not arrived yet")?;
let group = channel_group_key(&key, &ch.id, ch.epoch);
super::pins::serialize_sealed_pin_list(entries, group.conv_key(), ch.epoch.0)?
} else {
super::pins::serialize_public_pin_list(entries)?
};
let eid = super::derive::pins_locator(community.id(), &ch.id);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
let entity_hex = crate::simd::hex::bytes_to_hex_32(&eid);
// The version this publish will chain to — mirrors publish_control_edition.
let version = match crate::db::community::get_edition_head(&cid_hex, &entity_hex)? {
Some((v, _)) => v + 1,
None => 1,
};
crate::log_info!("[pins] publishing v{} with {} entries for channel {}", version, entries.len(), &ch_hex[..12]);
publish_control_edition(transport, community, vsk::PINS, &eid, &content).await?;
let _ = crate::db::community::set_community_pins(&cid_hex, &ch_hex, &content, version as i64);
crate::emit_event(
"community_pins_updated",
&serde_json::json!({ "community_id": cid_hex, "channel_id": ch_hex }),
);
if let Ok(me) = me_pk() {
use nostr_sdk::prelude::ToBech32;
let me_npub = me.to_bech32().unwrap_or_else(|_| me.to_hex());
note_pins_modified(&ch_hex, version, &me_npub, now_ms() / 1000).await;
}
Ok(())
})
.await
}
/// One centered system row per adopted Pin List edition — "X modified the
/// Pins". The id is deterministic on (channel, version), so the publisher's
/// echo and every fold that adopts the same edition collapse into one row,
/// and a catch-up fold stamps the edition's own time so history sorts true.
async fn note_pins_modified(channel_hex: &str, version: u64, actor_npub: &str, at_secs: u64) {
let event_id = format!("pins-mod-{}-v{}", &channel_hex[..16], version);
let inserted = crate::db::events::save_system_event_at(
&event_id,
channel_hex,
crate::stored_event::SystemEventType::PinsModified,
actor_npub,
None,
at_secs,
None,
None,
)
.await
.unwrap_or(false);
if inserted {
crate::emit_event(
"system_event",
&serde_json::json!({
"conversation_id": channel_hex,
"event_id": event_id,
"event_type": crate::stored_event::SystemEventType::PinsModified.as_u8(),
"member_pubkey": actor_npub,
}),
);
}
}
/// The current entries this writer may build on. Replace-entire cuts sharply
/// (§7): an empty view has two innocent causes indistinguishable from an empty
/// list, so a writer MUST refuse to build from a list it could not read.
fn writable_pin_entries(community: &CommunityV2, channel_id: &ChannelId) -> Result<Vec<super::pins::PinEntry>, String> {
let current = read_channel_pins(community, channel_id)?;
if current.sealed {
return Err("this channel's pins are sealed under a key you don't hold; pinning would erase them".to_string());
}
Ok(current.pins.into_iter().map(|p| p.entry).collect())
}
/// Pin a message: recover its wrap, rebuild its proof, append, republish.
///
/// The seal is re-fetched from the community relays by the stored wrapper id —
/// the DB retains rumors, not seals, and a proof needs the seal verbatim.
pub async fn pin_message<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
rumor_id_hex: &str,
) -> Result<(), String> {
crate::db::scoped(async move {
let ch = community.channel(channel_id).ok_or("no such channel in this community")?.clone();
let ch_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
let mut entries = writable_pin_entries(community, channel_id)?;
if entries.len() >= super::pins::PIN_MAX_ENTRIES {
return Err(format!("this channel already holds {} pins; unpin one first", super::pins::PIN_MAX_ENTRIES));
}
// Idempotent: re-pinning an already-pinned message is a no-op, not an error.
if entries
.iter()
.filter_map(|e| super::pins::verify_pin_entry(e, &ch_hex))
.any(|v| v.rumor_id == rumor_id_hex)
{
return Ok(());
}
let (wrap_id, _tags) = crate::db::events::get_event_wrap_context(rumor_id_hex)?
.ok_or("message not found in this device's history")?;
let wrap_id = wrap_id.ok_or("this message's original wrap id was not recorded")?;
// Recover the wrap verbatim — Full evidence: a pin is a permanent artifact,
// so don't build it from the first relay to answer.
let wraps = transport
.fetch(
&Query {
ids: vec![wrap_id.clone()],
kinds: vec![super::stream::KIND_WRAP],
limit: Some(1),
evidence: crate::community::transport::Evidence::Full,
..Default::default()
},
&community.relays,
)
.await?;
let wrap = wraps
.iter()
.find(|w| w.id.to_hex() == wrap_id)
.ok_or("the message's wrap is no longer served by this community's relays")?;
// The stored row does not retain the rumor's epoch binding, so re-derive it
// the way history reads do: try the channel's every held plane coordinate,
// current epoch first, until the wrap opens AND carries this rumor. The
// open itself verifies the channel + epoch binding, so a false coordinate
// fails closed rather than mis-attributing.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let mut coords: Vec<(u64, [u8; 32])> = Vec::new();
if ch.private {
if let Some(k) = ch.key {
coords.push((ch.epoch.0, k));
}
let held = crate::db::community::held_epoch_keys(&cid_hex, &ch_hex).unwrap_or_default();
coords.extend(held.into_iter().filter(|(_, k)| *k != community.community_root).map(|(ep, k)| (ep.0, k)));
} else {
coords.push((community.root_epoch.0, community.community_root));
let held = crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap_or_default();
coords.extend(held.into_iter().map(|(ep, k)| (ep.0, k)));
}
coords.dedup();
// A restricted Channel's posts sit at their writer epoch's address, under a read epoch's key.
let writer = ch.writers.as_ref().and_then(|l| l.writers().find(|(_, pk, _)| *pk == wrap.pubkey.to_bytes()).map(|(e, ..)| e));
let mut found: Option<(super::stream::OpenedStream, [u8; 32])> = None;
for (epoch, ikm) in coords {
let group = channel_group_key(&ikm, &ch.id, Epoch(epoch));
let event = match writer {
Some(wepoch) => super::chat::open_writer_chat_event(wrap, &wrap.pubkey, wepoch, group.conv_key(), channel_id, Epoch(epoch)),
None => super::chat::open_chat_event(wrap, &group, channel_id, Epoch(epoch)),
};
if let Ok(super::chat::ChatEvent::Message { opened, .. }) = event {
if opened.rumor_id.to_hex() == rumor_id_hex {
let conv: [u8; 32] = group
.conv_key()
.as_bytes()
.try_into()
.map_err(|_| "conversation key size".to_string())?;
found = Some((opened, conv));
break;
}
}
}
let Some((opened, conv_key)) = found else {
return Err("that message is from a key epoch this device no longer holds".to_string());
};
let entry = super::pins::build_pin_entry(&opened, &conv_key, &ch_hex).map_err(|e| match e {
super::pins::PinBuildFailure::NotEncrypted => "this message's seal form cannot be pinned".to_string(),
super::pins::PinBuildFailure::BadPayload => "that message is from a key epoch this device no longer holds".to_string(),
super::pins::PinBuildFailure::Unverifiable => "this message's proof did not verify".to_string(),
})?;
entries.push(entry);
publish_pin_list(transport, community, &ch, &entries).await
})
.await
}
/// The deriving secret (ikm) for a channel plane at `epoch` — the same lookup
/// `channel_conv_key_at` performs, surfaced for the open path.
fn channel_conv_ikm(community: &CommunityV2, ch: &ChannelV2, epoch: u64) -> Result<[u8; 32], String> {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
if ch.private {
if ch.epoch.0 == epoch {
return ch.key.ok_or("this private channel's key has not arrived yet".to_string());
}
let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
crate::db::community::held_epoch_keys(&cid_hex, &ch_hex)
.unwrap_or_default()
.into_iter()
.find(|(ep, _)| ep.0 == epoch)
.map(|(_, k)| k)
.ok_or("that message is from a key epoch this device no longer holds".to_string())
} else if community.root_epoch.0 == epoch {
Ok(community.community_root)
} else {
crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX)
.unwrap_or_default()
.into_iter()
.find(|(ep, _)| ep.0 == epoch)
.map(|(_, k)| k)
.ok_or("that message is from a root epoch this device no longer holds".to_string())
}
}
/// Unpin a message: the next edition without the entry (§7 — no deletion event).
pub async fn unpin_message<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
channel_id: &ChannelId,
rumor_id_hex: &str,
) -> Result<(), String> {
let ch = community.channel(channel_id).ok_or("no such channel in this community")?.clone();
let ch_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
let entries = writable_pin_entries(community, channel_id)?;
let kept: Vec<super::pins::PinEntry> = entries
.into_iter()
.filter(|e| {
super::pins::verify_pin_entry(e, &ch_hex)
.map(|v| v.rumor_id != rumor_id_hex)
// An entry we can't verify is kept: unpin removes exactly the
// named message, never collateral.
.unwrap_or(true)
})
.collect();
publish_pin_list(transport, community, &ch, &kept).await
}
/// §7 curator duties: converge the Pin List when a pinned message is deleted
/// or edited. Spawned fire-and-forget from ingest — a non-curator, a sealed
/// list, or an unpinned target all no-op silently; the duty is voluntary.
pub(crate) fn spawn_pin_duty(channel_hex: &str, target_rumor_hex: &str, edit: Option<super::stream::OpenedStream>) {
let channel_hex = channel_hex.to_string();
let target = target_rumor_hex.to_string();
crate::db::spawn_bound(async move {
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
let _ = run_pin_duty(&transport, &channel_hex, &target, edit).await;
});
}
/// The duty body, transport-injected so tests can drive it end to end.
///
/// The affected author acts at once; every other PIN_MESSAGES holder waits a
/// deterministic 5-25s stagger (hashed from (me, target) — no thundering herd
/// of racing editions) and re-reads before publishing, so a duty another
/// curator already performed dissolves into a no-op.
async fn run_pin_duty<T: Transport + ?Sized>(
transport: &T,
channel_hex: &str,
target: &str,
edit: Option<super::stream::OpenedStream>,
) -> Result<(), String> {
use crate::community::roles::Permissions;
let Some(cid_hex) = crate::db::community::community_id_for_channel(channel_hex)? else {
return Ok(());
};
let cid = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&cid_hex));
let Some(community) = crate::db::community::load_community_v2(&cid)? else {
return Ok(());
};
let channel_id = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_hex));
// Cheap pre-checks before any waiting: pinned target, readable list, held bit.
let read = read_channel_pins(&community, &channel_id)?;
if read.sealed {
return Ok(());
}
let Some(hit) = read.pins.iter().find(|p| p.rumor_id == target) else {
return Ok(());
};
if let Some(ed) = &edit {
// Monotonic: a bundle at or past this revision needs no refresh.
if hit.edited.as_ref().is_some_and(|held| held.ms >= ed.at_ms) {
return Ok(());
}
}
let me = me_pk()?;
let me_hex = me.to_hex();
let owner_hex = community.owner()?.to_hex();
let roster = crate::db::community::get_community_roles(&cid_hex)?;
if !roster.is_authorized(&me_hex, Some(&owner_hex), Permissions::PIN_MESSAGES) {
return Ok(());
}
if hit.author != me_hex {
let mut h: u32 = 0;
for b in me_hex.bytes().chain(target.bytes()) {
h = h.wrapping_mul(31).wrapping_add(u32::from(b));
}
crate::rt::time::sleep(std::time::Duration::from_secs(5 + u64::from(h % 21))).await;
}
// Re-read after the stagger: another curator's edition may have landed.
let read = read_channel_pins(&community, &channel_id)?;
if read.sealed {
return Ok(());
}
let Some(hit) = read.pins.iter().find(|p| p.rumor_id == target) else {
return Ok(());
};
let ch = community.channel(&channel_id).ok_or("no such channel")?.clone();
let entries: Vec<super::pins::PinEntry> = match &edit {
// Deletion: the next edition simply omits the entry (§7 — replace-entire).
None => read
.pins
.iter()
.filter(|p| p.rumor_id != target)
.map(|p| p.entry.clone())
.collect(),
// Edit: the same entry, its bundle refreshed to the newest revision.
Some(ed) => {
if hit.edited.as_ref().is_some_and(|held| held.ms >= ed.at_ms) {
return Ok(());
}
let ch_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
// The edit sealed under the channel's current plane in the common
// (realtime) case; older epochs are tried like every other read.
let mut bundle = None;
let mut epochs: Vec<u64> = vec![if ch.private { ch.epoch.0 } else { community.root_epoch.0 }];
let scope = if ch.private { ch_hex.clone() } else { crate::community::SERVER_ROOT_SCOPE_HEX.to_string() };
epochs.extend(
crate::db::community::held_epoch_keys(&cid_hex, &scope)
.unwrap_or_default()
.into_iter()
.map(|(ep, _)| ep.0),
);
epochs.dedup();
for epoch in epochs {
let Some(conv) = channel_conv_key_at(&community, &ch, epoch) else { continue };
if let Ok(b) = super::pins::build_pin_edit_bundle(ed, &conv, &hit.author, target, &ch_hex) {
bundle = Some(b);
break;
}
}
let Some(bundle) = bundle else { return Ok(()) };
read.pins
.iter()
.map(|p| {
let mut entry = p.entry.clone();
if p.rumor_id == target {
entry.edit = Some(bundle.clone());
}
entry
})
.collect()
}
};
crate::log_info!(
"[pins] duty {} for target {} in channel {}",
if edit.is_some() { "edit-refresh" } else { "omission" },
&target[..12],
&channel_hex[..12]
);
publish_pin_list(transport, &community, &ch, &entries).await
}
/// Communities this session has already offered [`upgrade_admin_role_pin_bit`].
/// Per session: whether the account folding is the owner decides what it does.
struct AdminPinUpgraded;
/// `true` the first time this session asks for `community`.
fn first_admin_pin_upgrade(community: &crate::community::CommunityId) -> bool {
let set = crate::db::current_session()
.scoped::<AdminPinUpgraded, std::sync::Mutex<std::collections::HashSet<[u8; 32]>>>();
let first = set.lock().unwrap_or_else(|e| e.into_inner()).insert(community.0);
first
}
/// Silent owner-side widening: an Admin role published before PIN_MESSAGES
/// existed gains the bit, so delegated admins can curate pins in communities
/// founded before this build. One edition, idempotent, converges across owner
/// devices (both publish the same widened mask as editions of one entity).
pub async fn upgrade_admin_role_pin_bit<T: Transport + ?Sized>(
transport: &T,
community: &CommunityV2,
) -> Result<bool, String> {
use crate::community::roles::{Permissions, RoleScope};
let my_pk = me_pk()?;
if community.owner()? != my_pk {
return Ok(false);
}
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let roles = crate::db::community::get_community_roles(&cid_hex)?;
let Some(role) = roles.roles.iter().find(|r| {
matches!(r.scope, RoleScope::Server)
&& r.permissions.contains(Permissions::ADMIN_FOUNDING_MASK)
&& !r.permissions.contains(Permissions::PIN_MESSAGES)
}) else {
return Ok(false);
};
let mut widened = role.clone();
widened.permissions.0 |= Permissions::PIN_MESSAGES;
set_role(transport, community, &widened).await?;
Ok(true)
}
/// Timings of one control follow's stages over what `transport` serves, for `cargo bench`:
/// (the read with its folds, one `fold_authority`, one `apply_control_fold`, editions read).
#[cfg(feature = "bench")]
pub(crate) async fn bench_control_stages<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> (std::time::Duration, std::time::Duration, std::time::Duration, usize) {
use crate::rt::time_std::Instant;
let t = Instant::now();
let read = read_control(transport, community).await.unwrap();
let read_at = t.elapsed();
let t = Instant::now();
let authority = fold_authority(community, &read.editions, &read.floors);
let authority_at = t.elapsed();
let t = Instant::now();
std::hint::black_box(apply_control_fold(community, &read.editions, &read.floors, &authority));
(read_at, authority_at, t.elapsed(), read.editions.len())
}
/// Forget every Control wrap held for `community`, as on a device that has read none, for `cargo bench`.
#[cfg(feature = "bench")]
pub(crate) fn bench_forget_control_wraps(community: &CommunityV2) {
let view = control_store::View::of(community);
for (id, _) in view.held().unwrap_or_default() {
view.forget(&id);
}
let _ = crate::db::remove_setting(&format!("ctl_reads:{}", community.id().to_hex()));
}
/// Whether follows read through the wraps held, for `cargo bench`.
#[cfg(feature = "bench")]
pub(crate) fn bench_control_store_on() -> bool {
control_store::mode() == control_store::Mode::On
}
/// An admin's whole read of the Control Plane, for `cargo bench`: the editions it held.
#[cfg(feature = "bench")]
pub(crate) async fn bench_control_whole<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> usize {
fetch_control_plane_whole(transport, community).await.map_or(0, |editions| editions.len())
}
/// One `ledger_chain_ok` over a Writers ledger `n` versions long, every edition authorized, read
/// newest first or oldest first, for `cargo bench`.
#[cfg(feature = "bench")]
pub(crate) fn bench_ledger_chain(n: usize, newest_first: bool) -> std::time::Duration {
use super::writers::{Ledger, Spell};
let ch = ChannelId([7; 32]);
let author = Keys::generate().public_key();
let base = now_ms() - (n as u64 + 10) * 1000;
let mut ledger = Ledger::new(&ch);
let mut editions = Vec::with_capacity(n);
let mut prev = None;
for i in 0..n as u64 {
let at = base + i * 1000;
let spell = Spell::Writer { epoch: Epoch(i + 1), pk: Keys::generate().public_key().to_bytes(), root: Epoch(0), by: author.to_bytes(), certifier: None };
ledger = ledger.appended(at, spell).expect("a ledger that grows");
let self_hash = crate::crypto::sha256::digest(&i.to_le_bytes());
editions.push(ParsedEdition {
author,
vsk: String::new(),
entity_id: [0; 32],
version: i + 1,
prev_hash: prev,
content: ledger.to_json(),
self_hash,
created_at: at / 1000,
inner_id: self_hash,
authority: None,
binding: None,
});
prev = Some(self_hash);
}
if newest_first {
editions.reverse();
}
let group: Vec<&ParsedEdition> = editions.iter().collect();
let authorized = vec![true; n];
let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.0);
let t = crate::rt::time_std::Instant::now();
let ok = ledger_chain_ok(&group, &authorized, &ch_hex, &|e| (0, e.inner_id), None);
let took = t.elapsed();
assert!(ok.len() == n && ok.values().all(|v| *v), "every edition of a well-formed chain stands");
took
}
#[cfg(test)]
mod tests {
std::thread_local! {
/// The Roster fixpoint's round bound, when a test sets one on its thread.
pub(super) static FOLD_BOUND: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
/// [`replay`] on fresh scratch for every call, as it ran before reusing it.
pub(super) static FRESH_SCRATCH: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
// The legacy (pre-split) Control derivation, still reachable for the
// migration-compat paths under test.
use super::super::derive::control_group_key;
use crate::ClientRelayExt;
use super::super::super::transport::memory::MemoryRelay;
use super::*;
mod control_sync;
mod paged_walks;
mod relay_reads;
use crate::community::roles::{MemberGrant, Permissions, Role, RoleScope};
/// A distinct npub-shaped account-dir name (bech32 charset) per counter.
fn account_name(n: u32) -> String {
const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
let mut acct = String::from("npub1");
let mut v = n as usize;
for _ in 0..58 {
acct.push(B[v % 32] as char);
v = v / 32 + 7;
}
acct
}
/// One test participant: its identity keys and its isolated account DB dir.
struct Actor {
keys: Keys,
account: String,
}
/// Two participants sharing one relay but isolated per-account DBs — the
/// cross-account harness a real invite/join loop needs. `swap_to` mirrors a
/// live `swap_session`: re-point the DB pool + rebind the identity + clear
/// the per-account id caches, so account A's community is invisible to B
/// until B legitimately joins.
struct TestBed {
_tmp: tempfile::TempDir,
_guard: std::sync::MutexGuard<'static, ()>,
relay: MemoryRelay,
relays: Vec<String>,
}
impl TestBed {
fn new() -> (TestBed, Actor, Actor) {
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(70_000);
let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
crate::db::close_database();
crate::db::clear_id_caches();
let tmp = tempfile::tempdir().unwrap();
crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
let mk = || {
let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let account = account_name(n);
std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
crate::db::set_current_account(account.clone()).unwrap();
crate::db::init_database(&account).unwrap();
Actor { keys: Keys::generate(), account }
};
let owner = mk();
let member = mk();
let _ = crate::state::take_nostr_client();
let bed = TestBed {
_tmp: tmp,
_guard: guard,
relay: MemoryRelay::new(),
relays: vec!["wss://r".to_string()],
};
(bed, owner, member)
}
/// Become `actor`: swap the account DB + identity, as a real session swap.
/// Bumps the session generation like production `swap_session` does — so any task a
/// prior actor spawned (e.g. the migration finalize) dies at its std::sync::Arc<crate::db::Session> check
/// instead of racing this actor's DB (a cross-test flake that can't happen in prod).
fn swap_to(&self, actor: &Actor) {
crate::db::close_database();
crate::db::set_current_account(actor.account.clone()).unwrap();
crate::db::init_database(&actor.account).unwrap();
crate::db::clear_id_caches();
crate::state::MY_SECRET_KEY.store_from_keys(&actor.keys, &[]);
crate::state::set_my_public_key(actor.keys.public_key());
}
}
/// Legacy single-actor helper (the create/send tests below).
pub(super) fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>, Keys) {
let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
crate::db::close_database();
crate::db::clear_id_caches();
let tmp = tempfile::tempdir().unwrap();
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(50_000);
let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let acct = account_name(n);
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 owner = Keys::generate();
crate::state::MY_SECRET_KEY.store_from_keys(&owner, &[]);
crate::state::set_my_public_key(owner.public_key());
(tmp, guard, owner)
}
/// A transport that simulates a session swap landing DURING a fetch await —
/// so a join straddling the fetch sees an invalid session and aborts.
/// Switches to a real second account on the first fetch, then stays out of
/// the way. It BORROWS the relay that built the community — a fresh one
/// would fail verification for want of a control plane, which is not the
/// thing being tested.
struct SwapMidFetch<'a> {
inner: &'a MemoryRelay,
to: String,
armed: std::sync::atomic::AtomicBool,
}
impl<'a> SwapMidFetch<'a> {
fn arm(inner: &'a MemoryRelay) -> Self {
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(88_000);
let to = account_name(N.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
std::fs::create_dir_all(crate::db::shared_test_data_dir().join(&to)).unwrap();
Self { inner, to, armed: std::sync::atomic::AtomicBool::new(true) }
}
}
#[async_trait::async_trait]
impl Transport for SwapMidFetch<'_> {
async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> { Ok(crate::community::transport::PlaneFetch::whole(self.fetch(query, relays).await?)) }
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.inner.publish(e, r).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.inner.publish_durable(e, r).await
}
async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
let out = self.inner.fetch(q, r).await;
if self.armed.swap(false, std::sync::atomic::Ordering::SeqCst) {
crate::db::set_current_account(self.to.clone()).unwrap();
crate::db::init_database(&self.to).unwrap();
}
out
}
}
/// Bumps the session generation on the first `publish_durable` — the rekey
/// crate a private-channel create ships before it writes anything locally.
struct SwapMidPublish {
inner: MemoryRelay,
}
#[async_trait::async_trait]
impl Transport for SwapMidPublish {
async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> { Ok(crate::community::transport::PlaneFetch::whole(self.fetch(query, relays).await?)) }
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.inner.publish(e, r).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
let out = self.inner.publish_durable(e, r).await;
crate::db::close_database();
out
}
async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
self.inner.fetch(q, r).await
}
}
/// A transport whose `fetch` returns a FIXED, UNSORTED event list — modelling
/// the production `LiveTransport` union (first-responding relay's batch, no
/// global newest-first sort), which `MemoryRelay` hides by sorting. This is
/// the only harness that can exercise the revocation-race ordering.
struct FixedFetch {
events: Vec<Event>,
}
#[async_trait::async_trait]
impl Transport for FixedFetch {
async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> { Ok(crate::community::transport::PlaneFetch::whole(self.fetch(query, relays).await?)) }
async fn publish(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
Ok(())
}
async fn publish_durable(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
Ok(())
}
async fn fetch(&self, _q: &Query, _r: &[String]) -> Result<Vec<Event>, String> {
Ok(self.events.clone())
}
}
/// Fetch a pending Direct Invite (kind 3313 giftwrap) addressed to `me` — the
/// indexed inbox query CORD-05 §6 defines: `{1059, #p:[me], #k:["3313"]}`.
async fn fetch_direct_invite(relay: &MemoryRelay, relays: &[String], me: &PublicKey) -> Event {
let q = Query {
kinds: vec![stream::KIND_WRAP],
p_tags: vec![me.to_hex()],
k_tags: vec!["3313".to_string()],
..Default::default()
};
relay.fetch(&q, relays).await.unwrap().into_iter().next().expect("a direct invite is waiting")
}
#[tokio::test]
async fn create_persists_and_reloads_a_v2_community() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let relays = vec!["wss://r".to_string()];
let created = create_community(&relay, "Vectorville", relays.clone(), Some("hi".into())).await.unwrap();
assert!(created.identity.verify());
assert_eq!(created.owner().unwrap(), owner.public_key());
assert_eq!(created.channels.len(), 1);
// Held, and it reloads byte-faithfully.
assert!(crate::db::community::community_held(created.id()).unwrap());
let loaded = crate::db::community::load_community_v2(created.id()).unwrap().expect("reloads");
assert_eq!(loaded.name, "Vectorville");
assert_eq!(loaded.community_root, created.community_root);
assert_eq!(loaded.identity, created.identity);
assert_eq!(loaded.channels[0].id.0, created.channels[0].id.0);
assert!(!loaded.channels[0].private);
// The genesis control editions + the owner Join landed on the relay.
assert!(relay.count_on("wss://r") >= 3, "2 genesis editions + 1 guestbook join");
}
/// The relay stores the event but its OK never arrives.
/// Every publish but a Channel's access-plane deliveries, as a client that doesn't deliver keys
/// with a grant.
struct NoAccessDeliveries<'a>(&'a MemoryRelay, PublicKey);
#[async_trait::async_trait]
impl Transport for NoAccessDeliveries<'_> {
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
if e.pubkey == self.1 {
return Ok(());
}
self.0.publish(e, r).await
}
async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
self.0.fetch(query, relays).await
}
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
self.0.fetch_plane(plane, query, relays).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
if e.pubkey == self.1 {
return Ok(());
}
self.0.publish_durable(e, r).await
}
}
struct LostAck<'a>(&'a MemoryRelay);
#[async_trait::async_trait]
impl Transport for LostAck<'_> {
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.0.publish(e, r).await?;
Err("timed out".into())
}
async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
self.0.fetch(query, relays).await
}
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
self.0.fetch_plane(plane, query, relays).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.0.publish_durable(e, r).await
}
}
/// Nothing reaches the relay.
struct Unreachable<'a>(&'a MemoryRelay);
#[async_trait::async_trait]
impl Transport for Unreachable<'_> {
async fn publish(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
Err("no relay accepted the event".into())
}
async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
self.0.fetch(query, relays).await
}
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
self.0.fetch_plane(plane, query, relays).await
}
async fn publish_durable(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
Err("no relay accepted the event".into())
}
}
/// A message sent through `transport` that fails to publish, and its rumor id.
async fn unconfirmed_send(relay: &MemoryRelay) -> (CommunityV2, ChannelId, String) {
let community = create_community(relay, "Chat", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let ms = now_ms();
let (author, _, epoch) = chat_send_context(&community, &general).unwrap();
let rumor = outbound_rumor(&community, &general, chat::build_message_rumor(author, &general, epoch, "lost", None, &[], vec![], ms));
let id = rumor.id.unwrap().to_hex();
assert!(send_chat_message_at(&Unreachable(relay), &community, &general, "lost", None, &[], vec![], ms).await.is_err());
(community, general, id)
}
#[tokio::test]
async fn a_send_whose_ok_was_lost_counts_as_sent() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Chat", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let id = send_message(&LostAck(&relay), &community, &general, "landed").await.expect("read back from the relay");
assert!(outbox::kept(&id).is_none(), "nothing left to resend");
}
#[tokio::test]
async fn a_failed_send_is_kept_to_go_again_as_itself() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let (community, general, id) = unconfirmed_send(&relay).await;
let wrap = outbox::kept(&id).expect("kept until a relay confirms it");
assert!(crate::db::community::get_message_key(&id).unwrap().is_some(), "deletable even though no relay confirmed it");
relay.publish(&wrap, &community.relays).await.unwrap();
let page = fetch_channel(&relay, &community, &general, 100).await.unwrap();
assert_eq!(page.iter().filter(|f| f.event.opened().rumor_id.to_hex() == id).count(), 1, "the kept wrap is the message itself");
}
#[tokio::test]
async fn our_failed_message_read_back_shows_as_sent() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let (community, general, id) = unconfirmed_send(&relay).await;
let channel = crate::simd::hex::bytes_to_hex_32(&general.0);
{
let mut st = crate::state::STATE.lock().await;
st.ensure_community_chat(&channel);
st.add_message_to_chat(&channel, &crate::types::Message { id: id.clone(), mine: true, failed: true, ..Default::default() });
}
relay.publish(&outbox::kept(&id).unwrap(), &community.relays).await.unwrap();
let me = crate::my_public_key().unwrap();
for f in fetch_channel(&relay, &community, &general, 100).await.unwrap() {
crate::community::v2::inbound::apply_chat_to_state(&mut *crate::state::STATE.lock().await, &f.event, &channel, &me);
}
let st = crate::state::STATE.lock().await;
let (_, row) = st.find_message(&id).expect("still one row");
assert!(!row.failed && !row.pending, "a relay holding it proves it sent");
assert!(outbox::kept(&id).is_none(), "and nothing is resent");
}
#[tokio::test]
async fn owner_sends_and_reads_back_a_message() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Chat", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let id1 = send_message(&relay, &community, &general, "hello world").await.unwrap();
let id2 = send_message(&relay, &community, &general, "second message").await.unwrap();
assert_ne!(id1, id2);
let page = fetch_channel(&relay, &community, &general, 100).await.unwrap();
let texts: Vec<String> = page
.iter()
.filter_map(|f| match &f.event {
ChatEvent::Message { .. } => Some(f.event.opened().rumor.content.clone()),
_ => None,
})
.collect();
assert_eq!(texts, vec!["hello world", "second message"], "messages round-trip in ms order");
}
#[test]
fn send_stamps_never_repeat_within_a_process() {
// Ordering is by the `ms` tag, and an optimized build seals several sends
// per millisecond. Identical stamps fell through to the reader's
// content-derived tiebreak, which knows nothing about which was typed
// first, so a fast sender could watch its own messages come back
// shuffled — the flake in `owner_sends_and_reads_back_a_message` once the
// suite began compiling optimized. Distinctness must not depend on how
// slow the build happens to be.
let stamps: Vec<u64> = (0..5_000).map(|_| next_send_ms()).collect();
for pair in stamps.windows(2) {
assert!(pair[1] > pair[0], "stamps must strictly increase: {} then {}", pair[0], pair[1]);
}
}
#[tokio::test]
async fn same_millisecond_messages_order_by_rumor_id_not_relay_order() {
// Cross-client half: when stamps DO collide (two senders, clock skew),
// every reader must still agree. A bare `ms` sort left ties in whatever
// order the relay served them across pages, so two readers could show the
// same pair in opposite orders. The rumor id is content-derived, so
// pinning ties to it is something every client computes identically.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Ties", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let at = now_ms();
for i in 0..6 {
send_chat_message_at(&relay, &community, &general, &format!("tied {i}"), None, &[], vec![], at)
.await
.unwrap();
}
let page = fetch_channel(&relay, &community, &general, 100).await.unwrap();
let msgs: Vec<(Vec<u8>, String)> = page
.iter()
.filter_map(|f| match &f.event {
ChatEvent::Message { .. } => {
let o = f.event.opened();
Some((o.rumor_id.as_bytes().to_vec(), o.rumor.content.clone()))
}
_ => None,
})
.collect();
assert_eq!(msgs.len(), 6, "all six tied messages read back");
let got: Vec<String> = msgs.iter().map(|(_, c)| c.clone()).collect();
let mut by_id = msgs.clone();
by_id.sort_by(|a, b| a.0.cmp(&b.0));
let expected: Vec<String> = by_id.into_iter().map(|(_, c)| c).collect();
assert_eq!(got, expected, "ties resolve by rumor id, never by the relay's serving order");
}
#[tokio::test]
async fn a_rapid_burst_carries_strictly_increasing_stamps() {
// The call-site half: sends must draw from the monotonic stamp, not the
// raw clock. An optimized build seals several per millisecond, and equal
// stamps hand a sender's own ordering to the content tiebreak, which
// knows nothing about typing order.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Burst", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
for i in 0..8 {
send_message(&relay, &community, &general, &format!("msg {i}")).await.unwrap();
}
let page = fetch_channel(&relay, &community, &general, 100).await.unwrap();
let stamps: Vec<u64> = page
.iter()
.filter_map(|f| match &f.event {
ChatEvent::Message { .. } => Some(f.event.opened().at_ms),
_ => None,
})
.collect();
assert_eq!(stamps.len(), 8);
for pair in stamps.windows(2) {
assert!(pair[1] > pair[0], "a sender's own stamps must strictly increase, got {pair:?}");
}
}
#[tokio::test]
async fn a_second_member_reads_the_public_channel_from_the_root() {
// A member who holds the community_root (via an invite bundle, modeled
// here by cloning the community) reads the owner's public-channel message
// — public channels need no key delivery, they derive from the root.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Public", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
send_message(&relay, &community, &general, "everyone can read this").await.unwrap();
// The "member" reconstructs the same read coordinates from the root.
let member_view = community.clone();
let page = fetch_channel(&relay, &member_view, &general, 100).await.unwrap();
assert_eq!(page.len(), 1);
assert!(matches!(&page[0].event, ChatEvent::Message { .. }));
assert_eq!(page[0].event.opened().rumor.content, "everyone can read this");
}
// ── Two-actor end-to-end (the create → invite → join → message loop) ──────
async fn texts_in<T: crate::community::transport::Transport + ?Sized>(relay: &T, community: &CommunityV2, channel: &ChannelId) -> Vec<String> {
fetch_channel(relay, community, channel, 100)
.await
.unwrap()
.iter()
.filter_map(|f| match &f.event {
ChatEvent::Message { .. } => Some(f.event.opened().rumor.content.clone()),
_ => None,
})
.collect()
}
/// History as the BACK-PAGING cursor reads it: every held epoch. Opening a
/// channel deliberately reads only the live planes, so pre-rotation history is
/// reached by paging, which is what a user scrolling up actually does.
async fn all_texts_in<T: crate::community::transport::Transport + ?Sized>(
relay: &T,
community: &CommunityV2,
channel: &ChannelId,
) -> Vec<String> {
let from_now = now_ms() / 1000 + 3600;
fetch_channel_history(
relay,
community,
channel,
100,
8,
None,
Some(from_now),
crate::community::transport::Evidence::Quorum,
|_, _| true,
|_| Default::default(),
)
.await
.unwrap()
.iter()
.filter_map(|f| match &f.event {
ChatEvent::Message { .. } => Some(f.event.opened().rumor.content.clone()),
_ => None,
})
.collect()
}
#[tokio::test]
async fn direct_invite_full_loop_owner_and_member_converse() {
let (bed, owner, member) = TestBed::new();
// Owner creates a community, posts, and Direct-Invites the member's npub.
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
send_message(&bed.relay, &community, &general, "owner: welcome!").await.unwrap();
send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
// Member (a DIFFERENT account, no prior knowledge) finds + accepts the invite.
bed.swap_to(&member);
assert!(
crate::db::community::load_community_v2(community.id()).unwrap().is_none(),
"the member does not hold the community before joining"
);
let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
assert_eq!(joined.id().0, community.id().0, "joined the same community");
assert!(joined.identity.verify(), "the joiner independently verifies the owner commitment");
assert_eq!(joined.owner().unwrap(), owner.keys.public_key());
// The member reads the owner's public-channel history and replies.
assert_eq!(texts_in(&bed.relay, &joined, &general).await, vec!["owner: welcome!"]);
send_message(&bed.relay, &joined, &general, "member: thanks for the invite").await.unwrap();
// The owner reads the member's reply.
bed.swap_to(&owner);
assert_eq!(
texts_in(&bed.relay, &community, &general).await,
vec!["owner: welcome!", "member: thanks for the invite"],
"both actors' messages interleave in ms order on the shared channel"
);
// The Guestbook memberlist now folds both participants.
let members = memberlist(&bed.relay, &community).await.unwrap();
assert!(members.contains(&owner.keys.public_key()), "owner is a member (genesis Join)");
assert!(members.contains(&member.keys.public_key()), "member is a member (invite Join)");
assert_eq!(members.len(), 2);
}
#[tokio::test]
async fn a_member_asleep_through_activation_catches_up_on_waking() {
// A device that stopped before Roles v2 (as code from before it would) misses the
// switch, a Role only v2 knows, and a ban that Role's holder refounds. On waking with
// this code it folds the new Roster and follows the rotation it would have refused.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Sleeper", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
bed.swap_to(&member);
let invite = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
let joined = accept_direct_invite(&bed.relay, &invite).await.unwrap();
follow_control(&bed.relay, &joined).await.unwrap();
bed.swap_to(&owner);
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
activate_roles_v2(&bed.relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::BAN | Permissions::KICK).await.unwrap();
let x = Keys::generate();
set_member_roles(&bed.relay, &held(), &x.public_key(), vec![mods]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
act_as(&x);
set_members_banned(&bed.relay, held().id(), &[Keys::generate().public_key()], true).await.unwrap();
act_as(&owner.keys);
let epoch = held().root_epoch;
assert_ne!(epoch, community.root_epoch, "the Mods holder refounded");
send_message(&bed.relay, &held(), &general, "after the ban").await.unwrap();
// Waking: floors written before families existed record none.
bed.swap_to(&member);
crate::db::get_write_connection_guard_static().unwrap().execute("UPDATE community_edition_heads SET family = NULL", []).unwrap();
let mine = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let session = crate::db::current_session();
let _ = follow_rekeys(&bed.relay, &mine(), &session).await;
assert_eq!(mine().root_epoch, community.root_epoch, "on its old Roster the rotator has no standing");
follow_control(&bed.relay, &mine()).await.unwrap();
follow_rekeys(&bed.relay, &mine(), &session).await.unwrap();
follow_control(&bed.relay, &mine()).await.unwrap();
assert_eq!(mine().root_epoch, epoch, "it followed the rotation");
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert!(roster.everyone.is_some(), "on the new Roster");
assert!(roster.is_authorized(&x.public_key().to_hex(), Some(&owner.keys.public_key().to_hex()), Permissions::BAN), "with the Role only it knows");
assert!(texts_in(&bed.relay, &mine(), &general).await.contains(&"after the ban".to_string()), "and reads what was said since");
}
/// Join-time ban gate: an honest client whose npub is on the authorized banlist
/// refuses to join — no Guestbook Join publish, no local write — through the shared
/// accept path every door (direct invite, parked, public link, migration) funnels into.
#[tokio::test]
async fn a_banned_member_is_refused_at_join_time() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "NoEntry", bed.relays.clone(), None).await.unwrap();
send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
set_banlist(&bed.relay, &community, &[member.keys.public_key().to_hex()]).await.unwrap();
bed.swap_to(&member);
let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
let err = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap_err();
assert!(err.contains("banned"), "refusal names the reason: {err}");
assert!(
crate::db::community::load_community_v2(community.id()).unwrap().is_none(),
"a refused join persists nothing"
);
// The gate is the LAST word only for banned members: an unbanned bystander with
// the same invite path still joins (the gate doesn't over-refuse).
bed.swap_to(&owner);
set_banlist(&bed.relay, &community, &[]).await.unwrap();
bed.swap_to(&member);
let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
assert_eq!(joined.id().0, community.id().0, "unban restores joinability");
}
#[tokio::test]
async fn every_device_lists_the_links_another_minted_and_drops_those_it_revoked() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Linked", bed.relays.clone(), 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 a = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, Some("Twitter".into())).await.unwrap();
let b = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
let (ta, tb) = (crate::simd::hex::bytes_to_hex_16(&a.token), crate::simd::hex::bytes_to_hex_16(&b.token));
let listed = || {
let mut out: Vec<(String, String, Option<String>)> = crate::db::community::list_public_invites(&cid_hex).unwrap().into_iter().map(|r| (r.token, r.url, r.label)).collect();
out.sort();
out
};
let minted = listed();
// Another device of the same account: it minted neither.
crate::db::community::delete_public_invite(&ta).unwrap();
crate::db::community::delete_public_invite(&tb).unwrap();
assert!(adopt_invite_list(&bed.relay, &held()).await.unwrap());
assert_eq!(listed(), minted, "both links, as minted");
assert!(!adopt_invite_list(&bed.relay, &held()).await.unwrap(), "nothing more to take");
// Revoked on the first device while this one still lists it.
revoke_public_link(&bed.relay, &held(), &ta).await.unwrap();
crate::db::community::adopt_public_invite(&ta, &cid_hex, &a.url, None, Some("Twitter"), 0).unwrap();
assert!(adopt_invite_list(&bed.relay, &held()).await.unwrap());
assert_eq!(listed().into_iter().map(|(t, ..)| t).collect::<Vec<_>>(), vec![tb]);
}
#[tokio::test]
async fn public_link_full_loop() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Public Guild", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
send_message(&bed.relay, &community, &general, "come on in").await.unwrap();
// Mint a shareable link (a non-stock relay so the fragment carries it).
let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
assert!(link.url.starts_with("https://vectorapp.io/invite/"));
assert!(link.url.contains('#'), "the fragment carries the token");
// Member joins purely from the URL string.
bed.swap_to(&member);
let joined = accept_public_link(&bed.relay, &link.url).await.unwrap();
assert_eq!(joined.id().0, community.id().0);
assert_eq!(texts_in(&bed.relay, &joined, &general).await, vec!["come on in"]);
}
#[test]
fn bundle_of_snapshots_the_held_icon() {
let owner = Keys::generate();
let g = control::genesis(&owner, control::CommunityMetadata { name: "Logo".into(), ..Default::default() }, 1_000).unwrap();
let mut c = CommunityV2::from_genesis(&g, "Logo", None, vec!["wss://r".into()], 0);
let icon = control::ImageRef { url: "https://blossom.example/i".into(), key: "k".into(), nonce: "n".into(), hash: "h".into(), extra: Default::default() };
c.icon = Some(icon.clone());
let bundle = bundle_of(&c, BundleAudience::Link, None, None, None);
assert_eq!(bundle.icon, Some(icon), "a parked invite renders the real logo from the mint-time snapshot");
}
#[test]
fn addressing_roots_fan_current_plus_archived_bounded_and_deduped() {
// follow_rekeys' fetch fan AND streamauth's plane registration share
// this. A channel rekey rides the PRIOR root (CORD-06 D2), so the set
// MUST include archived roots or an AUTH-gated relay never serves the
// rotation crate → the channel stalls at its old epoch.
let (_tmp, _guard, _owner) = init_test_db();
let cur_root = [9u8; 32];
let cid = crate::community::CommunityId([1u8; 32]);
let cid_hex = cid.to_hex();
// No archives yet → just the current root.
let roots = channel_rekey_addressing_roots(cur_root, &cid_hex);
assert_eq!(roots, vec![cur_root], "with no archived roots the fan is the current root alone");
// Archive two prior roots (freshest-first ordering is asserted below).
crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 0, &[1u8; 32]).unwrap();
crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 1, &[2u8; 32]).unwrap();
let roots = channel_rekey_addressing_roots(cur_root, &cid_hex);
assert_eq!(roots[0], cur_root, "current root leads");
assert!(roots.contains(&[1u8; 32]) && roots.contains(&[2u8; 32]), "both archived roots are in the fan");
assert_eq!(roots.len(), 3, "current + 2 archived, no dupes");
// Freshest-archived-first (epoch 1 before epoch 0).
assert_eq!(roots[1], [2u8; 32], "higher archived epoch is addressed before the lower");
// A stored root equal to the CURRENT one must not duplicate.
crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 2, &cur_root).unwrap();
let roots = channel_rekey_addressing_roots(cur_root, &cid_hex);
assert_eq!(roots.iter().filter(|r| **r == cur_root).count(), 1, "the current root is never duplicated");
// Cap: many archives truncate to MAX_ADDRESSING_ROOTS.
for e in 3..20u64 {
crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, e, &[e as u8; 32]).unwrap();
}
let roots = channel_rekey_addressing_roots(cur_root, &cid_hex);
assert_eq!(roots.len(), MAX_ADDRESSING_ROOTS, "the fan is bounded so a relay can't feed an unbounded walk");
}
#[tokio::test]
async fn inspecting_a_public_link_names_every_plane_and_publishes_nothing() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
send_message(&bed.relay, &community, &general, "hello").await.unwrap();
let staff = create_private_channel(&bed.relay, &community, "staff").await.unwrap();
let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
send_message(&bed.relay, &community, &staff, "staff only").await.unwrap();
let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
bed.swap_to(&member);
let before = bed.relay.stored_count();
let seen = inspect_public_link(&bed.relay, &link.url, None, None).await.unwrap();
assert_eq!(bed.relay.stored_count(), before, "inspecting publishes nothing");
assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_none(), "nor joins");
assert!(seen.verified);
assert_eq!((seen.name.as_str(), seen.community_id.as_str()), ("Guild", community.id().to_hex().as_str()));
// A public link carries no Private Channel's key: #staff's posts are the one address it
// can't name, and the inspection says so.
let staff_ch = community.channels.iter().find(|c| c.id == staff).unwrap();
let (staff_key, staff_epoch) = community.channel_secret(staff_ch);
let staff_posts = channel_group_key(&staff_key, &staff, staff_epoch).pk().to_hex();
assert!(seen.channels.iter().any(|c| c.name == "staff" && c.keyless));
assert!(seen.gaps.iter().any(|g| g.contains("#staff")), "{:?}", seen.gaps);
let named: std::collections::HashSet<&str> = seen.planes.iter().map(|p| p.pk.as_str()).collect();
let wraps = bed.relay.fetch(&Query { kinds: vec![stream::KIND_WRAP], ..Default::default() }, &bed.relays).await.unwrap();
let unnamed: Vec<String> = wraps.iter().map(|w| w.pubkey.to_hex()).filter(|pk| !named.contains(pk.as_str())).collect();
assert_eq!(unnamed, vec![staff_posts], "planes: {:#?}", seen.planes);
assert!(named.contains(link_signer_of(&link.url).as_str()));
}
#[test]
fn a_fold_takes_the_floors_of_its_family_as_their_rows_record_it() {
let (_tmp, _guard, _owner) = init_test_db();
let cid = "cd".repeat(32);
let (h, i, a) = ([1u8; 32], [2u8; 32], [3u8; 32]);
use crate::db::community::{set_edition_head_at_epoch, set_family_head_at_epoch, FLOOR_AUTHORITY, FLOOR_CONTROL};
set_family_head_at_epoch(&cid, "grant", 1, &h, &i, &a, 0, FLOOR_AUTHORITY).unwrap();
set_family_head_at_epoch(&cid, "meta", 1, &h, &i, &a, 0, FLOOR_CONTROL).unwrap();
set_family_head_at_epoch(&cid, "future", 1, &h, &i, &a, 0, "x").unwrap();
set_edition_head_at_epoch(&cid, "legacy", 1, &h, &i, &a, 0).unwrap();
let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid).unwrap().into_iter().map(|(e, f)| (e, (f.1, f.2, f.3, f.4, f.5))).collect();
let families = crate::db::community::edition_head_families(&cid).unwrap();
for family in [FLOOR_AUTHORITY, FLOOR_CONTROL] {
let mut by_query: Vec<String> = floors.keys().filter(|k| families.get(*k).is_none_or(|f| f == family)).cloned().collect();
let mut taken: Vec<String> = floors_of_family(&floors, family).into_keys().collect();
by_query.sort();
taken.sort();
assert_eq!(taken, by_query, "{family}");
}
let mut authority: Vec<String> = floors_of_family(&floors, FLOOR_AUTHORITY).into_keys().collect();
authority.sort();
assert_eq!(authority, ["grant", "legacy"], "a family this build doesn't know goes to neither fold");
}
#[test]
fn ledger_chains_are_judged_as_the_reference_judges_them() {
use super::super::writers::{Ledger, Spell};
let mut seed: u64 = 0x9e37_79b9_7f4a_7c15;
let mut rnd = move |n: usize| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % n as u64) as usize
};
let (ch, elsewhere) = (ChannelId([7; 32]), ChannelId([8; 32]));
let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.0);
let authors: Vec<Keys> = (0..3).map(|_| Keys::generate()).collect();
// One that is no point on the curve: a ledger naming it never parses.
let writers: Vec<[u8; 32]> = (0..6).map(|_| Keys::generate().public_key().to_bytes()).chain([[0xff; 32]]).collect();
let unserved: Vec<[u8; 32]> = (1..=3u8).map(|k| [k; 32]).collect();
let now = now_ms();
let mut forked = 0;
for case in 0..600u64 {
let n = 1 + rnd(36);
let mut eds: Vec<ParsedEdition> = Vec::new();
let mut ledgers: Vec<Ledger> = Vec::new();
for i in 0..n {
if !eds.is_empty() && rnd(14) == 0 {
// The same edition again, as two relays serve it. A Writers edition is read
// marked only, so its hash covers its signer: a copy is a copy.
let k = rnd(eds.len());
ledgers.push(ledgers[k].clone());
eds.push(eds[k].clone());
continue;
}
let parent = (!eds.is_empty() && rnd(5) != 0).then(|| rnd(eds.len()));
let author = &authors[rnd(authors.len())];
let at = now - 5_000_000 + i as u64 * 1000;
let base = parent.map(|p| ledgers[p].clone()).unwrap_or_else(|| Ledger::new(&ch));
let epoch = base.writers().last().map_or(1, |(e, ..)| e.0 + 1);
let spell = match rnd(5) {
0 => Spell::Open,
1 => Spell::Stop { writer: writers[rnd(writers.len())] },
_ => Spell::Writer { epoch: Epoch(epoch), pk: writers[rnd(writers.len())], root: Epoch(0), by: author.public_key().to_bytes(), certifier: None },
};
let grown = base.appended(at, spell).unwrap_or_else(|| base.clone());
let content = match rnd(12) {
0 => "not a ledger".to_string(),
1 => Ledger::new(&elsewhere).appended(at, Spell::Open).unwrap().to_json(),
2 => base.to_json(),
_ => grown.to_json(),
};
let prev_hash = match parent {
Some(p) => Some(eds[p].self_hash),
None if rnd(3) == 0 => Some(unserved[rnd(unserved.len())]),
None => None,
};
let version = parent.map_or(1, |p| eds[p].version + 1) + u64::from(rnd(12) == 0);
let created_at = at / 1000 + if rnd(10) == 0 { 3600 } else { 0 };
let self_hash = crate::crypto::sha256::digest(&[case.to_le_bytes(), (i as u64).to_le_bytes()].concat());
eds.push(ParsedEdition {
author: author.public_key(),
vsk: String::new(),
entity_id: [0; 32],
version,
prev_hash,
content,
self_hash,
created_at,
inner_id: self_hash,
authority: None,
binding: None,
});
ledgers.push(grown);
}
forked += usize::from(eds.iter().filter(|e| eds.iter().filter(|o| o.prev_hash == e.prev_hash && e.prev_hash.is_some()).count() > 1).count() > 0);
let mut order: Vec<usize> = (0..eds.len()).collect();
for k in (1..order.len()).rev() {
order.swap(k, rnd(k + 1));
}
let group: Vec<&ParsedEdition> = order.iter().map(|&k| &eds[k]).collect();
let authorized: Vec<bool> = group.iter().map(|_| rnd(4) != 0).collect();
let anchor = match rnd(4) {
0 => {
let k = rnd(eds.len());
Some((eds[k].self_hash, ledgers[k].clone()))
}
1 => Some((unserved[rnd(unserved.len())], ledgers[rnd(ledgers.len())].clone())),
_ => None,
};
let key = |e: &ParsedEdition| (u32::from(e.author.to_bytes()[0] % 2), e.inner_id);
assert_eq!(
ledger_chain_ok(&group, &authorized, &ch_hex, &key, anchor.as_ref()),
ledger_chain_ok_reference(&group, &authorized, &ch_hex, &key, anchor.as_ref()),
"case {case}"
);
}
assert!(forked > 200, "the cases fork: {forked}");
}
#[tokio::test]
async fn an_invite_bundle_inspects_as_its_link_does_less_the_link() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
send_message(&bed.relay, &community, &community.channels[0].id, "hello").await.unwrap();
let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
let json = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();
bed.swap_to(&member);
let by_link = inspect_public_link(&bed.relay, &link.url, None, None).await.unwrap();
let before = bed.relay.stored_count();
let bundle = CommunityInvite::from_bundle_json(&json).unwrap();
let by_bundle = inspect_bundle(&bed.relay, &bundle, None, None).await.unwrap();
assert_eq!(bed.relay.stored_count(), before, "inspecting publishes nothing");
assert!(by_bundle.verified);
assert_eq!(by_bundle.link_signer, None);
assert!(!serde_json::to_value(&by_bundle).unwrap().as_object().unwrap().contains_key("link_signer"));
assert_eq!((by_bundle.name.as_str(), by_bundle.community_id.as_str()), ("Guild", by_link.community_id.as_str()));
let signer = link_signer_of(&link.url);
let from_link: Vec<&InspectedPlane> = by_link.planes.iter().filter(|p| p.pk != signer).collect();
assert_eq!(by_bundle.planes.iter().collect::<Vec<_>>(), from_link);
}
#[tokio::test]
async fn an_inspection_reads_the_newest_posts_as_their_authors_left_them() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
let random = create_public_channel(&bed.relay, &community, "random").await.unwrap();
let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
create_private_channel(&bed.relay, &community, "staff").await.unwrap();
let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let tick = || crate::rt::time::sleep(std::time::Duration::from_millis(3));
let one = send_message(&bed.relay, &community, &general, "one").await.unwrap();
tick().await;
let two = send_message(&bed.relay, &community, &general, "two").await.unwrap();
tick().await;
let three = send_message(&bed.relay, &community, &general, "three").await.unwrap();
tick().await;
send_message(&bed.relay, &community, &random, "r1").await.unwrap();
tick().await;
send_edit(&bed.relay, &community, &general, &two, "two, edited", &[]).await.unwrap();
send_delete(&bed.relay, &community, &general, &three, 9, None).await.unwrap();
let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
bed.swap_to(&member);
// Anyone holding the link's keys can wrap an edit or a delete; only an author's own count.
let held = CommunityV2::from_bundle(&fetch_public_bundle(&bed.relay, &link.url).await.unwrap(), 0).unwrap();
tick().await;
send_edit(&bed.relay, &held, &general, &two, "hijacked", &[]).await.unwrap();
send_delete(&bed.relay, &held, &general, &one, 9, None).await.unwrap();
let read = |count: usize, channels: &[&str]| MessageRead { count, channels: channels.iter().map(|c| c.to_string()).collect() };
let texts = |seen: &Inspection| seen.messages.iter().map(|m| (m.channel.clone(), m.content.clone(), m.edited)).collect::<Vec<_>>();
let before = bed.relay.stored_count();
let all = inspect_public_link(&bed.relay, &link.url, None, Some(&read(2, &[]))).await.unwrap();
assert_eq!(bed.relay.stored_count(), before, "reading publishes nothing");
assert_eq!(texts(&all), [("general".into(), "two, edited".into(), true), ("random".into(), "r1".into(), false)]);
let npub = nostr_sdk::prelude::ToBech32::to_bech32(&owner.keys.public_key()).unwrap();
assert!(all.messages.iter().all(|m| m.author == npub));
let general_only = inspect_public_link(&bed.relay, &link.url, None, Some(&read(10, &["#General"]))).await.unwrap();
assert_eq!(texts(&general_only), [("general".into(), "one".into(), false), ("general".into(), "two, edited".into(), true)], "a self-deleted post is gone");
let missing = inspect_public_link(&bed.relay, &link.url, None, Some(&read(5, &["nope"]))).await.unwrap_err();
assert!(missing.contains("#general") && missing.contains("#random"), "{missing}");
assert!(inspect_public_link(&bed.relay, &link.url, None, Some(&read(5, &["staff"]))).await.unwrap_err().contains("private"));
assert!(inspect_public_link(&bed.relay, &link.url, None, None).await.unwrap().messages.is_empty());
// As Concord CLI reads: no account and no database.
crate::db::close_database();
let stateless = inspect_public_link(&bed.relay, &link.url, None, Some(&read(2, &[]))).await.unwrap();
assert_eq!(texts(&stateless), texts(&all));
}
fn link_signer_of(url: &str) -> String {
invite::parse_invite_link(url).unwrap().link_signer.to_hex()
}
#[tokio::test]
async fn public_link_preview_shows_live_name_and_icon_without_joining() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Soapbox", bed.relays.clone(), None).await.unwrap();
// The icon lives on the Control Plane, never in the bundle — publish it
// as a metadata edition so the preview must FOLD to see it.
let icon = control::ImageRef {
url: "https://blossom.example/soap".into(),
key: "k".into(),
nonce: "n".into(),
hash: "h".into(),
extra: Default::default(),
};
let mut meta = community.metadata();
meta.icon = Some(icon.clone());
edit_community_metadata(&bed.relay, &community, &meta).await.unwrap();
// An any-host base — the naddr#fragment payload is domain-agnostic.
let link = mint_public_link(&bed.relay, &community, "https://armada.buzz", None, None).await.unwrap();
// A NON-member previews: the real name + the live icon, nothing persisted.
bed.swap_to(&member);
let preview = preview_public_link(&bed.relay, &link.url).await.unwrap();
assert_eq!(preview.name, "Soapbox");
assert_eq!(preview.icon, Some(icon), "the icon folds from the live Control Plane, not the bundle");
assert!(
crate::db::community::load_community_v2(preview.id()).unwrap().is_none(),
"previewing must not persist a membership"
);
}
#[tokio::test]
async fn a_removed_icon_and_banner_leave_every_member() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Bare", bed.relays.clone(), None).await.unwrap();
let image = |name: &str| control::ImageRef {
url: format!("https://blossom.example/{name}"),
key: "k".into(),
nonce: "n".into(),
hash: "h".into(),
extra: Default::default(),
};
let mut meta = community.metadata();
meta.icon = Some(image("icon"));
meta.banner = Some(image("banner"));
edit_community_metadata(&bed.relay, &community, &meta).await.unwrap();
let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
bed.swap_to(&member);
let joined = accept_public_link(&bed.relay, &link.url).await.unwrap();
assert!(joined.icon.is_some() && joined.banner.is_some());
bed.swap_to(&owner);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let mut meta = held.metadata();
meta.icon = None;
meta.banner = None;
edit_community_metadata(&bed.relay, &held, &meta).await.unwrap();
persist_community_image(community.id(), None, false).await.unwrap();
let mine = persist_community_image(community.id(), None, true).await.unwrap();
assert!(mine.icon.is_none() && mine.banner.is_none(), "the remover's own copy drops them at once");
bed.swap_to(&member);
let theirs = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
follow_control(&bed.relay, &theirs).await.unwrap();
let theirs = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert!(theirs.icon.is_none(), "an edition without the icon removes it");
assert!(theirs.banner.is_none(), "and the banner");
assert_eq!(theirs.metadata().name, "Bare", "nothing else moves");
}
#[tokio::test]
async fn an_own_metadata_edit_reads_back_before_any_control_pass() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Echo", bed.relays.clone(), None).await.unwrap();
let mut meta = community.metadata();
meta.name = "Echoed".into();
meta.extra.insert("voice_relays".into(), serde_json::json!(["https://voice.example/"]));
edit_community_metadata(&bed.relay, &community, &meta).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(held().name, "Echoed");
assert_eq!(held().voice_relays(), vec!["https://voice.example/".to_string()]);
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(held().voice_relays(), vec!["https://voice.example/".to_string()], "the fold lands the same head");
}
#[tokio::test]
async fn a_previewed_join_reuses_the_verified_fold() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "FastJoin", bed.relays.clone(), None).await.unwrap();
let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
bed.swap_to(&member);
let _ = preview_public_link(&bed.relay, &link.url).await.unwrap();
let joined = accept_public_link(&bed.relay, &link.url).await.unwrap();
assert_eq!(joined.id().0, community.id().0);
assert!(joined.created_at_ms > 0, "the handoff stamps the JOIN's acquisition time, not the preview's");
// The slot was CONSUMED by the join — proving the handoff path ran (a
// verify re-walk would have left the preview's entry in place).
assert!(VERIFIED_PREVIEW.lock().unwrap().is_none(), "the handoff slot must be consumed by the join");
}
#[tokio::test]
async fn an_unjoined_preview_is_let_go_once_its_ttl_lapses() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Window", bed.relays.clone(), None).await.unwrap();
let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
bed.swap_to(&member);
let _ = preview_public_link(&bed.relay, &link.url).await.unwrap();
let seq = VERIFIED_PREVIEW.lock().unwrap().as_ref().map(|v| v.seq).expect("a preview parks its fold");
expire_verified_preview(seq.wrapping_add(1));
assert!(VERIFIED_PREVIEW.lock().unwrap().is_some(), "another preview's expiry leaves this one be");
// Paused, the clock jumps straight to each due timer.
tokio::time::pause();
tokio::time::sleep(VERIFIED_PREVIEW_TTL + std::time::Duration::from_secs(1)).await;
assert!(VERIFIED_PREVIEW.lock().unwrap().is_none(), "an unjoined preview must not stay resident");
}
#[tokio::test]
async fn the_admin_pin_upgrade_is_offered_once_per_account_session() {
let (a, b) = (crate::db::Session::empty(), crate::db::Session::empty());
let id = crate::community::CommunityId([0x5A; 32]);
let offer = |s| crate::db::with_session(s, async move { first_admin_pin_upgrade(&id) });
assert!(offer(a.clone()).await, "the first fold offers it");
assert!(!offer(a).await, "a one-shot within the session");
assert!(offer(b).await, "an owner logging in later in the same process still gets it");
}
#[tokio::test]
async fn guestbook_store_seeds_syncs_incrementally_and_matches_the_live_fold() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "GB", bed.relays.clone(), None).await.unwrap();
let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
bed.swap_to(&member);
let joined = accept_public_link(&bed.relay, &link.url).await.unwrap();
// Seed from zero: the stored fold equals the authoritative live fold.
assert!(!sync_guestbook(&bed.relay, &joined).await.unwrap().is_empty(), "the seed folds fresh events");
let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
let (_, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
assert!(cursor > 0, "the cursor advanced past zero");
let stored: std::collections::BTreeSet<_> = stored_memberlist(&joined).unwrap().into_iter().collect();
let live: std::collections::BTreeSet<_> = memberlist(&bed.relay, &joined).await.unwrap().into_iter().collect();
assert_eq!(stored, live, "stored fold == live fold after the seed");
assert!(stored.contains(&member.keys.public_key()));
// Nothing new on the plane → an idle re-sync folds nothing.
assert!(sync_guestbook(&bed.relay, &joined).await.unwrap().is_empty());
// The owner kicks the member; a CURSOR catch-up folds the kick in — no full walk.
bed.swap_to(&owner);
kick_member(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
bed.swap_to(&member);
assert!(!sync_guestbook(&bed.relay, &joined).await.unwrap().is_empty(), "the kick lands incrementally");
assert!(
!stored_memberlist(&joined).unwrap().contains(&member.keys.public_key()),
"an owner kick removes the member from the stored fold"
);
}
#[tokio::test]
async fn a_preview_then_revoke_still_refuses_the_join() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "RevokeRace", bed.relays.clone(), None).await.unwrap();
let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
// Member previews (warming the verified handoff), THEN the owner revokes.
bed.swap_to(&member);
let p = preview_public_link(&bed.relay, &link.url).await.unwrap();
assert_eq!(p.name, "RevokeRace");
bed.swap_to(&owner);
let tombstone = invite::build_revocation(&link.link_signer).unwrap();
bed.relay.publish_durable(&tombstone, &bed.relays).await.unwrap();
// The join MUST refuse: the handoff skips only the root re-verify, never
// the bundle re-fetch that carries the revocation gate.
bed.swap_to(&member);
let err = accept_public_link(&bed.relay, &link.url).await.unwrap_err();
assert!(err.contains("revoked"), "got: {err}");
}
#[tokio::test]
async fn a_revoked_link_refuses_to_join() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Revoked", bed.relays.clone(), None).await.unwrap();
let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
// Owner retires the link (re-posts the coordinate as a tombstone).
let tombstone = invite::build_revocation(&link.link_signer).unwrap();
bed.relay.publish_durable(&tombstone, &bed.relays).await.unwrap();
bed.swap_to(&member);
let err = accept_public_link(&bed.relay, &link.url).await.unwrap_err();
assert!(err.contains("revoked"), "a retired link finds the grave, not keys: {err}");
}
#[tokio::test]
async fn an_expired_direct_invite_refuses_to_join() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Expired", bed.relays.clone(), None).await.unwrap();
// Hand-mint an invite that expired in the past.
let inviter = owner.keys.clone();
let mut bundle = bundle_of(&community, BundleAudience::Link, Some(inviter.public_key()), Some(1_000), None);
bundle.expires_at = Some(1_000); // unix ms, long past
let wrap = invite::build_direct_invite(&inviter, &member.keys.public_key(), &bundle).unwrap();
bed.relay.publish(&wrap, &bed.relays).await.unwrap();
bed.swap_to(&member);
let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
let err = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap_err();
assert!(err.contains("expired"), "a past-expiry invite refuses to join: {err}");
}
#[tokio::test]
async fn a_tombstone_beats_a_live_bundle_regardless_of_fetch_order() {
// The revocation-durability fix: if ANY signer-valid tombstone is among the
// fetched events, refuse — even when a Live bundle is returned FIRST (the
// production union has no newest-first sort, so a stale relay's Live can lead).
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Rev", bed.relays.clone(), None).await.unwrap();
let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
let tombstone = invite::build_revocation(&link.link_signer).unwrap();
// A relay union that hands back [Live, tombstone] — Live FIRST. Old
// `events.first()` would join the Live; the scan-all fix must refuse.
let union = FixedFetch { events: vec![link.bundle_event.clone(), tombstone] };
bed.swap_to(&member);
let err = accept_public_link(&union, &link.url).await.unwrap_err();
assert!(err.contains("revoked"), "a tombstone must beat a Live returned first: {err}");
}
#[test]
fn from_bundle_refuses_an_over_cap_bundle_before_allocating() {
// The accept-side DoS bound: from_bundle (which accept_bundle calls)
// rejects a >256-channel bundle via validate() BEFORE the Vec allocation.
// (The Direct-Invite wire path is additionally bounded by NIP-44's 64KB
// cap, which trips even earlier — but the count guard is the real defense
// for the single-layer public-link bundle.)
let owner = Keys::generate();
let identity = super::super::control::CommunityIdentity::mint(&owner.public_key());
let hex = crate::simd::hex::bytes_to_hex_32;
let root = [0x11u8; 32];
let mut bundle = CommunityInvite {
community_id: hex(&identity.community_id.0),
owner: hex(&identity.owner_xonly),
owner_salt: hex(&identity.owner_salt),
community_root: hex(&root),
root_epoch: 0,
control_pk: None,
channels: vec![],
relays: vec!["wss://r".into()],
name: "X".into(),
icon: None,
expires_at: None,
creator_npub: None,
label: None,
extra: Default::default(),
};
bundle.channels = (0..=invite::MAX_BUNDLE_CHANNELS)
.map(|i| {
let mut id = [0u8; 32];
id[..8].copy_from_slice(&(i as u64).to_be_bytes());
invite::ChannelGrant { id: hex(&id), key: hex(&root), epoch: 0, name: "x".into() }
})
.collect();
assert!(CommunityV2::from_bundle(&bundle, 0).is_err(), "an over-cap bundle is refused before allocating");
}
#[tokio::test]
async fn a_join_swap_between_fetch_and_save_lands_in_the_joining_account() {
// A public-link accept fetches, then saves. A swap in that window used to
// abort the join outright; the community is now written to the account
// that clicked the link, and the account swapped in gets nothing.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Straddle", bed.relays.clone(), None).await.unwrap();
let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
bed.swap_to(&member);
let joiner = crate::db::current_session();
let swap_relay = SwapMidFetch::arm(&bed.relay);
accept_public_link(&swap_relay, &link.url).await.unwrap();
assert!(
crate::db::with_session(joiner, async {
crate::db::community::load_community_v2(community.id()).unwrap().is_some()
})
.await,
"the join completed for the account that accepted the link"
);
}
#[tokio::test]
async fn the_owner_is_a_member_even_without_a_fetched_genesis_join() {
// The owner is derived from the self-certifying community_id, so the
// memberlist includes them independent of any Guestbook fetch.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Owned", vec!["wss://r".into()], None).await.unwrap();
// A memberlist over an EMPTY guestbook (fetch a community-relay-less view)
// still contains the owner.
let empty = MemoryRelay::new();
let members = memberlist(&empty, &community).await.unwrap();
assert_eq!(members, vec![owner.public_key()], "owner present with no fetched Join");
}
#[tokio::test]
async fn an_expiring_minted_invite_refuses_after_the_deadline() {
// The mint path can now produce an expiring invite, and the accept gate
// trips on it (end-to-end through the real service, not a hand-built bundle).
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Timed", bed.relays.clone(), None).await.unwrap();
send_direct_invite(&bed.relay, &community, &member.keys.public_key(), Some(1_000), Some("beta".into()))
.await
.unwrap();
bed.swap_to(&member);
let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
assert!(
accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap_err().contains("expired"),
"a minted expiring invite refuses past its deadline"
);
}
#[tokio::test]
async fn a_member_who_leaves_drops_from_the_memberlist() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Leaving", bed.relays.clone(), None).await.unwrap();
send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
bed.swap_to(&member);
let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
// Let the leave land strictly after the join.
crate::rt::time::sleep(std::time::Duration::from_millis(2)).await;
leave_community(&bed.relay, &joined).await.unwrap();
bed.swap_to(&owner);
let members = memberlist(&bed.relay, &community).await.unwrap();
assert!(members.contains(&owner.keys.public_key()));
assert!(!members.contains(&member.keys.public_key()), "a member who left drops from the list");
}
#[tokio::test]
async fn a_request_from_a_fellow_member_shows_their_pictures_until_they_leave() {
use nostr_sdk::prelude::ToBech32;
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Mutual", bed.relays.clone(), None).await.unwrap();
let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
bed.swap_to(&member);
let joined = accept_public_link(&bed.relay, &link.url).await.unwrap();
let fellow = member.keys.public_key().to_bech32().unwrap();
let stranger = Keys::generate().public_key().to_bech32().unwrap();
let requests_from = |npubs: [String; 2]| async move {
let mut guard = crate::state::STATE.lock().await;
let state = &mut *guard;
for npub in npubs {
let mut chat = crate::chat::Chat::new_dm(npub, &mut state.interner);
let hi = crate::types::Message { id: "ab".repeat(32), content: "hi".into(), at: 1_700_000_000_000, ..Default::default() };
chat.add_message(hi, &mut state.interner);
state.chats.push(chat);
}
};
bed.swap_to(&owner);
sync_guestbook(&bed.relay, &community).await.unwrap();
requests_from([fellow.clone(), stranger.clone()]).await;
assert!(!crate::requests::pictures_held(&fellow).await, "a fellow member's pictures show");
assert!(crate::requests::pictures_held(&stranger).await, "a stranger's wait");
assert_eq!(crate::requests::request_mutuals().await, vec![fellow.clone()]);
assert_eq!(crate::requests::held_pictures().await, [stranger.clone()].into());
bed.swap_to(&member);
crate::rt::time::sleep(std::time::Duration::from_millis(2)).await;
leave_community(&bed.relay, &joined).await.unwrap();
bed.swap_to(&owner);
sync_guestbook(&bed.relay, &community).await.unwrap();
requests_from([fellow.clone(), stranger]).await;
assert!(crate::requests::pictures_held(&fellow).await, "gone from every Community we share, their request holds them again");
}
#[tokio::test]
async fn a_relay_that_has_reconciled_stays_confirmed_until_it_refuses() {
use crate::negentropy::{neg_ever_confirmed, record_neg_support};
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let url = "wss://slow.example";
assert!(!neg_ever_confirmed(url), "unknown is not confirmed");
record_neg_support(url, true);
assert!(neg_ever_confirmed(url));
record_neg_support(url, false);
assert!(!neg_ever_confirmed(url), "a refusal unlearns it");
}
#[tokio::test]
async fn a_local_leave_is_gone_at_once_and_announced_after() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Leaving", bed.relays.clone(), None).await.unwrap();
send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
bed.swap_to(&member);
let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
crate::rt::time::sleep(std::time::Duration::from_millis(2)).await;
let at_ms = leave_locally(&joined).unwrap();
let id_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
assert!(crate::db::community::load_community_v2(joined.id()).unwrap().is_none(), "gone here before any publish");
assert!(tombstone_suppresses(&id_hex, at_ms / 1000), "the tombstone is kept before it publishes");
assert!(load_pending().tombstones.iter().any(|t| t.community_id == id_hex), "pending until it lands");
bed.swap_to(&owner);
assert!(memberlist(&bed.relay, &community).await.unwrap().contains(&member.keys.public_key()), "nothing published yet");
bed.swap_to(&member);
announce_leave(&bed.relay, &joined, at_ms).await;
bed.swap_to(&owner);
assert!(!memberlist(&bed.relay, &community).await.unwrap().contains(&member.keys.public_key()), "the Leave lands after");
}
async fn chats_naming(community_hex: &str) -> usize {
crate::state::STATE.lock().await.chats.iter().filter(|c| c.metadata.community_id() == Some(community_hex)).count()
}
fn chat_rows(ids: &[String]) -> usize {
let conn = crate::db::get_db_connection_guard_static().unwrap();
ids.iter()
.filter(|id| conn.query_row("SELECT 1 FROM chats WHERE chat_identifier = ?1", [id.as_str()], |_| Ok(())).is_ok())
.count()
}
#[tokio::test]
async fn a_leave_takes_every_chat_of_the_community_with_it() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Chatty", vec!["wss://r".to_string()], None).await.unwrap();
create_public_channel(&relay, &community, "second").await.unwrap();
let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
crate::register_v2_chats_inner(&community).await;
let id_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let channels: Vec<String> = community.channels.iter().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)).collect();
assert_eq!((chats_naming(&id_hex).await, chat_rows(&channels)), (2, 2));
crate::VectorCore.leave_community_now(&id_hex).await.unwrap();
assert_eq!(chats_naming(&id_hex).await, 0);
assert_eq!(chat_rows(&channels), 0, "no chat row is left to come back as a ghost on the next load");
}
#[tokio::test]
async fn a_community_whose_chats_outlived_it_can_still_be_left_here_and_on_the_list() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Ghost", vec!["wss://r".to_string()], None).await.unwrap();
crate::register_v2_chats_inner(&community).await;
let id_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let channels: Vec<String> = community.channels.iter().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)).collect();
crate::db::community::delete_community(&id_hex).unwrap();
assert_eq!((chats_naming(&id_hex).await, chat_rows(&channels)), (1, 1), "the row is gone, its chat is not");
let at_ms = leave_unheld_locally(community.id()).await.expect("its chat names it");
assert_eq!((chats_naming(&id_hex).await, chat_rows(&channels)), (0, 0));
assert!(tombstone_suppresses(&id_hex, at_ms / 1000), "kept pending before it publishes");
announce_unheld_leave(&relay, community.id(), at_ms).await;
let read = read_fragments(&relay, &list_read_relays(&[]).await).await.unwrap();
let list = read.set.expect("the List was written").list;
assert!(list.tombstones.iter().any(|t| t.community_id == id_hex), "the List carries the leave");
assert!(leave_unheld_locally(community.id()).await.is_none(), "nothing here names it now");
assert!(crate::VectorCore.leave_community_now(&id_hex).await.is_err());
}
#[tokio::test]
async fn a_swapped_member_cannot_see_the_owners_community_until_joining() {
// Multi-account isolation: after the swap, the member's DB holds nothing
// of the owner's community — community storage is per-account.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Private-so-far", bed.relays.clone(), None).await.unwrap();
assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_some());
bed.swap_to(&member);
assert!(
crate::db::community::load_community_v2(community.id()).unwrap().is_none(),
"the owner's community must be invisible in the member's account DB"
);
assert_eq!(crate::db::community::list_community_ids().unwrap().len(), 0);
}
// ── Live control-follow ──────────────────────────────────────────────────
/// Publish an owner-grammar channel edition straight to the control plane,
/// signed by `signer` (the owner for a legit edit, a stranger for the
/// authority test). `version`/`deleted` drive add-vs-rename-vs-delete.
/// The entity's current head `self_hash` on the relay (highest version wins),
/// so a helper can chain a new edition the way a real owner client does.
async fn head_hash_on_relay(relay: &MemoryRelay, community: &CommunityV2, entity_id: &[u8; 32]) -> Option<[u8; 32]> {
let group = control::ControlPlane::of(&community).write_group().unwrap();
let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
let wraps = relay.fetch(&query, &community.relays).await.ok()?;
let mut head: Option<(u64, [u8; 32])> = None;
for w in &wraps {
if let Ok((ed, _)) = control::open_control_edition(w, &group) {
if ed.entity_id == *entity_id && head.is_none_or(|(v, _)| ed.version > v) {
head = Some((ed.version, ed.self_hash));
}
}
}
head.map(|(_, h)| h)
}
/// The `vac` a non-owner signer must attach, read off the Grant they were
/// given on the relay (CORD-04 §5). The owner cites nothing. Mirrors what a
/// real client does via `my_authority_citation`, so the fixtures publish the
/// shape Vector actually emits.
async fn cite_on_relay(
relay: &MemoryRelay,
community: &CommunityV2,
signer: &Keys,
) -> Option<crate::community::edition::AuthorityCitation> {
if community.owner().ok() == Some(signer.public_key()) {
return None;
}
let entity_id = crate::community::v2::derive::grant_locator(community.id(), &signer.public_key().to_bytes());
let group = control::ControlPlane::of(&community).write_group().unwrap();
let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
let wraps = relay.fetch(&query, &community.relays).await.ok()?;
let mut head: Option<(u64, [u8; 32])> = None;
for w in &wraps {
if let Ok((ed, _)) = control::open_control_edition(w, &group) {
if ed.entity_id == entity_id && head.is_none_or(|(v, _)| ed.version > v) {
head = Some((ed.version, ed.self_hash));
}
}
}
head.map(|(version, edition_hash)| crate::community::edition::AuthorityCitation { entity_id, version, edition_hash })
}
async fn publish_channel_edition(
relay: &MemoryRelay,
community: &CommunityV2,
signer: &Keys,
channel_id: &ChannelId,
name: &str,
private: bool,
version: u64,
deleted: bool,
) {
let group = control::ControlPlane::of(&community).write_group().unwrap();
let prev = head_hash_on_relay(relay, community, &channel_id.0).await;
let meta = control::ChannelMetadata { name: name.into(), private, deleted: deleted.then_some(true), ..Default::default() };
let content = serde_json::to_string(&meta).unwrap();
let rumor = control::build_edition_rumor(signer.public_key(), vsk::CHANNEL_METADATA, &channel_id.0, version, prev.as_ref(), &content, 1_000, None);
let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
/// A channel edition at an EXPLICIT time, so a paging test can order the plane —
/// the default helper stamps everything 1_000, which leaves newest-first paging
/// arbitrary and any "buried edition" scenario vacuous.
#[allow(clippy::too_many_arguments)]
async fn publish_channel_edition_at(
relay: &MemoryRelay,
community: &CommunityV2,
signer: &Keys,
channel_id: &ChannelId,
name: &str,
version: u64,
at_secs: u64,
) {
let group = control::ControlPlane::of(community).write_group().unwrap();
let meta = control::ChannelMetadata { name: name.into(), private: false, deleted: None, ..Default::default() };
let content = serde_json::to_string(&meta).unwrap();
let rumor = control::build_edition_rumor(signer.public_key(), vsk::CHANNEL_METADATA, &channel_id.0, version, None, &content, at_secs, None);
let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(at_secs)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
/// Publish an owner-grammar community-metadata edition (rename etc.), chained
/// to the current relay head like a real owner client.
async fn publish_community_meta(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, name: &str, version: u64) {
publish_community_meta_at(relay, community, signer, name, version, 1_000).await;
}
/// As [`publish_community_meta`] with an explicit timestamp, for tests that need
/// relay-side newest-first ordering (paging/eviction scenarios).
async fn publish_community_meta_at(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, name: &str, version: u64, at_secs: u64) {
let group = control::ControlPlane::of(&community).write_group().unwrap();
let prev = head_hash_on_relay(relay, community, &community.id().0).await;
let meta = control::CommunityMetadata { name: name.into(), ..Default::default() };
let content = serde_json::to_string(&meta).unwrap();
let cite = cite_on_relay(relay, community, signer).await;
let rumor = control::build_edition_rumor(signer.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, version, prev.as_ref(), &content, at_secs, cite.as_ref());
let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(at_secs)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
#[test]
fn past_the_category_cap_the_lowest_ids_stand_however_they_arrive() {
let owner = Keys::generate();
let g = control::genesis(&owner, control::CommunityMetadata { name: "A".into(), ..Default::default() }, 1_000).unwrap();
let cat = |name: &str| control::CategoryMetadata { name: name.into(), ..Default::default() };
let ids: Vec<[u8; 32]> = (0..=crate::community::v2::community::MAX_CATEGORIES).map(|i| { let mut id = [0u8; 32]; id[..8].copy_from_slice(&(i as u64).to_be_bytes()); id }).collect();
for order in [ids.clone(), ids.iter().rev().copied().collect()] {
let mut held = CommunityV2::from_genesis(&g, "A", None, vec!["wss://r".into()], 0);
for id in &order {
apply_category_metadata(&mut held, *id, cat("c"));
}
let mut got: Vec<[u8; 32]> = held.categories.iter().map(|c| c.id).collect();
got.sort();
assert_eq!(got, ids[..crate::community::v2::community::MAX_CATEGORIES].to_vec(), "the {} lowest ids stand", crate::community::v2::community::MAX_CATEGORIES);
}
}
#[test]
fn metadata_apply_captures_undriven_fields_for_republish() {
let owner = Keys::generate();
let g = control::genesis(&owner, control::CommunityMetadata { name: "A".into(), ..Default::default() }, 1_000).unwrap();
let mut held = CommunityV2::from_genesis(&g, "A", None, vec!["wss://r".into()], 0);
let general = held.channels[0].id;
// A foreign vsk-0 head carrying custom + unknown fields folds them in…
let mut custom = serde_json::Map::new();
custom.insert("accent".into(), serde_json::Value::from("#89f0b6"));
let mut extra = serde_json::Map::new();
extra.insert("vnd_flag".into(), serde_json::Value::Bool(true));
let meta = control::CommunityMetadata { name: "A".into(), custom: Some(custom.clone()), extra: extra.clone(), ..Default::default() };
assert!(apply_community_metadata(&mut held, meta), "gaining custom/extra is a change");
assert_eq!(held.meta_custom, Some(custom.clone()));
assert_eq!(held.meta_extra, extra);
// …and the next local edit's base document republishes them verbatim.
assert_eq!(held.metadata().custom, Some(custom));
assert_eq!(held.metadata().extra, held.meta_extra);
// Same contract for a vsk-2 channel head (voice included).
let mut ch_custom = serde_json::Map::new();
ch_custom.insert("slowmode".into(), serde_json::Value::from(30));
let ch_meta = control::ChannelMetadata {
name: "general".into(),
private: false,
voice: Some(true),
deleted: None,
custom: Some(ch_custom.clone()),
extra: Default::default(),
};
assert!(apply_channel_metadata(&mut held, general, ch_meta), "gaining voice/custom is a change");
let ch = held.channel(&general).unwrap();
assert_eq!(ch.voice, Some(true));
assert_eq!(ch.meta_custom, Some(ch_custom.clone()));
let rename = { let mut d = ch.metadata(); d.name = "lounge".into(); d };
assert_eq!(rename.voice, Some(true), "our rename edition carries the foreign voice flag");
assert_eq!(rename.custom, Some(ch_custom));
}
#[test]
fn community_metadata_apply_sets_and_clears_images() {
let owner = Keys::generate();
let g = control::genesis(&owner, control::CommunityMetadata { name: "A".into(), ..Default::default() }, 1_000).unwrap();
let mut held = CommunityV2::from_genesis(&g, "A", None, vec!["wss://r".into()], 0);
let icon = control::ImageRef {
url: "https://blossom.example/i".into(),
key: "k".into(),
nonce: "n".into(),
hash: "h".into(),
extra: Default::default(),
};
let with_icon = control::CommunityMetadata { name: "A".into(), icon: Some(icon.clone()), ..Default::default() };
assert!(apply_community_metadata(&mut held, with_icon), "gaining an icon is a change");
assert_eq!(held.icon.as_ref(), Some(&icon));
// An edition is the FULL document: a head without the icon removes it.
let without = control::CommunityMetadata { name: "A".into(), ..Default::default() };
assert!(apply_community_metadata(&mut held, without), "losing the icon is a change");
assert_eq!(held.icon, None);
}
/// Publish a Role edition (vsk 1) signed by `signer`, chained to the current head.
async fn publish_role(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, role: &Role, version: u64) {
publish_role_at(relay, community, signer, role, version, 1_000).await
}
/// Page filler: a signed edition that occupies a slot in the pager's window and
/// nothing else. It skips the head/citation relay scans `publish_role` does, which
/// are linear in plane size and make a 500-edition test quadratic.
async fn publish_filler_edition(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, role: &Role, version: u64, ts: u64) {
let group = control::ControlPlane::of(&community).write_group().unwrap();
let role_id = crate::simd::hex::hex_to_bytes_32_checked(&role.role_id).unwrap();
let content = crate::community::v2::roles::role_content_json(role).unwrap();
let rumor = control::build_edition_rumor(signer.public_key(), vsk::ROLE, &role_id, version, None, &content, ts, None);
let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(ts)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
/// `publish_role` with an explicit wall clock. Every other helper stamps 1_000, so a
/// test needing more than one page of history must spread its editions out — a page
/// that is entirely one second wide is a wall `until` cannot step past, and the
/// pager correctly refuses rather than paging forever.
async fn publish_role_at(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, role: &Role, version: u64, ts: u64) {
let group = control::ControlPlane::of(&community).write_group().unwrap();
let role_id = crate::simd::hex::hex_to_bytes_32_checked(&role.role_id).unwrap();
let prev = head_hash_on_relay(relay, community, &role_id).await;
let content = crate::community::v2::roles::role_content_json(role).unwrap();
let cite = cite_on_relay(relay, community, signer).await;
let rumor = control::build_edition_rumor(signer.public_key(), vsk::ROLE, &role_id, version, prev.as_ref(), &content, ts, cite.as_ref());
let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(ts)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
/// Hand-rotate a community view to `(new_root, epoch)`, minting the fresh
/// split pair a real base rotation would (CORD-06 §3) — the control_root is
/// the new root itself, which is fine for a test.
fn rotate_view(c: &CommunityV2, new_root: [u8; 32], epoch: u64) -> CommunityV2 {
let mut r = c.clone();
r.community_root = new_root;
r.root_epoch = Epoch(epoch);
r.control_root = Some(new_root);
r.control_pk = Some(crate::community::v2::derive::control_signer_group_key(&new_root, r.id(), Epoch(epoch)).pk());
r
}
/// Publish a Grant edition (vsk 3) signed by `signer`, at grant_locator(cid, member).
/// Like a compliant granter it delivers the staff write key inside the Grant
/// (CORD-04 §3) whenever the community view holds one — the recipient's
/// derive check drops it when it isn't owed, so attaching unconditionally
/// keeps the helper simple while exercising the real delivery pipeline.
async fn publish_grant(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, member: &PublicKey, role_ids: Vec<String>, version: u64) {
let group = control::ControlPlane::of(&community).write_group().unwrap();
let eid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
let prev = head_hash_on_relay(relay, community, &eid).await;
let grant = MemberGrant { member: member.to_hex(), role_ids };
let control_wrap = community.control_root.filter(|_| community.control_pk.is_some()).map(|cr| {
let ck = nostr_sdk::prelude::nip44::v2::ConversationKey::derive(signer.secret_key(), member).unwrap();
let payload = crate::community::cipher::encrypt_with_random_nonce(&ck, super::rekey::control_wrap_b64(community.root_epoch, &cr).as_bytes()).unwrap();
crate::simd::base64::STANDARD.encode_to_string(&payload)
});
let content = crate::community::v2::roles::grant_content_json_with_wrap(&grant, control_wrap).unwrap();
let cite = cite_on_relay(relay, community, signer).await;
let rumor = control::build_edition_rumor(signer.public_key(), vsk::GRANT, &eid, version, prev.as_ref(), &content, 1_000, cite.as_ref());
let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
/// Publish a Banlist edition (vsk 4) signed by `signer`, at banlist_locator(cid).
async fn publish_banlist(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, banned: &[String], version: u64) {
let group = control::ControlPlane::of(&community).write_group().unwrap();
let eid = crate::community::v2::derive::banlist_locator(community.id());
let prev = head_hash_on_relay(relay, community, &eid).await;
let content = crate::community::v2::roles::banlist_content_json(banned).unwrap();
let cite = cite_on_relay(relay, community, signer).await;
let rumor = control::build_edition_rumor(signer.public_key(), vsk::BANLIST, &eid, version, prev.as_ref(), &content, 1_000, cite.as_ref());
let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
fn admin_role(role_id: &str, perms: u64) -> Role {
Role { role_id: role_id.into(), name: "Admin".into(), position: 1, permissions: Permissions(perms), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() }
}
/// Hand-roll a LEGACY (pre-split) community exactly as a pre-0.4.2 build
/// created one: the whole Control Plane keyed by the community_root
/// derivation, no control pair anywhere. Publishes the two genesis-shaped
/// editions at the LEGACY address, persists, and folds to seed floors.
async fn create_legacy_community(relay: &MemoryRelay, owner: &Keys, name: &str, relays: Vec<String>) -> CommunityV2 {
let identity = control::CommunityIdentity::mint(&owner.public_key());
let root = crate::community::random_32();
let group = control_group_key(&root, &identity.community_id, Epoch(0));
let meta = control::CommunityMetadata { name: name.into(), relays: relays.clone(), ..Default::default() };
let meta_rumor = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &identity.community_id.0, 1, None, &serde_json::to_string(&meta).unwrap(), 1_000, None);
let ch_id = ChannelId(crate::community::random_32());
let ch = control::ChannelMetadata { name: "general".into(), private: false, ..Default::default() };
let ch_rumor = control::build_edition_rumor(owner.public_key(), vsk::CHANNEL_METADATA, &ch_id.0, 1, None, &serde_json::to_string(&ch).unwrap(), 1_000, None);
for r in [&meta_rumor, &ch_rumor] {
let (w, _) = control::seal_control_edition(r, &group, owner, Timestamp::from_secs(1_000)).unwrap();
relay.publish(&w, &relays).await.unwrap();
}
let community = CommunityV2 {
identity,
community_root: root,
root_epoch: Epoch(0),
control_pk: None,
control_root: None,
name: name.into(),
description: None,
icon: None,
banner: None,
meta_custom: None,
meta_extra: Default::default(),
relays,
channels: vec![ChannelV2 { id: ch_id, name: "general".into(), private: false, key: None, epoch: Epoch(0), voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed: None }],
categories: Vec::new(),
dissolved: false,
created_at_ms: 1_000_000,
};
crate::db::community::save_community_v2(&community).unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let _ = crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 0, &root);
let _ = follow_control(relay, &community).await;
crate::db::community::load_community_v2(community.id()).unwrap().unwrap()
}
#[tokio::test]
async fn a_refounding_mints_the_split_and_delivers_the_pair_by_staffness() {
// CORD-06 §1/§3 end to end: the rotation mints a fresh control pair, a
// STAFF recipient's blob carries the secret (136), a plain member's only
// the address (104), the compaction publishes ONLY at the new split
// address, and each follower adopts exactly what its blob delivered.
let (bed, owner, admin) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "SplitRefound", bed.relays.clone(), None).await.unwrap();
assert!(community.control_pk.is_some() && community.control_root.is_some(), "genesis mints the split");
// A staff admin (granted; the Grant delivers the wrap) and a plain
// member (Guestbook Join only — a recipient with no rank).
let rid = "d1".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin.keys.public_key(), vec![rid], 1).await;
let plain = Keys::generate();
let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let join = guestbook::build_join_rumor(plain.public_key(), None, 1_000);
let (w, _) = guestbook::seal_guestbook_rumor(&join, &gb, &plain, Timestamp::from_secs(1_000)).unwrap();
bed.relay.publish(&w, &community.relays).await.unwrap();
// The admin joins and folds — adopting the write key from their Grant.
let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, None, None, None)).unwrap();
bed.swap_to(&admin);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
assert_eq!(joined.control_pk, community.control_pk, "the bundle handed over the address");
assert_eq!(joined.control_root, None, "a bundle never carries the secret");
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
assert_eq!(joined.control_root, community.control_root, "the Grant's control_wrap delivered the secret");
// The owner refounds: a FRESH pair beside the new root.
bed.swap_to(&owner);
let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
assert_eq!(refounded.root_epoch, Epoch(1));
assert!(refounded.control_pk.is_some() && refounded.control_root.is_some());
assert_ne!(refounded.control_pk, community.control_pk, "the pair rolls with the root");
// Blob forms by staff-ness: the admin's carries the secret, the plain
// member's only the pk (CORD-06 §1).
let base_group = base_rekey_group_key(&community.community_root, community.id(), Epoch(1));
let chunks = fetch_rekey_chunks(&bed.relay, &community, &base_group).await.unwrap();
let rotation = &rekey::collect_rotations(&chunks)[0];
async fn open_as(rotation: &rekey::Rotation, community_id: &crate::community::CommunityId, keys: &Keys) -> rekey::BaseKeyDelivery {
let blob = rekey::find_my_blob(&rotation.blobs, &rotation.rotator.to_bytes(), &keys.public_key().to_bytes(), rotation.scope, rotation.new_epoch).expect("a blob for every recipient");
let signer = crate::signer::ActiveSigner::Keys(keys.clone());
rekey::open_base_blob(&signer, &rotation.rotator, community_id, Epoch(1), blob).await.unwrap()
}
let admin_delivery = open_as(rotation, community.id(), &admin.keys).await;
assert_eq!(admin_delivery.control_root, refounded.control_root, "staff blob = 136, secret included");
let plain_delivery = open_as(rotation, community.id(), &plain).await;
assert_eq!(plain_delivery.control_pk.map(|p| PublicKey::from_slice(p.as_slice()).unwrap()), refounded.control_pk);
assert_eq!(plain_delivery.control_root, None, "member blob = 104, never the secret");
// The compaction lives ONLY at the new split address — never mirrored to
// the new epoch's legacy-derived address (CORD-06 §3).
let legacy_new = control_group_key(&refounded.community_root, community.id(), Epoch(1));
let q = |pk: String| Query { kinds: vec![stream::KIND_WRAP], authors: vec![pk], limit: Some(50), ..Default::default() };
assert!(bed.relay.fetch(&q(legacy_new.pk_hex()), &community.relays).await.unwrap().is_empty(), "no legacy mirror");
assert!(!bed.relay.fetch(&q(refounded.control_pk.unwrap().to_hex()), &community.relays).await.unwrap().is_empty(), "the compaction rides the split address");
// The admin's follow adopts the whole pair from their 136-byte blob.
bed.swap_to(&admin);
let follow = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
let adopted = follow.updated.expect("the admin adopts the rotation");
assert_eq!(adopted.root_epoch, Epoch(1));
assert_eq!(adopted.control_pk, refounded.control_pk);
assert_eq!(adopted.control_root, refounded.control_root, "staff crossing a rotation get the new secret in the blob");
}
#[tokio::test]
async fn a_rescue_lets_a_stranded_member_walk_every_missed_hop() {
// A member forgotten by two consecutive rotations is wedged at epoch 0: their
// client derives base_rekey_group(root_0, cid, 1), finds no blob, and can never
// even compute where epoch 2 lives. The rescue publishes the blobs that should
// have existed, correlated into the ORIGINAL rotations — then the walk just works.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Stranded", vec!["wss://r".into()], None).await.unwrap();
let stranded = Keys::generate();
// Two rotations that never vend to `stranded` (they are in no fold: never
// joined the wire, never posted, not in the local store).
let e1 = refound_community(&relay, &community, &[]).await.unwrap();
let e2 = refound_community(&relay, &e1, &[]).await.unwrap();
assert_eq!(e2.root_epoch, Epoch(2));
// Wedged: no blob for them at the only plane they can derive.
let hop1 = base_rekey_group_key(&community.community_root, community.id(), Epoch(1));
let chunks = fetch_rekey_chunks(&relay, &community, &hop1).await.unwrap();
let r1 = &rekey::collect_rotations(&chunks)[0];
assert!(
rekey::find_my_blob(&r1.blobs, &r1.rotator.to_bytes(), &stranded.public_key().to_bytes(), r1.scope, r1.new_epoch).is_none(),
"genuinely stranded before the rescue"
);
let report = rescue_stranded_members(&relay, &e2, &[stranded.public_key()]).await.unwrap();
assert_eq!(report.hops, 2, "one catch-up per missed hop");
assert_eq!(report.hops_skipped, 0);
// Walk exactly as a client would: derive each hop's plane from the PREVIOUS
// root, find our blob inside the correlated rotation, open, adopt, repeat.
let signer = crate::signer::ActiveSigner::Keys(stranded.clone());
let mut held_root = community.community_root;
for e in 1..=2u64 {
let group = base_rekey_group_key(&held_root, community.id(), Epoch(e));
let chunks = fetch_rekey_chunks(&relay, &community, &group).await.unwrap();
let rotations = rekey::collect_rotations(&chunks);
let rot = rotations
.iter()
.find(|r| {
rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), &stranded.public_key().to_bytes(), r.scope, r.new_epoch).is_some()
})
.expect("a rotation now carries our blob");
let blob = rekey::find_my_blob(&rot.blobs, &rot.rotator.to_bytes(), &stranded.public_key().to_bytes(), rot.scope, rot.new_epoch).unwrap();
let delivery = rekey::open_base_blob(&signer, &rot.rotator, community.id(), Epoch(e), blob).await.unwrap();
held_root = delivery.new_root;
}
assert_eq!(held_root, e2.community_root, "the walk ends on the live root");
// Merge safety on DEPLOYED clients: the catch-up extended the original chunk
// set (disjoint indices), so everything folds as ONE complete rotation and no
// original recipient's blob was displaced — a slot collision would fold as
// their removal.
let chunks = fetch_rekey_chunks(&relay, &community, &hop1).await.unwrap();
let rotations = rekey::collect_rotations(&chunks);
assert_eq!(rotations.len(), 1, "catch-up merged into the original rotation, not a fork");
assert!(rotations[0].is_complete(), "the extended set still reads complete");
let owner_pk = e2.owner().unwrap();
assert!(
rekey::find_my_blob(&rotations[0].blobs, &rotations[0].rotator.to_bytes(), &owner_pk.to_bytes(), rotations[0].scope, rotations[0].new_epoch).is_some(),
"the original recipient's blob survived the extension"
);
// And the outside world counts them again: the snapshot addendum seeded them
// onto the current epoch's guestbook plane.
let wire = wire_guestbook_members(&relay, &e2).await.unwrap();
assert!(wire.contains(&stranded.public_key()), "the invite page's fold now includes them");
}
#[tokio::test]
async fn a_non_owner_refounders_snapshot_seeds_the_roster() {
// CORD-02 §5: a snapshot is honored "only from the npub whose Refounding
// minted that epoch". Vector read that as the OWNER always, so a moderation
// bot's containment rolled the epoch and vended the keys while its survivor
// list was thrown away — every client then folded its own accumulated Joins,
// keeping members the containment had cut and disagreeing with each other.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "MintedBy", vec!["wss://r".into()], None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let owner = community.owner().unwrap();
// An admin (NOT the owner) refounded to epoch 1 — this device verified and
// adopted that rotation, so it knows who minted it.
let admin = Keys::generate();
let mut at_epoch_1 = community.clone();
at_epoch_1.root_epoch = Epoch(1);
record_epoch_minter(&cid_hex, 1, &admin.public_key().to_hex());
// Someone the containment cut: joined at the old epoch, never banned, and
// absent from the survivor list the refounder published.
let cut = Keys::generate().public_key();
let join = guestbook::GuestbookEvent {
epoch: None, observed_at: None, rumor_id: [11u8; 32],
entry: guestbook::GuestbookEntry::Join { member: cut, invited_by: None, at_ms: 1_000 },
};
let snapshot = |by: &Keys, id: u8| guestbook::GuestbookEvent {
epoch: Some(1), observed_at: None, rumor_id: [id; 32],
entry: guestbook::GuestbookEntry::Snapshot {
refounder: by.public_key(),
members: vec![owner], // survivors: the cut member is NOT here
snapshot_id: [id; 32],
chunk: (1, 1),
at_ms: 5_000, // newer than the Join it supersedes
},
};
// A stranger's snapshot must change nothing — authority is the minter, not
// whoever manages to write a 3312.
let stranger = Keys::generate();
crate::db::community::set_guestbook(&cid_hex, &[join.clone(), snapshot(&stranger, 0x51)], 6).unwrap();
assert!(
stored_memberlist(&at_epoch_1).unwrap().contains(&cut),
"a snapshot from an npub that minted nothing seeds no roster"
);
// The actual refounder's snapshot IS the guest list.
crate::db::community::set_guestbook(&cid_hex, &[join, snapshot(&admin, 0x52)], 6).unwrap();
let members = stored_memberlist(&at_epoch_1).unwrap();
assert!(
!members.contains(&cut),
"the refounder's survivor list is adopted, so a cut member stops being one"
);
assert!(members.contains(&owner), "a survivor the snapshot names stays");
}
#[tokio::test]
async fn a_device_that_missed_the_rotation_takes_the_earliest_snapshot_from_someone_who_may_rotate() {
use crate::community::roles::{CommunityRoles, MemberGrant, Permissions, Role, RoleScope};
// A joiner holds only the epoch it was invited into, so it never saw who minted it.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Joiner", vec!["wss://r".into()], None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let owner = community.owner().unwrap();
let mut at_epoch_1 = community.clone();
at_epoch_1.root_epoch = Epoch(1);
let bot = Keys::generate();
let late_mod = Keys::generate();
let stranger = Keys::generate();
let role = |id: &str, bits: u64| Role { role_id: id.into(), name: id.into(), position: 1, permissions: Permissions(bits), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() };
let roster = |granted: Vec<String>| CommunityRoles {
roles: vec![role("guard", Permissions::BAN)],
grants: granted.into_iter().map(|member| MemberGrant { member, role_ids: vec!["guard".into()] }).collect(),
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
};
let survivor = Keys::generate().public_key();
let cut = Keys::generate().public_key();
let join = |member: PublicKey, id: u8| guestbook::GuestbookEvent {
epoch: None, observed_at: None, rumor_id: [id; 32],
entry: guestbook::GuestbookEntry::Join { member, invited_by: None, at_ms: 1_000 },
};
let snapshot = |by: &Keys, members: Vec<PublicKey>, at_ms: u64, id: u8| guestbook::GuestbookEvent {
epoch: Some(1), observed_at: None, rumor_id: [id; 32],
entry: guestbook::GuestbookEntry::Snapshot { refounder: by.public_key(), members, snapshot_id: [id; 32], chunk: (1, 1), at_ms },
};
let events = vec![
join(cut, 1),
snapshot(&stranger, vec![cut], 4_000, 0x61),
snapshot(&bot, vec![owner, survivor], 5_000, 0x62),
snapshot(&late_mod, vec![owner, cut], 9_000, 0x63),
];
crate::db::community::set_guestbook(&cid_hex, &events, 10).unwrap();
// Nobody but the owner may rotate: no snapshot here is theirs, so none seeds anything.
crate::db::community::set_community_roles(&cid_hex, &roster(vec![]), 1).unwrap();
let members = stored_memberlist(&at_epoch_1).unwrap();
assert!(!members.contains(&survivor) && members.contains(&cut), "without the right to rotate, a snapshot is noise");
// The bot and a later moderator both hold BAN: the bot's came first, so it is the Refounding's.
crate::db::community::set_community_roles(&cid_hex, &roster(vec![bot.public_key().to_hex(), late_mod.public_key().to_hex()]), 2).unwrap();
let members = stored_memberlist(&at_epoch_1).unwrap();
assert!(members.contains(&survivor), "the refounder's survivors are members without re-posting");
assert!(!members.contains(&cut), "and whoever it cut is not, whatever a later snapshot says");
// A device that saw the rotation keeps the minter it verified.
record_epoch_minter(&cid_hex, 1, &late_mod.public_key().to_hex());
assert!(stored_memberlist(&at_epoch_1).unwrap().contains(&cut), "a verified minter outranks the inference");
}
/// A moderation report quotes what was said, so it may only reach someone who
/// could have read the room it was said in. Community power is NOT that
/// question — BAN says what a moderator may do to people, never which rooms
/// they may see — and a bot holding every key would otherwise forward a
/// private channel's contents to whoever holds the ban bit.
#[tokio::test]
async fn reading_a_private_channel_needs_its_own_role_not_community_power() {
let (bed, owner, mod_without_access) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Rooms", bed.relays.clone(), None).await.unwrap();
let public = community.channels[0].id;
let private = create_private_channel(&bed.relay, &community, "back-room").await.unwrap();
let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
use nostr_sdk::prelude::ToBech32;
let them = mod_without_access.keys.public_key();
let them_npub = them.to_bech32().unwrap();
// Give them the fullest COMMUNITY powers there are. It must buy nothing
// in a room they were never admitted to.
let admin_rid = crate::simd::hex::bytes_to_hex_32(&[0xa7; 32]);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&admin_rid, Permissions::ADMIN_ALL), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &them, vec![admin_rid], 1).await;
follow_control(&bed.relay, &community).await.unwrap();
assert!(
crate::VectorCore.member_has_permission(&cid_hex, &them_npub, Permissions::BAN).unwrap(),
"they really do hold BAN"
);
let pub_hex = crate::simd::hex::bytes_to_hex_32(&public.0);
let priv_hex = crate::simd::hex::bytes_to_hex_32(&private.0);
assert!(
crate::VectorCore.member_can_read_channel(&cid_hex, &pub_hex, &them_npub).unwrap(),
"a public channel is the community's"
);
assert!(
!crate::VectorCore.member_can_read_channel(&cid_hex, &priv_hex, &them_npub).unwrap(),
"BAN is not a key: community power must never open a private room"
);
// The access role is what opens it — and it carries no powers at all.
grant_channel_access(&bed.relay, &community, &private, &them).await.unwrap();
let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let _ = follow_control(&bed.relay, &community).await;
assert!(
crate::VectorCore.member_can_read_channel(&cid_hex, &priv_hex, &them_npub).unwrap(),
"the channel-scoped grant is what admits them"
);
}
/// An empty retain means "cut nobody", never "keep nobody".
///
/// The console's "Rotate keys" sends an empty retain when nothing is unticked.
/// `members_to_remove` reads that correctly and removes nobody — but the same
/// empty list also became an ALLOW-LIST, and an allow-list keeps only the
/// rotating device and the owner. So a plain rotation vended to two people and
/// stranded everyone else at the previous epoch, permanently, presenting as
/// members vanishing some time later nowhere near the button that did it.
///
/// The two paths are pinned here against each other, because they take the same
/// empty list and must disagree about what it means.
#[tokio::test]
async fn an_empty_retain_cuts_nobody_rather_than_keeping_nobody() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "EmptyRetain", bed.relays.clone(), None).await.unwrap();
// A third party who is neither the rotator nor the owner — the only kind of
// member an empty allow-list silently drops.
let bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();
bed.swap_to(&member);
accept_parked_invite(&bed.relay, &bundle, None).await.unwrap();
bed.swap_to(&owner);
assert!(memberlist(&bed.relay, &community).await.unwrap().contains(&member.keys.public_key()));
// The plain reading: cut nobody, vend to everybody. This is what the button
// must reach. (The allow-list reading of the same empty list is covered by
// `a_rotation_that_would_strand_staff_refuses_to_publish`.)
refound_community(&bed.relay, &community, &[]).await.expect("cutting nobody must succeed");
assert!(
vended_to(&bed, &community, &member.keys).await,
"a plain rotation must vend to a member who is neither the rotator nor the owner"
);
}
/// The console's rotate button reaches the "cut nobody" path, not the allow-list
/// one. Pinned from source: the two are one `if` apart and read the same empty
/// list in opposite directions, which is exactly how this shipped.
#[test]
fn an_empty_retain_does_not_become_an_allow_list() {
let src = include_str!("../../lib.rs");
let at = src.find("pub async fn purge_and_refound").expect("purge_and_refound");
let body = &src[at..at + 3000];
let guard = body.find("if keep.is_empty()").expect("an empty retain must branch away from the allow-list");
let retaining = body.find("refound_community_retaining").expect("the allow-list call");
assert!(guard < retaining, "the branch has to come BEFORE the allow-list call");
}
/// If the recipients would strand a granted member, publish NOTHING.
///
/// A member missed at a hop is stranded there permanently, and every other
/// client goes on reading them as staff — silent, irreversible without the
/// rescue primitive, and only noticed because a human saw the member list
/// shrink. So the rotation refuses instead, exactly as the entity carry-forward
/// already refuses a floored head it cannot serve.
#[tokio::test]
async fn a_rotation_that_would_strand_staff_refuses_to_publish() {
let (bed, owner, staffer) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "NoSilentSever", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let them = staffer.keys.public_key();
let rid = crate::simd::hex::bytes_to_hex_32(&[0xb6; 32]);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &them, vec![rid], 1).await;
follow_control(&bed.relay, &community).await.unwrap();
// An operator purge whose allow-list forgets an admin: the recipient set
// ends up without somebody the roster still grants a role to.
let err = refound_community_retaining(&bed.relay, &community, &[], &[owner.keys.public_key()])
.await
.expect_err("must refuse rather than strand staff");
assert!(
err.contains("stranded"),
"the refusal has to say what it protected, got: {err}"
);
// And nothing was published: the epoch did not move.
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(held.root_epoch, community.root_epoch, "no state published");
assert!(!vended_to(&bed, &community, &staffer.keys).await, "no half-rotation left on the plane");
let _ = cid_hex;
}
/// The backstop protects a SILENT granted member. An ACTIVE one is the gap.
///
/// `fold_members` seeds granted members with `observed.entry(pk).or_insert(0)`,
/// and ts 0 is what dodges `stale_pre_refound`. A staffer who actually talks
/// already sits in `observed` with a REAL timestamp, so `or_insert` leaves it
/// alone — and if some earlier refounding's snapshot omitted them while their
/// last word predates its cut, they are suppressed despite holding a grant.
///
/// That is Sentire, 2026-08-26: admin, constantly posting, vended no key.
#[tokio::test]
async fn a_granted_member_who_talks_is_not_dropped_by_an_old_snapshot() {
let (bed, owner, staffer) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "TalkingAdmin", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let them = staffer.keys.public_key();
let rid = crate::simd::hex::bytes_to_hex_32(&[0xb5; 32]);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &them, vec![rid], 1).await;
follow_control(&bed.relay, &community).await.unwrap();
// They joined and spoke — so `observed` holds a REAL timestamp for them,
// not the 0 the grant backstop would have inserted.
let spoke_at = 5_000u64;
let join = guestbook::GuestbookEvent {
epoch: Some(community.root_epoch.0), observed_at: None, rumor_id: [0x31; 32],
entry: guestbook::GuestbookEntry::Join { member: them, invited_by: None, at_ms: spoke_at },
};
// A PRIOR refounding whose snapshot omitted them, cutting after they spoke.
let snapshot = guestbook::GuestbookEvent {
epoch: Some(community.root_epoch.0), observed_at: None, rumor_id: [0x32; 32],
entry: guestbook::GuestbookEntry::Snapshot {
refounder: owner.keys.public_key(),
members: vec![owner.keys.public_key()], // them: omitted
snapshot_id: [0x32; 32],
chunk: (1, 1),
at_ms: spoke_at + 1_000,
},
};
crate::db::community::set_guestbook(&cid_hex, &[join, snapshot], 9).unwrap();
assert!(
stored_memberlist(&community).unwrap().contains(&them),
"a grant is proof of membership — an old snapshot must not shed the staff it forgot"
);
let _ = refound_community(&bed.relay, &community, &[]).await.unwrap();
assert!(
vended_to(&bed, &community, &staffer.keys).await,
"and the rotation must vend to them, or they are stranded holding a grant"
);
}
/// A GRANT is proof of membership, so a rotation must vend to it.
///
/// Sentire's shape, 2026-08-26: an admin whose Join had been superseded by an
/// earlier refounding's snapshot fell out of BOTH folds the recipient union is
/// built from, held a valid admin grant the whole time, and was vended no key.
/// It could then only derive `held + 1`, so it was stranded permanently while
/// still appearing to be staff to everyone else.
///
/// `fold_members` already treats a grant as consensus-complete proof — "this is
/// what keeps a Refounding from severing a lurking admin". The rotation has to
/// agree with it.
#[tokio::test]
async fn a_rotation_vends_to_a_granted_member_the_folds_forgot() {
let (bed, owner, staffer) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "LurkingAdmin", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let them = staffer.keys.public_key();
// Staff by GRANT, with no Join anywhere — the lurking admin the backstop
// exists for. Never posted, never announced.
let rid = crate::simd::hex::bytes_to_hex_32(&[0xb4; 32]);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &them, vec![rid], 1).await;
follow_control(&bed.relay, &community).await.unwrap();
assert!(
crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&them.to_hex()),
"they hold the grant"
);
// An empty guestbook is the whole point: neither fold can see them.
crate::db::community::set_guestbook(&cid_hex, &[], 1).unwrap();
let _rotated = refound_community(&bed.relay, &community, &[]).await.unwrap();
// The blob is the answer. A member absent from the rotation's recipients is
// stranded at the previous epoch for good — they can only ever derive
// `held + 1`, so no later rotation reaches them.
assert!(
vended_to(&bed, &community, &staffer.keys).await,
"a rotation removing nobody must vend to a granted member, or it severs its own staff"
);
}
/// "Rotate keys" with nobody unticked must remove NOBODY — and must vend to
/// everyone, not merely leave them on a list. A rotation that forgets a
/// member strands them at the previous epoch permanently: they can only
/// derive `held + 1`, so no later rotation can ever reach them.
#[tokio::test]
async fn a_rotation_that_removes_nobody_vends_to_everybody() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "KeepAll", bed.relays.clone(), None).await.unwrap();
// A second member joins for real, via the invite path.
let bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();
bed.swap_to(&member);
accept_parked_invite(&bed.relay, &bundle, None).await.unwrap();
bed.swap_to(&owner);
let before = memberlist(&bed.relay, &community).await.unwrap();
assert!(before.contains(&member.keys.public_key()), "present before the rotation");
// Rotate keeping everyone — the empty `removed` the console sends when
// nothing is unticked.
let rotated = refound_community(&bed.relay, &community, &[]).await.unwrap();
assert_eq!(rotated.root_epoch.0, community.root_epoch.0 + 1, "the epoch rolled");
let after = memberlist(&bed.relay, &community).await.unwrap();
assert!(
after.contains(&member.keys.public_key()),
"a rotation removing nobody must keep everybody: {before:?} -> {after:?}"
);
// And the member must actually be able to WALK to the new epoch, which is
// the half a memberlist cannot show.
bed.swap_to(&member);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let follow = follow_rekeys(&bed.relay, &held, &crate::db::current_session()).await.unwrap();
assert!(!follow.self_removed, "they were not excluded");
let now = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(now.root_epoch.0, rotated.root_epoch.0, "they adopted the new epoch — a blob was vended to them");
}
/// A revocation has to reach the NETWORK, not just the revoker.
///
/// Every other client decides who is staff by folding the control plane, so
/// an owner whose demotion never published is the only person who believes
/// it happened — and the demoted admin keeps every power everywhere else,
/// which is the worst possible direction for this to fail in.
#[tokio::test]
async fn revoking_admin_publishes_where_everyone_else_reads_it() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Demotion", bed.relays.clone(), None).await.unwrap();
let them = member.keys.public_key();
let them_hex = them.to_hex();
grant_admin(&bed.relay, &community, &them).await.unwrap();
let view = fetch_authority(&bed.relay, &community).await;
assert!(view.roles.is_admin(&them_hex), "granted, and readable from the plane");
revoke_admin(&bed.relay, &community, &them).await.unwrap();
// The plane, NOT the local row: this is the copy every peer folds.
let view = fetch_authority(&bed.relay, &community).await;
assert!(
!view.roles.is_admin(&them_hex),
"the demotion must be on the plane, or only the owner believes it"
);
// And the same answer through the public API a bot or client would ask.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
use nostr_sdk::prelude::ToBech32;
assert!(
!crate::VectorCore
.member_has_permission(&cid_hex, &them.to_bech32().unwrap(), crate::community::roles::Permissions::BAN)
.unwrap(),
"a demoted admin holds no powers"
);
}
/// Authority must fail CLOSED. A bot gating a chat command on this is the
/// only thing standing between "a moderator asked" and "anyone in the room
/// asked", so an unfolded, empty or unreadable roster has to authorise
/// nobody — `has_permission` finds no grant and denies. The owner is the one
/// exception, and is answered without consulting the roster at all.
#[tokio::test]
async fn permission_is_refused_to_everyone_the_roster_does_not_name() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Authority", vec!["wss://r".into()], None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
use nostr_sdk::prelude::ToBech32;
let owner_npub = community.owner().unwrap().to_bech32().unwrap();
let stranger = Keys::generate().public_key().to_bech32().unwrap();
use crate::community::roles::Permissions;
for p in [Permissions::KICK, Permissions::BAN, Permissions::MANAGE_ROLES] {
assert!(
!crate::VectorCore.member_has_permission(&cid_hex, &stranger, p).unwrap(),
"an npub the roster never granted anything holds nothing"
);
assert!(
crate::VectorCore.member_has_permission(&cid_hex, &owner_npub, p).unwrap(),
"the owner is supreme without a grant to cite"
);
}
// A banned npub holds nothing, whatever a stale grant still says.
crate::db::community::set_community_banlist(&cid_hex, &[community.owner().unwrap().to_hex()], 1).unwrap();
let banned_owner_is_still_owner =
crate::VectorCore.member_has_permission(&cid_hex, &owner_npub, Permissions::BAN).unwrap();
assert!(banned_owner_is_still_owner, "the owner cannot be locked out of their own community");
// And a malformed npub is an error, never a silent grant.
assert!(crate::VectorCore.member_has_permission(&cid_hex, "not-an-npub", Permissions::BAN).is_err());
}
#[tokio::test]
async fn stored_members_fold_observed_authors_grants_and_bans() {
use nostr_sdk::prelude::ToBech32;
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Observed", vec!["wss://r".into()], None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let channel_hex = crate::simd::hex::bytes_to_hex_32(&community.channels[0].id.0);
let [talker, banned, staff, revoked] = std::array::from_fn(|_| Keys::generate().public_key());
for (i, pk) in [talker, banned, revoked].iter().enumerate() {
let mut m = crate::types::Message::default();
m.id = format!("{:02x}", i + 1).repeat(32);
m.npub = Some(pk.to_bech32().unwrap());
m.at = 1_000_000;
crate::db::events::save_message(&channel_hex, &m).await.unwrap();
}
crate::db::community::set_community_banlist(&cid_hex, &[banned.to_hex()], 1).unwrap();
let roles = crate::community::roles::CommunityRoles {
roles: Vec::new(),
grants: vec![
MemberGrant { member: staff.to_hex(), role_ids: vec!["ab".repeat(32)] },
MemberGrant { member: revoked.to_hex(), role_ids: Vec::new() },
],
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
};
crate::db::community::set_community_roles(&cid_hex, &roles, 1).unwrap();
// A reaction later than their text, ahead of it in index order: the newest of the two counts.
let chat = crate::db::id_cache::get_chat_id_by_identifier(&channel_hex).unwrap();
crate::db::get_write_connection_guard_static()
.unwrap()
.execute(
"INSERT INTO events (id, kind, chat_id, content, created_at, received_at, npub) VALUES (?1, 7, ?2, '', 2000000, 2000000, ?3)",
rusqlite::params!["ee".repeat(32), chat, talker.to_bech32().unwrap()],
)
.unwrap();
let activity: std::collections::HashMap<String, u64> =
crate::db::community::community_member_activity(&cid_hex).unwrap().into_iter().collect();
let at = |pk: &PublicKey| activity.get(&pk.to_bech32().unwrap()).copied();
assert_eq!(at(&talker), Some(2_000_000), "an author keeps the newest time they spoke");
assert!(at(&revoked).is_some_and(|t| t < 1_000_000_000), "an empty grant is not re-asserted");
assert!(at(&staff).is_some(), "a grant holder counts without a word");
assert_eq!(at(&banned), None);
let members = stored_memberlist(&community).unwrap();
for pk in [community.owner().unwrap(), talker, staff, revoked] {
assert!(members.contains(&pk));
}
assert!(!members.contains(&banned));
assert!(crate::db::community::community_member_activity(&"cd".repeat(32)).unwrap().is_empty());
}
#[tokio::test]
async fn a_refound_keeps_a_quiet_member_the_network_fold_forgot() {
// The network fold only sees the current guestbook + the recent posting window,
// so a quiet member whose Join lives on a buried epoch vanishes from it — and a
// rotation that trusts the fold alone silently sheds them. Being forgotten must
// not be a removal: only the explicit `removed` list is.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "QuietOnes", vec!["wss://r".into()], None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
// A member the LOCAL store remembers (an old synced Join) but the WIRE has no
// trace of: never posted, Join never published on the current plane.
let quiet = Keys::generate().public_key();
let ev = guestbook::GuestbookEvent { epoch: None, observed_at: None,
rumor_id: [7u8; 32],
entry: guestbook::GuestbookEntry::Join { member: quiet, invited_by: None, at_ms: 1_000 },
};
crate::db::community::set_guestbook(&cid_hex, std::slice::from_ref(&ev), 1).unwrap();
assert!(stored_memberlist(&community).unwrap().contains(&quiet), "locally known");
assert!(!memberlist(&relay, &community).await.unwrap().contains(&quiet), "network fold has forgotten them");
let rotated = refound_community(&relay, &community, &[]).await.unwrap();
// They made the new epoch's snapshot — the wire now carries them, so an outside
// reader counts them and their client has a rekey blob to walk forward on.
let wire = wire_guestbook_members(&relay, &rotated).await.unwrap();
assert!(wire.contains(&quiet), "the quiet member survived the rotation onto the wire");
// The explicit removed list still removes, union or no union.
let rotated2 = refound_community(&relay, &rotated, &[quiet]).await.unwrap();
let wire2 = wire_guestbook_members(&relay, &rotated2).await.unwrap();
assert!(!wire2.contains(&quiet), "an explicit removal is honoured");
}
#[tokio::test]
async fn revoking_a_husk_prunes_the_local_row_instead_of_erroring_forever() {
// The list is per-creator and cross-device: another device (or Armada) can
// retire a link this one still holds a row for. That row carries no signer_sk,
// so no revocation can ever be built from it — the old behaviour errored with
// "no such link in the invite list" BEFORE the local delete, leaving an entry
// the owner could neither use nor remove.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Husks", vec!["wss://r".into()], None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let minted = mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
let token_hex = crate::simd::hex::bytes_to_hex_16(&minted.token);
assert_eq!(crate::db::community::list_public_invites(&cid_hex).unwrap().len(), 1);
// "Another device" retires the link: republish the invite list without it.
let signer = crate::signer::active_signer().unwrap();
let my_pk = me_pk().unwrap();
let mut list = fetch_invite_list(&relay, &community.relays).await.unwrap().unwrap();
list.entries.retain(|e| e.token != token_hex);
let ev = invite::build_invite_list_event_signed(&signer, my_pk, &list).await.unwrap();
relay.publish(&ev, &community.relays).await.unwrap();
// This device's revoke now completes by pruning, not by erroring.
revoke_public_link(&relay, &community, &token_hex).await.unwrap();
assert!(
crate::db::community::list_public_invites(&cid_hex).unwrap().is_empty(),
"the husk row is gone — the panel can no longer show a link nobody can use or remove"
);
// An unreadable list is NOT proof of absence: only a fetched list may prune.
// (Guarded by the ok_or above the husk branch; a fresh row + an empty relay
// would hit "no invite list found", never the prune.)
}
#[tokio::test]
async fn revoking_the_last_link_privatizes_and_rotates_but_an_earlier_revoke_does_not() {
// CORD-06 §3: converting a Public Community to Private is a Refounding
// trigger — revoking stops NEW acquisitions, only the rotation cuts off
// everyone who already fetched the bundle. Revoking a link while ANOTHER
// stays live is not the conversion, and must not burn an epoch.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Privatize", vec!["wss://r".into()], None).await.unwrap();
assert_eq!(community.root_epoch, Epoch(0));
let a = mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
let b = mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
assert!(community_is_public(&relay, &community).await, "two live links = Public");
// Revoking ONE of two: still Public, still epoch 0 — no rotation.
revoke_public_link(&relay, &community, &crate::simd::hex::bytes_to_hex_16(&a.token)).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(held.root_epoch, Epoch(0), "a link remains live — not the Public→Private conversion");
assert!(community_is_public(&relay, &held).await, "still Public");
// Revoking the LAST one privatizes AND rotates.
revoke_public_link(&relay, &held, &crate::simd::hex::bytes_to_hex_16(&b.token)).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert!(!community_is_public(&relay, &held).await, "no live links = Private");
assert_eq!(held.root_epoch, Epoch(1), "privatizing rotated the base key");
// The rotation is a real one: the new epoch carries the split pair and
// the old root is retired, so a link-joined lurker's key is now dead.
assert!(held.control_pk.is_some(), "the privatize rotation mints the split like any base rotation");
assert_ne!(held.community_root, community.community_root, "the base key actually rolled");
}
#[tokio::test]
async fn a_legacy_community_upgrades_as_a_side_effect_of_its_next_refounding() {
// CORD-06 §3: a compliant Rotator performing ANY base rotation MUST mint
// the split — a pre-split community upgrades with nobody deciding to.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_legacy_community(&relay, &owner, "Legacy", vec!["wss://r".into()]).await;
assert!(community.control_pk.is_none(), "starts pre-split");
let refounded = refound_community(&relay, &community, &[]).await.unwrap();
assert_eq!(refounded.root_epoch, Epoch(1));
assert!(refounded.control_pk.is_some() && refounded.control_root.is_some(), "the rotation minted the split");
// And the persisted row agrees (the pair survives a reload).
let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(reloaded.control_pk, refounded.control_pk);
assert_eq!(reloaded.control_root, refounded.control_root);
}
#[tokio::test]
async fn an_old_build_deletion_recovers_from_the_stale_bundle_across_the_split() {
// The 0.4.0/0.4.1 upgrade path: those builds hit the widened base blob,
// conclude a false removal, and DELETE the community locally. Recovery on
// upgrade is the Community-List resurrection: re-accept the STALE-epoch
// material (the old plane is still served), then walk the rekey chain
// forward — now parsing the 104-byte form — to the current epoch.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_legacy_community(&bed.relay, &owner.keys, "Recover", bed.relays.clone()).await;
let stale_bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, None, None, None)).unwrap();
// The member joins at the legacy epoch 0.
bed.swap_to(&member);
let joined = accept_parked_invite(&bed.relay, &stale_bundle, None).await.unwrap();
assert!(joined.control_pk.is_none());
// The owner bans nobody but rotates (any refound upgrades to the split).
bed.swap_to(&owner);
let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
// The member's OLD build falsely self-removes and deletes the community.
bed.swap_to(&member);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::delete_community(&cid_hex).unwrap();
assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_none());
// Upgrade-recovery: re-accept the stale epoch-0 material (what
// sync_community_list does from the surviving 13302 entry)...
let readopted = accept_parked_invite(&bed.relay, &stale_bundle, None).await.unwrap();
assert_eq!(readopted.root_epoch, Epoch(0), "re-anchored at the stale epoch");
// ...then the walk crosses the split rotation and adopts the pair.
let follow = follow_rekeys(&bed.relay, &readopted, &crate::db::current_session()).await.unwrap();
assert!(!follow.self_removed, "never a false removal on this build");
let healed = follow.updated.expect("the walk adopts the split rotation");
assert_eq!(healed.root_epoch, Epoch(1));
assert_eq!(healed.control_pk, refounded.control_pk, "the member reads the upgraded plane");
assert_eq!(healed.control_root, None, "a plain member never receives the secret");
// And the upgraded control plane folds for them (the compacted state).
let folded = follow_control(&bed.relay, &healed).await;
assert!(folded.is_ok(), "the recovered member folds the split plane: {folded:?}");
}
#[tokio::test]
async fn an_unopenable_blob_at_my_locator_never_concludes_removal() {
// CORD-06 §2: removal = NO blob for my locator across a complete
// rotation. A blob that EXISTS but won't open (a future width, a rotator
// bug) must park — turning it into a self-removal is exactly how the
// pre-split builds deleted communities on the first widened rotation.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Garbled", bed.relays.clone(), None).await.unwrap();
let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, None, None, None)).unwrap();
bed.swap_to(&member);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
// The owner mints a complete, authorized rotation whose blob AT THE
// MEMBER'S LOCATOR is garbage (undecryptable), owner's own blob real.
bed.swap_to(&owner);
let new_epoch = Epoch(1);
let new_root = [0x4Du8; 32];
let control_root = [0x4Eu8; 32];
let control_pk = super::super::derive::control_signer_group_key(&control_root, community.id(), new_epoch).pk();
let prev_commit = super::super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
let garbled = rekey::RekeyBlob {
locator: rekey::blob_locator(&owner.keys.public_key().to_bytes(), &member.keys.public_key().to_bytes(), RekeyScope::Root, new_epoch),
wrapped: "bm90LWEtcmVhbC1uaXA0NC1wYXlsb2Fk".into(),
};
let own = rekey::build_base_blob(
&crate::signer::ActiveSigner::Keys(owner.keys.clone()),
&owner.keys.public_key().to_bytes(),
&owner.keys.public_key(),
new_epoch,
&new_root,
&control_pk.to_bytes(),
Some(&control_root),
)
.await
.unwrap();
let base_group = base_rekey_group_key(&community.community_root, community.id(), new_epoch);
let chunks = rekey::build_rekey_chunks_local(&owner.keys, &base_group, RekeyScope::Root, new_epoch, Epoch(0), &prev_commit, &[garbled, own], 2_000, None, false).unwrap();
for c in &chunks {
bed.relay.publish(c, &community.relays).await.unwrap();
}
// The member's follow PARKS: no adoption, and NEVER a removal.
bed.swap_to(&member);
let follow = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
assert!(!follow.self_removed, "an unopenable blob at my locator is not an exclusion");
assert!(follow.updated.is_none(), "nothing adopted from an unreadable blob");
assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_some(), "the community survives");
// …and the park is LEGIBLE. A silent park is indistinguishable from "no
// rotation happened", which is what makes an undecryptable blob planted
// at a protected member's locator an abusable severing tool.
assert!(follow.wedged, "an unopenable key delivery must be surfaced, not swallowed");
}
#[tokio::test]
async fn a_control_wrap_is_refused_on_a_stale_epoch_or_a_non_deriving_secret() {
// What the "no rank-gating on adoption" argument rests on (CORD-04 §3):
// a wrap is adopted only if its secret derives to the control_pk held
// for the epoch named INSIDE its ciphertext. That derive check is the
// load-bearing gate (revert-verified); the explicit epoch comparison
// beside it is defense in depth and can't be isolated, since deriving
// at a stale epoch already misses the held address. Compaction re-wraps
// a Grant head verbatim across Refoundings, so stale wraps are a
// structural certainty, not an edge case.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "AdoptGate", bed.relays.clone(), None).await.unwrap();
let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, None, None, None)).unwrap();
bed.swap_to(&member);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
assert!(joined.control_root.is_none());
// Build a Grant edition carrying `control_wrap` with a chosen plaintext.
let wrap_for = |epoch: Epoch, secret: &[u8; 32]| {
let ck = nostr_sdk::prelude::nip44::v2::ConversationKey::derive(owner.keys.secret_key(), &member.keys.public_key()).unwrap();
let ct = crate::community::cipher::encrypt_with_random_nonce(&ck, super::rekey::control_wrap_b64(epoch, secret).as_bytes()).unwrap();
crate::simd::base64::STANDARD.encode_to_string(&ct)
};
let eid = crate::community::v2::derive::grant_locator(community.id(), &member.keys.public_key().to_bytes());
let ed_with = |wrap: String| {
let grant = MemberGrant { member: member.keys.public_key().to_hex(), role_ids: vec![] };
let content = crate::community::v2::roles::grant_content_json_with_wrap(&grant, Some(wrap)).unwrap();
let rumor = control::build_edition_rumor(owner.keys.public_key(), vsk::GRANT, &eid, 1, None, &content, 1_000, None);
control::parse_edition_rumor(&rumor).unwrap()
};
// (a) A wrap for a DIFFERENT epoch — the real secret, wrong epoch.
let real = community.control_root.unwrap();
let stale = ed_with(wrap_for(Epoch(joined.root_epoch.0 + 1), &real));
assert_eq!(adopt_my_control_wrap(&joined, std::slice::from_ref(&stale)).await, None, "a stale-epoch wrap is refused");
// (b) Right epoch, a secret that does NOT derive to the held pk.
let forged = ed_with(wrap_for(joined.root_epoch, &[0x66u8; 32]));
assert_eq!(adopt_my_control_wrap(&joined, std::slice::from_ref(&forged)).await, None, "a non-deriving secret is refused");
// (c) The real secret at the held epoch IS adopted — the gates above
// reject on their own merits, not because adoption is broken.
let good = ed_with(wrap_for(joined.root_epoch, &real));
assert_eq!(adopt_my_control_wrap(&joined, std::slice::from_ref(&good)).await, Some(real), "the true wrap adopts");
}
#[test]
fn the_vault_carries_the_control_split() {
// CORD-02 §8: the list carries every key its holder has — the address
// for all, the secret for staff.
let owner = Keys::generate();
let g = control::genesis(&owner, control::CommunityMetadata { name: "Vault".into(), ..Default::default() }, 1_000).unwrap();
let c = CommunityV2::from_genesis(&g, "Vault", None, vec!["wss://r".into()], 0);
let jm = join_material(&c);
assert_eq!(jm.control_pk, c.control_pk.map(|p| p.to_hex()));
assert_eq!(jm.control_root, Some(crate::simd::hex::bytes_to_hex_32(&g.control_root)));
let bundle = material_to_invite(&jm);
assert_eq!(bundle.control_pk, jm.control_pk, "a rehydrating bundle carries the address");
}
// ── CORD-04 §1 author-aware fold: a seat-holder (holds community_root, so can seal
// any control edition) must not be able to SUPPRESS a role or grant by forging a
// higher version at its coordinate. Owner-only signers mask this entirely, so every
// attacker below signs as a NON-owner member.
#[tokio::test]
async fn a_non_owner_cannot_suppress_the_admin_role_by_forging_a_higher_version() {
let (bed, owner, attacker) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "AttackA", bed.relays.clone(), None).await.unwrap();
let victim = Keys::generate().public_key();
grant_admin(&bed.relay, &community, &victim).await.unwrap();
// The admin role sits at a deterministic, publicly-computable coordinate.
let admin_rid = fetch_authority(&bed.relay, &community)
.await
.roles
.roles
.iter()
.find(|r| r.permissions.contains(Permissions::ADMIN_ALL))
.unwrap()
.role_id
.clone();
// Attacker forges v2 of that exact role, stripping its powers.
publish_role(
&bed.relay,
&community,
&attacker.keys,
&Role { role_id: admin_rid.clone(), name: "pwned".into(), position: 1, permissions: Permissions(0), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() },
2,
)
.await;
let authority = fold_authority(&community, &fetch_control(&bed.relay, &community).await, &load_floors(&community));
assert!(authority.roles.is_admin(&victim.to_hex()), "the forged strip is DROPPED; the owner's admin role survives beneath it");
assert!(
authority.heads.iter().any(|h| h.entity_hex == admin_rid && h.version == 1),
"the floor advances only to the AUTHORIZED head (owner v1)"
);
assert!(!authority.heads.iter().any(|h| h.version == 2), "the forged v2 never poisons the floor");
}
#[tokio::test]
async fn a_non_owner_cannot_strip_a_members_grant_by_forging_a_higher_version() {
let (bed, owner, attacker) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "AttackC", bed.relays.clone(), None).await.unwrap();
let victim = Keys::generate();
grant_admin(&bed.relay, &community, &victim.public_key()).await.unwrap();
// Attacker forges a higher-version EMPTY grant at the victim's grant coordinate.
publish_grant(&bed.relay, &community, &attacker.keys, &victim.public_key(), vec![], 9).await;
let authority = fold_authority(&community, &fetch_control(&bed.relay, &community).await, &load_floors(&community));
assert!(
authority.roles.is_admin(&victim.public_key().to_hex()),
"the forged strip is dropped; the owner's grant survives and the victim keeps admin"
);
}
#[tokio::test]
async fn forged_low_id_roles_by_a_non_owner_never_enter_the_authorized_roster() {
let (bed, owner, attacker) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "AttackB", bed.relays.clone(), None).await.unwrap();
let victim = Keys::generate().public_key();
grant_admin(&bed.relay, &community, &victim).await.unwrap();
// Low-id roles that WOULD evict the admin from a pre-authorize cap — but they're
// unauthorized, so the post-authorize cap never sees them.
for i in 0u8..6 {
let rid = crate::simd::hex::bytes_to_hex_32(&[i; 32]);
publish_role(&bed.relay, &community, &attacker.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
}
let authority = fold_authority(&community, &fetch_control(&bed.relay, &community).await, &load_floors(&community));
assert!(authority.roles.is_admin(&victim.to_hex()), "the legit admin survives the forged flood");
assert_eq!(authority.roles.roles.len(), 1, "only the owner's admin role is authorized; every forgery is dropped");
}
#[tokio::test]
async fn a_same_version_role_fork_folds_to_the_lowest_rumor_id_in_any_order() {
// CORD-04 §1: two authorized editions tying on version converge on the LOWEST
// id — the rule grants, metadata, the persisted floor and Armada all apply.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "RoleFork", bed.relays.clone(), None).await.unwrap();
let eid = [0x42u8; 32];
let rid = crate::simd::hex::bytes_to_hex_32(&eid);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
let v1 = head_hash_on_relay(&bed.relay, &community, &eid).await.unwrap();
// The owner on two devices: two v2 editions off the same v1.
let group = control::ControlPlane::of(&community).write_group().unwrap();
let mut forks: Vec<(&str, [u8; 32])> = Vec::new();
for (name, ts) in [("Left", 2_000u64), ("Right", 2_001)] {
let mut role = admin_role(&rid, Permissions::ADMIN_ALL);
role.name = name.into();
let content = crate::community::v2::roles::role_content_json(&role).unwrap();
let rumor = control::build_edition_rumor(owner.keys.public_key(), vsk::ROLE, &eid, 2, Some(&v1), &content, ts, None);
forks.push((name, rumor.id.unwrap().to_bytes()));
let (wrap, _) = control::seal_control_edition(&rumor, &group, &owner.keys, Timestamp::from_secs(ts)).unwrap();
bed.relay.publish(&wrap, &community.relays).await.unwrap();
}
let (winner, winner_id) = *forks.iter().min_by_key(|(_, id)| *id).unwrap();
let editions = fetch_control(&bed.relay, &community).await;
let floors = load_floors(&community);
let mut reversed = editions.clone();
reversed.reverse();
for (order, set) in [("served", &editions), ("reversed", &reversed)] {
let folded = fold_authority(&community, set, &floors);
assert_eq!(folded.roles.role(&rid).unwrap().name, winner, "{order} order folds the lowest-id fork");
// The head the floor commits to — and a refound re-wraps — is that same edition.
let head = folded.heads.iter().find(|h| h.entity_hex == rid).unwrap();
assert_eq!((head.version, head.inner_id), (2, winner_id), "{order} order heads the lowest-id fork");
}
}
/// Publish one side of a same-version fork to every relay given, nudging its clock until
/// its rumor id sorts as `order` against another id. A test can then pit authority against
/// the id rule instead of hoping the hashes fall the right way.
#[allow(clippy::too_many_arguments)]
async fn publish_fork(
relays: &[&MemoryRelay],
community: &CommunityV2,
signer: &Keys,
vsk_code: &str,
eid: &[u8; 32],
version: u64,
prev: Option<[u8; 32]>,
content: &str,
order: Option<(std::cmp::Ordering, [u8; 32])>,
) -> [u8; 32] {
let group = control::ControlPlane::of(community).write_group().unwrap();
let cite = cite_on_relay(relays[0], community, signer).await;
for ts in 5_000u64.. {
let rumor = control::build_edition_rumor(signer.public_key(), vsk_code, eid, version, prev.as_ref(), content, ts, cite.as_ref());
let id = rumor.id.unwrap().to_bytes();
if order.is_some_and(|(want, other)| id.cmp(&other) != want) {
continue;
}
for relay in relays {
let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(ts)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
return id;
}
unreachable!()
}
fn channel_meta_json(name: &str) -> String {
serde_json::to_string(&control::ChannelMetadata { name: name.into(), private: false, ..Default::default() }).unwrap()
}
/// The persisted floor of one entity: `(version, inner_id, author)`.
/// Drop every Control wrap held of `community`: its floors and roster stay, as on a device
/// that kept no wraps when it read them.
fn forget_held(community: &CommunityV2) {
let view = control_store::View::of(community);
for (id, _) in view.held().unwrap() {
view.forget(&id);
}
}
fn floor_of(community: &CommunityV2, entity: &[u8; 32]) -> (u64, Option<[u8; 32]>, Option<[u8; 32]>) {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let f = crate::db::community::get_all_edition_heads_full(&cid_hex).unwrap()[&crate::simd::hex::bytes_to_hex_32(entity)];
(f.1, f.3, f.4)
}
/// A community whose `admin` holds a position-1 role with `perms`, granted by the owner.
async fn with_admin(relay: &MemoryRelay, name: &str, owner: &Keys, perms: u64) -> (CommunityV2, Keys) {
let community = create_community(relay, name, vec!["wss://r".into()], None).await.unwrap();
let admin = Keys::generate();
let rid = "d1".repeat(32);
publish_role(relay, &community, owner, &admin_role(&rid, perms), 1).await;
publish_grant(relay, &community, owner, &admin.public_key(), vec![rid], 1).await;
(community, admin)
}
#[tokio::test]
async fn a_same_version_channel_fork_goes_to_the_owner_over_a_lower_id_admin_edit() {
// CORD-04 §1: authority first, then the lower rumor id. The admin's edit sorts
// lower, so the old id-only rule would have seated it; Armada seats the owner's.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let (community, admin) = with_admin(&relay, "ForkAuth", &owner, Permissions::MANAGE_CHANNELS).await;
let ch = community.channels[0].id;
let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
let owner_id = publish_fork(&[&relay], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("owner-pick"), None).await;
let admin_id = publish_fork(&[&relay], &community, &admin, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("admin-pick"), Some((std::cmp::Ordering::Less, owner_id))).await;
let updated = follow_control(&relay, &community).await.unwrap().updated.expect("the fork folds");
assert_eq!(updated.channel(&ch).unwrap().name, "owner-pick", "authority beats the lower id");
assert_eq!(floor_of(&community, &ch.0), (2, Some(owner_id), Some(owner.public_key().to_bytes())), "the floor commits to the owner's edition");
assert_ne!(owner_id, admin_id);
// A fresh joiner (no floor for the entity) bootstraps to the same head.
let editions = fetch_control(&relay, &community).await;
let mut floors = load_floors(&community);
floors.remove(&crate::simd::hex::bytes_to_hex_32(&ch.0));
let authority = fold_authority(&community, &editions, &floors);
for set in [editions.clone(), editions.iter().rev().cloned().collect()] {
let fold = apply_control_fold(&community, &set, &floors, &authority);
let head = fold.heads.iter().find(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(&ch.0)).unwrap();
assert_eq!(head.inner_id, owner_id, "bootstrap picks the owner's fork in any order");
}
}
#[tokio::test]
async fn a_tracking_client_holding_the_admins_fork_converges_to_the_owners_higher_id() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let (community, admin) = with_admin(&relay, "ForkTrack", &owner, Permissions::MANAGE_CHANNELS).await;
let ch = community.channels[0].id;
let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
let admin_id = publish_fork(&[&relay], &community, &admin, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("admin-pick"), None).await;
let first = follow_control(&relay, &community).await.unwrap().updated.expect("the admin's edit folds");
assert_eq!(first.channel(&ch).unwrap().name, "admin-pick");
assert_eq!(floor_of(&community, &ch.0).1, Some(admin_id));
// The owner's sibling arrives later and sorts HIGHER: only authority can seat it.
let owner_id = publish_fork(&[&relay], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("owner-pick"), Some((std::cmp::Ordering::Greater, admin_id))).await;
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let second = follow_control(&relay, &held).await.unwrap().updated.expect("the floor converges");
assert_eq!(second.channel(&ch).unwrap().name, "owner-pick");
assert_eq!(floor_of(&community, &ch.0), (2, Some(owner_id), Some(owner.public_key().to_bytes())));
}
#[tokio::test]
async fn a_withheld_owner_floor_is_not_swapped_for_a_served_admin_sibling() {
// The floor holds the owner's v2. A relay serving only the admin's v2 (lower id)
// must not flip it: the held key carries the owner's authority even unserved.
let (_tmp, _guard, owner) = init_test_db();
let full = MemoryRelay::new();
let (community, admin) = with_admin(&full, "ForkHold", &owner, Permissions::MANAGE_CHANNELS).await;
let thin = MemoryRelay::new();
mirror_control(&full, &thin, &community).await;
let ch = community.channels[0].id;
let v1 = head_hash_on_relay(&full, &community, &ch.0).await;
let owner_id = publish_fork(&[&full], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("owner-pick"), None).await;
publish_fork(&[&full, &thin], &community, &admin, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("admin-pick"), Some((std::cmp::Ordering::Less, owner_id))).await;
follow_control(&full, &community).await.unwrap();
assert_eq!(floor_of(&community, &ch.0).1, Some(owner_id));
// The thin relay's plane is coherent: the admin's edit alone would fold there.
let editions = fetch_control(&thin, &community).await;
let authority = fold_authority(&community, &editions, &load_floors(&community));
assert!(
editions.iter().any(|e| e.entity_id == ch.0 && e.version == 2 && authority.roles.is_authorized(&admin.public_key().to_hex(), None, Permissions::MANAGE_CHANNELS)),
"the admin's sibling is served and authorized on the thin relay"
);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
follow_control(&thin, &held).await.unwrap();
assert_eq!(floor_of(&community, &ch.0).1, Some(owner_id), "a served worse sibling never takes the floor");
let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(after.channel(&ch).unwrap().name, "owner-pick");
}
/// Copy every control wrap one relay holds onto another, so both serve one coherent plane.
async fn mirror_control(from: &MemoryRelay, to: &MemoryRelay, community: &CommunityV2) {
let group = control::ControlPlane::of(community).write_group().unwrap();
let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
for w in from.fetch(&query, &community.relays).await.unwrap() {
to.publish(&w, &community.relays).await.unwrap();
}
}
#[tokio::test]
async fn a_floor_written_before_authors_were_recorded_still_converges_on_authority() {
// A pre-upgrade client held the admin's v2 (lower id) with no author recorded. With
// both siblings served, the tiebreak decides: authority seats the owner's.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let (community, admin) = with_admin(&relay, "ForkLegacy", &owner, Permissions::MANAGE_CHANNELS).await;
let ch = community.channels[0].id;
let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
let owner_id = publish_fork(&[&relay], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("owner-pick"), None).await;
let admin_id = publish_fork(&[&relay], &community, &admin, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("admin-pick"), Some((std::cmp::Ordering::Less, owner_id))).await;
let editions = fetch_control(&relay, &community).await;
let admin_hash = editions.iter().find(|e| e.inner_id == admin_id).unwrap().self_hash;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::set_edition_head_with_id(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&ch.0), 2, &admin_hash, &admin_id).unwrap();
assert_eq!(floor_of(&community, &ch.0), (2, Some(admin_id), None), "a legacy row: id, no author");
let updated = follow_control(&relay, &community).await.unwrap().updated.expect("the legacy floor converges");
assert_eq!(updated.channel(&ch).unwrap().name, "owner-pick");
assert_eq!(floor_of(&community, &ch.0), (2, Some(owner_id), Some(owner.public_key().to_bytes())));
}
#[tokio::test]
async fn a_role_floor_written_before_authors_were_recorded_still_converges_on_authority() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let (community, admin) = with_admin(&relay, "RoleLegacy", &owner, Permissions::ADMIN_ALL).await;
let rlow = "f1".repeat(32);
let mut low = admin_role(&rlow, Permissions::KICK);
low.position = 5;
publish_role(&relay, &community, &owner, &low, 1).await;
let eid = crate::simd::hex::hex_to_bytes_32_checked(&rlow).unwrap();
let v1 = head_hash_on_relay(&relay, &community, &eid).await;
let named = |name: &str| {
let mut r = low.clone();
r.name = name.into();
crate::community::v2::roles::role_content_json(&r).unwrap()
};
let owner_id = publish_fork(&[&relay], &community, &owner, vsk::ROLE, &eid, 2, v1, &named("owner-pick"), None).await;
let admin_id = publish_fork(&[&relay], &community, &admin, vsk::ROLE, &eid, 2, v1, &named("admin-pick"), Some((std::cmp::Ordering::Less, owner_id))).await;
let editions = fetch_control(&relay, &community).await;
let admin_hash = editions.iter().find(|e| e.inner_id == admin_id).unwrap().self_hash;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::set_edition_head_with_id(&cid_hex, &rlow, 2, &admin_hash, &admin_id).unwrap();
assert_eq!(floor_of(&community, &eid), (2, Some(admin_id), None));
let a = fold_authority(&community, &editions, &load_floors(&community));
assert_eq!(a.roles.role(&rlow).unwrap().name, "owner-pick", "a served held edition competes on the tiebreak");
assert_eq!(a.heads.iter().find(|h| h.entity_hex == rlow).map(|h| h.inner_id), Some(owner_id));
}
#[tokio::test]
async fn a_floor_holding_a_marked_editions_unsigned_hash_heals_and_its_authority_returns() {
// The admin's grant moved to a marked v2, and a build before marked editions floored it
// under its unsigned hash, which nothing served carries: the grant folded no head, and
// every edition the admin signed after it fell unauthorized.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let (community, admin) = with_admin(&relay, "UnsignedFloor", &owner, Permissions::MANAGE_CHANNELS).await;
let eid = crate::community::v2::derive::grant_locator(community.id(), &admin.public_key().to_bytes());
let group = control::ControlPlane::of(&community).write_group().unwrap();
let prev = head_hash_on_relay(&relay, &community, &eid).await;
let grant = MemberGrant { member: admin.public_key().to_hex(), role_ids: vec!["d1".repeat(32)] };
let content = crate::community::v2::roles::grant_content_json_with_wrap(&grant, None).unwrap();
let cite = cite_on_relay(&relay, &community, &owner).await;
let binding = Some(crate::community::v2::derive::edition_binding(community.id()));
let rumor = control::build_edition_rumor_bound(owner.public_key(), vsk::GRANT, &eid, 2, prev.as_ref(), &content, 1_001, cite.as_ref(), binding);
let (wrap, _) = control::seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(1_001)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
follow_control(&relay, &community).await.unwrap();
let v2 = fetch_control(&relay, &community).await.into_iter().find(|e| e.entity_id == eid && e.version == 2).unwrap();
let unsigned = crate::community::version::edition_hash(&eid, 2, v2.prev_hash.as_ref(), v2.content.as_bytes());
assert!(v2.binding.is_some() && unsigned != v2.self_hash, "a marked edition's hash covers its signer");
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let eid_hex = crate::simd::hex::bytes_to_hex_32(&eid);
crate::db::community::delete_edition_head(&cid_hex, &eid_hex).unwrap();
crate::db::community::set_edition_head_at_epoch(&cid_hex, &eid_hex, 2, &unsigned, &v2.inner_id, &owner.public_key().to_bytes(), community.root_epoch.0).unwrap();
let ch = community.channels[0].id;
let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
publish_fork(&[&relay], &community, &admin, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("renamed-by-admin"), None).await;
let updated = follow_control(&relay, &community).await.unwrap().updated.expect("the admin's rename folds");
assert_eq!(updated.channel(&ch).unwrap().name, "renamed-by-admin", "the admin's authority is back");
let held = crate::db::community::get_all_edition_heads_full(&cid_hex).unwrap()[&eid_hex];
assert_eq!((held.1, held.2), (2, v2.self_hash), "the floor names the served edition");
}
#[tokio::test]
async fn only_the_same_edition_heals_an_unsigned_floor() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "HealScope", vec!["wss://r".into()], None).await.unwrap();
let group = control::ControlPlane::of(&community).write_group().unwrap();
let binding = Some(crate::community::v2::derive::edition_binding(community.id()));
let eid = [7u8; 32];
let key = crate::simd::hex::bytes_to_hex_32(&eid);
let publish = |rumor: nostr_sdk::prelude::UnsignedEvent, signer: Keys, ts: u64| {
let (wrap, _) = control::seal_control_edition(&rumor, &group, &signer, Timestamp::from_secs(ts)).unwrap();
(wrap, signer)
};
let (wrap, _) = publish(control::build_edition_rumor_bound(owner.public_key(), vsk::CHANNEL_METADATA, &eid, 3, Some(&[1u8; 32]), &channel_meta_json("x"), 1_000, None, binding), owner.clone(), 1_000);
relay.publish(&wrap, &community.relays).await.unwrap();
let mine = fetch_control(&relay, &community).await;
let e = mine.iter().find(|x| x.entity_id == eid).unwrap().clone();
let unsigned = crate::community::version::edition_hash(&eid, 3, e.prev_hash.as_ref(), e.content.as_bytes());
let owner_pk = Some(owner.public_key().to_bytes());
let heal = |floor: Floor, served: &[ParsedEdition]| {
let mut floors: Floors = Default::default();
floors.insert(key.clone(), floor);
let mut healed = Vec::new();
heal_unsigned_floors(&mut floors, owner_pk, served, &mut healed);
(floors[&key].1, healed.len())
};
let only_e = std::slice::from_ref(&e);
assert_eq!(heal((3, unsigned, None, None, None), only_e), (e.self_hash, 1), "its unsigned hash, by the owner, heals");
assert_eq!(heal((3, [9u8; 32], Some(e.inner_id), None, None), only_e), (e.self_hash, 1), "its inner id heals");
assert_eq!(heal((3, [9u8; 32], Some([8u8; 32]), None, None), only_e), ([9u8; 32], 0), "another edition stays");
assert_eq!(heal((2, unsigned, None, None, None), only_e), (unsigned, 0), "another version stays");
assert_eq!(heal((3, unsigned, None, Some([5u8; 32]), None), only_e), (unsigned, 0), "another signer's floor stays");
// The same content re-signed by another key carries the same unsigned hash.
let other = Keys::generate();
let (wrap, _) = publish(control::build_edition_rumor_bound(other.public_key(), vsk::CHANNEL_METADATA, &eid, 3, Some(&[1u8; 32]), &channel_meta_json("x"), 1_001, None, binding), other.clone(), 1_001);
relay.publish(&wrap, &community.relays).await.unwrap();
let both: Vec<ParsedEdition> = fetch_control(&relay, &community).await.into_iter().filter(|x| x.entity_id == eid).collect();
assert_eq!(both.len(), 2);
let theirs: Vec<ParsedEdition> = both.iter().filter(|x| x.author == other.public_key()).cloned().collect();
assert_eq!(heal((3, unsigned, None, None, None), &theirs), (unsigned, 0), "with no signer recorded, nobody's copy but the owner's");
assert_eq!(heal((3, unsigned, None, None, None), &both), (e.self_hash, 1), "the owner's copy when none was recorded");
assert_eq!(heal((3, unsigned, None, Some(other.public_key().to_bytes()), None), &both).0, theirs[0].self_hash, "the recorded signer's copy");
// An unmarked copy carries the unsigned hash itself, but not the floor's inner id: it
// must not pass for the held edition and keep the real one from healing.
let (wrap, _) = publish(control::build_edition_rumor(other.public_key(), vsk::CHANNEL_METADATA, &eid, 3, Some(&[1u8; 32]), &channel_meta_json("x"), 1_002, None), other.clone(), 1_002);
relay.publish(&wrap, &community.relays).await.unwrap();
let all: Vec<ParsedEdition> = fetch_control(&relay, &community).await.into_iter().filter(|x| x.entity_id == eid).collect();
assert!(all.iter().any(|x| x.self_hash == unsigned), "the unmarked copy's hash is the unsigned one");
assert_eq!(heal((3, unsigned, Some(e.inner_id), None, None), &all), (e.self_hash, 1), "the floor's own edition still heals");
}
/// A channel edition sealed for the plane and published nowhere: only a live fold sees it.
fn live_edition(community: &CommunityV2, signer: &Keys, eid: &[u8; 32], version: u64, prev: Option<[u8; 32]>, name: &str, ts: u64) -> Event {
let group = control::ControlPlane::of(community).write_group().unwrap();
let rumor = control::build_edition_rumor(signer.public_key(), vsk::CHANNEL_METADATA, eid, version, prev.as_ref(), &channel_meta_json(name), ts, None);
control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(ts)).unwrap().0
}
#[tokio::test]
async fn a_settled_community_folds_live_editions_without_reading_the_plane() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "LiveFold", vec!["wss://r".into()], None).await.unwrap();
let ch = community.channels[0].id;
follow_control(&relay, &community).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
let rename = live_edition(&held, &owner, &ch.0, 2, v1, "live-name", 5_000);
let follow = follow_control_live(&held, &rename).await.expect("the held window decides it");
assert_eq!(follow.updated.expect("the rename folds").channel(&ch).unwrap().name, "live-name");
assert_eq!(floor_of(&community, &ch.0).0, 2);
let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(after.channel(&ch).unwrap().name, "live-name", "persisted");
assert!(!follow_control_live(&after, &rename).await.expect("already held").moved(), "a repeat folds nothing");
let v2 = control::ControlPlane::of(&after).open_edition(&rename).unwrap().self_hash;
let again = live_edition(&after, &owner, &ch.0, 3, Some(v2), "again", 5_001);
let follow = follow_control_live(&after, &again).await.expect("extends the edition folded live");
assert_eq!(follow.updated.unwrap().channel(&ch).unwrap().name, "again");
// A relay that never saw them can't roll the live editions back.
let latest = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
follow_control(&relay, &latest).await.unwrap();
let reread = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(reread.channel(&ch).unwrap().name, "again");
assert_eq!(floor_of(&community, &ch.0).0, 3);
}
#[tokio::test]
async fn a_live_edition_only_a_read_can_settle_waits_for_one() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "LiveRead", vec!["wss://r".into()], None).await.unwrap();
let ch = community.channels[0].id;
follow_control(&relay, &community).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
let stranger = Keys::generate();
assert!(follow_control_live(&held, &live_edition(&held, &stranger, &ch.0, 2, v1, "theirs", 5_000)).await.is_none(), "an author the window grants nothing");
let gone = serde_json::to_string(&control::ChannelMetadata { name: "x".into(), deleted: Some(true), ..Default::default() }).unwrap();
let group = control::ControlPlane::of(&held).write_group().unwrap();
let rumor = control::build_edition_rumor(owner.public_key(), vsk::CHANNEL_METADATA, &ch.0, 2, v1.as_ref(), &gone, 5_001, None);
let delete = control::seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(5_001)).unwrap().0;
assert!(follow_control_live(&held, &delete).await.is_none(), "a deletion");
let fine = live_edition(&held, &owner, &ch.0, 2, v1, "fine", 5_002);
let read = reading(community.id());
assert!(follow_control_live(&held, &fine).await.is_none(), "a read in flight");
drop(read);
super::super::realtime::note_resubscribe();
assert!(follow_control_live(&held, &fine).await.is_none(), "a resubscribe since the read");
assert_eq!(floor_of(&community, &ch.0).0, 1);
// No relay kept those: the read finds the plane as it was.
forget_held(&held);
follow_control(&relay, &held).await.unwrap();
assert!(follow_control_live(&held, &fine).await.expect("a fresh read holds again").updated.is_some());
}
#[tokio::test]
async fn a_live_edition_the_roster_refuses_waits_for_a_read() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let (community, admin) = with_admin(&relay, "LiveRefused", &owner, Permissions::KICK).await;
let ch = community.channels[0].id;
follow_control(&relay, &community).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
let group = control::ControlPlane::of(&held).write_group().unwrap();
let cite = cite_on_relay(&relay, &held, &admin).await;
let rumor = control::build_edition_rumor(admin.public_key(), vsk::CHANNEL_METADATA, &ch.0, 2, v1.as_ref(), &channel_meta_json("not-theirs"), 5_000, cite.as_ref());
let rename = control::seal_control_edition(&rumor, &group, &admin, Timestamp::from_secs(5_000)).unwrap().0;
assert!(follow_control_live(&held, &rename).await.is_none(), "staff, but without the permission");
assert_eq!(floor_of(&community, &ch.0).0, 1);
}
#[tokio::test]
async fn a_window_missing_a_floored_grant_waits_for_a_read() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let (community, admin) = with_admin(&relay, "LiveDemoted", &owner, Permissions::MANAGE_CHANNELS).await;
let ch = community.channels[0].id;
follow_control(&relay, &community).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
// The admin's demotion floored by another path, and so not in the window.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let geid = crate::community::v2::derive::grant_locator(community.id(), &admin.public_key().to_bytes());
crate::db::community::set_edition_head_with_id(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&geid), 2, &[2u8; 32], &[2u8; 32]).unwrap();
let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
let group = control::ControlPlane::of(&held).write_group().unwrap();
let cite = cite_on_relay(&relay, &held, &admin).await;
let rumor = control::build_edition_rumor(admin.public_key(), vsk::CHANNEL_METADATA, &ch.0, 2, v1.as_ref(), &channel_meta_json("demoted-rename"), 5_000, cite.as_ref());
let rename = control::seal_control_edition(&rumor, &group, &admin, Timestamp::from_secs(5_000)).unwrap().0;
assert!(follow_control_live(&held, &rename).await.is_none(), "the window can't see the newer grant");
let owners = live_edition(&held, &owner, &ch.0, 2, v1, "owner-rename", 5_001);
assert!(follow_control_live(&held, &owners).await.is_none(), "nor fold anything over it");
assert_eq!(floor_of(&community, &ch.0).0, 1);
}
#[tokio::test]
async fn our_own_grant_joins_the_held_window_and_its_member_folds_live() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let (community, _admin) = with_admin(&relay, "LiveOwn", &owner, Permissions::MANAGE_CHANNELS).await;
let ch = community.channels[0].id;
follow_control(&relay, &community).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let fresh = Keys::generate();
grant_roles(&relay, &held, &fresh.public_key(), vec!["d1".repeat(32)]).await.unwrap();
let geid = crate::community::v2::derive::grant_locator(community.id(), &fresh.public_key().to_bytes());
let window = held_control().lock().unwrap().get(&community.id().0).cloned().expect("still held");
assert!(window.editions.iter().any(|e| e.entity_id == geid), "our grant is in the window");
let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
let now = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let group = control::ControlPlane::of(&now).write_group().unwrap();
let cite = cite_on_relay(&relay, &now, &fresh).await;
let rumor = control::build_edition_rumor(fresh.public_key(), vsk::CHANNEL_METADATA, &ch.0, 2, v1.as_ref(), &channel_meta_json("by-the-new-admin"), 5_000, cite.as_ref());
let rename = control::seal_control_edition(&rumor, &group, &fresh, Timestamp::from_secs(5_000)).unwrap().0;
let follow = follow_control_live(&now, &rename).await.expect("the window holds their grant");
assert_eq!(follow.updated.unwrap().channel(&ch).unwrap().name, "by-the-new-admin");
}
#[tokio::test]
async fn a_read_a_newer_floor_overtook_persists_nothing() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Overtaken", vec!["wss://r".into()], None).await.unwrap();
let ch = community.channels[0].id;
let name = community.channels[0].name.clone();
let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
publish_fork(&[&relay], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("on-the-relay"), None).await;
let read = read_control(&relay, &community).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::set_edition_head_with_id(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&ch.0), 3, &[3u8; 32], &[3u8; 32]).unwrap();
let (follow, window) = persist_control(&relay, &community, read).await.unwrap();
assert!(follow.updated.is_none() && window.is_none(), "folded against floors that have moved on");
let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(after.channel(&ch).unwrap().name, name);
}
#[tokio::test]
async fn a_live_edition_the_held_window_cannot_decide_waits_for_a_follow() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "LiveGap", vec!["wss://r".into()], None).await.unwrap();
let ch = community.channels[0].id;
let name = community.channels[0].name.clone();
follow_control(&relay, &community).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
let gap = live_edition(&held, &owner, &ch.0, 3, Some([9u8; 32]), "gap", 5_000);
assert!(follow_control_live(&held, &gap).await.is_none(), "a link the window doesn't hold");
let fine = live_edition(&held, &owner, &ch.0, 2, v1, "fine", 5_001);
let mut rotated = held.clone();
rotated.root_epoch = crate::community::Epoch(held.root_epoch.0 + 1);
assert!(follow_control_live(&rotated, &fine).await.is_none(), "another epoch's window");
hold_control(&held, None);
assert!(follow_control_live(&held, &fine).await.is_none(), "no settled window");
let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(after.channel(&ch).unwrap().name, name);
assert_eq!(floor_of(&community, &ch.0).0, 1);
}
#[tokio::test]
async fn a_fork_branch_the_chain_extended_is_followed_not_stranded() {
// CORD-04 §1 "the highest version whose chain is intact": the admin's v2 lost the
// tiebreak to the owner's, but v3 was built on the admin's. The head is v3.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let (community, admin) = with_admin(&relay, "ForkExtend", &owner, Permissions::MANAGE_CHANNELS).await;
let ch = community.channels[0].id;
let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
publish_fork(&[&relay], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("owner-v2"), None).await;
let admin_v2 = publish_fork(&[&relay], &community, &admin, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("admin-v2"), None).await;
let editions = fetch_control(&relay, &community).await;
let admin_hash = editions.iter().find(|e| e.inner_id == admin_v2).unwrap().self_hash;
publish_fork(&[&relay], &community, &admin, vsk::CHANNEL_METADATA, &ch.0, 3, Some(admin_hash), &channel_meta_json("admin-v3"), None).await;
let updated = follow_control(&relay, &community).await.unwrap().updated.expect("folds");
assert_eq!(updated.channel(&ch).unwrap().name, "admin-v3", "the extended branch is followed");
assert_eq!(floor_of(&community, &ch.0).0, 3);
// A client that had already settled on the owner's v2 follows it too.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let owner_v2 = editions.iter().find(|e| e.version == 2 && e.author == owner.public_key()).unwrap();
let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.0);
crate::db::community::delete_edition_head(&cid_hex, &ch_hex).unwrap();
crate::db::community::set_edition_head_at_epoch(&cid_hex, &ch_hex, 2, &owner_v2.self_hash, &owner_v2.inner_id, &owner.public_key().to_bytes(), community.root_epoch.0).unwrap();
let editions = fetch_control(&relay, &community).await;
let floors = load_floors(&community);
let authority = fold_authority(&community, &editions, &floors);
let fold = apply_control_fold(&community, &editions, &floors, &authority);
let head = fold.heads.iter().find(|h| h.entity_hex == ch_hex).expect("a head, not a gap");
assert_eq!(head.version, 3, "the sibling's descendant outranks a dead-end winner");
assert!(!fold.gapped);
}
#[tokio::test]
async fn a_same_content_copy_does_not_rekey_the_floor_to_a_weaker_author() {
// The edition hash covers content, not signer: an admin re-signing the owner's exact
// v2 makes the same hash. Serving only that copy must not lower the floor's bar.
let (_tmp, _guard, owner) = init_test_db();
let full = MemoryRelay::new();
let (community, admin) = with_admin(&full, "ForkCopy", &owner, Permissions::MANAGE_CHANNELS).await;
let thin = MemoryRelay::new();
mirror_control(&full, &thin, &community).await;
let ch = community.channels[0].id;
let v1 = head_hash_on_relay(&full, &community, &ch.0).await;
let owner_id = publish_fork(&[&full], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("same"), None).await;
publish_fork(&[&thin], &community, &admin, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("same"), None).await;
follow_control(&full, &community).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
follow_control(&thin, &held).await.unwrap();
assert_eq!(floor_of(&community, &ch.0), (2, Some(owner_id), Some(owner.public_key().to_bytes())), "the floor keeps the owner's key");
}
#[tokio::test]
async fn a_role_above_its_granter_stays_out_of_reach_when_bundled_with_one_below() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Bundled", vec!["wss://r".into()], None).await.unwrap();
let (moderator, member) = (Keys::generate(), Keys::generate().public_key());
let (rhigh, rmod, rlow) = ("a1".repeat(32), "a2".repeat(32), "a3".repeat(32));
for (rid, perms, position) in [(&rhigh, Permissions::ADMIN_ALL, 1), (&rmod, Permissions::MANAGE_ROLES, 2), (&rlow, Permissions::KICK, 3)] {
let mut role = admin_role(rid, perms);
role.position = position;
publish_role(&relay, &community, &owner, &role, 1).await;
}
publish_grant(&relay, &community, &owner, &moderator.public_key(), vec![rmod], 1).await;
let held_by = |community: &CommunityV2| {
let roles = crate::db::community::get_community_roles(&community.id().to_hex()).unwrap();
let mut ids: Vec<String> = roles.roles_of(&member.to_hex()).map(|r| r.role_id.clone()).collect();
ids.sort();
ids
};
publish_grant(&relay, &community, &moderator, &member, vec![rlow.clone()], 1).await;
follow_control(&relay, &community).await.unwrap();
assert_eq!(held_by(&community), [rlow.clone()], "a role beneath the granter stands");
publish_grant(&relay, &community, &moderator, &member, vec![rhigh.clone(), rlow.clone()], 2).await;
follow_control(&relay, &community).await.unwrap();
assert_eq!(held_by(&community), [rlow], "the highest role a grant names sets its reach, so the bundle is refused");
}
#[tokio::test]
async fn a_higher_ranked_admin_wins_a_fork_over_a_lower_id_from_a_lesser_admin() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "ForkRanks", vec!["wss://r".into()], None).await.unwrap();
let (senior, junior) = (Keys::generate(), Keys::generate());
let (rs, rj) = ("e1".repeat(32), "e2".repeat(32));
let mut junior_role = admin_role(&rj, Permissions::MANAGE_CHANNELS);
junior_role.position = 2;
publish_role(&relay, &community, &owner, &admin_role(&rs, Permissions::MANAGE_CHANNELS), 1).await;
publish_role(&relay, &community, &owner, &junior_role, 1).await;
publish_grant(&relay, &community, &owner, &senior.public_key(), vec![rs], 1).await;
publish_grant(&relay, &community, &owner, &junior.public_key(), vec![rj], 1).await;
let ch = community.channels[0].id;
let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
let senior_id = publish_fork(&[&relay], &community, &senior, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("senior-pick"), None).await;
publish_fork(&[&relay], &community, &junior, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("junior-pick"), Some((std::cmp::Ordering::Less, senior_id))).await;
let updated = follow_control(&relay, &community).await.unwrap().updated.expect("folds");
assert_eq!(updated.channel(&ch).unwrap().name, "senior-pick", "position 1 outranks position 2 whatever the ids");
}
#[tokio::test]
async fn role_grant_and_banlist_forks_go_to_authority_in_any_order() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let (community, admin) = with_admin(&relay, "ForkAuthority", &owner, Permissions::ADMIN_ALL).await;
// A role beneath the admin, and a member holding it.
let (rlow, rextra) = ("f1".repeat(32), "f2".repeat(32));
let mut low = admin_role(&rlow, Permissions::KICK);
low.position = 5;
let mut extra = admin_role(&rextra, 0);
extra.position = 6;
publish_role(&relay, &community, &owner, &low, 1).await;
publish_role(&relay, &community, &owner, &extra, 1).await;
let member = Keys::generate().public_key();
publish_grant(&relay, &community, &owner, &member, vec![rlow.clone()], 1).await;
// Role fork at v2.
let role_eid = crate::simd::hex::hex_to_bytes_32_checked(&rlow).unwrap();
let rv1 = head_hash_on_relay(&relay, &community, &role_eid).await;
let named = |name: &str| {
let mut r = low.clone();
r.name = name.into();
crate::community::v2::roles::role_content_json(&r).unwrap()
};
let owner_role = publish_fork(&[&relay], &community, &owner, vsk::ROLE, &role_eid, 2, rv1, &named("owner-pick"), None).await;
publish_fork(&[&relay], &community, &admin, vsk::ROLE, &role_eid, 2, rv1, &named("admin-pick"), Some((std::cmp::Ordering::Less, owner_role))).await;
// Grant fork at v2.
let grant_eid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
let gv1 = head_hash_on_relay(&relay, &community, &grant_eid).await;
let grant_json = |ids: Vec<String>| crate::community::v2::roles::grant_content_json_with_wrap(&MemberGrant { member: member.to_hex(), role_ids: ids }, None).unwrap();
let owner_grant = publish_fork(&[&relay], &community, &owner, vsk::GRANT, &grant_eid, 2, gv1, &grant_json(vec![rlow.clone(), rextra.clone()]), None).await;
publish_fork(&[&relay], &community, &admin, vsk::GRANT, &grant_eid, 2, gv1, &grant_json(vec![]), Some((std::cmp::Ordering::Less, owner_grant))).await;
// Banlist fork at v1: each bans a different roleless member.
let (x, y) = ("aa".repeat(32), "bb".repeat(32));
let ban_eid = crate::community::v2::derive::banlist_locator(community.id());
let ban_json = |t: &str| crate::community::v2::roles::banlist_content_json(&[t.to_string()]).unwrap();
let owner_ban = publish_fork(&[&relay], &community, &owner, vsk::BANLIST, &ban_eid, 1, None, &ban_json(&x), None).await;
publish_fork(&[&relay], &community, &admin, vsk::BANLIST, &ban_eid, 1, None, &ban_json(&y), Some((std::cmp::Ordering::Less, owner_ban))).await;
let editions = fetch_control(&relay, &community).await;
let floors = load_floors(&community);
for set in [editions.clone(), editions.iter().rev().cloned().collect::<Vec<_>>()] {
let a = fold_authority(&community, &set, &floors);
assert_eq!(a.roles.role(&rlow).unwrap().name, "owner-pick", "role fork");
let mut held = a.roles.grants.iter().find(|g| g.member == member.to_hex()).expect("the owner's grant stands").role_ids.clone();
held.sort();
assert_eq!(held, vec![rlow.clone(), rextra.clone()], "grant fork");
assert!(a.banned.contains(&x) && !a.banned.contains(&y), "banlist fork");
let head = |eid: &[u8; 32]| a.heads.iter().find(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(eid)).map(|h| h.inner_id);
assert_eq!((head(&role_eid), head(&grant_eid), head(&ban_eid)), (Some(owner_role), Some(owner_grant), Some(owner_ban)));
}
}
#[tokio::test]
async fn a_withheld_owner_role_head_is_not_replaced_by_a_served_admin_sibling() {
let (_tmp, _guard, owner) = init_test_db();
let full = MemoryRelay::new();
let community = create_community(&full, "RoleHold", vec!["wss://r".into()], None).await.unwrap();
let admin = Keys::generate();
let (radmin, rlow) = ("d1".repeat(32), "f1".repeat(32));
let mut low = admin_role(&rlow, Permissions::KICK);
low.position = 5;
publish_role(&full, &community, &owner, &admin_role(&radmin, Permissions::ADMIN_ALL), 1).await;
publish_grant(&full, &community, &owner, &admin.public_key(), vec![radmin.clone()], 1).await;
publish_role(&full, &community, &owner, &low, 1).await;
// The thin relay gets everything the full one has so far.
let thin = MemoryRelay::new();
let group = control::ControlPlane::of(&community).write_group().unwrap();
let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
for w in full.fetch(&query, &community.relays).await.unwrap() {
thin.publish(&w, &community.relays).await.unwrap();
}
let role_eid = crate::simd::hex::hex_to_bytes_32_checked(&rlow).unwrap();
let rv1 = head_hash_on_relay(&full, &community, &role_eid).await;
let named = |name: &str| {
let mut r = low.clone();
r.name = name.into();
crate::community::v2::roles::role_content_json(&r).unwrap()
};
let owner_id = publish_fork(&[&full], &community, &owner, vsk::ROLE, &role_eid, 2, rv1, &named("owner-pick"), None).await;
let admin_id = publish_fork(&[&full, &thin], &community, &admin, vsk::ROLE, &role_eid, 2, rv1, &named("admin-pick"), Some((std::cmp::Ordering::Less, owner_id))).await;
follow_control(&full, &community).await.unwrap();
assert_eq!(floor_of(&community, &role_eid).1, Some(owner_id));
let editions = fetch_control(&thin, &community).await;
let a = fold_authority(&community, &editions, &load_floors(&community));
let head = a.heads.iter().find(|h| h.entity_hex == rlow).map(|h| h.inner_id);
assert_ne!(head, Some(admin_id), "the admin's sibling never heads over the held owner edition");
assert_ne!(a.roles.role(&rlow).map(|r| r.name.as_str()), Some("admin-pick"));
}
/// Owner grants a senior admin (position 1) and a junior admin (position 2), both full
/// admins, plus a role beneath both held by a member.
async fn two_admins(relay: &MemoryRelay, name: &str, owner: &Keys) -> (CommunityV2, Keys, Keys, String, PublicKey) {
let community = create_community(relay, name, vec!["wss://r".into()], None).await.unwrap();
let (senior, junior) = (Keys::generate(), Keys::generate());
let (rs, rj, rlow) = ("e1".repeat(32), "e2".repeat(32), "f1".repeat(32));
let mut jr = admin_role(&rj, Permissions::ADMIN_ALL);
jr.position = 2;
let mut low = admin_role(&rlow, Permissions::KICK);
low.position = 5;
publish_role(relay, &community, owner, &admin_role(&rs, Permissions::ADMIN_ALL), 1).await;
publish_role(relay, &community, owner, &jr, 1).await;
publish_role(relay, &community, owner, &low, 1).await;
publish_grant(relay, &community, owner, &senior.public_key(), vec![rs], 1).await;
publish_grant(relay, &community, owner, &junior.public_key(), vec![rj], 1).await;
let member = Keys::generate().public_key();
publish_grant(relay, &community, owner, &member, vec![rlow.clone()], 1).await;
(community, senior, junior, rlow, member)
}
#[tokio::test]
async fn admin_versus_admin_role_grant_and_banlist_forks_go_to_the_higher_position() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let (community, senior, junior, rlow, member) = two_admins(&relay, "ForkPositions", &owner).await;
let low_eid = crate::simd::hex::hex_to_bytes_32_checked(&rlow).unwrap();
let rv1 = head_hash_on_relay(&relay, &community, &low_eid).await;
let named = |name: &str| {
let mut r = admin_role(&rlow, Permissions::KICK);
r.position = 5;
r.name = name.into();
crate::community::v2::roles::role_content_json(&r).unwrap()
};
let senior_role = publish_fork(&[&relay], &community, &senior, vsk::ROLE, &low_eid, 2, rv1, &named("senior-pick"), None).await;
publish_fork(&[&relay], &community, &junior, vsk::ROLE, &low_eid, 2, rv1, &named("junior-pick"), Some((std::cmp::Ordering::Less, senior_role))).await;
let grant_eid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
let gv1 = head_hash_on_relay(&relay, &community, &grant_eid).await;
let grant_json = |ids: Vec<String>| crate::community::v2::roles::grant_content_json_with_wrap(&MemberGrant { member: member.to_hex(), role_ids: ids }, None).unwrap();
let senior_grant = publish_fork(&[&relay], &community, &senior, vsk::GRANT, &grant_eid, 2, gv1, &grant_json(vec![rlow.clone()]), None).await;
publish_fork(&[&relay], &community, &junior, vsk::GRANT, &grant_eid, 2, gv1, &grant_json(vec![]), Some((std::cmp::Ordering::Less, senior_grant))).await;
let (x, y) = ("aa".repeat(32), "bb".repeat(32));
let ban_eid = crate::community::v2::derive::banlist_locator(community.id());
let ban_json = |t: &str| crate::community::v2::roles::banlist_content_json(&[t.to_string()]).unwrap();
let senior_ban = publish_fork(&[&relay], &community, &senior, vsk::BANLIST, &ban_eid, 1, None, &ban_json(&x), None).await;
publish_fork(&[&relay], &community, &junior, vsk::BANLIST, &ban_eid, 1, None, &ban_json(&y), Some((std::cmp::Ordering::Less, senior_ban))).await;
let editions = fetch_control(&relay, &community).await;
let floors = load_floors(&community);
for set in [editions.clone(), editions.iter().rev().cloned().collect::<Vec<_>>()] {
let a = fold_authority(&community, &set, &floors);
assert_eq!(a.roles.role(&rlow).unwrap().name, "senior-pick", "role fork");
assert_eq!(a.roles.grants.iter().find(|g| g.member == member.to_hex()).map(|g| g.role_ids.clone()), Some(vec![rlow.clone()]), "grant fork");
assert!(a.banned.contains(&x) && !a.banned.contains(&y), "banlist fork");
}
}
#[tokio::test]
async fn a_withheld_owner_grant_head_is_not_replaced_by_a_served_admin_revocation() {
let (_tmp, _guard, owner) = init_test_db();
let full = MemoryRelay::new();
let (community, _senior, junior, rlow, member) = two_admins(&full, "GrantHold", &owner).await;
let thin = MemoryRelay::new();
mirror_control(&full, &thin, &community).await;
let grant_eid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
let gv1 = head_hash_on_relay(&full, &community, &grant_eid).await;
let grant_json = |ids: Vec<String>| crate::community::v2::roles::grant_content_json_with_wrap(&MemberGrant { member: member.to_hex(), role_ids: ids }, None).unwrap();
let owner_id = publish_fork(&[&full], &community, &owner, vsk::GRANT, &grant_eid, 2, gv1, &grant_json(vec![rlow.clone()]), None).await;
let junior_id = publish_fork(&[&full, &thin], &community, &junior, vsk::GRANT, &grant_eid, 2, gv1, &grant_json(vec![]), Some((std::cmp::Ordering::Less, owner_id))).await;
follow_control(&full, &community).await.unwrap();
assert_eq!(floor_of(&community, &grant_eid).1, Some(owner_id));
let editions = fetch_control(&thin, &community).await;
let a = fold_authority(&community, &editions, &load_floors(&community));
let head = a.heads.iter().find(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(&grant_eid)).map(|h| h.inner_id);
assert_ne!(head, Some(junior_id), "the junior's revocation never heads over the held owner grant");
// Without the guard the junior's empty grant would stand: prove it is admissible on its own.
let mut unfloored = load_floors(&community);
unfloored.remove(&crate::simd::hex::bytes_to_hex_32(&grant_eid));
let free = fold_authority(&community, &editions, &unfloored);
assert_eq!(free.heads.iter().find(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(&grant_eid)).map(|h| h.inner_id), Some(junior_id));
}
#[test]
fn a_held_key_ranks_rivals_by_what_the_row_recorded() {
let (lo, hi) = ([1u8; 32], [9u8; 32]);
let floor = |inner, author| -> Floor { (2, [0u8; 32], inner, author, None) };
let owner_ranked = |_: &[u8; 32]| 0u32;
assert!(HeldKey::of(&floor(None, None), &owner_ranked).beaten_by(u32::MAX, &hi), "an unkeyed row yields to anyone");
let legacy = HeldKey::of(&floor(Some(hi), None), &owner_ranked);
assert!(legacy.beaten_by(u32::MAX, &lo) && !legacy.beaten_by(0, &[0xFF; 32]), "a row without an author compares ids only");
let ranked = HeldKey::of(&floor(Some(hi), Some([7u8; 32])), &owner_ranked);
assert!(!ranked.beaten_by(1, &lo), "the owner's held head beats a lower-id admin");
assert!(ranked.beaten_by(0, &lo), "and loses only to a lower id at the same rank");
}
/// A canonical (order-independent) fingerprint of an AuthoritySet's authorized
/// roster + banlist — two clients converge iff these match.
fn authority_fingerprint(a: &AuthoritySet) -> String {
let mut roles = a.roles.roles.clone();
roles.sort_by(|x, y| x.role_id.cmp(&y.role_id));
let mut grants = a.roles.grants.clone();
for g in &mut grants {
g.role_ids.sort();
}
grants.sort_by(|x, y| x.member.cmp(&y.member));
let banned: Vec<&String> = a.banned.iter().collect();
serde_json::json!({ "roles": roles, "grants": grants, "banned": banned }).to_string()
}
fn folded_role<'a>(view: &'a AuthorityView, id: &str) -> &'a crate::community::roles::Role {
view.roles.role(id).unwrap_or_else(|| panic!("role {id} folded"))
}
#[tokio::test]
async fn roles_are_created_at_the_bottom_edited_in_place_and_reordered() {
use crate::community::roles::{Permissions, RoleScope};
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Roles", bed.relays.clone(), None).await.unwrap();
let a = create_role(&bed.relay, &community, "Alpha", 0, Permissions::KICK, RoleScope::Server).await.unwrap();
let b = create_role(&bed.relay, &community, "Beta", 0, 0, RoleScope::Server).await.unwrap();
let c = create_role(&bed.relay, &community, "Gamma", 0, 0, RoleScope::Server).await.unwrap();
let view = fetch_authority(&bed.relay, &community).await;
let pos = |v: &AuthorityView, id: &str| folded_role(v, id).position;
assert!(pos(&view, &a) < pos(&view, &b) && pos(&view, &b) < pos(&view, &c), "each new role lands beneath the last");
assert!(pos(&view, &a) >= 1, "no role claims the owner's position");
edit_role(&bed.relay, &community, &b, "Beta Prime", 0x59fcb3, Permissions::BAN, RoleScope::Server).await.unwrap();
let view = fetch_authority(&bed.relay, &community).await;
let edited = folded_role(&view, &b);
assert_eq!((edited.name.as_str(), edited.color, edited.permissions.0), ("Beta Prime", 0x59fcb3, Permissions::BAN));
assert_eq!(edited.position, pos(&view, &b), "an edit keeps the role where it was");
let moved = reorder_roles(&bed.relay, &community, &[c.clone(), a.clone(), b.clone()]).await.unwrap();
assert_eq!(moved, 3, "every role whose position changed is republished");
let view = fetch_authority(&bed.relay, &community).await;
assert!(pos(&view, &c) < pos(&view, &a) && pos(&view, &a) < pos(&view, &b), "the fold holds the requested order");
assert_eq!(pos(&view, &c), 1, "renumbered from just beneath the owner");
let again = reorder_roles(&bed.relay, &community, &[c, a, b]).await.unwrap();
assert_eq!(again, 0, "the same order again publishes nothing");
}
#[tokio::test]
async fn new_roles_stack_above_the_access_band_and_never_share_a_position() {
use crate::community::roles::{Permissions, RoleScope};
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Band", bed.relays.clone(), None).await.unwrap();
create_private_channel(&bed.relay, &community, "secret").await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let a = create_role(&bed.relay, &held, "A", 0, Permissions::empty().0, RoleScope::Server).await.unwrap();
let b = create_role(&bed.relay, &held, "B", 0, Permissions::empty().0, RoleScope::Server).await.unwrap();
let view = fetch_authority(&bed.relay, &held).await;
let (pa, pb) = (folded_role(&view, &a).position, folded_role(&view, &b).position);
assert!(pa < pb, "each new role lands beneath the last");
assert!(pb < ACCESS_ROLE_POSITION, "and above the access band, never in the slot beneath it");
}
#[tokio::test]
async fn a_members_role_set_is_written_whole_and_the_owner_holds_roles_for_display_alone() {
use crate::community::roles::{Permissions, RoleScope};
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Grants", bed.relays.clone(), None).await.unwrap();
let a = create_role(&bed.relay, &community, "A", 0, Permissions::KICK, RoleScope::Server).await.unwrap();
let b = create_role(&bed.relay, &community, "B", 0, 0, RoleScope::Server).await.unwrap();
let admin_role = create_role(&bed.relay, &community, "Admin", 0, Permissions::MANAGE_ROLES, RoleScope::Server).await.unwrap();
let below = create_role(&bed.relay, &community, "Below", 0, 0, RoleScope::Server).await.unwrap();
let lowest = create_role(&bed.relay, &community, "Lowest", 0, 0, RoleScope::Server).await.unwrap();
let member = Keys::generate().public_key();
set_member_roles(&bed.relay, &community, &member, vec![a.clone(), b.clone()]).await.unwrap();
let view = fetch_authority(&bed.relay, &community).await;
let held: Vec<String> = view.roles.roles_of(&member.to_hex()).map(|r| r.role_id.clone()).collect();
assert!(held.contains(&a) && held.contains(&b), "both roles granted");
set_member_roles(&bed.relay, &community, &member, vec![b.clone()]).await.unwrap();
let view = fetch_authority(&bed.relay, &community).await;
let held: Vec<String> = view.roles.roles_of(&member.to_hex()).map(|r| r.role_id.clone()).collect();
assert_eq!(held, vec![b.clone()], "the set replaces, it does not append");
// The owner may hold Roles, for display alone, on the new roles (CORD-04 §3).
let owner_pk = owner.keys.public_key();
let owner_hex = owner_pk.to_hex();
let err = set_member_roles(&bed.relay, &community, &owner_pk, vec![below.clone()]).await.unwrap_err();
assert!(err.contains("new roles"), "not on the legacy roles: {err}");
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
set_member_roles(&bed.relay, &community, &owner_pk, vec![below.clone()]).await.unwrap();
let view = fetch_authority(&bed.relay, &community).await;
let held: Vec<String> = view.roles.roles_of(&owner_hex).map(|r| r.role_id.clone()).collect();
assert_eq!(held, vec![below.clone()], "the owner holds the role they gave themselves");
assert!(view.roles.outranks(&owner_hex, Some(&owner_hex), 1), "and still outranks every role");
assert_eq!(fork_rank(&view.roles, Some(&owner_hex), &owner_hex), 0, "their rank stays the owner's");
// Nobody else's Grant names the owner, even an admin above every Role it touches.
let admin = Keys::generate();
publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![admin_role], 1).await;
publish_grant(&bed.relay, &community, &admin, &owner_pk, vec![below.clone(), lowest.clone()], 2).await;
let view = fetch_authority(&bed.relay, &community).await;
let held: Vec<String> = view.roles.roles_of(&owner_hex).map(|r| r.role_id.clone()).collect();
assert_eq!(held, vec![below.clone()], "an admin's Grant naming the owner is refused");
let other = Keys::generate().public_key();
publish_grant(&bed.relay, &community, &admin, &other, vec![below.clone(), lowest], 1).await;
let view = fetch_authority(&bed.relay, &community).await;
assert_eq!(view.roles.roles_of(&other.to_hex()).count(), 2, "the same Grant stands for anyone else");
}
#[tokio::test]
async fn losing_the_last_role_that_opens_a_channel_rotates_it_and_keeping_one_does_not() {
use crate::community::roles::{Permissions, RoleScope};
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Keys", bed.relays.clone(), None).await.unwrap();
let chan = create_private_channel(&bed.relay, &community, "secret").await.unwrap();
let chan_hex = crate::simd::hex::bytes_to_hex_32(&chan.0);
let reload = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let epoch = |c: &CommunityV2| c.channel(&chan).unwrap().epoch.0;
let held = reload();
let access = fetch_authority(&bed.relay, &held).await.roles.channel_role_ids(&chan_hex);
assert!(!access.is_empty(), "the private channel came with its access role");
let second = create_role(&bed.relay, &held, "Also Secret", 0, Permissions::empty().0, RoleScope::Channel(chan_hex.clone())).await.unwrap();
let member = Keys::generate().public_key();
set_member_roles(&bed.relay, &reload(), &member, vec![access[0].clone(), second.clone()]).await.unwrap();
let start = epoch(&reload());
// Drop one of the two: still entitled, so nobody is cut and nothing rotates.
set_member_roles(&bed.relay, &reload(), &member, vec![second.clone()]).await.unwrap();
assert_eq!(epoch(&reload()), start, "a kept role still opens the channel");
// Drop the last: the channel rotates without them.
set_member_roles(&bed.relay, &reload(), &member, vec![]).await.unwrap();
assert_eq!(epoch(&reload()), start + 1, "losing the last access role severs them");
}
#[test]
fn a_role_author_carries_only_bits_they_hold_and_acts_only_beneath_themselves() {
use crate::community::roles::{CommunityRoles, MemberGrant, Permissions, Role, RoleScope};
let role = |id: &str, position: u32, bits: u64| Role { role_id: id.into(), name: id.into(), position, permissions: Permissions(bits), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() };
// A moderator at 3 holding MANAGE_ROLES|KICK, plus a low role at 8 carrying BAN.
let roles = CommunityRoles {
roles: vec![role("mod", 3, Permissions::MANAGE_ROLES | Permissions::KICK), role("low", 8, Permissions::BAN)],
grants: vec![MemberGrant { member: "m".into(), role_ids: vec!["mod".into(), "low".into()] }],
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
};
let moderator = RoleAuthor { me_hex: "m".into(), owner_hex: "o".into(), is_owner: false, rank: 3, roles };
assert!(moderator.supports(4, Permissions::KICK), "a bit they hold, beneath them");
assert!(moderator.supports(4, 0), "or none at all");
assert!(!moderator.supports(4, Permissions::BAN), "BAN comes only from a role beneath 4, so it can't support acting there");
assert!(moderator.supports(9, Permissions::BAN), "but it does beneath that role");
assert!(!moderator.supports(3, 0), "never at their own position");
assert!(moderator.outranks(4) && !moderator.outranks(3) && !moderator.outranks(1), "strictly beneath only");
let owner = RoleAuthor { is_owner: true, rank: 0, ..moderator };
assert!(owner.supports(1, u64::MAX) && owner.outranks(1));
}
/// Everything a fold decides, as one comparable string.
fn authority_whole(a: &AuthoritySet) -> String {
let mut admitted: Vec<String> = a.admitted.iter().map(crate::simd::hex::bytes_to_hex_32).collect();
admitted.sort();
format!("{} refused={:?} carried={:?} admitted={admitted:?} gapped={} complete={}", authority_and_heads(a), a.refused, a.carried, a.gapped, a.complete)
}
/// The roster, banlist and the heads a follow would floor, as one comparable string.
fn authority_and_heads(a: &AuthoritySet) -> String {
let mut heads: Vec<_> = a.heads.iter().map(|h| (h.entity_hex.clone(), h.version, crate::simd::hex::bytes_to_hex_32(&h.self_hash), crate::simd::hex::bytes_to_hex_32(&h.inner_id), h.rebased)).collect();
heads.sort();
format!("{} heads={heads:?} converged={}", authority_fingerprint(a), a.converged)
}
#[test]
fn hash_groups_list_each_hash_in_index_order_whatever_came_before() {
let mut seed = 0x2545_f491_4f6c_dd1du64;
let mut next = move |n: u64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed % n
};
let mut groups = HashGroups::default();
for _ in 0..200 {
let n = next(12) as usize;
let hashes: Vec<[u8; 32]> = (0..n).map(|_| [next(4) as u8; 32]).collect();
groups.build(n, |j| hashes[j]);
let mut want: std::collections::HashMap<[u8; 32], Vec<usize>> = Default::default();
for (j, h) in hashes.iter().enumerate() {
want.entry(*h).or_default().push(j);
}
for h in (0..5u8).map(|b| [b; 32]) {
assert_eq!(groups.get(&h), want.get(&h).map(|v| v.as_slice()), "{hashes:?}");
}
}
}
#[tokio::test]
async fn random_control_planes_fold_alike_in_any_order_and_for_a_reader_holding_its_heads() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Random planes", vec!["wss://r".into()], None).await.unwrap();
let group = control::ControlPlane::of(&community).write_group().unwrap();
let cid = community.id();
let actors: Vec<Keys> = (0..4).map(|_| Keys::generate()).collect();
let mut signers = vec![owner.clone()];
signers.extend(actors.iter().cloned());
let roles: Vec<String> = (1..=3u8).map(|i| crate::simd::hex::bytes_to_hex_32(&[i; 32])).collect();
let mut seed = 0x9e37_79b9_7f4a_7c15u64;
let mut next = move |n: u64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed % n
};
let perms: [u64; 5] = [Permissions::MANAGE_ROLES | Permissions::BAN, Permissions::MANAGE_ROLES, Permissions::BAN, Permissions::KICK, 0];
let mut failures: Vec<String> = Vec::new();
for case in 0..400 {
// Entities: three Roles, a Grant per actor, the Banlist.
let mut entities: Vec<([u8; 32], &str)> = roles.iter().map(|r| (crate::simd::hex::hex_to_bytes_32(r), vsk::ROLE)).collect();
entities.extend(actors.iter().map(|a| (crate::community::v2::derive::grant_locator(cid, &a.public_key().to_bytes()), vsk::GRANT)));
entities.push((crate::community::v2::derive::banlist_locator(cid), vsk::BANLIST));
let mut eds: Vec<ParsedEdition> = Vec::new();
// Grants written so far by entity: what a citation can name.
let mut written: std::collections::HashMap<[u8; 32], Vec<(u64, [u8; 32])>> = Default::default();
// Interleave entities by version, so a citation can name what came before it.
let lens: Vec<u64> = entities.iter().map(|_| 1 + next(3)).collect();
let mut at_version: std::collections::HashMap<[u8; 32], Vec<[u8; 32]>> = Default::default();
// Every entity's editions one version down: what a link aimed at another entity names.
let mut any_below: Vec<[u8; 32]> = Vec::new();
for v in 1..=3u64 {
let mut any_here: Vec<[u8; 32]> = Vec::new();
for (k, (eid, kind)) in entities.iter().enumerate() {
if v > lens[k] {
continue;
}
let below = at_version.get(eid).cloned().unwrap_or_default();
let mut here = Vec::new();
for _ in 0..(1 + u64::from(next(4) == 0)) {
let signer = if next(2) == 0 { &signers[0] } else { &signers[1 + next(4) as usize] };
let prev = match (v, next(7)) {
(1, _) => None,
(_, 0) => Some([0xee; 32]),
(_, 1) if !any_below.is_empty() => Some(any_below[next(any_below.len() as u64) as usize]),
_ if below.is_empty() => None,
_ => Some(below[next(below.len() as u64) as usize]),
};
let content = match *kind {
vsk::ROLE => {
let rid = crate::simd::hex::bytes_to_hex_32(eid);
let mut r = admin_role(&rid, perms[next(perms.len() as u64) as usize]);
r.position = 1 + next(4) as u32;
crate::community::v2::roles::role_content_json(&r).unwrap()
}
vsk::GRANT => {
let member = actors.iter().find(|a| crate::community::v2::derive::grant_locator(cid, &a.public_key().to_bytes()) == *eid).unwrap();
let role_ids = roles.iter().filter(|_| next(2) == 0).cloned().collect();
crate::community::v2::roles::grant_content_json(&MemberGrant { member: member.public_key().to_hex(), role_ids }).unwrap()
}
_ => {
let banned: Vec<String> = actors.iter().filter(|_| next(3) == 0).map(|a| a.public_key().to_hex()).collect();
crate::community::v2::roles::banlist_content_json(&banned).unwrap()
}
};
let own = crate::community::v2::derive::grant_locator(cid, &signer.public_key().to_bytes());
let cite = match (signer.public_key() == owner.public_key(), next(3), written.get(&own)) {
(true, ..) | (_, 0, _) => None,
(_, 1, Some(held)) if !held.is_empty() => {
let (version, edition_hash) = held[next(held.len() as u64) as usize];
Some(crate::community::edition::AuthorityCitation { entity_id: own, version, edition_hash })
}
_ => Some(crate::community::edition::AuthorityCitation { entity_id: own, version: 1, edition_hash: [0xcc; 32] }),
};
let ts = 1_000 + next(3);
let rumor = control::build_edition_rumor(signer.public_key(), kind, eid, v, prev.as_ref(), &content, ts, cite.as_ref());
let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(ts)).unwrap();
let (ed, _) = control::open_control_edition(&wrap, &group).unwrap();
here.push(ed.self_hash);
if *kind == vsk::GRANT {
written.entry(*eid).or_default().push((v, ed.self_hash));
}
eds.push(ed);
// A copy of it under another signer: the same hash, on that signer's authority.
if next(3) == 0 {
let copier = &signers[next(signers.len() as u64) as usize];
let rumor = control::build_edition_rumor(copier.public_key(), kind, eid, v, prev.as_ref(), &content, ts + 1, None);
let (wrap, _) = control::seal_control_edition(&rumor, &group, copier, Timestamp::from_secs(ts + 1)).unwrap();
eds.push(control::open_control_edition(&wrap, &group).unwrap().0);
}
}
any_here.extend(&here);
at_version.insert(*eid, here);
}
any_below = any_here;
}
let base = fold_authority(&community, &eds, &Floors::default());
let want = authority_and_heads(&base);
for order in 0..4 {
let mut shuffled = eds.clone();
for i in (1..shuffled.len()).rev() {
shuffled.swap(i, next(i as u64 + 1) as usize);
}
let got = authority_and_heads(&fold_authority(&community, &shuffled, &Floors::default()));
if got != want {
failures.push(format!("case {case} order {order}:\n want {want}\n got {got}"));
}
}
// A reader holding exactly the heads it decided folds them again.
let floors: Floors = base.heads.iter().map(|h| (h.entity_hex.clone(), (h.version, h.self_hash, Some(h.inner_id), Some(h.author), None))).collect();
let tracked = authority_fingerprint(&fold_authority(&community, &eds, &floors));
if tracked != authority_fingerprint(&base) {
failures.push(format!("case {case} tracking:\n fresh {}\n held {tracked}", authority_fingerprint(&base)));
}
// A reader holding any served edition of each entity, refused ones among them.
let mut held: Floors = Floors::default();
for (eid, _) in &entities {
let of: Vec<&ParsedEdition> = eds.iter().filter(|e| e.entity_id == *eid).collect();
if !of.is_empty() && next(4) != 0 {
let e = of[next(of.len() as u64) as usize];
held.insert(crate::simd::hex::bytes_to_hex_32(eid), (e.version, e.self_hash, Some(e.inner_id), Some(e.author.to_bytes()), None));
}
}
// Every fold above again with fresh scratch per entity, as replay ran before reusing it.
for (label, f) in [("floorless", Floors::default()), ("tracking", floors.clone()), ("holding", held)] {
let reused = authority_whole(&fold_authority(&community, &eds, &f));
FRESH_SCRATCH.with(|x| x.set(true));
let fresh = authority_whole(&fold_authority(&community, &eds, &f));
FRESH_SCRATCH.with(|x| x.set(false));
if reused != fresh {
failures.push(format!("case {case} scratch {label}:\n fresh {fresh}\n reused {reused}"));
}
}
}
assert!(failures.is_empty(), "{} of 400 cases folded differently:\n{}", failures.len(), failures.join("\n"));
}
#[tokio::test]
async fn the_v2_authority_fold_is_order_independent() {
// THE core consensus property: two honest clients that receive the SAME
// control editions in DIFFERENT arrival orders must resolve the IDENTICAL
// authorized roster + banlist (author-aware select_authorized + banlist
// fold + cap, all deterministic). A divergence here would fork the
// community's moderation state between honest members.
let (bed, owner, _a) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Determinism", bed.relays.clone(), None).await.unwrap();
// A rich control plane: two admins, an extra role, two grants (one of them a
// grant to a member the owner then bans), a banlist, a rename, a channel.
let admin1 = Keys::generate().public_key();
let admin2 = Keys::generate().public_key();
grant_admin(&bed.relay, &community, &admin1).await.unwrap();
grant_admin(&bed.relay, &community, &admin2).await.unwrap();
let mod_rid = "5c".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&mod_rid, Permissions::KICK | Permissions::MANAGE_MESSAGES), 1).await;
let member = Keys::generate().public_key();
publish_grant(&bed.relay, &community, &owner.keys, &member, vec![mod_rid.clone()], 1).await;
let banned_member = Keys::generate().public_key();
publish_grant(&bed.relay, &community, &owner.keys, &banned_member, vec![mod_rid], 1).await;
set_banlist(&bed.relay, &community, &[banned_member.to_hex()]).await.unwrap();
let meta = control::CommunityMetadata { name: "Renamed".into(), relays: community.relays.clone(), ..Default::default() };
edit_community_metadata(&bed.relay, &community, &meta).await.unwrap();
create_public_channel(&bed.relay, &community, "extra").await.unwrap();
let editions = fetch_control(&bed.relay, &community).await;
let floors = load_floors(&community);
assert!(editions.len() >= 6, "a rich plane was built ({} editions)", editions.len());
let baseline = authority_fingerprint(&fold_authority(&community, &editions, &floors));
// Fold under many arrival permutations: reversed, and several deterministic
// rotations/interleavings. Every one must match the baseline.
let mut orders: Vec<Vec<ParsedEdition>> = Vec::new();
let mut rev = editions.clone();
rev.reverse();
orders.push(rev);
for shift in [1usize, 3, 5, 7] {
let n = editions.len();
orders.push((0..n).map(|i| editions[(i + shift) % n].clone()).collect());
}
// A deterministic "shuffle": interleave from both ends.
let mut zip = Vec::with_capacity(editions.len());
let (mut lo, mut hi) = (0isize, editions.len() as isize - 1);
while lo <= hi {
zip.push(editions[lo as usize].clone());
if lo != hi {
zip.push(editions[hi as usize].clone());
}
lo += 1;
hi -= 1;
}
orders.push(zip);
for (i, order) in orders.iter().enumerate() {
let got = authority_fingerprint(&fold_authority(&community, order, &floors));
assert_eq!(got, baseline, "arrival order #{i} must resolve the identical authority (consensus)");
}
// Sanity: the fingerprint reflects real state (the banned member is out, the
// honest admins are in).
assert!(baseline.contains(&admin1.to_hex()) || baseline.contains(&member.to_hex()), "grants are present in the fingerprint");
assert!(baseline.contains(&banned_member.to_hex()), "the banlist entry is in the fingerprint");
}
/// A transport that ACKs publishes but ERRORS every fetch — a relay outage / withhold.
struct FetchErrors(MemoryRelay);
#[async_trait::async_trait]
impl crate::community::transport::Transport for FetchErrors {
async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> { Ok(crate::community::transport::PlaneFetch::whole(self.fetch(query, relays).await?)) }
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.0.publish(e, r).await
}
async fn fetch(&self, _q: &Query, _r: &[String]) -> Result<Vec<Event>, String> {
Err("relay down".to_string())
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.0.publish_durable(e, r).await
}
}
#[tokio::test]
async fn fetch_authority_retains_the_persisted_banlist_on_a_transport_error() {
let (bed, owner, victim) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "BanRetain", bed.relays.clone(), None).await.unwrap();
let victim_hex = victim.keys.public_key().to_hex();
// A ban is persisted locally (as a completed set_banlist + follow leaves it).
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::set_community_banlist(&cid_hex, &[victim_hex.clone()], 1).unwrap();
// A relay that ERRORS on fetch must degrade FAIL-SAFE: retain the ban, never
// return an empty banlist (which would silently un-ban on withheld data).
let down = FetchErrors(MemoryRelay::new());
let view = fetch_authority(&down, &community).await;
assert!(view.banned.contains(&victim_hex), "a transport error retains the persisted banlist");
}
#[tokio::test]
async fn the_fold_pages_past_a_full_window_to_find_the_roster_it_tracks() {
// Soapbox's actual shape. The grants that define the admin list are OLDER than
// one page of a busy control plane. An entity absent from the window dangles no
// link, so it raises no gap, so the pager called the very first page "coherent"
// and stopped — every fold offered zero grants, forever, and only the
// completeness guard retaining the cache kept the admin list alive. That made
// the cache the last surviving copy of the roster rather than a cache.
//
// Coherent is not complete. The fold must page until what it tracks is found.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "DeepFold", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let rid = "e7".repeat(32);
let admin = Keys::generate();
// The roster, at t=1_000 — the OLDEST thing on the plane.
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid.clone()], 1).await;
follow_control(&bed.relay, &community).await.unwrap();
assert!(
crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&admin.public_key().to_hex()),
"baseline: the admin folds while its editions are still in reach",
);
// Bury it under MORE than one page of strictly NEWER control traffic.
for i in 0..(FOLLOW_PAGE + 50) {
publish_channel_edition_at(
&bed.relay, &community, &owner.keys,
&ChannelId(crate::simd::hex::hex_to_bytes_32(&format!("{:064x}", i + 1))),
&format!("ch{i}"), 1, 2_000 + i as u64,
).await;
}
// Forget the grant's FLOOR. Re-establishing it is the observable proof that
// the fold actually reached the grant edition, rather than merely retaining a
// cached roster it could not re-derive.
let grant_eid = crate::simd::hex::bytes_to_hex_32(
&crate::community::v2::derive::grant_locator(community.id(), &admin.public_key().to_bytes()),
);
crate::db::community::delete_edition_head(&cid_hex, &grant_eid).unwrap();
assert!(
crate::db::community::get_edition_head(&cid_hex, &grant_eid).unwrap().is_none(),
"precondition: the floor is gone",
);
follow_control(&bed.relay, &community).await.unwrap();
assert!(
crate::db::community::get_edition_head(&cid_hex, &grant_eid).unwrap().is_some(),
"the fold MUST page past the newest window and reach the grant that defines the \
admin list — stopping at the first coherent-looking page is how a community \
becomes unable to re-derive its own roster",
);
assert!(
crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&admin.public_key().to_hex()),
"and the admin survives",
);
}
#[tokio::test]
async fn a_grant_whose_roles_resolve_to_none_leaves_no_entry() {
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Unresolved", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let (kept, lost) = (Keys::generate(), Keys::generate());
let role = "aa".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&role, Permissions::BAN), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &kept.public_key(), vec!["cc".repeat(32), role.clone()], 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &lost.public_key(), vec!["dd".repeat(32)], 1).await;
follow_control(&bed.relay, &community).await.unwrap();
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
let of = |k: &Keys| roster.grants.iter().find(|g| g.member == k.public_key().to_hex()).map(|g| g.role_ids.clone());
assert_eq!(of(&kept), Some(vec![role]), "a grant keeps only the roles that resolve");
assert_eq!(of(&lost), None, "and one that resolves none stands for nothing");
}
#[tokio::test]
async fn a_grant_naming_a_role_its_own_holder_created_still_folds() {
// The deadlock that emptied two live communities' rosters.
//
// A community grows the ordinary way: the owner promotes an admin, the admin
// creates a role of their own, and the owner then grants that role onward. Now
// the grant references a role whose AUTHOR draws authority from a grant — and
// under all-or-nothing resolution neither can go first. The fixpoint lands
// empty, and every grant in the community dies with it, the owner's included.
//
// Resolving the roles a grant CAN resolve breaks the cycle without granting
// anything the author did not write: the retained roles are still rank-checked,
// and the rest fold in on a later iteration.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "GrantCycle", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let admin = Keys::generate();
let member = Keys::generate();
// 1. The owner's own role, and a grant of it to the admin.
let owner_role = "aa".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&owner_role, Permissions::ADMIN_ALL), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![owner_role.clone()], 1).await;
follow_control(&bed.relay, &community).await.unwrap();
assert!(
crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&admin.public_key().to_hex()),
"the admin is promoted",
);
// 2. The ADMIN creates a role of their own, beneath theirs.
let admin_made = "bb".repeat(32);
let mut made = admin_role(&admin_made, Permissions::BAN);
made.position = 5;
publish_role(&bed.relay, &community, &admin, &made, 1).await;
follow_control(&bed.relay, &community).await.unwrap();
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert!(
roster.role(&admin_made).is_some(),
"an admin-authored role folds while its author's grant is resolvable",
);
assert!(
roster.is_admin(&admin.public_key().to_hex()),
"and the admin keeps their own standing — a cycle here empties the roster",
);
// 3. The owner grants the ADMIN-MADE role to a member, alongside a role that
// is not resolvable at all. Under all-or-nothing the whole grant dies and
// takes the roster with it; resolved partially, the member gets what the
// owner actually granted.
publish_grant(
&bed.relay, &community, &owner.keys, &member.public_key(),
vec![admin_made.clone(), "cc".repeat(32)], 1,
).await;
follow_control(&bed.relay, &community).await.unwrap();
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
let mg = roster.grants.iter().find(|g| g.member == member.public_key().to_hex());
assert!(
mg.is_some_and(|g| g.role_ids.contains(&admin_made)),
"the resolvable half of the grant is honored",
);
assert!(
mg.is_some_and(|g| !g.role_ids.iter().any(|r| r == &"cc".repeat(32))),
"and the unresolvable half is NOT — partial resolution only ever grants less",
);
assert!(
roster.is_admin(&admin.public_key().to_hex()),
"the rest of the roster survives it",
);
}
#[tokio::test]
async fn a_cold_device_pages_past_the_first_window_to_find_an_older_grant() {
// The early break stops paging once every entity we track has a head. On a
// COLD device we track NOTHING, so that condition is vacuously true and the
// walk stops at page one — the roster is then whatever the newest window
// happened to hold, and an admin granted before it silently is not one.
// That is the roster collapse, arrived at by an optimisation.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "ColdPage", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
// The grant that matters goes down FIRST, so a full newest-first page buries it.
let admin = Keys::generate();
let rid = "e5".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid.clone()], 1).await;
// Then bury it under a full page of newer editions.
for v in 2..(FOLLOW_PAGE as u64 + 2) {
publish_filler_edition(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), v, 1_000 + v).await;
}
follow_control(&bed.relay, &community).await.unwrap();
assert!(
crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&admin.public_key().to_hex()),
"a cold device must page PAST the first window — stopping there caches a \
partial authority as its own baseline and drops every older grant",
);
}
#[tokio::test]
async fn a_truncated_cold_fold_banks_nothing_at_all() {
// A second holding more than a page is a wall for a relay read by pages: what else it
// holds there cannot be asked for, so the fold is TRUNCATED. Refusing to show that
// partial roster is not enough — it must not be BANKED either. A stored baseline
// carries a provenance stamp that the next, complete fold has to beat, and names
// entities that a complete fold may not head, so banking a partial window is how a
// client talks itself into a permanent wedge.
let (bed, owner, _m) = TestBed::new();
bed.relay.without_reconcile(&bed.relays);
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Wall", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let admin = Keys::generate();
let rid = "e5".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid.clone()], 1).await;
// A full page of editions sharing ONE second, burying the grant behind the wall.
for v in 2..(FOLLOW_PAGE as u64 + 2) {
publish_filler_edition(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), v, 1_000).await;
}
follow_control(&bed.relay, &community).await.unwrap();
assert_eq!(
crate::db::community::get_community_roles_at(&cid_hex).unwrap(),
0,
"a truncated fold must bank NO baseline — a stored partial roster outranks \
the complete fold that follows it and can never be replaced",
);
}
#[tokio::test]
async fn an_older_window_never_overwrites_a_newer_cached_roster() {
// The roster cache carries the provenance timestamp of the fold that wrote it.
// A later fold reading an OLDER window (a lagging relay, a short page) must not
// replace it — that is a downgrade with no gap and no truncation to catch it.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Monotone", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let admin = Keys::generate();
let rid = "e5".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid], 1).await;
follow_control(&bed.relay, &community).await.unwrap();
assert!(crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&admin.public_key().to_hex()));
// Stamp the cached roster now: every edition here is older.
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
let now = (now_ms() / 1000) as i64;
crate::db::community::set_community_roles(&cid_hex, &roster, now).unwrap();
follow_control(&bed.relay, &community).await.unwrap();
assert!(
crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&admin.public_key().to_hex()),
"an older window must not overwrite a newer cached roster",
);
assert_eq!(
crate::db::community::get_community_roles_at(&cid_hex).unwrap(),
now,
"and the newer provenance stamp survives — otherwise the next fold downgrades freely",
);
}
/// A fast majority that does not hold the older editions. Quorum returns as soon
/// as it answers, so those editions read as absent; only a Full read waits for the
/// relay that has them. This is the shape a slow Ditto/Soapbox relay produces.
struct SlowMajority<'a>(&'a MemoryRelay, u64);
#[async_trait::async_trait]
impl Transport for SlowMajority<'_> {
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.0.publish(e, r).await
}
async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
let out = self.0.fetch(query, relays).await?;
if query.evidence == crate::community::transport::Evidence::Full {
return Ok(out);
}
Ok(out.into_iter().filter(|e| e.created_at.as_secs() > self.1).collect())
}
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
self.0.fetch_plane(plane, query, relays).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.0.publish_durable(e, r).await
}
}
#[tokio::test]
async fn a_live_link_a_quorum_cannot_see_still_reads_public() {
// The ban path asks this to decide whether to refound. CORD-05 §5 forbids
// refounding a Public community — the link refresh re-posts the bundle behind
// the same URL, so the rotation severs nothing and strands foreign-link joiners
// on a buried epoch. A Quorum read that misses another creator's Registry makes
// a Public community read Private, which takes exactly that forbidden branch.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "QuorumBlind", vec!["wss://r".into()], None).await.unwrap();
mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
assert!(community_is_public(&relay, &community).await, "the link is live on the plane");
// u64::MAX: nothing is newer, so the Quorum read is blinded entirely. The
// link is minted with the real clock, so a small cutoff filters nothing.
let slow = SlowMajority(&relay, u64::MAX);
assert!(
community_is_public(&slow, &community).await,
"a live link only a minority relay serves must still read Public — reading \
Private here refounds a Public community on ban, severing nothing",
);
}
#[tokio::test]
async fn a_quorum_that_cannot_see_a_stored_entity_escalates_to_full() {
// The roster fold draws an absence verdict, and an absence verdict from a
// MAJORITY is not one: the same fast subset answers every boot, so the retain
// never lifts and the cache freezes holding the only surviving copy of the
// roster. Read again at Full before concluding anything is gone.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Escalate", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let admin = Keys::generate();
let rid = "e5".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid.clone()], 1).await;
// Bank a complete roster the honest way, so the entities are STORED and floored.
follow_control(&bed.relay, &community).await.unwrap();
assert!(crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&admin.public_key().to_hex()));
// A SECOND admin is granted. Its edition lands on the plane like every other,
// below the cutoff — so a Quorum read cannot see it, and a client that concludes
// from Quorum alone retains the old roster and never learns about them.
let admin2 = Keys::generate();
publish_grant(&bed.relay, &community, &owner.keys, &admin2.public_key(), vec![rid], 1).await;
let slow = SlowMajority(&bed.relay, 5_000);
follow_control(&slow, &community).await.unwrap();
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert!(
roster.is_admin(&admin.public_key().to_hex()),
"the first admin survives — the retain is doing its job",
);
assert!(
roster.is_admin(&admin2.public_key().to_hex()),
"and the roster still ADVANCES: a Quorum read that could not account for a \
stored entity must re-read at Full, or the cache freezes holding the only \
surviving copy of the roster and no promotion ever lands again",
);
}
#[tokio::test]
async fn one_gapped_entity_does_not_freeze_the_rest_of_the_roster() {
// `authority.gapped` is a global OR across every entity, but the spec makes a
// gap fail closed FOR THAT ENTITY — suspend it, refetch it — not for the whole
// community. Treating it as a veto froze live rosters that were otherwise
// folding perfectly, and permanently once the plane is exhausted and no further
// paging can resolve the hole.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "OneGap", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
// A healthy admin the plane fully describes.
let admin = Keys::generate();
let rid = "e5".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid], 1).await;
// And a second role the plane DOES serve, floored at a hash nothing chains to:
// its editions are present but unanchored, which is the withholding shape that
// fails closed and raises the gap. A floor on an entity absent from the window
// would not — the fold only visits entities it sees.
let rid2 = "c7".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid2, Permissions::BAN), 5).await;
crate::db::community::set_edition_head_at_epoch(&cid_hex, &rid2, 3, &[9u8; 32], &[9u8; 32], &owner.keys.public_key().to_bytes(), community.root_epoch.0).unwrap();
follow_control(&bed.relay, &community).await.unwrap();
assert!(
crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&admin.public_key().to_hex()),
"a hole in ONE entity must not withhold every other entity's authority — that is \
how a community that folds correctly still shows an empty roster",
);
}
#[tokio::test]
async fn follow_control_retains_the_roster_when_a_floored_role_ages_out() {
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Complete", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
let rid = crate::simd::hex::bytes_to_hex_32(&[0x7c; 32]);
// Full state on relay1: an Admin role + two grants → both fold + persist as admins.
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &a, vec![rid.clone()], 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &b, vec![rid.clone()], 1).await;
follow_control(&bed.relay, &community).await.unwrap().updated;
assert!(crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&a.to_hex()), "seeded");
// relay2 serves A's grant but NOT the role (aged out of the window): the fold
// drops both admins yet raises no gap. The completeness gate must RETAIN the
// stored roster rather than persist the lossy one.
let relay2 = MemoryRelay::new();
publish_grant(&relay2, &community, &owner.keys, &a, vec![rid.clone()], 1).await;
follow_control(&relay2, &community).await.unwrap().updated;
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert!(roster.is_admin(&a.to_hex()) && roster.is_admin(&b.to_hex()), "a floored-but-unfetched role retains the stored roster");
}
#[tokio::test]
async fn an_uncited_metadata_or_banlist_edition_is_dropped() {
// CORD-04 §5 covers EVERY control entity, not just the delegation chain.
// Vector already gated roles and grants in-fold; metadata, channels and
// the banlist resolved on permission alone, so a client one sweep behind
// honored an edit from an admin whose demotion it had not read yet.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Base", vec!["wss://r".into()], None).await.unwrap();
let admin = Keys::generate();
let rid = "a7".repeat(32);
publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::MANAGE_METADATA | Permissions::BAN), 1).await;
publish_grant(&relay, &community, &owner, &admin.public_key(), vec![rid], 1).await;
// The admin acts WITHOUT citing (what every pre-citation client emitted).
let group = control::ControlPlane::of(&community).write_group().unwrap();
let meta = control::CommunityMetadata { name: "Uncited Rename".into(), ..Default::default() };
let rumor = control::build_edition_rumor(
admin.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 2,
head_hash_on_relay(&relay, &community, &community.id().0).await.as_ref(),
&serde_json::to_string(&meta).unwrap(), 1_000, None,
);
let (wrap, _) = control::seal_control_edition(&rumor, &group, &admin, Timestamp::from_secs(1_000)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
let ban_eid = crate::community::v2::derive::banlist_locator(community.id());
let victim = Keys::generate().public_key().to_hex();
let ban_rumor = control::build_edition_rumor(
admin.public_key(), vsk::BANLIST, &ban_eid, 1, None,
&serde_json::to_string(&vec![victim.clone()]).unwrap(), 1_000, None,
);
let (ban_wrap, _) = control::seal_control_edition(&ban_rumor, &group, &admin, Timestamp::from_secs(1_000)).unwrap();
relay.publish(&ban_wrap, &community.relays).await.unwrap();
let updated = follow_control(&relay, &community).await.unwrap().updated;
assert!(
updated.as_ref().is_none_or(|c| c.name != "Uncited Rename"),
"an uncited metadata edit must not be honored",
);
let authority = fetch_authority(&relay, &community).await;
assert!(!authority.banned.contains(&victim), "an uncited banlist edition must not be honored");
// The positive case (this same admin, citing, lands) is
// `an_authorized_admin_edits_metadata_but_a_demoted_one_cannot` — its
// helper cites, so it proves the gate is the CITATION and not the
// permission. Re-proving it here would need a fresh chain anyway: a
// cited edition chaining onto the rejected one above is gapped, not
// refused.
}
#[tokio::test]
async fn an_authorized_admin_edits_metadata_but_a_demoted_one_cannot() {
// CORD-04 §5: an admin holding MANAGE_METADATA renames the community; once the
// owner revokes the grant, the (now unauthorized) admin's further edit drops
// and the name holds at the last authorized state.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Base", vec!["wss://r".into()], None).await.unwrap();
let admin = Keys::generate();
let rid = "a1".repeat(32);
publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::MANAGE_METADATA), 1).await;
publish_grant(&relay, &community, &owner, &admin.public_key(), vec![rid.clone()], 1).await;
publish_community_meta(&relay, &community, &admin, "Admin Rename", 2).await;
let updated = follow_control(&relay, &community).await.unwrap().updated.expect("admin edit authorized");
assert_eq!(updated.name, "Admin Rename", "an admin with MANAGE_METADATA renames");
publish_grant(&relay, &community, &owner, &admin.public_key(), vec![], 2).await; // revoke
publish_community_meta(&relay, &community, &admin, "Demoted Rename", 3).await;
let _ = follow_control(&relay, &community).await.unwrap().updated;
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(held.name, "Admin Rename", "a demoted admin's edit is dropped; the name holds");
}
#[tokio::test]
async fn a_roleless_member_cannot_edit_metadata() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Guarded", vec!["wss://r".into()], None).await.unwrap();
let stranger = Keys::generate();
publish_community_meta(&relay, &community, &stranger, "Hijacked", 2).await;
assert!(
follow_control(&relay, &community).await.unwrap().updated.is_none(),
"a roleless member's metadata edit never folds"
);
}
#[tokio::test]
async fn a_self_signed_grant_is_not_authority() {
// The self-promotion defense: a member self-signs both a role and a grant of
// it to themselves. authorize_delegation drops both (their signer never traces
// to the owner), so their metadata edit stays unauthorized.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "NoSelfPromo", vec!["wss://r".into()], None).await.unwrap();
let rogue = Keys::generate();
let rid = "b2".repeat(32);
publish_role(&relay, &community, &rogue, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
publish_grant(&relay, &community, &rogue, &rogue.public_key(), vec![rid.clone()], 1).await;
publish_community_meta(&relay, &community, &rogue, "Seized", 2).await;
assert!(
follow_control(&relay, &community).await.unwrap().updated.is_none(),
"a self-signed grant confers no authority"
);
}
#[tokio::test]
async fn the_banlist_is_enforced_only_from_a_ban_holder() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Bans", vec!["wss://r".into()], None).await.unwrap();
let target = "cc".repeat(32);
// A non-BAN-holder's banlist edition is folded but NOT enforced.
let rogue = Keys::generate();
publish_banlist(&relay, &community, &rogue, &[target.clone()], 1).await;
let floors = load_floors(&community);
let editions = fetch_control(&relay, &community).await;
let authority = fold_authority(&community, &editions, &floors);
assert!(authority.banned.is_empty(), "a non-owner (no BAN) banlist is not enforced");
// The owner (supreme, holds BAN) bans the target: now enforced.
publish_banlist(&relay, &community, &owner, &[target.clone()], 2).await;
let editions = fetch_control(&relay, &community).await;
let authority = fold_authority(&community, &editions, &floors);
assert!(authority.banned.contains(&target), "the owner's banlist is enforced");
}
#[tokio::test]
async fn a_malformed_banlist_edition_unbans_nobody() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "BadList", vec!["wss://r".into()], None).await.unwrap();
let target = "cc".repeat(32);
publish_banlist(&relay, &community, &owner, &[target.clone()], 1).await;
let group = control::ControlPlane::of(&community).write_group().unwrap();
let eid = crate::community::v2::derive::banlist_locator(community.id());
let prev = head_hash_on_relay(&relay, &community, &eid).await;
let rumor = control::build_edition_rumor(owner.public_key(), vsk::BANLIST, &eid, 2, prev.as_ref(), r#"{"not":"a list"}"#, 1_000, None);
let (wrap, _) = control::seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(1_000)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
let authority = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
assert!(authority.banned.contains(&target), "an edition that isn't a list is no Banlist edition");
}
#[tokio::test]
async fn every_invite_list_copy_merges_and_an_unreadable_one_is_never_written_over() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Lists", vec!["wss://r".into()], None).await.unwrap();
let entry = |t: &str| invite::InviteEntry { token: t.into(), signer_sk: "11".repeat(32), community_id: "22".repeat(32), url: format!("https://v/{t}"), label: None, created_at: 1, expires_at: None, epoch: Some(0), extra: Default::default() };
let signer = crate::signer::active_signer().unwrap();
for (t, at) in [("aa", 1_000u64), ("bb", 2_000)] {
let list = invite::InviteList { entries: vec![entry(t)], ..Default::default() };
let ev = invite::build_invite_list_event_at(&signer, owner.public_key(), &list, at).await.unwrap();
relay.publish(&ev, &[format!("wss://copy{at}")]).await.unwrap();
}
let relays = vec!["wss://copy1000".to_string(), "wss://copy2000".to_string()];
let (merged, newest) = read_invite_list(&relay, &relays).await.unwrap().unwrap();
let mut tokens: Vec<_> = merged.entries.iter().map(|e| e.token.as_str()).collect();
tokens.sort();
assert_eq!((tokens, newest), (vec!["aa", "bb"], 2_000), "every copy counts, not only the newest");
use nostr_sdk::prelude::FinalizeEvent;
let junk = nostr_sdk::prelude::EventBuilder::new(nostr_sdk::prelude::Kind::Custom(crate::community::v2::kind::INVITE_LIST), "not a ciphertext").finalize(&owner).unwrap();
relay.publish(&junk, &["wss://copy1000".to_string()]).await.unwrap();
assert!(read_invite_list(&relay, &relays).await.is_err(), "a copy that won't open blocks the write");
// Someone else's list, served by a relay, is no copy of mine.
let other = Keys::generate();
let foreign = nostr_sdk::prelude::EventBuilder::new(nostr_sdk::prelude::Kind::Custom(crate::community::v2::kind::INVITE_LIST), "whatever").finalize(&other).unwrap();
relay.publish(&foreign, &["wss://copy3000".to_string()]).await.unwrap();
let only_foreign = vec!["wss://copy3000".to_string()];
assert!(read_invite_list(&relay, &only_foreign).await.unwrap().is_none(), "another account's event is ignored, not a wedge");
let _ = community;
}
#[tokio::test]
async fn a_banned_admin_loses_all_authority() {
// CORD-04 §4: a banned npub vanishes — even holding an un-stripped grant, a
// banned admin's authority is dropped and their edits refused.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "BanAuth", vec!["wss://r".into()], None).await.unwrap();
let admin = Keys::generate();
let rid = "e5".repeat(32);
publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::MANAGE_METADATA), 1).await;
publish_grant(&relay, &community, &owner, &admin.public_key(), vec![rid.clone()], 1).await;
publish_banlist(&relay, &community, &owner, &[admin.public_key().to_hex()], 1).await; // ban, grant left intact
publish_community_meta(&relay, &community, &admin, "Banned Rename", 2).await;
assert!(
follow_control(&relay, &community).await.unwrap().updated.is_none(),
"a banned admin's edit is dropped even with an unstripped grant"
);
let authority = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
assert!(authority.banned.contains(&admin.public_key().to_hex()));
assert!(
!authority.roles.is_authorized(&admin.public_key().to_hex(), Some(&owner.public_key().to_hex()), Permissions::MANAGE_METADATA),
"a banned admin holds no bit"
);
}
#[tokio::test]
async fn a_ban_holder_cannot_ban_a_superior_or_the_owner() {
// CORD-04 §3/§5: BAN needs the bit AND a strict outrank of the target. A mod
// (pos 2, holds BAN) can ban a lower member but NOT a superior admin (pos 1)
// and NOT the owner (supreme, unbannable).
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Ranks", vec!["wss://r".into()], None).await.unwrap();
let admin = Keys::generate();
let moder = Keys::generate();
let stranger = Keys::generate();
let (admin_rid, mod_rid) = ("a1".repeat(32), "b2".repeat(32));
publish_role(&relay, &community, &owner, &Role { role_id: admin_rid.clone(), name: "Admin".into(), position: 1, permissions: Permissions(Permissions::ADMIN_ALL), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() }, 1).await;
publish_role(&relay, &community, &owner, &Role { role_id: mod_rid.clone(), name: "Mod".into(), position: 2, permissions: Permissions(Permissions::BAN), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() }, 1).await;
publish_grant(&relay, &community, &owner, &admin.public_key(), vec![admin_rid], 1).await;
publish_grant(&relay, &community, &owner, &moder.public_key(), vec![mod_rid], 1).await;
publish_banlist(&relay, &community, &moder, &[admin.public_key().to_hex(), owner.public_key().to_hex(), stranger.public_key().to_hex()], 1).await;
let authority = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
assert!(!authority.banned.contains(&admin.public_key().to_hex()), "a mod cannot ban a superior admin");
assert!(!authority.banned.contains(&owner.public_key().to_hex()), "nobody can ban the owner");
assert!(authority.banned.contains(&stranger.public_key().to_hex()), "the mod CAN ban a lower-ranked member");
}
#[tokio::test]
async fn an_unauthorized_higher_banlist_cannot_unban() {
// CORD-04 §4 anti-roster fail-CLOSED: a rogue's higher-version empty banlist
// must not erase the owner's ban (author-aware head selection + persisted
// banlist retention).
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "NoUnban", vec!["wss://r".into()], None).await.unwrap();
let target = "cc".repeat(32);
publish_banlist(&relay, &community, &owner, &[target.clone()], 1).await;
follow_control(&relay, &community).await.unwrap().updated; // persists the ban
let rogue = Keys::generate();
publish_banlist(&relay, &community, &rogue, &[], 2).await; // unauthorized higher, empty
let authority = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
assert!(authority.banned.contains(&target), "an unauthorized higher banlist cannot un-ban");
}
#[tokio::test]
async fn the_community_list_syncs_a_membership_to_a_fresh_device() {
// CORD-02 §8: create publishes the 13302; a fresh device (community dropped
// locally, the 13302 + genesis still on the relay) rehydrates it on sync.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let relays = vec!["wss://r".to_string()];
let community = create_community(&relay, "Synced", relays.clone(), None).await.unwrap();
crate::db::community::delete_community(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_none());
let rehydrated = sync_community_list(&relay, &relays).await.unwrap().joined;
assert_eq!(rehydrated.len(), 1, "the left-behind membership rehydrates");
assert_eq!(rehydrated[0].id().0, community.id().0);
assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_some(), "and is now held locally");
}
#[tokio::test]
async fn a_retried_leave_tombstone_cannot_bury_a_rejoin_made_meanwhile() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let relays = vec!["wss://r".to_string()];
let community = create_community(&relay, "Left", relays.clone(), None).await.unwrap();
let cid = crate::simd::hex::bytes_to_hex_32(&community.id().0);
// The leave stamps its own removal time, and its publish fails.
let left_at = now_ms() - 1000;
tombstone_community_list(&relay, community.id(), &relays, left_at, true).await.unwrap();
// The user rejoins before the retry gets through.
republish_community_list(&relay, Some(community.id())).await.unwrap();
assert!(fetch_fragments(&relay, &relays).await.unwrap().unwrap().list.is_live(&cid));
// The retry lands late, carrying the ORIGINAL stamp — which the rejoin outranks.
tombstone_community_list(&relay, community.id(), &relays, left_at, true).await.unwrap();
let set = fetch_fragments(&relay, &relays).await.unwrap().unwrap();
assert!(set.list.is_live(&cid), "a retry re-stamping `now` would have buried the rejoin");
}
#[tokio::test]
async fn a_boot_with_no_fragments_seeds_the_list_from_local_state() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let relays = vec!["wss://r".to_string()];
let community = create_community(&relay, "Seeded", relays.clone(), None).await.unwrap();
// An account arriving from the retired single-event list: held locally, nothing
// at the fragment coordinate. Boot alone has to write it — no membership changes.
let bare = MemoryRelay::new();
sync_community_list(&bare, &relays).await.unwrap();
let set = fetch_fragments(&bare, &relays).await.unwrap().expect("boot seeded the List");
let live = set.list.live_entries();
assert_eq!(live.len(), 1);
assert_eq!(live[0].community_id, crate::simd::hex::bytes_to_hex_32(&community.id().0));
// Latched: a LATER empty read is a relay that lost the fragments, not a fresh
// account, and republishing local state there would bury a sibling's tombstones.
let empty = MemoryRelay::new();
sync_community_list(&empty, &relays).await.unwrap();
assert_eq!(empty.stored_count(), 0, "the seed runs once");
}
#[tokio::test]
async fn a_dissolved_invite_retires_on_accept_and_tombstones_the_list() {
// The invite to a dissolved community is the one join failure with no
// retry: the refusal is an owner-signed grave. The boundary must retire
// the parked row AND write the §8 tombstone siblings purge on.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Grave", bed.relays.clone(), None).await.unwrap();
let bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();
dissolve_community(&bed.relay, &community).await.unwrap();
bed.swap_to(&member);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::save_pending_invite(&cid_hex, &bundle, "inviter", i64::MAX).unwrap();
let err = accept_parked_invite(&bed.relay, &bundle, None).await.unwrap_err();
assert_eq!(err, ERR_DISSOLVED, "the grave refusal is the sentinel the boundary matches");
retire_dead_invite(&bed.relay, &cid_hex, &bed.relays).await;
assert!(crate::db::community::get_pending_invite(&cid_hex).unwrap().is_none(), "the dead invite leaves this device");
let set = fetch_fragments(&bed.relay, &bed.relays).await.unwrap().expect("the tombstone published");
assert!(set.list.tombstones.iter().any(|t| t.community_id == cid_hex), "and siblings get the §8 tombstone");
assert!(!set.list.is_live(&cid_hex));
}
#[tokio::test]
async fn an_owner_dissolve_tombstones_the_list_for_sibling_devices() {
// Dissolving IS leaving. The grave alone reaches every MEMBER, but only a §8
// tombstone reaches the owner's own sibling devices — without it they keep the
// membership LIVE in the List, fold the grave, and show a sealed husk the owner
// already deleted, on every device, until each is cleaned up by hand.
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Doomed", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let before = fetch_fragments(&bed.relay, &bed.relays).await.unwrap().expect("create published the List");
assert!(before.list.is_live(&cid_hex), "the membership is live before the dissolve");
dissolve_community(&bed.relay, &community).await.unwrap();
let set = fetch_fragments(&bed.relay, &bed.relays).await.unwrap().expect("the List outlives the dissolve");
assert!(
set.list.tombstones.iter().any(|t| t.community_id == cid_hex),
"the dissolve published the §8 tombstone alongside the grave"
);
assert!(!set.list.is_live(&cid_hex), "sibling devices tear the husk down on their next list sync");
}
#[tokio::test]
async fn a_sibling_devices_list_tombstone_purges_the_parked_invite() {
// Device A declined (or retired a dead invite): its §8 tombstone must
// clear device B's parked copy on the next list sync — and ONLY when the
// removal post-dates the invite, so a fresh re-invite survives an old leave.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let relays = vec!["wss://r".to_string()];
let cid = crate::community::CommunityId([0x5A; 32]);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
// An OLD tombstone (a past leave) must not kill an invite received after it.
tombstone_community_list(&relay, &cid, &relays, now_ms() - 600_000, true).await.unwrap();
crate::db::community::save_pending_invite(&cid_hex, "{}", "inviter", i64::MAX).unwrap();
sync_community_list(&relay, &relays).await.unwrap();
assert!(crate::db::community::get_pending_invite(&cid_hex).unwrap().is_some(), "a re-invite supersedes a past leave");
// A tombstone NEWER than the invite is a verdict on it: purged on sync.
tombstone_community_list(&relay, &cid, &relays, now_ms() + 10_000, true).await.unwrap();
sync_community_list(&relay, &relays).await.unwrap();
assert!(crate::db::community::get_pending_invite(&cid_hex).unwrap().is_none(), "the sibling's removal clears the parked copy");
}
#[tokio::test]
async fn a_removal_answers_every_invite_no_newer_than_it() {
let (_tmp, _guard, me) = init_test_db();
let relay = MemoryRelay::new();
let relays = vec!["wss://r".to_string()];
let sibling = "5b".repeat(32);
let ours = crate::community::CommunityId([0x5C; 32]);
let ours_hex = crate::simd::hex::bytes_to_hex_32(&ours.0);
publish_remote_tombstone(&relay, &me, &relays, &sibling, 5_000_000).await;
assert!(!tombstone_suppresses(&sibling, 1), "unknown until a sync reads it");
sync_community_list(&relay, &relays).await.unwrap();
assert!(tombstone_suppresses(&sibling, 5_000), "a same-time re-delivery");
assert!(tombstone_suppresses(&sibling, 4_999));
assert!(tombstone_suppresses(&sibling.to_ascii_uppercase(), 4_999));
assert!(!tombstone_suppresses(&sibling, 5_001), "a newer re-invite resurfaces");
assert!(!tombstone_suppresses(&ours_hex, 1));
// Our own removal counts before it lands, and after it has.
add_pending_tombstone(&ours, 7_000_000);
assert!(tombstone_suppresses(&ours_hex, 7_000));
let landed = super::super::list::Tombstone { community_id: ours_hex.clone(), removed_at: 7_000_000, extra: Default::default() };
settle_pending(&super::super::list::CommunityList { tombstones: vec![landed], ..Default::default() });
assert!(load_pending().tombstones.is_empty());
assert!(tombstone_suppresses(&ours_hex, 7_000));
mirror_tombstones([(sibling.as_str(), 1_000)]);
assert!(tombstone_suppresses(&sibling, 5_000), "an older removal never lowers the bar");
let kicked = "5f".repeat(32);
note_local_removal(&kicked, 8_000_000);
assert!(tombstone_suppresses(&kicked, 8_000), "a kick answers the invites before it");
let queued = "5e".repeat(32);
edit_pending(|p| p.tombstones.push(PendingTombstone { community_id: queued.clone(), removed_at: 9_000_000 }));
assert!(tombstone_suppresses(&queued, 9_000), "a leave queued before the mirror existed");
crate::db::settings::set_sql_setting(LIST_TOMBSTONES_KEY.to_string(), "not json".into()).unwrap();
assert!(!tombstone_suppresses(&sibling, 1));
let aside = crate::db::settings::get_sql_setting(format!("{LIST_TOMBSTONES_KEY}_unread")).unwrap();
assert_eq!(aside.as_deref(), Some("not json"), "an unreadable mirror is set aside, not overwritten");
}
#[tokio::test]
async fn a_left_community_cannot_reinvite_with_an_older_wrap() {
#[derive(Default)]
struct Invites(std::sync::Mutex<Vec<String>>);
impl crate::InboundEventHandler for Invites {
fn on_community_invite(&self, community_id: &str) {
self.0.lock().unwrap().push(community_id.to_string());
}
}
let (_tmp, _guard, _me) = init_test_db();
let cid = crate::community::CommunityId([0x5D; 32]);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
let now = now_ms() / 1000;
let invite = |sent_at: u64, wrap: u8| crate::event_handler::PreparedEvent::CommunityInviteV2 {
bundle_json: "{}".into(),
community_id: cid_hex.clone(),
inviter: Keys::generate().public_key().to_hex(),
is_mine: false,
wrapper_event_id_bytes: [wrap; 32],
wrapper_created_at: sent_at,
rumor_created_at: sent_at,
expires_at: 0,
};
add_pending_tombstone(&cid, now * 1000);
let parked = Invites::default();
crate::event_handler::commit_prepared_event(invite(now - 60, 1), true, &parked).await;
assert!(parked.0.lock().unwrap().is_empty(), "the leave already answered it");
assert!(crate::db::community::get_pending_invite(&cid_hex).unwrap().is_none());
crate::event_handler::commit_prepared_event(invite(now + 1, 2), true, &parked).await;
assert_eq!(*parked.0.lock().unwrap(), vec![cid_hex.clone()], "a re-invite after the leave parks");
}
#[tokio::test]
async fn an_unchanged_republish_rewrites_no_fragment() {
// Nothing changed since the last write: the rebuilt fragment serializes to
// the bytes already on the relay, so the write must not touch the wire —
// a bumped created_at on identical content is pure churn.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let relays = vec!["wss://r".to_string()];
create_community(&relay, "Stable", relays.clone(), None).await.unwrap();
let before = fetch_fragments(&relay, &relays).await.unwrap().unwrap().created_at;
republish_community_list(&relay, None).await.unwrap();
let after = fetch_fragments(&relay, &relays).await.unwrap().unwrap().created_at;
assert_eq!(before, after, "a byte-identical fragment must not republish");
}
#[tokio::test]
async fn a_frags_tie_at_equal_age_resolves_to_the_larger_count() {
// A torn repack's worst case: two fragments at the SAME created_at
// disagreeing on the total. The larger count must govern (CORD-02 §8) —
// the smaller would push index 2 out of range and its memberships dormant.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let relays = vec!["wss://r".to_string()];
let at = now_ms() / 1000;
let two = super::super::list_frag::FragList { frags: 2, entries: vec![], tombstones: vec![], extra: Default::default() };
let three = super::super::list_frag::FragList { frags: 3, entries: vec![], tombstones: vec![], extra: Default::default() };
// The larger count sits at the LOWER index: an age-only rule that keeps
// the last fragment seen would pick 2 here, not 3.
for (frag, index) in [(&three, 0usize), (&two, 1usize)] {
let e = super::super::list_frag::build_fragment_event_keys(&owner, frag, index, at).unwrap();
relay.publish(&e, &relays).await.unwrap();
}
let set = fetch_fragments(&relay, &relays).await.unwrap().unwrap();
assert_eq!(set.declared, 3, "an age tie resolves to the larger frags");
assert!(!set.is_complete(), "index 2 is unread, so the set refuses to write");
}
fn ext(pairs: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
pairs.as_object().expect("an object").clone()
}
#[tokio::test]
async fn fragment_level_unknowns_resolve_to_the_lowest_index_whatever_their_ages() {
// CORD-02 §8: fragment-level unknowns belong to the List, and where two
// fragments carry one key the LOWEST index wins. Age decides which copy of an
// index speaks, never which index outranks another.
let (_tmp, _guard, owner) = init_test_db();
let relays = vec!["wss://r".to_string()];
let at = now_ms() / 1000;
let frag = |v: &str| super::super::list_frag::FragList { frags: 2, entries: vec![], tombstones: vec![], extra: ext(serde_json::json!({ "x-ext": v })) };
// Both age orders: the higher index newer, then older.
for (age0, age1) in [(at, at + 5), (at + 5, at)] {
let relay = MemoryRelay::new();
for (index, value, age) in [(0usize, "zero", age0), (1usize, "one", age1)] {
let e = super::super::list_frag::build_fragment_event_keys(&owner, &frag(value), index, age).unwrap();
relay.publish(&e, &relays).await.unwrap();
}
let set = fetch_fragments(&relay, &relays).await.unwrap().unwrap();
assert_eq!(
set.list.extra.get("x-ext"),
Some(&serde_json::json!("zero")),
"index 0 wins at ages ({age0}, {age1})"
);
}
}
#[tokio::test]
async fn a_newer_copy_of_a_fragment_edits_its_unknown_field() {
// Within ONE index the newest copy is the fragment (relays resolve the
// coordinate the same way), so an unknown field edited by its own client
// sticks, whatever order the relay serves the copies in.
let (_tmp, _guard, owner) = init_test_db();
let at = now_ms() / 1000;
let frag = |v: &str| super::super::list_frag::FragList { frags: 1, entries: vec![], tombstones: vec![], extra: ext(serde_json::json!({ "x-ext": v })) };
// Two relays disagreeing on the copy — the shape every version-merge reads —
// with the stale copy on each side in turn.
let relays = vec!["wss://a".to_string(), "wss://b".to_string()];
for stale_on_first in [true, false] {
let relay = MemoryRelay::new();
let (stale_at, fresh_at) = if stale_on_first { (&relays[0], &relays[1]) } else { (&relays[1], &relays[0]) };
for (value, age, on) in [("old", at, stale_at), ("new", at + 5, fresh_at)] {
let e = super::super::list_frag::build_fragment_event_keys(&owner, &frag(value), 0, age).unwrap();
relay.publish(&e, std::slice::from_ref(on)).await.unwrap();
}
let set = fetch_fragments(&relay, &relays).await.unwrap().unwrap();
assert_eq!(set.list.extra.get("x-ext"), Some(&serde_json::json!("new")), "the newest copy speaks for index 0");
}
}
#[tokio::test]
async fn a_republish_keeps_a_peer_clients_unknown_fields_when_a_known_field_changed() {
// The List is the member's vault (CORD-02 §8): a republish rebuilds each
// snapshot from local state, and if that rebuild sheds what another client
// wrote — Armada's channel `priors` are retired keys — the material is gone on
// every device. The trap is the same-epoch tiebreak: once a KNOWN field also
// differs (a rename, a new key), the whole lower-sorting snapshot wins, and a
// bare local rebuild that sorts lower takes nothing of the peer's with it.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let relays = vec!["wss://r".to_string()];
let community = create_community(&relay, "Alpha", relays.clone(), None).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&relay, &held, "alpha-ch").await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let key = held.channel(&ch).and_then(|c| c.key).unwrap();
let b64 = |b: &[u8; 32]| crate::simd::base64::URL_SAFE_NO_PAD.encode_to_string(b);
// A peer client's write of fragment 0: this channel listed under its own
// label, and its own fields at every level. Its channel name sorts ABOVE
// ours, so our rebuild out-sorts its snapshot at the first key.
let set = fetch_fragments(&relay, &relays).await.unwrap().unwrap();
let mut frag = set.read_frags.get(&0).unwrap().clone();
frag.extra.insert("frag-ext".into(), serde_json::json!(true));
let entry = frag.entries.first_mut().unwrap();
entry.extra.insert("entry-ext".into(), serde_json::json!(1));
entry.current.extra.insert("zz-ext".into(), serde_json::json!({ "held": "root" }));
entry.current.channels = vec![super::super::list_frag::FragChannel {
id: b64(&ch.0),
key: Some(b64(&key)),
epoch: 1,
name: "zeta-ch".into(),
extra: ext(serde_json::json!({ "priors": [{ "epoch": 0, "key": "retired" }] })),
}];
// Everywhere the List lives: a stale copy left on any relay is a separate
// hazard.
let e = super::super::list_frag::build_fragment_event_keys(&owner, &frag, 0, set.created_at[&0] + 1).unwrap();
relay.publish(&e, &list_read_relays(&[]).await).await.unwrap();
republish_community_list(&relay, None).await.unwrap();
let after = fetch_fragments(&relay, &relays).await.unwrap().unwrap().list;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let entry = after.entries.iter().find(|e| e.community_id == cid_hex).unwrap();
assert_eq!(entry.current.extra.get("zz-ext"), Some(&serde_json::json!({ "held": "root" })), "snapshot unknowns survive");
let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.0);
let kept = entry.current.channels.iter().find(|c| c.id == ch_hex).unwrap();
assert_eq!(kept.name, "alpha-ch");
assert_eq!(kept.extra.get("priors"), Some(&serde_json::json!([{ "epoch": 0, "key": "retired" }])), "channel unknowns survive");
assert_eq!(entry.extra.get("entry-ext"), Some(&serde_json::json!(1)), "entry unknowns survive");
assert_eq!(after.extra.get("frag-ext"), Some(&serde_json::json!(true)), "fragment unknowns survive");
}
fn snap(epoch: u64, rev: u64, channels: &[(u8, u64, Option<u8>)]) -> super::super::list::JoinMaterial {
let hex = |b: u8| crate::simd::hex::bytes_to_hex_32(&[b; 32]);
super::super::list::JoinMaterial {
community_id: hex(0x01),
owner: hex(0x02),
owner_salt: hex(0x03),
community_root: hex(0x04),
root_epoch: epoch,
control_pk: Some(hex(0x05)),
control_root: None,
channels: channels
.iter()
.map(|(id, ep, key)| super::super::list::ChannelKeyRef { id: hex(*id), key: key.map(hex), epoch: *ep, name: format!("ch{id}"), extra: Default::default() })
.collect(),
relays: vec!["wss://r".into()],
name: "N".into(),
rev,
extra: Default::default(),
}
}
fn list_entry_of(list: &super::super::list::CommunityList, community: &CommunityV2) -> super::super::list::CommunityListEntry {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
list.entries.iter().find(|e| e.community_id == cid_hex).cloned().expect("the membership is listed")
}
#[test]
fn a_rebuild_keeps_its_revision_when_nothing_changed_and_bumps_it_when_something_did() {
let read = snap(2, 4, &[(0xA1, 1, Some(0xB1))]);
let same = rebuild_snapshot(snap(2, 0, &[(0xA1, 1, Some(0xB1))]), Some(&read));
assert_eq!(same.rev, 4, "an unchanged snapshot republishes byte-identical");
let mut renamed = snap(2, 0, &[(0xA1, 1, Some(0xB1))]);
renamed.name = "Renamed".into();
assert_eq!(rebuild_snapshot(renamed, Some(&read)).rev, 5, "a change is one revision past what was read");
let first = rebuild_snapshot(snap(2, 0, &[(0xA2, 1, Some(0xB2)), (0xA1, 1, Some(0xB1))]), None);
assert_eq!(first.rev, 0, "a first write needs no revision");
assert!(first.channels[0].id < first.channels[1].id, "and is written in the canonical order too");
}
#[test]
fn two_devices_listing_channels_in_different_orders_agree_without_a_bump() {
// Without one canonical order each device reads the other's copy as a
// change and bumps, forever.
let read = snap(2, 4, &[(0xA1, 1, Some(0xB1)), (0xA2, 1, Some(0xB2))]);
let ours = rebuild_snapshot(snap(2, 0, &[(0xA2, 1, Some(0xB2)), (0xA1, 1, Some(0xB1))]), Some(&read));
assert_eq!(ours.rev, 4, "the same channels in another order are no change");
let ids: Vec<&str> = ours.channels.iter().map(|c| c.id.as_str()).collect();
let mut sorted = ids.clone();
sorted.sort();
assert_eq!(ids, sorted, "written in one canonical order");
}
#[test]
fn a_rebuild_keeps_what_it_read_but_does_not_hold_itself() {
// A device behind its sibling — no key for a channel yet, an older key for
// another — must not publish its smaller view one revision higher and erase
// what the sibling recorded. Only the same epoch's snapshot is merged: across
// a Refounding the read copy is a different snapshot.
let read = snap(2, 6, &[(0xA1, 3, Some(0xC3)), (0xA2, 1, Some(0xB2))]);
let ours = rebuild_snapshot(snap(2, 0, &[(0xA1, 2, Some(0xC2))]), Some(&read));
let a1 = ours.channels.iter().find(|c| c.id.starts_with("a1")).expect("still listed");
assert_eq!((a1.epoch, a1.key.as_deref().map(|k| &k[..2])), (3, Some("c3")), "the sibling's newer channel key stays");
assert!(ours.channels.iter().any(|c| c.id.starts_with("a2")), "a key only the sibling holds stays");
assert_eq!(ours.rev, 6, "nothing we know is news, so nothing to revise");
let mut staff = snap(2, 6, &[]);
staff.control_root = Some("e".repeat(64));
assert_eq!(rebuild_snapshot(snap(2, 0, &[]), Some(&staff)).control_root, staff.control_root, "the staff key stays too");
let other_epoch = rebuild_snapshot(snap(3, 0, &[]), Some(&read));
assert!(other_epoch.channels.is_empty(), "a Refounding's snapshot is not merged with the epoch before it");
}
#[tokio::test]
async fn a_first_private_channel_key_reaches_the_list_past_a_stale_copy() {
// The creation write still sits on the fallback relays with no channels, and
// "channels":[] sorts below "channels":[{ — so without revisions the stale
// copy out-sorted the key forever, and a fresh device never received it.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let relays = vec!["wss://r".to_string()];
let community = create_community(&relay, "Keyed", relays.clone(), None).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&relay, &held, "inner").await.unwrap();
republish_community_list(&relay, None).await.unwrap();
let read_from = list_read_relays(&[]).await;
let entry = list_entry_of(&fetch_fragments(&relay, &read_from).await.unwrap().unwrap().list, &community);
let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.0);
assert!(
entry.current.channels.iter().any(|c| c.id == ch_hex && c.key.is_some()),
"the new key is in the List every device reads"
);
assert!(entry.current.rev >= 1, "it landed as a revision");
// And it stays put: an unchanged republish moves nothing.
let before = fetch_fragments(&relay, &read_from).await.unwrap().unwrap();
republish_community_list(&relay, None).await.unwrap();
let after = fetch_fragments(&relay, &read_from).await.unwrap().unwrap();
assert_eq!(list_entry_of(&after.list, &community).current.rev, entry.current.rev, "no change, no revision");
assert_eq!(after.created_at, before.created_at, "and no fragment rewritten");
}
#[tokio::test]
async fn a_rename_at_the_same_epoch_reaches_the_list() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Alpha", vec!["wss://r".into()], None).await.unwrap();
let mut held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
held.name = "Zulu".into();
crate::db::community::save_community_v2(&held).unwrap();
republish_community_list(&relay, None).await.unwrap();
let entry = list_entry_of(&fetch_fragments(&relay, &list_read_relays(&[]).await).await.unwrap().unwrap().list, &community);
assert_eq!(entry.current.name, "Zulu", "a rename that sorts later still lands");
}
#[tokio::test]
async fn a_device_behind_never_erases_a_key_its_sibling_recorded() {
// The sibling holds a private-channel key this device has not received yet,
// and recorded it at rev 2. Our republish — prompted by anything — must keep it.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let relays = vec!["wss://r".to_string()];
let community = create_community(&relay, "Behind", relays.clone(), None).await.unwrap();
let set = fetch_fragments(&relay, &relays).await.unwrap().unwrap();
let mut frag = set.read_frags.get(&0).unwrap().clone();
let b64 = |b: &[u8; 32]| crate::simd::base64::URL_SAFE_NO_PAD.encode_to_string(b);
let entry = frag.entries.first_mut().unwrap();
entry.current.channels.push(super::super::list_frag::FragChannel {
id: b64(&[0x5A; 32]),
key: Some(b64(&[0x6B; 32])),
epoch: 1,
name: "siblings".into(),
extra: Default::default(),
});
entry.current.rev = 2;
let e = super::super::list_frag::build_fragment_event_keys(&owner, &frag, 0, set.created_at[&0] + 1).unwrap();
relay.publish(&e, &list_read_relays(&[]).await).await.unwrap();
republish_community_list(&relay, None).await.unwrap();
let entry = list_entry_of(&fetch_fragments(&relay, &list_read_relays(&[]).await).await.unwrap().unwrap().list, &community);
let sibling = crate::simd::hex::bytes_to_hex_32(&[0x5A; 32]);
assert!(entry.current.channels.iter().any(|c| c.id == sibling && c.key.is_some()), "the sibling's key survives our republish");
}
/// Aggregate fetches answer from the healthy relay; asked alone, the dead
/// relay errors — the partial-failure shape a boot read can't see through.
struct HalfDeaf<'a>(&'a MemoryRelay, String);
#[async_trait::async_trait]
impl Transport for HalfDeaf<'_> {
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.0.publish(e, r).await
}
async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
if relays.len() == 1 && relays[0] == self.1 {
return Err("relay did not answer the fetch".to_string());
}
self.0.fetch(query, relays).await
}
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
self.0.fetch_plane(plane, query, relays).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.0.publish_durable(e, r).await
}
}
/// A relay too slow for an aggregate read (it answers after the rest have), and
/// silent when asked alone; it still takes writes.
struct Slow<'a>(&'a MemoryRelay, &'static str);
#[async_trait::async_trait]
impl Transport for Slow<'_> {
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.0.publish(e, r).await
}
async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
let quick: Vec<String> = relays.iter().filter(|r| *r != self.1).cloned().collect();
if quick.is_empty() {
return Err("relay did not answer the fetch".to_string());
}
self.0.fetch(query, &quick).await
}
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
self.0.fetch_plane(plane, query, relays).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.0.publish_durable(e, r).await
}
}
/// Publishes reach only `to`, as when the other relays drop the write.
struct WritesOnly<'a>(&'a MemoryRelay, &'static str);
#[async_trait::async_trait]
impl Transport for WritesOnly<'_> {
async fn publish(&self, e: &Event, _r: &[String]) -> Result<(), String> {
self.0.publish(e, &[self.1.to_string()]).await
}
async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
self.0.fetch(query, relays).await
}
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
self.0.fetch_plane(plane, query, relays).await
}
async fn publish_durable(&self, e: &Event, _r: &[String]) -> Result<(), String> {
self.0.publish_durable(e, &[self.1.to_string()]).await
}
}
#[tokio::test]
async fn an_unlanded_leave_is_kept_for_the_next_boot() {
let (_tmp, _guard, _owner) = init_test_db();
let id = crate::community::CommunityId([7; 32]);
tombstone_community_list_durable(id, vec!["wss://r".into()], 2_000);
tombstone_community_list_durable(id, vec!["wss://r".into()], 1_000);
let pending = load_pending();
assert_eq!(pending.tombstones.len(), 1, "one pending removal per community");
assert_eq!(pending.tombstones[0].removed_at, 2_000, "an older retry never replaces a newer removal");
republish_community_list_durable(Some(id));
assert_eq!(load_pending().joins.len(), 1, "a join waits for a client rather than being dropped");
}
#[tokio::test]
async fn a_leave_still_on_its_way_is_not_undone_by_the_next_sync() {
// The leave's tombstone never reached the relays (the app closed mid-retry), so
// the List still lists the community live. The next sync must not re-adopt it.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let relays = vec!["wss://r".to_string()];
let community = create_community(&relay, "Leaving", relays.clone(), None).await.unwrap();
let hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
tombstone_community_list_durable(*community.id(), relays.clone(), now_ms());
crate::db::community::delete_community(&hex).unwrap();
assert!(fetch_fragments(&relay, &relays).await.unwrap().unwrap().list.is_live(&hex), "the relays never heard");
let outcome = sync_community_list(&relay, &relays).await.unwrap();
assert!(outcome.joined.is_empty(), "a pending leave is not re-adopted");
assert!(!crate::db::community::community_exists(community.id()).unwrap());
}
/// Yields mid-read, so overlapping writes really interleave as they do on a network.
struct Yielding<'a>(&'a MemoryRelay);
#[async_trait::async_trait]
impl Transport for Yielding<'_> {
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
tokio::task::yield_now().await;
self.0.publish(e, r).await
}
async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
tokio::task::yield_now().await;
self.0.fetch(query, relays).await
}
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
self.0.fetch_plane(plane, query, relays).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.0.publish_durable(e, r).await
}
}
#[tokio::test]
async fn ten_leaves_at_once_all_land() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let relays = vec!["wss://r".to_string()];
let mut held = Vec::new();
for i in 0..10 {
held.push(create_community(&relay, &format!("C{i}"), relays.clone(), None).await.unwrap());
}
let net = Yielding(&relay);
let started = std::time::Instant::now();
for left in futures_util::future::join_all(held.iter().map(|c| leave_community(&net, c))).await {
left.unwrap();
}
assert!(started.elapsed() < std::time::Duration::from_secs(2), "no leave waits behind another");
// One background write carries every leave still pending.
if let Some(t) = load_pending().tombstones.first().cloned() {
let id = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&t.community_id));
tombstone_community_list(&net, &id, &relays, t.removed_at, true).await.unwrap();
}
assert!(load_pending().tombstones.is_empty(), "the first queued write landed them all");
let list = fetch_fragments(&relay, &relays).await.unwrap().unwrap().list;
for c in &held {
assert!(!list.is_live(&crate::simd::hex::bytes_to_hex_32(&c.id().0)), "every leave landed");
}
}
#[tokio::test]
async fn rapid_leaves_and_joins_all_land() {
// Overlapping writes read the same version and publish in the same second; a relay
// keeps one per coordinate, so unserialized, all but one change is lost.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let relays = vec!["wss://r".to_string()];
let a = create_community(&relay, "A", relays.clone(), None).await.unwrap();
let b = create_community(&relay, "B", relays.clone(), None).await.unwrap();
let c = create_community(&relay, "C", relays.clone(), None).await.unwrap();
let net = Yielding(&relay);
let (left_a, left_b, d) = tokio::join!(
leave_community(&net, &a),
leave_community(&net, &b),
create_community(&net, "D", relays.clone(), None),
);
left_a.unwrap();
left_b.unwrap();
let d = d.unwrap();
// What the background queue does: each pending write, waiting its turn.
for t in load_pending().tombstones {
let id = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&t.community_id));
if load_pending().tombstones.iter().any(|p| p.community_id == t.community_id) {
tombstone_community_list(&net, &id, &relays, t.removed_at, true).await.unwrap();
}
}
for j in load_pending().joins {
let id = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&j.community_id));
assert!(republish_community_list_at(&net, Some((&id, j.joined_at)), true).await.unwrap());
}
assert!(load_pending().tombstones.is_empty() && load_pending().joins.is_empty(), "everything landed");
let list = fetch_fragments(&relay, &relays).await.unwrap().unwrap().list;
let hex = |c: &CommunityV2| crate::simd::hex::bytes_to_hex_32(&c.id().0);
assert!(!list.is_live(&hex(&a)), "A's leave landed");
assert!(!list.is_live(&hex(&b)), "B's leave landed");
assert!(list.is_live(&hex(&c)), "C untouched");
assert!(list.is_live(&hex(&d)), "D's join landed");
}
#[tokio::test]
async fn a_write_never_replaces_a_copy_it_did_not_read() {
// A sibling's leave lives only on a relay too slow to answer this device's read,
// which sees an older copy elsewhere. Writing that stale view back out with a newer
// created_at would replace the tombstone on every relay and revive the community.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let relays = vec!["wss://own".to_string(), "wss://slow".to_string()];
let left = create_community(&relay, "Left", relays.clone(), None).await.unwrap();
let left_hex = crate::simd::hex::bytes_to_hex_32(&left.id().0);
leave_community(&WritesOnly(&relay, "wss://slow"), &left).await.unwrap();
let slow = vec!["wss://slow".to_string()];
assert!(!fetch_fragments(&relay, &slow).await.unwrap().unwrap().list.is_live(&left_hex), "the leave reached the slow relay");
create_community(&Slow(&relay, "wss://slow"), "Other", relays.clone(), None).await.unwrap();
let after = fetch_fragments(&relay, &slow).await.unwrap().unwrap().list;
assert!(!after.is_live(&left_hex), "the unread tombstone survives this device's write");
// A read that does reach every relay merges both copies: the leave wins.
let all = fetch_fragments(&relay, &relays).await.unwrap().unwrap().list;
assert!(!all.is_live(&left_hex), "a full read keeps the newest removal");
}
#[tokio::test]
async fn an_unconfirmed_empty_read_never_seeds() {
// One of the account's relays never answers. The aggregate read comes back
// empty (the healthy relay has nothing), which is indistinguishable from a
// fresh account — but the dead relay may hold a sibling's tombstones, so
// seeding here would bury them. The seed must defer, unlatched, and land
// once every relay confirms empty.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let relays = vec!["wss://r".to_string(), "wss://dead".to_string()];
let community = create_community(&relay, "Gated", relays.clone(), None).await.unwrap();
let cid = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let bare = MemoryRelay::new();
let half_deaf = HalfDeaf(&bare, "wss://dead".to_string());
sync_community_list(&half_deaf, &relays).await.unwrap();
assert_eq!(bare.stored_count(), 0, "a failed read must never seed");
assert!(
crate::db::settings::get_sql_setting(LIST_SEEDED_KEY.to_string()).unwrap().is_none(),
"a deferred seed must not latch"
);
// The relay comes back: every relay now confirms empty, and the seed lands.
sync_community_list(&bare, &relays).await.unwrap();
let set = fetch_fragments(&bare, &relays).await.unwrap().expect("the confirmed-empty boot seeds");
assert!(set.list.is_live(&cid));
assert!(crate::db::settings::get_sql_setting(LIST_SEEDED_KEY.to_string()).unwrap().is_some());
}
#[tokio::test]
async fn a_leave_tombstones_the_membership_so_sync_does_not_rejoin() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let relays = vec!["wss://r".to_string()];
let community = create_community(&relay, "Left", relays.clone(), None).await.unwrap();
leave_community(&relay, &community).await.unwrap(); // tombstones the 13302 + deletes
let rehydrated = sync_community_list(&relay, &relays).await.unwrap().joined;
assert!(rehydrated.is_empty(), "a tombstoned membership is not rejoined on sync");
}
#[tokio::test]
async fn accepting_the_same_bundle_twice_is_idempotent() {
// A bot restart or a duplicate invite delivery: accepting the SAME bundle
// again must upsert cleanly — same community_id, no duplicate channels, no
// corruption, the keys unchanged.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Idem", bed.relays.clone(), None).await.unwrap();
create_public_channel(&bed.relay, &community, "extra").await.unwrap();
let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();
bed.swap_to(&member);
let first = accept_parked_invite(&bed.relay, &bundle, None).await.unwrap();
let channels_after_first = first.channels.len();
let root_after_first = first.community_root;
// Accept the identical bundle again (restart / redelivery).
let second = accept_parked_invite(&bed.relay, &bundle, None).await.unwrap();
assert_eq!(second.id().0, first.id().0, "same community_id");
assert_eq!(second.channels.len(), channels_after_first, "no duplicate channels on re-accept");
assert_eq!(second.community_root, root_after_first, "root unchanged");
// The persisted state is a single clean community with the expected channels.
let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(reloaded.channels.len(), channels_after_first, "the DB holds one clean channel set");
assert_eq!(crate::db::community::list_community_ids().unwrap().iter().filter(|id| id.0 == community.id().0).count(), 1, "exactly one community row");
}
#[tokio::test]
async fn a_fresh_joiner_can_authorize_a_moderators_hide_before_any_follow() {
// The join walk reads the control plane to genesis anyway, and it already
// folds the full roster for the ban gate. Throwing that roster away left
// the fresh member's stored roles EMPTY until the follow worker's queued
// re-walk — and the hide gate reads the stored roster, so every message a
// moderator had hidden rendered to exactly the person who should never
// see it: someone who just walked in.
let (bed, owner, member) = TestBed::new();
let admin = Keys::generate();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Moderated", bed.relays.clone(), None).await.unwrap();
grant_admin(&bed.relay, &community, &admin.public_key()).await.unwrap();
send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
// A FRESH account accepts. No follow_control runs in this test — what the
// join itself persisted is all the joiner has.
bed.swap_to(&member);
let invite = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
let joined = accept_direct_invite(&bed.relay, &invite).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert!(!roster.grants.is_empty(), "the join persisted the roster it already folded");
let owner_hex = joined.owner().unwrap().to_hex();
let victim = Keys::generate().public_key().to_hex();
assert!(
crate::community::moderation::can_hide(Some(&owner_hex), &roster, &admin.public_key().to_hex(), &victim),
"the admin's hides are honorable on the FIRST history ingest, not after a follow"
);
// And the grant's refuse-downgrade floor is seeded, so the citation gate
// (`actor_authority_pinned`) can resolve the same grant.
let grant_hex = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::grant_locator(
joined.id(),
&admin.public_key().to_bytes(),
));
assert!(
crate::db::community::get_edition_head(&cid_hex, &grant_hex).unwrap().is_some(),
"the admin-signed grant head survived the join"
);
}
#[tokio::test]
async fn a_severed_member_can_be_unbanned_and_re_admitted() {
// The full moderation HEAL lifecycle: ban (banlist + grant strip + refound)
// severs a member; the owner then unbans + sends a FRESH invite carrying the
// NEW root; the member rejoins at the new epoch and converses again. Proves
// a ban is reversible end-to-end, not a one-way door.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let mut community = create_community(&bed.relay, "Redeemable", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
send_message(&bed.relay, &community, &general, "owner: welcome").await.unwrap();
bed.swap_to(&member);
let invite = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
let joined = accept_direct_invite(&bed.relay, &invite).await.unwrap();
assert!(texts_in(&bed.relay, &joined, &general).await.contains(&"owner: welcome".to_string()));
// Owner bans the member (CORD-04 §6 three-removal) → refound severs them.
bed.swap_to(&owner);
set_banlist(&bed.relay, &community, &[member.keys.public_key().to_hex()]).await.unwrap();
grant_roles(&bed.relay, &community, &member.keys.public_key(), vec![]).await.unwrap();
community = refound_community(&bed.relay, &community, &[member.keys.public_key()]).await.unwrap();
assert_eq!(community.root_epoch, Epoch(1));
send_message(&bed.relay, &community, &general, "owner: after the ban").await.unwrap();
// The member's follow concludes severance (no blob at the new epoch).
bed.swap_to(&member);
let session = crate::db::current_session();
assert!(follow_rekeys(&bed.relay, &joined, &session).await.unwrap().self_removed, "the member is cryptographically severed");
// Owner unbans + re-invites: build the fresh epoch-1 bundle (accept it
// directly, so the test picks the NEW invite unambiguously rather than an
// arbitrary one of the two pending 3313s).
bed.swap_to(&owner);
set_banlist(&bed.relay, &community, &[]).await.unwrap();
community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(community.root_epoch, Epoch(1), "the owner's bundle carries epoch 1");
let fresh_bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();
// Member accepts the fresh invite → rejoins at epoch 1, reads current + posts.
bed.swap_to(&member);
let rejoined = accept_parked_invite(&bed.relay, &fresh_bundle, None).await.unwrap();
assert_eq!(rejoined.root_epoch, Epoch(1), "rejoined at the current epoch");
assert_eq!(rejoined.community_root, community.community_root, "holds the NEW root");
let seen = texts_in(&bed.relay, &rejoined, &general).await;
assert!(seen.contains(&"owner: after the ban".to_string()), "reads post-ban history with the new root");
send_message(&bed.relay, &rejoined, &general, "member: i am back").await.unwrap();
bed.swap_to(&owner);
community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert!(
texts_in(&bed.relay, &community, &general).await.contains(&"member: i am back".to_string()),
"the re-admitted member converses again at the new epoch"
);
// And they're back in the memberlist.
let members = memberlist(&bed.relay, &community).await.unwrap();
assert!(members.contains(&member.keys.public_key()), "the re-admitted member is in the list");
}
#[tokio::test]
async fn dissolution_blocks_a_join() {
// CORD-02 §9: the owner dissolves; a would-be joiner resolves the grave and
// refuses to join.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Doomed", bed.relays.clone(), None).await.unwrap();
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
dissolve_community(&bed.relay, &community).await.unwrap();
assert!(crate::db::community::load_community_v2(community.id()).unwrap().unwrap().dissolved, "the owner's local hold is sealed");
bed.swap_to(&member);
let err = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap_err();
assert!(err.contains("dissolved"), "a join refuses a dissolved community: {err}");
}
#[tokio::test]
async fn dissolution_seals_writes_but_not_reads() {
// CORD-02 §9: sealed means NO further activity, ever. Reads must survive —
// the history stays browsable, and only explicit user intent deletes it.
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Doomed", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
send_message(&bed.relay, &community, &general, "before the end").await.unwrap();
dissolve_community(&bed.relay, &community).await.unwrap();
let sealed = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
for err in [
send_message(&bed.relay, &sealed, &general, "after the end").await.unwrap_err(),
send_reaction(&bed.relay, &sealed, &general, &"a".repeat(64), &"b".repeat(64), crate::community::v2::kind::MESSAGE, "+", None)
.await
.unwrap_err(),
send_edit(&bed.relay, &sealed, &general, &"a".repeat(64), "revised", &[]).await.unwrap_err(),
] {
assert!(err.contains("dissolved"), "every write is refused, got: {err}");
}
assert!(
texts_in(&bed.relay, &sealed, &general).await.contains(&"before the end".to_string()),
"but the history still reads"
);
}
#[tokio::test]
async fn only_the_owner_can_dissolve() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Mine", bed.relays.clone(), None).await.unwrap();
bed.swap_to(&member);
assert!(dissolve_community(&bed.relay, &community).await.is_err(), "only the owner can dissolve");
assert!(!is_dissolved(&bed.relay, &community).await, "and no tombstone was published");
}
#[tokio::test]
async fn a_foreign_tombstone_is_not_death() {
// A non-owner sealing the dissolved plane is noise (verify_dissolved is
// owner-gated), so the community is not treated as dead.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Safe", vec!["wss://r".into()], None).await.unwrap();
let rogue = Keys::generate();
let rumor = crate::community::v2::dissolution::dissolved_tombstone_rumor(rogue.public_key(), community.id(), 1_000);
let wrap = crate::community::v2::dissolution::seal_dissolved(&rumor, community.id(), &rogue, Timestamp::from_secs(1_000)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
assert!(!is_dissolved(&relay, &community).await, "a foreign-signed tombstone is not death");
}
#[tokio::test]
async fn a_public_channel_reads_history_across_a_refounding() {
// CORD-03 §3: after a Refounding rolls the base root, a Public channel's
// pre-rotation messages stay readable (the prior epoch's root is archived and
// the read fans out across held epochs).
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "History", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
send_message(&relay, &community, &general, "before the refounding").await.unwrap();
let refounded = refound_community(&relay, &community, &[]).await.unwrap();
assert_eq!(refounded.root_epoch, Epoch(1), "the epoch advanced");
send_message(&relay, &refounded, &general, "after the refounding").await.unwrap();
let open = texts_in(&relay, &refounded, &general).await;
assert!(open.contains(&"after the refounding".to_string()), "opening reads the live epoch");
assert!(
!open.contains(&"before the refounding".to_string()),
"and NOT the rotated-past one — that plane is the back-paging cursor's job"
);
let paged = all_texts_in(&relay, &refounded, &general).await;
assert!(paged.contains(&"before the refounding".to_string()), "the epoch-0 message stays reachable by paging");
assert!(paged.contains(&"after the refounding".to_string()), "alongside the epoch-1 one");
}
#[tokio::test]
async fn refounding_aborts_when_control_state_is_withheld() {
// B1 coverage gate (CORD-06 §3): a relay serving none of the committed control
// heads must ABORT the Refounding — never silently drop state (e.g. unban a
// member at the new epoch a fresh joiner bootstraps).
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Withheld", vec!["wss://good".into()], None).await.unwrap();
publish_banlist(&relay, &community, &owner, &["cc".repeat(32)], 1).await;
follow_control(&relay, &community).await.unwrap().updated; // seed the banlist floor
// Re-point the held community to an EMPTY relay + save, so the Refounding (which
// reloads fresh state) fetches none of the committed heads.
let mut moved = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
moved.relays = vec!["wss://empty".into()];
crate::db::community::save_community_v2(&moved).unwrap();
let err = refound_community(&relay, &moved, &[]).await.unwrap_err();
assert!(err.contains("was not served"), "a withheld control head aborts the refounding: {err}");
assert_eq!(
crate::db::community::load_community_v2(community.id()).unwrap().unwrap().root_epoch,
Epoch(0),
"the epoch did NOT advance (zero published state)"
);
}
#[tokio::test]
async fn refounding_rolls_the_root_and_severs_a_removed_member() {
// CORD-06 §3: the owner re-founds, removing a member. The base root rolls, the
// epoch advances, and the removed member's rekey-follow concludes they're cut.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Refound", bed.relays.clone(), None).await.unwrap();
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&member);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
bed.swap_to(&owner);
let refounded = refound_community(&bed.relay, &community, &[member.keys.public_key()]).await.unwrap();
assert_eq!(refounded.root_epoch, Epoch(1), "the epoch advanced");
assert_ne!(refounded.community_root, community.community_root, "the base root rolled");
// The owner still reads the compacted control plane at the new epoch.
assert_eq!(
crate::db::community::load_community_v2(community.id()).unwrap().unwrap().root_epoch,
Epoch(1),
"the owner committed the new epoch"
);
// The removed member, following rekeys, is severed (no blob in the rotation).
// Guard captured AFTER the swap: it must belong to the ACTING account (the harness
// swap now bumps the generation exactly like a production swap_session).
bed.swap_to(&member);
let session = crate::db::current_session();
let follow = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
assert!(follow.self_removed, "the removed member is cut by the re-founding");
}
#[tokio::test]
async fn a_ban_holding_admin_can_re_found_but_not_evict_a_superior() {
// CORD-06 §Authority: a Refounding requires BAN, not owner-identity. A
// non-owner admin granted BAN CAN re-found (and every member follows it —
// see the receive-side test), but the "strictly outrank every removed
// target" rule still holds: they can't use it to evict the owner.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Guarded", bed.relays.clone(), None).await.unwrap();
let rid = "b0".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid], 1).await;
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&member);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
// Fold the roster so this member's own DB reflects their BAN grant (the
// authority check reads the folded Roster, not the bundle).
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
// Can't evict the owner (no one outranks the owner).
assert!(refound_community(&bed.relay, &joined, &[owner.keys.public_key()]).await.is_err(), "a BAN-holder can't re-found to evict the owner");
// But CAN re-found removing a plain member they outrank (here, nobody).
assert!(refound_community(&bed.relay, &joined, &[]).await.is_ok(), "a BAN-holding admin can re-found");
}
#[tokio::test]
async fn follow_rekeys_adopts_an_authorized_non_owner_base_rotation() {
// A BAN-holding ADMIN (not the owner) re-founds, and every member must
// follow it — owner-only receive silently strands members whose community
// was refounded by an admin (CORD-06 §Authority: "a Refounding requires
// BAN", checked against the folded Roster).
let (bed, owner, me) = TestBed::new();
let admin = Keys::generate();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "AdminRefound", bed.relays.clone(), None).await.unwrap();
let rid = "b0".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid], 1).await;
// I (a plain member) join, then fold the roster so I know the admin holds BAN.
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
// The admin re-founds keeping the owner + me — the owner must always be a
// recipient of a non-owner Refounding.
let new_root = [0xC7; 32];
publish_base_rotation(&bed.relay, &joined, &admin, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await;
let updated = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap().updated
.expect("an authorized admin's Refounding is adopted");
assert_eq!(updated.root_epoch, Epoch(1), "advanced past the admin's rotation");
assert_eq!(updated.community_root, new_root, "adopted the admin's fresh root");
}
#[tokio::test]
async fn the_adopted_rotations_minter_owns_the_epochs_snapshot_not_the_owner() {
// CORD-02 §5: a snapshot is honored "only from the npub whose Refounding
// minted that epoch". The minter must come from the rotation this device
// verified and adopted, and once an admin minted the epoch the OWNER holds no
// snapshot power over it — or the owner could re-seed members the admin cut.
let (bed, owner, me) = TestBed::new();
let admin = Keys::generate();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Minter", bed.relays.clone(), None).await.unwrap();
let rid = "b7".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid], 1).await;
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
publish_base_rotation(&bed.relay, &joined, &admin, &[owner.keys.public_key(), me.keys.public_key()], &[0xC8; 32], &joined.community_root).await;
let at_1 = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap().updated.expect("adopted");
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
assert_eq!(
epoch_minters(&cid_hex).get(&1).map(String::as_str),
Some(admin.public_key().to_hex().as_str()),
"adoption records the verified rotator as the epoch's minter"
);
// A member the admin's containment cut, and the owner trying to re-seed them.
let cut = Keys::generate().public_key();
let survivors = vec![owner.keys.public_key(), me.keys.public_key()];
let snapshot = |by: PublicKey, members: Vec<PublicKey>, id: u8, at_ms: u64| guestbook::GuestbookEvent {
epoch: Some(1), observed_at: None, rumor_id: [id; 32],
entry: guestbook::GuestbookEntry::Snapshot { refounder: by, members, snapshot_id: [id; 32], chunk: (1, 1), at_ms },
};
let events = vec![
guestbook::GuestbookEvent {
epoch: Some(0), observed_at: None, rumor_id: [0x61; 32],
entry: guestbook::GuestbookEntry::Join { member: cut, invited_by: None, at_ms: 1_000 },
},
snapshot(admin.public_key(), survivors, 0x62, 5_000),
snapshot(owner.keys.public_key(), vec![cut], 0x63, 6_000),
];
crate::db::community::set_guestbook(&cid_hex, &events, 6).unwrap();
let members = stored_memberlist(&at_1).unwrap();
assert!(!members.contains(&cut), "the owner's snapshot holds no power over an epoch the admin minted");
assert!(members.contains(&me.keys.public_key()), "the minter's survivors stay members");
}
#[tokio::test]
async fn adopting_a_severing_rotation_revokes_my_own_links_instead_of_refreshing_them() {
// The inverse of the sibling test: a SEVERING refound flips the stable-URL
// contract. A raid arrives through the door, so every creator's client
// buries its own links on adopt rather than carrying them into the new
// epoch — which is the only way the OWNER's link dies when a bot admin ran
// the containment (only the creator holds a link's signer secret).
let (bed, owner, me) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "SeverHeal", bed.relays.clone(), None).await.unwrap();
let rid = "b1".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN | Permissions::CREATE_INVITE), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
let minted = mint_public_link(&bed.relay, &joined, "https://x", None, None).await.unwrap();
assert!(fetch_public_bundle(&bed.relay, &minted.url).await.is_ok(), "my link is live before the raid");
// The owner runs a SEVERING refound (the raid lane).
let new_root = [0xD5; 32];
publish_severing_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await;
let updated = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap().updated
.expect("the owner's severing Refounding is adopted");
assert_eq!(updated.root_epoch, Epoch(1), "I still advance to the new epoch");
let err = fetch_public_bundle(&bed.relay, &minted.url).await.unwrap_err();
assert!(err.contains("revoked"), "my link must be a grave, not a refreshed door: {err}");
assert!(
crate::db::community::list_public_invites(&crate::simd::hex::bytes_to_hex_32(&updated.id().0)).unwrap().is_empty(),
"and the local record goes with it",
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_severing_adopt_never_deadlocks_the_last_link_creator() {
// The severance runs INSIDE the follow, which holds `follow_lock` for the
// whole call. `revoke_public_link`'s last-live-link escalation re-founds —
// taking that same non-reentrant lock — so routing severance through it
// would wedge this community's follow forever, for the very client whose
// revocation empties the registry (typically the owner). The escalation-free
// path is the fix; this test is its guard.
let (bed, owner, me) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "NoDeadlock", bed.relays.clone(), None).await.unwrap();
let rid = "b2".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN | Permissions::CREATE_INVITE), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
// My link is the ONLY one in the registry — revoking it empties the
// aggregate, which is exactly the escalation's trigger condition.
let minted = mint_public_link(&bed.relay, &joined, "https://x", None, None).await.unwrap();
assert!(fetch_public_bundle(&bed.relay, &minted.url).await.is_ok());
let new_root = [0xD6; 32];
publish_severing_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await;
let followed = crate::rt::time::timeout(
std::time::Duration::from_secs(20),
follow_rekeys(&bed.relay, &joined, &crate::db::current_session()),
)
.await
.expect("the severing follow must not deadlock on follow_lock")
.unwrap();
assert_eq!(followed.updated.expect("adopted").root_epoch, Epoch(1));
}
#[tokio::test(flavor = "multi_thread")]
async fn a_severing_adopt_spares_a_link_minted_after_the_raid() {
// Severance is bounded by the rotation's own wire stamp, not "now". A
// second device that adopts late must not eat the fresh link the owner
// minted to re-open the community after the raid was over.
let (bed, owner, me) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "FreshDoor", bed.relays.clone(), None).await.unwrap();
let rid = "b3".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN | Permissions::CREATE_INVITE), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
let raid_era = mint_public_link(&bed.relay, &joined, "https://old", None, None).await.unwrap();
let new_root = [0xD7; 32];
publish_severing_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await;
let updated = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap().updated.expect("adopted");
assert!(
fetch_public_bundle(&bed.relay, &raid_era.url).await.unwrap_err().contains("revoked"),
"the raid-era link is buried",
);
// The raid is over and the owner deliberately re-opens the community. The
// pending-severance retry runs on every follow, so a door minted after the
// containment must survive them all — otherwise no one could ever re-open.
let fresh = mint_public_link(&bed.relay, &updated, "https://new", None, None).await.unwrap();
let _ = follow_rekeys(&bed.relay, &updated, &crate::db::current_session()).await.unwrap();
assert!(
fetch_public_bundle(&bed.relay, &fresh.url).await.is_ok(),
"a link minted after the containment survives later follow passes",
);
}
#[tokio::test(flavor = "multi_thread")]
async fn an_unauthorized_severing_rotation_never_touches_my_links() {
// The sever tag grants no authority of its own: it rides a rotation the
// adopt gate has already verified. A plain member's forged severing
// rotation is refused whole, so the tag is never even read.
let (bed, owner, me) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "NoForge", bed.relays.clone(), None).await.unwrap();
let rid = "b4".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::CREATE_INVITE), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
let minted = mint_public_link(&bed.relay, &joined, "https://x", None, None).await.unwrap();
// A stranger with no BAN mints a severing rotation.
let stranger = Keys::generate();
publish_severing_base_rotation(&bed.relay, &joined, &stranger, &[me.keys.public_key(), owner.keys.public_key()], &[0xD8; 32], &joined.community_root).await;
let followed = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
assert!(followed.updated.is_none(), "an unauthorized rotation is not adopted");
assert!(fetch_public_bundle(&bed.relay, &minted.url).await.is_ok(), "and my link is untouched");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_degraded_plane_read_is_not_evidence_of_absence() {
// One honest relay is enough to RUN Concord — a sealed, signed rotation is
// proof on its own. What one relay's silence is NOT enough for is concluding
// a rotation does not exist. Those two cases used to be the same empty list,
// so a client that could not reach anyone decided the community had simply
// stopped rotating, and parked. Coverage is what separates them, and it is
// measured against the REACHABLE set, so a single-relay community still gets
// definitive answers.
use crate::community::transport::adversarial::{AdversarialRelay, Fault, Match};
let relay = AdversarialRelay::new();
let (bed, owner, me) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(relay.relay(), "Coverage", bed.relays.clone(), None).await.unwrap();
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(relay.relay(), &bundle_json, None).await.unwrap();
let _ = follow_control(relay.relay(), &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
bed.swap_to(&owner);
publish_base_rotation(relay.relay(), &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &[0xE9; 32], &joined.community_root).await;
bed.swap_to(&me);
// The plane cannot be reached at all: an Err, not an empty answer.
let plane = base_rekey_group_key(&joined.community_root, joined.id(), Epoch(1));
relay.on(Match::author(&plane.pk_hex()), Fault::FailFetch("relay down".into()));
let _ = follow_rekeys(&relay, &joined, &crate::db::current_session()).await;
let during = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
assert_eq!(
during.root_epoch, joined.root_epoch,
"an unreachable plane must not advance anything — but it must also not be \
mistaken for a community that stopped rotating",
);
// The relay comes back. The rotation was there the whole time.
relay.heal();
let _ = follow_rekeys(&relay, &during, &crate::db::current_session()).await;
let after = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
assert_eq!(
after.root_epoch, Epoch(1),
"once a relay answers, the rotation it was holding is adopted — the earlier \
silence was never evidence",
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_short_rekey_page_ends_the_walk_only_when_every_relay_answered() {
// A short page reads as "the plane ends here" — true only if nobody was left
// out. With a relay unheard, the rotation may sit just past the page, and
// stopping there parks the member on a dead epoch.
use crate::community::transport::adversarial::{AdversarialRelay, Fault, Match};
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
for (fault, expect_found) in [(Fault::ShortUnconfirmed(3), true), (Fault::ShortPage(3), false)] {
let relay = AdversarialRelay::new();
let community = create_community(relay.relay(), "Pager", bed.relays.clone(), None).await.unwrap();
// The genuine rotation, OLDER than everything served on the first page.
publish_base_rotation(relay.relay(), &community, &owner.keys, &[owner.keys.public_key()], &[0xA1; 32], &community.community_root).await;
let plane = base_rekey_group_key(&community.community_root, community.id(), Epoch(1));
for ts in 2_001..=2_005u64 {
let rumor = stream::build_rumor_secs(1, owner.keys.public_key(), "noise", vec![], ts);
let seal = stream::build_seal(&rumor, stream::SealForm::Encrypted, &plane, &owner.keys).unwrap();
let (wrap, _) = stream::wrap_seal(&seal, &plane, stream::KIND_WRAP, Timestamp::from_secs(ts)).unwrap();
relay.relay().publish(&wrap, &community.relays).await.unwrap();
}
let label = format!("{fault:?}");
relay.on(Match::author(&plane.pk_hex()).nth(1), fault);
let wraps = plane_wraps_paged(&relay, &community.relays, &plane).await.unwrap();
let found = wraps.iter().filter_map(|w| stream::open_wrap(w, &plane).ok()).filter_map(|o| rekey::parse_rekey_chunk(&o).ok()).any(|c| c.rotator == owner.keys.public_key());
assert_eq!(found, expect_found, "{label}: the walk {} past a short first page", if expect_found { "pages on" } else { "stops" });
// Compared as sets, the shape of a page is nothing to go by.
let chunks = fetch_rekey_chunks(&relay, &community, &plane).await.unwrap();
assert!(chunks.iter().any(|c| c.rotator == owner.keys.public_key()), "{label}: through the wraps held");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn an_older_banlist_edition_can_never_un_ban() {
// Un-banning is the fail-open direction: the un-banned party's rotations and
// messages start being honored again. So a stale edition arriving late — a
// slow relay, a replay, a re-fold under a narrowed window — must never
// overwrite a newer list. Enforced at the storage layer so no future folding
// change can reintroduce it.
let (bed, owner, _me) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "BanMonotonic", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let villain_keys = Keys::generate();
let villain = villain_keys.public_key().to_hex();
crate::db::community::set_community_banlist(&cid_hex, &[villain.clone()], 5).unwrap();
assert!(crate::db::community::get_community_banlist(&cid_hex).unwrap().contains(&villain));
// An OLDER edition (version 3) tries to replace it with an empty list.
crate::db::community::set_community_banlist(&cid_hex, &[], 3).unwrap();
assert!(
crate::db::community::get_community_banlist(&cid_hex).unwrap().contains(&villain),
"a lower-versioned edition must not un-ban",
);
assert!(
crate::db::community::is_author_banned(&cid_hex, &villain_keys.public_key()),
"and the hot cache must not hold the list we declined to persist",
);
// A NEWER edition legitimately un-bans.
crate::db::community::set_community_banlist(&cid_hex, &[], 6).unwrap();
assert!(
!crate::db::community::is_author_banned(&cid_hex, &villain_keys.public_key()),
"a newer edition still lifts a ban — monotonic, not frozen",
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_withholding_relay_cannot_wipe_the_banlist_or_the_roster() {
// Absence is not evidence. A relay that serves NO control editions folds an
// empty aggregate, and an empty fold raises no gap flag — nothing is missing
// from a window that contains nothing. Persisting that would un-ban every
// banned member and strip every admin, locally, on one bad fetch. Un-banning
// is the fail-OPEN direction: the un-banned party's rotations start being
// honored again, which is how one client ends up on a branch minted by
// someone everyone else has evicted.
use crate::community::transport::adversarial::{AdversarialRelay, Fault, Match};
let relay = AdversarialRelay::new();
let (bed, owner, _me) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(relay.relay(), "WitholdWipe", bed.relays.clone(), None).await.unwrap();
let rid = "c4".repeat(32);
let admin = Keys::generate();
publish_role(relay.relay(), &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
publish_grant(relay.relay(), &community, &owner.keys, &admin.public_key(), vec![rid], 1).await;
let villain = Keys::generate();
set_banlist(relay.relay(), &community, &[villain.public_key().to_hex()]).await.unwrap();
let _ = follow_control(&relay, &community).await;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
assert!(
crate::db::community::get_community_banlist(&cid_hex).unwrap().contains(&villain.public_key().to_hex()),
"the ban folded",
);
let roster_before = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert!(!roster_before.grants.is_empty(), "the admin's grant folded");
// Now the control plane serves nothing at all.
let control_pk = control::ControlPlane::of(&community).pk_hex();
relay.on(Match::author(&control_pk), Fault::Empty);
let _ = follow_control(&relay, &community).await;
assert!(
crate::db::community::get_community_banlist(&cid_hex).unwrap().contains(&villain.public_key().to_hex()),
"an empty control window must NEVER un-ban — that is the fail-open direction",
);
let roster_after = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert_eq!(
roster_after.grants.len(), roster_before.grants.len(),
"and must never strip standing: an empty fold is absence, not a demotion",
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_banned_rotators_refounding_is_never_honored() {
// Holding a key is never authority (CORD-06 §Authority). A member banned
// moments ago still holds the current root, so they can mint a perfectly
// shaped Refounding — right prev_commit, right epoch, real blobs. If a
// client honors it, the banned party has just re-keyed the community around
// itself and split every member who folded the ban from every member who
// did not. The banlist has to be consulted at ADOPT time, not only at send.
let (bed, owner, me) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "BannedRotator", bed.relays.clone(), None).await.unwrap();
let rid = "a9".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
let rogue = Keys::generate();
publish_grant(&bed.relay, &community, &owner.keys, &rogue.public_key(), vec![rid], 1).await;
let _ = follow_control(&bed.relay, &community).await;
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
// The rogue admin is banned, and we fold that ban.
bed.swap_to(&owner);
set_banlist(&bed.relay, &community, &[rogue.public_key().to_hex()]).await.unwrap();
bed.swap_to(&me);
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
assert!(
crate::db::community::get_community_banlist(&cid_hex).unwrap().contains(&rogue.public_key().to_hex()),
"the ban folded before the rotation arrives",
);
// Still holding the root, the banned admin mints a Refounding anyway.
bed.swap_to(&owner);
publish_base_rotation(
&bed.relay, &joined, &rogue,
&[owner.keys.public_key(), me.keys.public_key(), rogue.public_key()],
&[0xBA; 32], &joined.community_root,
).await;
bed.swap_to(&me);
let held_before = joined.root_epoch;
let follow = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
assert!(!follow.self_removed, "a banned rotator can never remove anyone");
let after = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
assert_eq!(
after.root_epoch, held_before,
"a banned member's rotation must not move the epoch — honoring it hands the community to the party just evicted",
);
assert_eq!(after.community_root, joined.community_root, "and must not move the root");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_rekey_exclusion_keeps_my_epoch_keys() {
// Being removed must not cost me the ability to scrub my own history. The
// epoch keys open no FUTURE epoch — post-removal keys are never delivered —
// so retaining them leaks nothing; they are only what lets me author a 3305
// self-delete of messages I already sent, each sealed under the epoch it was
// sent at. Every other self-removal path retains them. The rekey-exclusion
// path silently did not, so an eviction (or a false positive) destroyed that.
let (bed, owner, me) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "ExclusionKeys", bed.relays.clone(), None).await.unwrap();
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
assert!(
!crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap().is_empty(),
"the joiner archived its epoch key",
);
// The owner rotates and leaves me out — a genuine, authorized removal.
bed.swap_to(&owner);
publish_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key()], &[0xD1; 32], &joined.community_root).await;
bed.swap_to(&me);
let follow = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
assert!(follow.self_removed, "an authorized rotation that excluded me IS a removal");
// Dated by the rotation, not by when this device noticed it: a rejoin made in between
// must not be out-dated by a late notice.
assert_eq!(follow.removed_at, Some(2_000_000), "the rotation's own time (the helper sends it at 2 000 s)");
// The teardown the caller performs on self_removed.
crate::db::community::delete_community_retain_keys(&cid_hex).unwrap();
assert!(
crate::db::community::load_community_v2(joined.id()).unwrap().is_none(),
"the community is gone",
);
assert!(
!crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap().is_empty(),
"but my epoch keys survive, so I can still self-delete what I wrote",
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_client_that_adopted_the_losing_fork_converges_down_onto_the_canonical_one() {
// Two authorized rotators mint the same epoch concurrently. The tiebreak is
// deterministic — lowest new base key wins — but it only ever ran across
// rotations seen in ONE fetch. A client that saw only the higher sibling
// adopted it and then looked exclusively for its successor, so the canonical
// branch became permanently unreachable: two halves of a community at the
// same epoch number, different keys, unable to read each other, with nobody
// misbehaving. Convergence has to be re-checked, not decided once.
let (bed, owner, me) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "ForkHeal", bed.relays.clone(), None).await.unwrap();
let rid = "f1".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
// TWO rotators, which is what a real fork requires: rotations correlate on
// (rotator, scope, epoch, prevcommit), so one rotator minting twice would
// merge into a single rotation rather than fork — and `mint_or_reuse` stops
// an honest rotator doing that anyway. A second BAN-holder is the genuine
// concurrent-refound case. Low wins the spec's tiebreak.
let rival = Keys::generate();
bed.swap_to(&owner);
publish_grant(&bed.relay, &community, &owner.keys, &rival.public_key(), vec!["f1".repeat(32)], 1).await;
// The owner's client must fold the grant before minting the rival's rotation:
// a non-owner rotation carries a `vac` citing the Grant it acts under, and an
// uncited one is inadmissible by design.
let _ = follow_control(&bed.relay, &community).await;
bed.swap_to(&me);
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
let low = [0x11u8; 32];
let high = [0xF1u8; 32];
let recipients = [owner.keys.public_key(), me.keys.public_key(), rival.public_key()];
bed.swap_to(&owner);
publish_base_rotation(&bed.relay, &joined, &owner.keys, &recipients, &high, &joined.community_root).await;
// We see ONLY the high sibling first and adopt it — the fork is now set.
bed.swap_to(&me);
let session = crate::db::current_session();
let _ = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
let forked = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
assert_eq!(forked.root_epoch, Epoch(1), "adopted the sibling we could see");
assert_eq!(forked.community_root, high, "and it is the LOSING branch");
// The rival BAN-holder's sibling surfaces afterwards — a separate rotation,
// and the one the deterministic tiebreak says everyone must land on.
bed.swap_to(&owner);
publish_base_rotation(&bed.relay, &joined, &rival, &recipients, &low, &joined.community_root).await;
bed.swap_to(&me);
let _ = follow_rekeys(&bed.relay, &forked, &session).await.unwrap();
let healed = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
assert_eq!(
healed.community_root, low,
"a settled epoch MUST converge down onto the canonical sibling, or the community stays split",
);
assert_eq!(healed.root_epoch, Epoch(1), "same epoch — this is a sideways step, not an advance");
// Down-only: re-running must not bounce back up to the higher sibling, or two
// clients seeing the pair in different orders would oscillate forever.
let _ = follow_rekeys(&bed.relay, &healed, &session).await.unwrap();
let settled = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
assert_eq!(settled.community_root, low, "convergence is down-only and stable");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_deep_catch_up_never_loses_ground_and_lands_on_the_head() {
// The scenario this program exists for: a member returns after a community
// rotated hard while they were away, on a link that keeps dropping.
//
// This asserts MONOTONICITY and CONVERGENCE — the epoch never moves
// backward across passes, and the client ends exactly on the head, not one
// short and not overshooting. Retention of a partial walk is a different
// property with its own test (see the interrupted-mid-walk case, which fails
// without per-hop banking); this one would still pass without banking, and
// is not claiming otherwise.
use crate::community::transport::adversarial::{AdversarialRelay, Fault, Match};
const HOPS: u64 = 12;
let relay = AdversarialRelay::new();
let (bed, owner, me) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(relay.relay(), "DeepStorm", bed.relays.clone(), None).await.unwrap();
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(relay.relay(), &bundle_json, None).await.unwrap();
let _ = follow_control(relay.relay(), &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
// The community rotates HOPS times while we are offline. Owner-signed, so
// authority is never the variable under test here — reachability is.
bed.swap_to(&owner);
let recipients = [owner.keys.public_key(), me.keys.public_key()];
let mut cur = community.clone();
let mut planes: Vec<String> = Vec::new();
for i in 1..=HOPS {
let root = [(0x40 + i) as u8; 32];
planes.push(base_rekey_group_key(&cur.community_root, cur.id(), Epoch(i)).pk_hex());
publish_base_rotation(relay.relay(), &cur, &owner.keys, &recipients, &root, &cur.community_root).await;
cur.community_root = root;
cur.root_epoch = Epoch(i);
}
// Come back into a storm. The failures are placed MID-WALK on purpose: each
// pass gets several hops in before dying, so a walk that does not bank as it
// goes loses a batch of work every time and can never get past the first
// barrier. Failing only the first ask of each barrier means the link is
// genuinely recovering, so the only question is whether progress survives.
bed.swap_to(&me);
for barrier in [5usize, 9] {
relay.on(Match::author(&planes[barrier - 1]).nth(1), Fault::FailFetch("flaky link".into()));
}
let session = crate::db::current_session();
let mut last = 0u64;
// Bounded retries — the point is that each pass strictly advances, so a
// finite number of them suffices however unlucky the link is.
for pass in 0..(HOPS * 3) {
let held = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
let now = held.root_epoch.0;
assert!(
now >= last,
"pass {pass}: epoch went BACKWARD ({last} -> {now}); a catch-up must never lose ground",
);
last = now;
if now == HOPS {
break;
}
let _ = follow_rekeys(&relay, &held, &session).await;
}
let healed = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
assert_eq!(
healed.root_epoch, Epoch(HOPS),
"a deep backlog on a failing link must still converge on the head; stuck at {}",
healed.root_epoch.0,
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_missing_chunk_does_not_block_adopting_the_key_i_already_hold() {
// Completeness gates ADOPTION today, not just removal. A 1,000-member
// rotation spans thirteen chunks, so one unreachable chunk parks every
// member of the community — including everyone whose key is sitting in a
// chunk they already fetched and can open right now. Requiring the whole set
// to adopt makes a large community's rotation as fragile as its worst chunk,
// and the walk is sequential, so the strand blocks every epoch above it too.
//
// Completeness is required to conclude REMOVAL, which is destructive and
// must stay conservative. Adoption is the safe direction: the blob is bound
// to (scope, epoch) inside its ciphertext, so a key that opens is the key
// for this rotation whatever else is missing.
let (bed, owner, me) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "PartialChunks", bed.relays.clone(), None).await.unwrap();
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
// A two-chunk rotation where only the chunk carrying MY blob is published.
bed.swap_to(&owner);
let new_root = [0xC7u8; 32];
let new_epoch = Epoch(joined.root_epoch.0 + 1);
let prev_commit = super::super::derive::epoch_key_commitment(joined.root_epoch, &joined.community_root);
let group = base_rekey_group_key(&joined.community_root, joined.id(), new_epoch);
let my_blob = rekey::build_blob_local(
owner.keys.secret_key(), &owner.keys.public_key().to_bytes(),
&me.keys.public_key(), RekeyScope::Root, new_epoch, &new_root,
).unwrap();
// Declares 2 chunks; only chunk 1 ever reaches the relay.
let rumor = rekey::build_rekey_rumor(
owner.keys.public_key(), RekeyScope::Root, new_epoch, joined.root_epoch,
&prev_commit, &[my_blob], 1, 2, 2_000,
my_authority_citation(&joined, &owner.keys.public_key()).as_ref(), false,
).unwrap();
let (wrap, _) = rekey::seal_rekey_chunk(&rumor, &group, &owner.keys, Timestamp::from_secs(2_000)).unwrap();
bed.relay.publish(&wrap, &bed.relays).await.unwrap();
bed.swap_to(&me);
let follow = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
assert!(!follow.self_removed, "a missing chunk is never a removal");
let after = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
assert_eq!(
after.root_epoch, new_epoch,
"my blob was present and opened — the missing sibling chunk says nothing about MY key, \
and parking here strands the whole community behind its least reachable chunk",
);
}
#[tokio::test(flavor = "multi_thread")]
async fn an_empty_rotation_is_never_a_mass_removal() {
// `is_complete` is satisfied by a single chunk declaring n=1 — including one
// carrying ZERO blobs, which the builders emit verbatim for an empty
// recipient set. Read literally that is "a complete, authorized rotation
// containing no blob for me", i.e. removal — and the removal path DELETES the
// community locally, keys and all. From the owner, one such rotation would
// evict every member of the community at once, irreversibly.
//
// Nobody can be removed by a rotation that removed everybody.
let (bed, owner, me) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "EmptyRotation", bed.relays.clone(), None).await.unwrap();
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
// The owner publishes a complete rotation with no recipients at all.
bed.swap_to(&owner);
publish_base_rotation(&bed.relay, &joined, &owner.keys, &[], &[0xB0; 32], &joined.community_root).await;
bed.swap_to(&me);
let follow = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
assert!(
!follow.self_removed,
"an all-empty rotation must NEVER read as my removal — that path deletes the community",
);
assert!(
crate::db::community::load_community_v2(joined.id()).unwrap().is_some(),
"and the community must still be held",
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_catch_up_interrupted_mid_walk_keeps_the_hops_it_already_took() {
// A client back from a week offline walks many epochs in one pass. Today the
// community row is written ONCE, after the loop, so a fetch failure on the
// last hop discards every hop already walked — the next attempt starts from
// zero, costs the same again, and on a flaky link may never converge at all.
// Progress must be banked per hop.
use crate::community::transport::adversarial::{AdversarialRelay, Fault, Match};
// The bed supplies isolated per-account DBs; the adversarial relay replaces
// its transport so a fault plan governs what the client can read back.
let relay = AdversarialRelay::new();
let (bed, owner, me) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(relay.relay(), "DeepCatchUp", bed.relays.clone(), None).await.unwrap();
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(relay.relay(), &bundle_json, None).await.unwrap();
let _ = follow_control(relay.relay(), &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
// Owner rotates three times while we are away. Owner rotations need no roster.
bed.swap_to(&owner);
let mut cur = community.clone();
let roots = [[0xA1u8; 32], [0xA2; 32], [0xA3; 32]];
let recipients = [owner.keys.public_key(), me.keys.public_key()];
for (i, root) in roots.iter().enumerate() {
publish_base_rotation(relay.relay(), &cur, &owner.keys, &recipients, root, &cur.community_root).await;
cur.community_root = *root;
cur.root_epoch = Epoch(i as u64 + 1);
}
// Come back, but the plane for the LAST hop is unreachable.
bed.swap_to(&me);
let third_hop = base_rekey_group_key(&roots[1], joined.id(), Epoch(3));
relay.on(Match::author(&third_hop.pk_hex()), Fault::FailFetch("relay dropped".into()));
let _ = follow_rekeys(&relay, &joined, &crate::db::current_session()).await;
let after = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
assert!(
after.root_epoch.0 >= 2,
"hops 1 and 2 succeeded and MUST be banked; an interrupted walk that reverts to epoch {} \
restarts from scratch every attempt and may never converge on a flaky link",
after.root_epoch.0,
);
// Faults cease: the walk resumes from where it banked and reaches the head.
relay.heal();
let _ = follow_rekeys(&relay, &after, &crate::db::current_session()).await;
let healed = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
assert_eq!(healed.root_epoch, Epoch(3), "once faults cease the walk converges on the head");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_promote_is_reported_as_an_authority_change() {
// The single line whose absence was the fork. A promote moves the ROSTER,
// which lives in its own column and never appears in the returned document —
// so a caller keying its retry off `updated` alone sees "nothing happened",
// skips the re-walk, and leaves the rekey pass that just refused this admin's
// rotation to never reconsider it. Asserted at the unit level deliberately:
// an integration drill can pass for the wrong reason (a roster cached on some
// earlier pass), and this codebase has been bitten by exactly that before.
let (bed, owner, admin) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "PromoteReports", bed.relays.clone(), None).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap(); // settle the baseline
let rid = "e1".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin.keys.public_key(), vec![rid], 1).await;
let control = follow_control(&bed.relay, &community).await.unwrap();
assert!(
control.authority_changed,
"a promote MUST report an authority change — this is what re-runs the rekey walk",
);
assert!(control.moved(), "and therefore counts as movement");
assert!(
control.updated.is_none(),
"while moving no document at all — which is precisely why `updated` alone was blind",
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_seeded_roster_never_vetoes_a_coherent_control_fold() {
// `merge_local_roster` seeds an optimistic roster at `roles_at = 0` so a
// just-created role works before its edition folds. That seed names entities
// the plane may never head, which made `stored_complete` false FOREVER — the
// roster could never be replaced, and a roster that never updates cannot
// authorize anyone, so the client silently refused every rotation that admin
// published. It landed on owners, who seed the most.
let (bed, owner, admin) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "SeedVeto", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let rid = "c1".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin.keys.public_key(), vec![rid], 1).await;
// A seed naming an entity the plane will never head, with NO provenance —
// exactly what creating a private channel leaves behind.
let ghost = "d4".repeat(32);
let mut seeded = crate::community::roles::CommunityRoles::default();
seeded.roles.push(admin_role(&ghost, Permissions::MANAGE_CHANNELS));
seeded.grants.push(crate::community::roles::MemberGrant {
member: owner.keys.public_key().to_hex(),
role_ids: vec![ghost.clone()],
});
crate::db::community::set_community_roles(&cid_hex, &seeded, 0).unwrap();
// A floor for the ghost is what turns `stored_complete` false.
crate::db::community::set_edition_head_at_epoch(&cid_hex, &ghost, 1, &[0u8; 32], &[0u8; 32], &[0u8; 32], community.root_epoch.0).unwrap();
follow_control(&bed.relay, &community).await.unwrap().updated;
let folded = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert!(
folded.grants.iter().any(|g| g.member == admin.keys.public_key().to_hex()),
"a coherent fold must replace a provenance-less seed, or the client is deaf to this admin forever",
);
assert_ne!(
crate::db::community::get_community_roles_at(&cid_hex).unwrap(),
0,
"and the replacement carries the plane's provenance",
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_pending_severance_heals_on_a_quiet_follow_pass() {
// The retry must run on passes that adopt NOTHING. A one-shot transport
// blip during the original severance otherwise has no healing trigger
// until some future rotation happens to be adopted — and until then the
// community reads Public, which silently strips the refound from every
// ordinary ban.
let (bed, owner, me) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "QuietHeal", bed.relays.clone(), None).await.unwrap();
let rid = "b5".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN | Permissions::CREATE_INVITE), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
let minted = mint_public_link(&bed.relay, &joined, "https://x", None, None).await.unwrap();
// A containment was adopted but its revoke was interrupted: the mark is
// down, the epoch-0 link still stands.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
add_sever_mark(&cid_hex, 1, 5_000);
assert!(fetch_public_bundle(&bed.relay, &minted.url).await.is_ok());
// A QUIET follow — no rotation anywhere — must finish the burial.
let followed = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
assert!(followed.updated.is_none(), "nothing to adopt");
assert!(
fetch_public_bundle(&bed.relay, &minted.url).await.unwrap_err().contains("revoked"),
"the interrupted severance healed with no rotation to carry it",
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_sever_survives_a_later_ordinary_rotation_in_the_same_walk() {
// Sticky severance: a client catching up walks EVERY missed rotation in
// one pass. If the containment hop is followed by an ordinary one,
// last-hop-wins semantics would refresh the links right back open — the
// door the raid came through, re-armed with the newest root.
let (bed, owner, me) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "StickySever", bed.relays.clone(), None).await.unwrap();
let rid = "b6".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN | Permissions::CREATE_INVITE), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
let minted = mint_public_link(&bed.relay, &joined, "https://x", None, None).await.unwrap();
// Hop 1: the containment. Hop 2: an ordinary rotation on top of it.
let root1 = [0xE1; 32];
publish_severing_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &root1, &joined.community_root).await;
let mut stepped = joined.clone();
stepped.community_root = root1;
stepped.root_epoch = Epoch(1);
let root2 = [0xE2; 32];
publish_base_rotation(&bed.relay, &stepped, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &root2, &root1).await;
let updated = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap().updated.expect("both hops adopt");
assert_eq!(updated.root_epoch, Epoch(2), "the walk reached the ordinary head");
assert!(
fetch_public_bundle(&bed.relay, &minted.url).await.unwrap_err().contains("revoked"),
"the containment's burial survived the ordinary hop behind it",
);
}
/// Did the severing refound vend `who` a key? Opens the base rotation and looks
/// for a blob at their locator.
async fn vended_to(bed: &TestBed, before: &CommunityV2, who: &Keys) -> bool {
let next = Epoch(before.root_epoch.0 + 1);
let group = base_rekey_group_key(&before.community_root, before.id(), next);
let chunks = fetch_rekey_chunks(&bed.relay, &before, &group).await.unwrap();
rekey::collect_rotations(&chunks).iter().any(|r| {
rekey::find_my_blobs(
&r.blobs,
&r.rotator.to_bytes(),
&who.public_key().to_bytes(),
RekeyScope::Root,
next,
)
.next()
.is_some()
})
}
/// Local guestbook row for `who`, claiming `at_ms` but OBSERVED at `seen`.
fn local_join_observed(who: &Keys, at_ms: u64, seen: u64, epoch: u64, tag: u8) -> guestbook::GuestbookEvent {
guestbook::GuestbookEvent {
rumor_id: [tag; 32],
entry: guestbook::GuestbookEntry::Join { member: who.public_key(), invited_by: None, at_ms },
epoch: Some(epoch),
observed_at: Some(seen),
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_backdated_join_cannot_slide_under_the_window_when_we_watched_it_arrive() {
// `at_ms` is author-claimed, so a raider can put it a year in the past and pass
// any window computed from the claim alone. What this client WATCHED arrive is
// not theirs to write.
let (bed, owner, _o) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Backdate", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let liar = Keys::generate();
// Claims it joined long before the window; we saw it arrive INSIDE the window.
let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let join = guestbook::build_join_rumor(liar.public_key(), None, 1_000);
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &liar, Timestamp::from_secs(1)).unwrap();
bed.relay.publish(&wrap, &bed.relays).await.unwrap();
crate::db::community::set_guestbook(&cid_hex, &[local_join_observed(&liar, 1_000, 9_000, community.root_epoch.0, 3)], 0).unwrap();
// We were following well before the window opened.
crate::db::settings::set_sql_setting(format!("gb_observed_since:{cid_hex}"), "100".into()).unwrap();
refound_community_severing(&bed.relay, &community, &[], 5_000).await.unwrap();
assert!(
!vended_to(&bed, &community, &liar).await,
"a backdated Join must not beat the arrival we watched with our own clock",
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_client_that_started_watching_late_evicts_nobody() {
// Same row, same claim, same observation — but this client only began following
// the guestbook AFTER the window opened, so everything looks new to it. Its
// observations prove nothing, and acting on them would evict the community.
let (bed, owner, _o) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "LateWatcher", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let quiet = Keys::generate();
let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let join = guestbook::build_join_rumor(quiet.public_key(), None, 1_000);
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &quiet, Timestamp::from_secs(1)).unwrap();
bed.relay.publish(&wrap, &bed.relays).await.unwrap();
crate::db::community::set_guestbook(&cid_hex, &[local_join_observed(&quiet, 1_000, 9_000, community.root_epoch.0, 4)], 0).unwrap();
// Coverage begins INSIDE the window — we were not here before it.
crate::db::settings::set_sql_setting(format!("gb_observed_since:{cid_hex}"), "7000".into()).unwrap();
refound_community_severing(&bed.relay, &community, &[], 5_000).await.unwrap();
assert!(
vended_to(&bed, &community, &quiet).await,
"without coverage predating the window our observations prove nothing — an \
old member must not be evicted for having been noticed late",
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_purge_vends_only_to_the_retain_list_however_late_a_stranger_arrives() {
// The Admin Terminal hands over a RETAIN list. Internally that used to become a
// removal list computed from the memberlist at one instant, while the refound
// fetched its own later — so an account appearing in between was on neither
// list and got a key by DEFAULT, implicitly retained by the purge meant to be
// exhaustive. An allow-list closes it with no window and nothing to backdate.
let (bed, owner, _o) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Purge", bed.relays.clone(), None).await.unwrap();
let kept = Keys::generate();
let stranger = Keys::generate();
let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
// The stranger even BACKDATES their Join — an allow-list does not care.
for (who, at_ms) in [(&kept, 2_000_000u64), (&stranger, 1_000u64)] {
let join = guestbook::build_join_rumor(who.public_key(), None, at_ms);
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, who, Timestamp::from_secs(at_ms / 1000)).unwrap();
bed.relay.publish(&wrap, &bed.relays).await.unwrap();
}
// The operator selected exactly one member. Nobody named the stranger.
refound_community_retaining(&bed.relay, &community, &[], &[kept.public_key()]).await.unwrap();
assert!(
vended_to(&bed, &community, &kept).await,
"the selected member keeps their key",
);
assert!(
!vended_to(&bed, &community, &stranger).await,
"an account not on the retain list is vended NO key, no matter when it \
appeared or what Join time it claims",
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_raid_window_joiner_is_vended_no_key_even_if_nobody_named_them() {
// The recipient set is a LIVE fetch taken AFTER the cut was computed, and
// re-taken on every retry. A bot arriving in that gap is in the memberlist and
// absent from the cut — and was handed a working key for the very epoch meant
// to evict it. Testing join TIME catches it with nobody naming it.
let (bed, owner, _o) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "RaceCut", bed.relays.clone(), None).await.unwrap();
let established = Keys::generate();
let late = Keys::generate();
let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
for (who, at_ms) in [(&established, 2_000_000u64), (&late, 9_000_000)] {
let join = guestbook::build_join_rumor(who.public_key(), None, at_ms);
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, who, Timestamp::from_secs(at_ms / 1000)).unwrap();
bed.relay.publish(&wrap, &bed.relays).await.unwrap();
}
// Window opens at 5_000s. `late` is named by NOBODY — the cut is empty.
refound_community_severing(&bed.relay, &community, &[], 5_000).await.unwrap();
assert!(
!vended_to(&bed, &community, &late).await,
"a raid-window joiner must be vended NO key, even when nobody named them",
);
assert!(
vended_to(&bed, &community, &established).await,
"and the member who was already here keeps theirs",
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_member_whose_join_is_not_on_the_plane_is_never_read_as_a_late_joiner() {
// THE regression that matters. A quiet member's Join lives on a buried epoch,
// so the reachable guestbook has no trace of them at all. Absence must read as
// OLD, never as new — reading it the other way shed 39 real members across five
// rotations. Here the Join exists ONLY locally, exactly as a buried one does.
let (bed, owner, _o) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Buried", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let quiet = Keys::generate();
let local_join = guestbook::GuestbookEvent {
rumor_id: [7u8; 32],
entry: guestbook::GuestbookEntry::Join { member: quiet.public_key(), invited_by: None, at_ms: 9_900_000 },
epoch: Some(community.root_epoch.0),
observed_at: None,
};
crate::db::community::set_guestbook(&cid_hex, &[local_join], 0).unwrap();
// Even stamped INSIDE the window, a Join the plane does not serve must not evict.
refound_community_severing(&bed.relay, &community, &[], 5_000).await.unwrap();
assert!(
vended_to(&bed, &community, &quiet).await,
"no Join on the reachable plane means OLD — absence of evidence must never evict",
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_member_who_rejoined_inside_the_window_is_not_cut() {
let (bed, owner, _other) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Rejoin", bed.relays.clone(), None).await.unwrap();
mint_public_link(&bed.relay, &community, "https://x", None, None).await.unwrap();
let veteran = Keys::generate();
let raider = Keys::generate();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
// The veteran's first Join, from an earlier epoch: held locally, gone from the plane.
let old = guestbook::GuestbookEvent {
epoch: Some(0),
observed_at: None,
rumor_id: [7u8; 32],
entry: guestbook::GuestbookEntry::Join { member: veteran.public_key(), invited_by: None, at_ms: 1_000_000 },
};
crate::db::community::store_guestbook_events(&cid_hex, &[old], 0).unwrap();
let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
for (who, at_ms) in [(&veteran, 9_000_000u64), (&raider, 9_500_000)] {
let join = guestbook::build_join_rumor(who.public_key(), None, at_ms);
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, who, Timestamp::from_secs(at_ms / 1000)).unwrap();
bed.relay.publish(&wrap, &bed.relays).await.unwrap();
}
let report = contain_raid(&bed.relay, community.id(), &[raider.public_key()], 5_000, &[]).await.unwrap();
assert_eq!(report.window_cut, 0, "the veteran's re-Join is not their arrival");
let updated = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let members = memberlist(&bed.relay, &updated).await.unwrap();
assert!(members.contains(&veteran.public_key()), "the veteran rides into the new epoch");
assert!(!members.contains(&raider.public_key()));
}
#[tokio::test(flavor = "multi_thread")]
async fn a_snapshot_a_raider_forged_does_not_date_their_arrival() {
let (bed, owner, _other) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Forged", bed.relays.clone(), None).await.unwrap();
mint_public_link(&bed.relay, &community, "https://x", None, None).await.unwrap();
let raider = Keys::generate();
let lurker = Keys::generate();
let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
for (who, at_ms) in [(&raider, 9_000_000u64), (&lurker, 9_500_000)] {
let join = guestbook::build_join_rumor(who.public_key(), None, at_ms);
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, who, Timestamp::from_secs(at_ms / 1000)).unwrap();
bed.relay.publish(&wrap, &bed.relays).await.unwrap();
}
// The lurker claims an ancient snapshot that already listed them.
for rumor in guestbook::build_snapshot_rumors(lurker.public_key(), &[lurker.public_key()], [9u8; 32], 1_000_000) {
let (wrap, _) = guestbook::seal_guestbook_rumor(&rumor, &gb, &lurker, Timestamp::from_secs(1_000)).unwrap();
bed.relay.publish(&wrap, &bed.relays).await.unwrap();
}
let report = contain_raid(&bed.relay, community.id(), &[raider.public_key()], 5_000, &[]).await.unwrap();
assert_eq!(report.window_cut, 1, "only someone who may rotate the base can vouch for an arrival");
let updated = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert!(!memberlist(&bed.relay, &updated).await.unwrap().contains(&lurker.public_key()));
}
#[tokio::test(flavor = "multi_thread")]
async fn contain_raid_bans_cuts_and_severs_end_to_end() {
let (bed, owner, _other) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Containment", bed.relays.clone(), None).await.unwrap();
let minted = mint_public_link(&bed.relay, &community, "https://x", None, None).await.unwrap();
// Three arrivals: an established member (before the window), a convicted
// raider and a quiet lurker (both inside it).
let established = Keys::generate();
let raider = Keys::generate();
let lurker = Keys::generate();
let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
for (who, at_ms) in [(&established, 2_000_000u64), (&raider, 9_000_000), (&lurker, 9_500_000)] {
let join = guestbook::build_join_rumor(who.public_key(), None, at_ms);
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, who, Timestamp::from_secs(at_ms / 1000)).unwrap();
bed.relay.publish(&wrap, &bed.relays).await.unwrap();
}
let report = contain_raid(&bed.relay, community.id(), &[raider.public_key()], 5_000, &[]).await.unwrap();
assert_eq!(report.banned, 1, "the convicted raider is banned");
assert_eq!(report.window_cut, 1, "the lurker who joined inside the window is cut");
assert!(report.refound_ok, "the severing refound landed: {:?}", report.warnings);
assert_eq!((report.epoch_before, report.epoch_after), (0, 1), "the root rolled");
assert_eq!(report.own_links_revoked, 1, "the door closed with it");
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let banlist = crate::db::community::get_community_banlist(&cid_hex).unwrap();
assert!(banlist.contains(&raider.public_key().to_hex()), "raider on the banlist");
assert!(!banlist.contains(&lurker.public_key().to_hex()), "the lurker is cut, never banned — they can rejoin through a fresh link");
assert!(!banlist.contains(&established.public_key().to_hex()));
assert!(
fetch_public_bundle(&bed.relay, &minted.url).await.unwrap_err().contains("revoked"),
"the invite URL the raid used is a grave",
);
// The rotation's recipient set is the severance line: the established
// member rides into the new epoch, the raider and the lurker do not.
let updated = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(updated.root_epoch, Epoch(1));
let members = memberlist(&bed.relay, &updated).await.unwrap();
assert!(members.contains(&established.public_key()), "established member survives");
assert!(!members.contains(&raider.public_key()), "raider gone");
}
#[tokio::test(flavor = "multi_thread")]
async fn adopting_someone_elses_rotation_refreshes_my_own_live_links() {
// CORD-05 §2: a link shared once keeps working across rotations, because
// its bundle is re-posted behind the same URL. The Refounder can only
// refresh the bundles they hold signer secrets for — their OWN — so
// every other creator has to heal their links when they ADOPT the
// rotation. Without that, an admin's links keep vending the superseded
// root and drop new joiners onto a dead epoch, which is precisely the
// stranding the stable-URL refresh exists to prevent.
let (bed, owner, me) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "LinkHeal", bed.relays.clone(), None).await.unwrap();
let rid = "b1".repeat(32);
// CREATE_INVITE too: minting is offer-gated by the same bit readers use.
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN | Permissions::CREATE_INVITE), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
// I mint a link of my own at the CURRENT epoch.
let minted = mint_public_link(&bed.relay, &joined, "https://x", None, None).await.unwrap();
let vended_before = fetch_public_bundle(&bed.relay, &minted.url).await.unwrap();
assert_eq!(vended_before.root_epoch, 0, "my link vends the epoch I minted it at");
// The OWNER re-founds. Their refresh can't touch my bundle: only I hold
// its signer secret.
let new_root = [0xD4; 32];
publish_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await;
let updated = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap().updated
.expect("the owner's Refounding is adopted");
assert_eq!(updated.root_epoch, Epoch(1), "I advanced to the new epoch");
let vended_after = fetch_public_bundle(&bed.relay, &minted.url).await.unwrap();
assert_eq!(vended_after.root_epoch, 1, "my link must now vend the NEW epoch, not strand its joiners");
assert_eq!(
crate::simd::hex::hex_to_bytes_32(&vended_after.community_root),
new_root,
"and the new root behind the same URL",
);
}
#[tokio::test]
async fn follow_rekeys_refuses_a_refounding_that_excludes_the_owner() {
// Authority escalation: a BAN-admin can't use a Refounding to evict the
// OWNER (no one outranks the owner). Excluding them makes the rotation
// inadmissible — members fork-reject it rather than migrate to the coup.
let (bed, owner, me) = TestBed::new();
let admin = Keys::generate();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "NoCoup", bed.relays.clone(), None).await.unwrap();
let rid = "b0".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid], 1).await;
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
// The admin re-founds delivering to me but NOT the owner — a takeover.
publish_base_rotation(&bed.relay, &joined, &admin, &[me.keys.public_key()], &[0xEE; 32], &joined.community_root).await;
let follow = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
assert!(follow.updated.is_none() && !follow.self_removed, "an owner-excluding Refounding is not adopted");
}
#[tokio::test]
async fn follow_rekeys_refuses_a_refounding_that_excludes_a_peer_admin() {
// Authority escalation: two equal-rank BAN-admins — neither strictly
// outranks the other, so one can't Refound the other out. Excluding a
// peer makes the rotation inadmissible.
let (bed, owner, me) = TestBed::new();
let admin_a = Keys::generate();
let admin_b = Keys::generate(); // the peer admin the rotation excludes.
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Peers", bed.relays.clone(), None).await.unwrap();
let rid = "b0".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
// Both A and B hold the SAME role (same position 1) → peers.
publish_grant(&bed.relay, &community, &owner.keys, &admin_a.public_key(), vec![rid.clone()], 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin_b.public_key(), vec![rid], 1).await;
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
// Admin A re-founds keeping the owner + me but EXCLUDING peer admin B.
publish_base_rotation(&bed.relay, &joined, &admin_a, &[owner.keys.public_key(), me.keys.public_key()], &[0xDD; 32], &joined.community_root).await;
let follow = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
assert!(follow.updated.is_none() && !follow.self_removed, "excluding an equal-rank peer admin is inadmissible");
}
#[tokio::test]
async fn a_retried_refounding_reuses_the_same_root() {
// B1 idempotency: minting for the same (scope, epoch) twice yields the SAME
// root, so a retried Refounding re-delivers one root — never a double-mint fork.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Retry", vec!["wss://r".into()], None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let first = mint_or_reuse_rotation_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 1).unwrap();
let second = mint_or_reuse_rotation_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 1).unwrap();
assert_eq!(first, second, "a retry reuses the archived root, never double-mints");
}
fn role_at(id: &str, name: &str, position: u32, bits: u64) -> Role {
Role { role_id: id.into(), name: name.into(), position, permissions: Permissions(bits), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() }
}
#[tokio::test]
async fn a_role_carrying_a_bit_its_author_lacks_never_folds_whatever_history_is_served() {
// CORD-04 §3, strict: a role carries only bits its author holds through roles above
// it, judged on the edition alone. Every reader reaches one verdict: the whole chain,
// the compacted head alone, or a device whose floor sits on the refused head.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Subset", vec!["wss://r".into()], None).await.unwrap();
let (mgr, banner) = (Keys::generate(), Keys::generate());
let (rmgr, rban_mgr, rban_bits) = ("a2".repeat(32), "a3".repeat(32), "a4".repeat(32));
publish_role(&relay, &community, &owner, &role_at(&rmgr, "Mgr", 2, Permissions::MANAGE_ROLES | Permissions::KICK), 1).await;
// The banner's authority spans two roles: MANAGE_ROLES from one, BAN from the next.
publish_role(&relay, &community, &owner, &role_at(&rban_mgr, "Bmgr", 3, Permissions::MANAGE_ROLES), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rban_bits, "Bbits", 4, Permissions::BAN), 1).await;
publish_grant(&relay, &community, &owner, &mgr.public_key(), vec![rmgr.clone()], 1).await;
publish_grant(&relay, &community, &owner, &banner.public_key(), vec![rban_mgr.clone(), rban_bits.clone()], 1).await;
let (kick_id, ban_id, ping_id, banner_minted) = ("b1".repeat(32), "b2".repeat(32), "b3".repeat(32), "b4".repeat(32));
publish_role(&relay, &community, &mgr, &role_at(&kick_id, "Kickers", 5, Permissions::KICK), 1).await;
publish_role(&relay, &community, &mgr, &role_at(&ban_id, "Banners", 6, Permissions::BAN), 1).await;
// A social bit the manager lacks: not every gated bit is a staff bit.
publish_role(&relay, &community, &mgr, &role_at(&ping_id, "Pingers", 6, Permissions::MENTION_EVERYONE), 1).await;
publish_role(&relay, &community, &banner, &role_at(&banner_minted, "Bans2", 6, Permissions::BAN), 1).await;
// An owner-made role with BAN beneath everyone, renamed at v2 by each of them.
let (renamed_by_mgr, renamed_by_banner) = ("c1".repeat(32), "c2".repeat(32));
for (id, by) in [(&renamed_by_mgr, &mgr), (&renamed_by_banner, &banner)] {
publish_role(&relay, &community, &owner, &role_at(id, "Original", 7, Permissions::BAN), 1).await;
publish_role(&relay, &community, by, &role_at(id, "Renamed", 7, Permissions::BAN), 2).await;
}
let editions = fetch_control(&relay, &community).await;
let full = fold_authority(&community, &editions, &load_floors(&community));
assert!(full.roles.role(&kick_id).is_some(), "a role carrying only held bits folds");
assert!(full.roles.role(&ban_id).is_none(), "a role carrying a bit its minter lacks never folds");
assert!(full.roles.role(&ping_id).is_none(), "nor one carrying a social bit they lack");
assert!(full.roles.role(&banner_minted).is_some(), "bits from every role above count, not just the highest");
assert_eq!(full.roles.role(&renamed_by_mgr).unwrap().name, "Original", "a manager without BAN can't rename a role that bans");
assert_eq!(full.roles.role(&renamed_by_banner).unwrap().name, "Renamed", "one holding BAN can");
// A fresh joiner after a Refounding holds only the heads.
let is_v1_of = |e: &ParsedEdition, ids: &[&String]| e.version == 1 && ids.contains(&&crate::simd::hex::bytes_to_hex_32(&e.entity_id));
let heads_only: Vec<ParsedEdition> = editions.iter().filter(|e| !is_v1_of(e, &[&renamed_by_mgr, &renamed_by_banner])).cloned().collect();
let fresh = fold_authority(&community, &heads_only, &load_floors(&community));
assert_eq!(fresh.roles.role(&renamed_by_banner).map(|r| r.name.as_str()), Some("Renamed"), "the same verdict from the head alone");
assert!(fresh.roles.role(&renamed_by_mgr).is_none(), "and the refused rename stays refused");
// A device whose floor sits on the refused v2 folds what a reader without it folds.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
follow_control(&relay, &community).await.unwrap();
let refused = editions.iter().find(|e| e.version == 2 && crate::simd::hex::bytes_to_hex_32(&e.entity_id) == renamed_by_mgr).unwrap();
crate::db::community::set_edition_head_at_epoch(&cid_hex, &renamed_by_mgr, 2, &refused.self_hash, &refused.inner_id, &mgr.public_key().to_bytes(), community.root_epoch.0).unwrap();
let tracked = fold_authority(&community, &editions, &load_floors(&community));
assert!(tracked.complete, "every floored head is served");
assert_eq!(tracked.roles.role(&renamed_by_mgr).map(|r| r.name.as_str()), Some("Original"), "the floor yields to the newest admitted edition");
let head = tracked.heads.iter().find(|h| h.entity_hex == renamed_by_mgr).unwrap();
assert!(head.rebased && head.version == 1);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
follow_control(&relay, &held).await.unwrap();
assert_eq!(floor_of(&community, &crate::simd::hex::hex_to_bytes_32_checked(&renamed_by_mgr).unwrap()).0, 1, "and the floor moves down to it");
}
#[tokio::test]
async fn the_fold_has_one_answer_whatever_else_a_reader_holds() {
// A role that props up its own authority made the fixpoint oscillate, so the round
// bound picked the phase and readers holding a different number of entities split.
// Downward support breaks the loop: B's MANAGE_ROLES comes from a role beneath R2.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Fixpoint", vec!["wss://r".into()], None).await.unwrap();
let (a, b) = (Keys::generate(), Keys::generate());
let (ra, r2, rb, r3) = ("d1".repeat(32), "d2".repeat(32), "d3".repeat(32), "d4".repeat(32));
publish_role(&relay, &community, &owner, &role_at(&ra, "RA", 3, Permissions::MANAGE_ROLES), 1).await;
publish_role(&relay, &community, &owner, &role_at(&r2, "R2", 5, Permissions::KICK), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rb, "RB", 4, 0), 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone(), r2.clone()], 1).await;
publish_role(&relay, &community, &a, &role_at(&r3, "R3", 6, Permissions::MANAGE_ROLES | Permissions::KICK), 1).await;
publish_grant(&relay, &community, &owner, &b.public_key(), vec![rb.clone(), r3.clone()], 1).await;
publish_role(&relay, &community, &b, &role_at(&r2, "R2", 5, 0), 2).await;
let editions = fetch_control(&relay, &community).await;
let floors = load_floors(&community);
let base = fold_authority(&community, &editions, &floors);
assert!(base.converged, "the fold settles rather than running out its bound");
assert!(base.roles.role(&r2).unwrap().permissions.contains(Permissions::KICK), "B can't strip R2 on authority from a role beneath it");
assert!(base.roles.roles_of(&b.public_key().to_hex()).any(|r| r.role_id == r3), "and B keeps R3");
// Unrelated extra entities change nothing about the rest.
let mut extra = editions.clone();
for (i, id) in ["d7", "d8", "d9"].iter().enumerate() {
publish_role(&relay, &community, &owner, &role_at(&id.repeat(32), "Extra", 9 + i as u32, 0), 1).await;
}
extra.extend(fetch_control(&relay, &community).await.into_iter().filter(|e| !editions.iter().any(|x| x.self_hash == e.self_hash)));
let more = fold_authority(&community, &extra, &floors);
let mut trimmed = more.roles.clone();
trimmed.roles.retain(|r| !["d7", "d8", "d9"].iter().any(|p| r.role_id == p.repeat(32)));
let fp = |roles: &crate::community::roles::CommunityRoles| {
let mut rs = roles.roles.clone();
rs.sort_by(|x, y| x.role_id.cmp(&y.role_id));
let mut gs = roles.grants.clone();
gs.sort_by(|x, y| x.member.cmp(&y.member));
serde_json::json!({ "roles": rs, "grants": gs }).to_string()
};
assert_eq!(fp(&trimmed), fp(&base.roles), "the roster is the same whatever else a reader holds");
}
#[tokio::test]
async fn a_strip_is_judged_against_the_rank_the_member_stood_at() {
// A grant edition acts on the member as the previous grant left them: a manager at 5
// can't rewrite the grant of a member a senior role puts at 2.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Standing", vec!["wss://r".into()], None).await.unwrap();
let (mgr, senior_member) = (Keys::generate(), Keys::generate().public_key());
let (rsen, rmgr, rlow) = ("a1".repeat(32), "a5".repeat(32), "a9".repeat(32));
publish_role(&relay, &community, &owner, &role_at(&rsen, "Senior", 2, 0), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rmgr, "Mgr", 5, Permissions::MANAGE_ROLES), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
publish_grant(&relay, &community, &owner, &senior_member, vec![rsen.clone()], 1).await;
publish_grant(&relay, &community, &owner, &mgr.public_key(), vec![rmgr.clone()], 1).await;
publish_grant(&relay, &community, &mgr, &senior_member, vec![rlow.clone()], 2).await;
// And a manager re-granting themselves only a lower role is acting on their own standing.
publish_grant(&relay, &community, &mgr, &mgr.public_key(), vec![rlow.clone()], 2).await;
let a = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
assert!(a.converged);
assert_eq!(a.roles.highest_position(&senior_member.to_hex()), Some(2), "the senior member keeps their rank");
assert_eq!(a.roles.highest_position(&mgr.public_key().to_hex()), Some(5), "nobody rewrites their own standing");
}
#[tokio::test]
async fn a_device_holding_a_floor_judges_its_head_with_the_full_chain_behind_it() {
// The floored version is replayed after its predecessors, so a tracking device
// judges it as a reader without the floor does.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Replay", vec!["wss://r".into()], None).await.unwrap();
let (x, m) = (Keys::generate(), Keys::generate().public_key());
let (rx, radm, rlow) = ("b1".repeat(32), "b2".repeat(32), "b6".repeat(32));
publish_role(&relay, &community, &owner, &role_at(&rx, "X", 1, Permissions::MANAGE_ROLES), 1).await;
publish_role(&relay, &community, &owner, &role_at(&radm, "Adm2", 2, 0), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 60, 0), 1).await;
publish_grant(&relay, &community, &owner, &x.public_key(), vec![rx.clone()], 1).await;
publish_grant(&relay, &community, &owner, &m, vec![radm.clone()], 1).await;
publish_grant(&relay, &community, &x, &m, vec![rlow.clone()], 2).await;
follow_control(&relay, &community).await.unwrap();
let geid = crate::community::v2::derive::grant_locator(community.id(), &m.to_bytes());
assert_eq!(floor_of(&community, &geid).0, 2, "everyone took X's v2 while X ranked at 1");
// X drops to 10: X's v2 no longer outranks the member as v1 left them.
publish_role(&relay, &community, &owner, &role_at(&rx, "X", 10, Permissions::MANAGE_ROLES), 2).await;
let editions = fetch_control(&relay, &community).await;
let cold = fold_authority(&community, &editions, &Default::default());
let tracked = fold_authority(&community, &editions, &load_floors(&community));
assert_eq!(cold.roles.highest_position(&m.to_hex()), Some(2), "a cold reader replays v1, then refuses v2");
assert_eq!(tracked.roles.highest_position(&m.to_hex()), Some(2), "the tracking device agrees");
assert!(tracked.heads.iter().any(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(&geid) && h.rebased && h.version == 1));
}
#[tokio::test]
async fn a_chain_refused_whole_on_complete_evidence_settles_and_locks_nothing() {
// Everything an admin authored alone falls when they lose the bit. On a complete
// fold that is a verdict, not a gap: the roster drops it, the cache moves on, and the
// owner can still manage the member it touched.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Settled", bed.relays.clone(), None).await.unwrap();
let admin = Keys::generate();
let member = Keys::generate().public_key();
let (radm, rmade) = ("c1".repeat(32), "c2".repeat(32));
publish_role(&bed.relay, &community, &owner.keys, &role_at(&radm, "Adm", 1, Permissions::MANAGE_ROLES), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![radm.clone()], 1).await;
publish_role(&bed.relay, &community, &admin, &role_at(&rmade, "Made", 5, 0), 1).await;
publish_grant(&bed.relay, &community, &admin, &member, vec![rmade.clone()], 1).await;
follow_control(&bed.relay, &community).await.unwrap();
let geid = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes()));
assert!(load_floors(&community).contains_key(&geid) && load_floors(&community).contains_key(&rmade));
// The admin is stripped: the role and the grant they authored have nothing left.
publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![], 2).await;
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
follow_control(&bed.relay, &held).await.unwrap();
let a = fold_authority(&held, &fetch_control(&bed.relay, &held).await, &load_floors(&held));
assert!(a.complete && a.refused.contains(&rmade) && a.refused.contains(&geid), "both settle as refused");
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let cached = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert!(cached.role(&rmade).is_none(), "the cached roster moves on");
// The owner manages the member without a "could not be fetched" lockout.
set_member_roles(&bed.relay, &held, &member, vec![radm.clone()]).await.expect("no lockout on a settled entity");
}
#[tokio::test]
async fn siblings_are_judged_together_so_a_low_claim_cant_lean_on_its_own_acceptance() {
// A version's siblings are judged at the strictest rank any of them claims. Judged
// apart, the sibling claiming 50 leaned on a role that exists only because the
// sibling claiming 4 was accepted, and the fixpoint cycled.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Siblings", vec!["wss://r".into()], None).await.unwrap();
let (x, a, b, c) = (Keys::generate(), Keys::generate(), Keys::generate(), Keys::generate());
let (xr, cos, admp, e, f) = ("d0".repeat(32), "d2".repeat(32), "d3".repeat(32), "de".repeat(32), "df".repeat(32));
let mr = Permissions::MANAGE_ROLES;
publish_role(&relay, &community, &owner, &role_at(&xr, "XR", 1, mr), 1).await;
publish_grant(&relay, &community, &owner, &x.public_key(), vec![xr.clone()], 1).await;
publish_role(&relay, &community, &x, &role_at(&cos, "COS", 2, 0), 1).await;
publish_role(&relay, &community, &x, &role_at(&admp, "ADM'", 3, mr), 1).await;
// E has two v1 siblings: A's at 4 and B's at 50, both carrying MR.
let e_eid = crate::simd::hex::hex_to_bytes_32_checked(&e).unwrap();
let role_json = |pos| crate::community::v2::roles::role_content_json(&role_at(&e, "E", pos, mr)).unwrap();
publish_grant(&relay, &community, &x, &a.public_key(), vec![admp.clone()], 1).await;
publish_role(&relay, &community, &c, &role_at(&f, "F", 20, mr), 1).await;
publish_grant(&relay, &community, &x, &b.public_key(), vec![cos.clone(), f.clone()], 1).await;
publish_grant(&relay, &community, &x, &c.public_key(), vec![e.clone()], 1).await;
publish_fork(&[&relay], &community, &a, vsk::ROLE, &e_eid, 1, None, &role_json(4), None).await;
publish_fork(&[&relay], &community, &b, vsk::ROLE, &e_eid, 1, None, &role_json(50), None).await;
let editions = fetch_control(&relay, &community).await;
let floors = load_floors(&community);
let first = fold_authority(&community, &editions, &floors);
assert!(first.converged, "the fold settles");
assert_eq!(first.roles.role(&e).map(|r| r.position), Some(4), "A's sibling, the one authority above 4 supports");
let reversed: Vec<ParsedEdition> = editions.iter().rev().cloned().collect();
let again = fold_authority(&community, &reversed, &floors);
assert_eq!(authority_fingerprint(&again), authority_fingerprint(&first), "in any order");
}
/// `mirror_control`, leaving out the editions `skip` names: a relay withholding them.
async fn mirror_control_except(from: &MemoryRelay, to: &MemoryRelay, community: &CommunityV2, skip: &dyn Fn(&ParsedEdition) -> bool) {
let group = control::ControlPlane::of(community).write_group().unwrap();
let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
for w in from.fetch(&query, &community.relays).await.unwrap() {
if control::open_control_edition(&w, &group).is_ok_and(|(ed, _)| !skip(&ed)) {
to.publish(&w, &community.relays).await.unwrap();
}
}
}
fn eid_of(id: &str) -> [u8; 32] {
crate::simd::hex::hex_to_bytes_32_checked(id).unwrap()
}
#[tokio::test]
async fn a_demotion_to_a_role_the_member_minted_settles() {
// A grant is judged on the roles it names, never on whether they resolve, or demoting
// A to a role only A's old rank supported makes each answer imply the other.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Demote", vec!["wss://r".into()], None).await.unwrap();
let a = Keys::generate();
let (r1, rmod) = ("f1".repeat(32), "f2".repeat(32));
publish_role(&relay, &community, &owner, &role_at(&r1, "R1", 1, Permissions::MANAGE_ROLES), 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![r1.clone()], 1).await;
publish_role(&relay, &community, &a, &role_at(&rmod, "Mod", 5, Permissions::MANAGE_ROLES), 1).await;
let before = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
assert!(before.converged && before.roles.role(&rmod).is_some(), "Mod folds while A holds R1");
follow_control(&relay, &community).await.unwrap();
publish_grant(&relay, &community, &owner, &a.public_key(), vec![rmod.clone()], 2).await;
let editions = fetch_control(&relay, &community).await;
let geid = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::grant_locator(community.id(), &a.public_key().to_bytes()));
let reversed: Vec<ParsedEdition> = editions.iter().rev().cloned().collect();
for (eds, floors) in [(&editions, Floors::default()), (&editions, load_floors(&community)), (&reversed, load_floors(&community))] {
let after = fold_authority(&community, eds, &floors);
assert!(after.converged, "the fold settles");
assert!(after.roles.role(&rmod).is_none(), "nothing above Mod supports it now");
assert_eq!(after.roles.roles_of(&a.public_key().to_hex()).count(), 0, "so A holds what v2 confers: nothing");
assert!(after.heads.iter().any(|h| h.entity_hex == geid && h.version == 2 && !h.rebased), "v2 is the head");
}
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
follow_control(&relay, &held).await.unwrap();
let cached = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
assert!(cached.role(&rmod).is_none() && cached.roles_of(&a.public_key().to_hex()).count() == 0, "and the cache moves on");
}
#[tokio::test]
async fn a_withheld_held_head_stops_what_would_be_judged_without_it() {
// A device judges the next edition against what its held one left. Withholding the
// held edition must not let a manager's edits be judged as if nothing stood there;
// the owner, who acts whatever the rank, still moves the entity.
let (_tmp, _guard, owner) = init_test_db();
let full = MemoryRelay::new();
let community = create_community(&full, "Withheld", vec!["wss://r".into()], None).await.unwrap();
let mgr = Keys::generate();
let senior = Keys::generate().public_key();
let (rsen, radm, rmgr, rlow) = ("a1".repeat(32), "a3".repeat(32), "a5".repeat(32), "a9".repeat(32));
publish_role(&full, &community, &owner, &role_at(&rsen, "Senior", 2, 0), 1).await;
publish_role(&full, &community, &owner, &role_at(&radm, "Adm", 3, Permissions::MANAGE_ROLES), 1).await;
publish_role(&full, &community, &owner, &role_at(&rmgr, "Mgr", 5, Permissions::MANAGE_ROLES), 1).await;
publish_role(&full, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
publish_grant(&full, &community, &owner, &mgr.public_key(), vec![rmgr.clone()], 1).await;
publish_grant(&full, &community, &owner, &senior, vec![rsen.clone()], 1).await;
follow_control(&full, &community).await.unwrap();
let geid = crate::community::v2::derive::grant_locator(community.id(), &senior.to_bytes());
let geid_hex = crate::simd::hex::bytes_to_hex_32(&geid);
let (g1, adm1) = (head_hash_on_relay(&full, &community, &geid).await.unwrap(), head_hash_on_relay(&full, &community, &eid_of(&radm)).await.unwrap());
// The manager demotes the senior member and moves Adm beneath themselves.
publish_grant(&full, &community, &mgr, &senior, vec![rlow.clone()], 2).await;
publish_role(&full, &community, &mgr, &role_at(&radm, "Adm", 8, Permissions::MANAGE_ROLES), 2).await;
let whole = fold_authority(&community, &fetch_control(&full, &community).await, &load_floors(&community));
assert_eq!(whole.roles.highest_position(&senior.to_hex()), Some(2), "on the whole plane both edits are refused");
assert_eq!(whole.roles.role(&radm).map(|r| r.position), Some(3));
let thin = MemoryRelay::new();
mirror_control_except(&full, &thin, &community, &|e| e.self_hash == g1 || e.self_hash == adm1).await;
let a = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
assert_ne!(a.roles.highest_position(&senior.to_hex()), Some(9), "the demotion is not judged against nothing");
assert!(a.roles.role(&radm).is_none_or(|r| r.position == 3), "nor the move");
assert!(!a.heads.iter().any(|h| h.entity_hex == geid_hex || h.entity_hex == radm), "neither entity advances");
assert!(a.gapped, "the device pages for the held editions");
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
follow_control(&thin, &held).await.unwrap();
let cached = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
assert_eq!(cached.highest_position(&senior.to_hex()), Some(2), "the cached roster keeps the senior member");
assert_eq!(cached.role(&radm).map(|r| r.position), Some(3));
assert_eq!((floor_of(&community, &geid).0, floor_of(&community, &eid_of(&radm)).0), (1, 1), "and the floors hold");
// Stacking a second edit on the first proves nothing: the first was judged blind.
publish_grant(&thin, &community, &mgr, &senior, vec![rlow.clone()], 3).await;
let m = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
assert!(!m.heads.iter().any(|h| h.entity_hex == geid_hex), "the manager's second edit doesn't advance it either");
// The owner's edit above the same withheld head moves it.
publish_grant(&thin, &community, &owner, &senior, vec![rlow.clone()], 4).await;
let o = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
assert!(o.heads.iter().any(|h| h.entity_hex == geid_hex && h.version == 4), "the owner acts regardless of rank");
assert_eq!(o.roles.highest_position(&senior.to_hex()), Some(9));
}
#[tokio::test]
async fn a_refused_held_head_falls_back_only_along_a_served_chain() {
// A refused held head falls back to what it stood on, walked down its own links. A
// relay withholding a link picks neither the target nor a verdict that it's gone.
let (_tmp, _guard, owner) = init_test_db();
let full = MemoryRelay::new();
let community = create_community(&full, "Walk", vec!["wss://r".into()], None).await.unwrap();
let (adm, member) = (Keys::generate(), Keys::generate().public_key());
let (radm, rhigh, rmid, rlow) = ("b1".repeat(32), "b3".repeat(32), "b4".repeat(32), "b9".repeat(32));
publish_role(&full, &community, &owner, &role_at(&radm, "Adm", 1, Permissions::MANAGE_ROLES), 1).await;
publish_role(&full, &community, &owner, &role_at(&rhigh, "High", 3, 0), 1).await;
publish_role(&full, &community, &owner, &role_at(&rmid, "Mid", 4, 0), 1).await;
publish_role(&full, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
publish_grant(&full, &community, &owner, &adm.public_key(), vec![radm.clone()], 1).await;
let geid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
let geid_hex = crate::simd::hex::bytes_to_hex_32(&geid);
publish_grant(&full, &community, &owner, &member, vec![rlow.clone()], 1).await;
let m1 = head_hash_on_relay(&full, &community, &geid).await.unwrap();
publish_grant(&full, &community, &owner, &member, vec![rhigh.clone()], 2).await;
let m2 = head_hash_on_relay(&full, &community, &geid).await.unwrap();
publish_grant(&full, &community, &adm, &member, vec![rhigh.clone(), rmid.clone()], 3).await;
follow_control(&full, &community).await.unwrap();
assert_eq!(floor_of(&community, &geid).0, 3);
// The admin is stripped, so their v3 no longer stands.
publish_grant(&full, &community, &owner, &adm.public_key(), vec![], 2).await;
let editions = fetch_control(&full, &community).await;
let floors = load_floors(&community);
let pick = |eds: Vec<ParsedEdition>| {
let a = fold_authority(&community, &eds, &floors);
(a.complete, a.heads.iter().find(|h| h.entity_hex == geid_hex).map(|h| (h.version, h.rebased)), a.refused.contains(&geid_hex))
};
let without = |hs: &[[u8; 32]]| editions.iter().filter(|e| !hs.contains(&e.self_hash)).cloned().collect::<Vec<_>>();
assert_eq!(pick(editions.clone()), (true, Some((2, true)), false), "the whole chain falls back to v2");
assert_eq!(pick(without(&[m2])), (true, Some((3, false)), false), "not past a withheld v2 to v1: v3 is kept");
assert_eq!(pick(without(&[m1, m2])), (true, Some((3, false)), false), "nor to a verdict that the grant is gone");
let thin = MemoryRelay::new();
mirror_control_except(&full, &thin, &community, &|e| e.self_hash == m2).await;
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
forget_held(&held);
follow_control(&thin, &held).await.unwrap();
assert_eq!(floor_of(&community, &geid).0, 3, "the floor holds on the thin read");
follow_control(&full, &held).await.unwrap();
assert_eq!(floor_of(&community, &geid).0, 2, "and moves to v2 on the whole one");
let cached = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
assert_eq!(cached.highest_position(&member.to_hex()), Some(3));
}
#[tokio::test]
async fn an_undecided_entity_is_carried_so_nothing_resting_on_it_moves() {
// C's authority runs through role Y. With Y undecided the device keeps Y as it holds
// it, so C's edit to X is judged as before rather than refused for Y's absence.
let (_tmp, _guard, owner) = init_test_db();
let full = MemoryRelay::new();
let community = create_community(&full, "Cascade", vec!["wss://r".into()], None).await.unwrap();
let (b, c) = (Keys::generate(), Keys::generate());
let (rb, ry, rx) = ("c1".repeat(32), "c2".repeat(32), "c6".repeat(32));
let mr = Permissions::MANAGE_ROLES;
publish_role(&full, &community, &owner, &role_at(&rb, "B", 1, mr), 1).await;
publish_role(&full, &community, &owner, &role_at(&ry, "Y", 2, mr), 1).await;
let y1 = head_hash_on_relay(&full, &community, &eid_of(&ry)).await.unwrap();
publish_role(&full, &community, &owner, &role_at(&rx, "X", 6, 0), 1).await;
publish_grant(&full, &community, &owner, &b.public_key(), vec![rb.clone()], 1).await;
publish_grant(&full, &community, &owner, &c.public_key(), vec![ry.clone()], 1).await;
publish_role(&full, &community, &b, &role_at(&ry, "Y2", 2, mr), 2).await;
publish_role(&full, &community, &c, &role_at(&rx, "X2", 6, 0), 2).await;
follow_control(&full, &community).await.unwrap();
publish_grant(&full, &community, &owner, &b.public_key(), vec![], 2).await;
let editions = fetch_control(&full, &community).await;
let floors = load_floors(&community);
let x_head = |a: &AuthoritySet| a.heads.iter().find(|h| h.entity_hex == rx).map(|h| (h.version, h.rebased));
let whole = fold_authority(&community, &editions, &floors);
assert!(whole.heads.iter().any(|h| h.entity_hex == ry && h.version == 1 && h.rebased), "Y falls back to the owner's v1");
assert_eq!(x_head(&whole), Some((2, false)), "so C keeps authority and X2 stands");
let thin: Vec<ParsedEdition> = editions.iter().filter(|e| e.self_hash != y1).cloned().collect();
let a = fold_authority(&community, &thin, &floors);
assert!(a.complete && a.carried.contains(&ry), "Y's fallback is withheld on the thin read");
assert!(a.heads.iter().any(|h| h.entity_hex == ry && h.version == 2 && !h.rebased) && a.roles.role(&ry).is_some_and(|r| r.name == "Y2"), "so it stays on its held head");
assert_eq!(x_head(&a), Some((2, false)), "and X stands");
// The rest of the roster still moves: B's strip reaches the cache.
let relay_thin = MemoryRelay::new();
mirror_control_except(&full, &relay_thin, &community, &|e| e.self_hash == y1).await;
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
forget_held(&held);
follow_control(&relay_thin, &held).await.unwrap();
let cached = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
assert_eq!(cached.roles_of(&b.public_key().to_hex()).count(), 0, "B's strip is cached");
assert!(cached.role(&ry).is_some_and(|r| r.name == "Y2"), "beside Y as this device holds it");
}
#[tokio::test]
async fn a_refused_head_with_nothing_to_fall_back_to_is_kept_and_a_ban_still_drops_it() {
// M's grant is all A's work, and A is demoted: the held head is refused and so is its
// predecessor, which may be a copy, so the device keeps the grant as it holds it.
// A ban is a verdict about M, and drops it.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Kept", vec!["wss://r".into()], None).await.unwrap();
let a = Keys::generate();
let m = Keys::generate().public_key();
let (radm, rmod, rhelp) = ("a1".repeat(32), "a5".repeat(32), "a6".repeat(32));
publish_role(&relay, &community, &owner, &role_at(&radm, "Adm", 1, Permissions::MANAGE_ROLES), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rmod, "Mod", 5, 0), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rhelp, "Helper", 6, 0), 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![radm.clone()], 1).await;
publish_grant(&relay, &community, &a, &m, vec![rmod.clone()], 1).await;
publish_grant(&relay, &community, &a, &m, vec![rmod.clone(), rhelp.clone()], 2).await;
follow_control(&relay, &community).await.unwrap();
publish_grant(&relay, &community, &owner, &a.public_key(), vec![], 2).await;
let gm = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::grant_locator(community.id(), &m.to_bytes()));
// A re-signed copy of the held edition, sorting first, is not the edition kept.
let gm_eid = crate::community::v2::derive::grant_locator(community.id(), &m.to_bytes());
let (held_content, held_prev, held_id) = content_at(&fetch_control(&relay, &community).await, &gm_eid, 2, &a.public_key());
publish_fork(&[&relay], &community, &Keys::generate(), vsk::GRANT, &gm_eid, 2, held_prev, &held_content, Some((std::cmp::Ordering::Less, held_id))).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
assert!(f.complete && f.carried.contains(&gm), "refused, nothing to fall back to: kept");
assert_eq!(f.heads.iter().find(|h| h.entity_hex == gm).map(|h| h.inner_id), Some(held_id), "the genuine edition, not the copy");
assert_eq!(f.roles.roles_of(&m.to_hex()).count(), 2);
assert!(f.heads.iter().any(|h| h.entity_hex == gm && h.version == 2 && !h.rebased), "on the held head");
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
follow_control(&relay, &held).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let cached = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert!(!cached.is_admin(&a.public_key().to_hex()) && cached.roles_of(&m.to_hex()).count() == 2, "and the cache moves on with it");
publish_banlist(&relay, &community, &owner, &[m.to_hex()], 1).await;
let b = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
assert!(b.refused.contains(&gm) && b.roles.roles_of(&m.to_hex()).count() == 0, "a banned member's kept grant goes");
}
#[tokio::test]
async fn a_fallback_target_must_stand_on_evidence_too() {
// The floor steps down only to an admitted predecessor that was itself judged with its
// own predecessor in hand: A2's v2 passes only when nobody can see the member stood
// above A2. A refused link is never stepped past, since it may be a re-signed copy.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Target", vec!["wss://r".into()], None).await.unwrap();
let (b, a2, member) = (Keys::generate(), Keys::generate(), Keys::generate().public_key());
let (rb, rsen, ra2, rlow) = ("e1".repeat(32), "e2".repeat(32), "e3".repeat(32), "e9".repeat(32));
let mr = Permissions::MANAGE_ROLES;
publish_role(&relay, &community, &owner, &role_at(&rb, "B", 1, mr), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rsen, "Senior", 2, 0), 1).await;
publish_role(&relay, &community, &owner, &role_at(&ra2, "A2", 3, mr), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
publish_grant(&relay, &community, &owner, &b.public_key(), vec![rb.clone()], 1).await;
publish_grant(&relay, &community, &owner, &a2.public_key(), vec![ra2.clone()], 1).await;
let geid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
let geid_hex = crate::simd::hex::bytes_to_hex_32(&geid);
publish_grant(&relay, &community, &owner, &member, vec![rsen.clone()], 1).await;
let m1 = head_hash_on_relay(&relay, &community, &geid).await.unwrap();
publish_grant(&relay, &community, &a2, &member, vec![rlow.clone()], 2).await;
publish_grant(&relay, &community, &b, &member, vec![rsen.clone()], 3).await;
follow_control(&relay, &community).await.unwrap();
assert_eq!(floor_of(&community, &geid).0, 3);
publish_grant(&relay, &community, &owner, &b.public_key(), vec![], 2).await;
let editions = fetch_control(&relay, &community).await;
let floors = load_floors(&community);
let head = |eds: &[ParsedEdition]| fold_authority(&community, eds, &floors).heads.into_iter().find(|h| h.entity_hex == geid_hex).map(|h| (h.version, h.rebased));
assert_eq!(head(&editions), Some((3, false)), "A2's v2 is refused, and the floor never steps past a refused link: v3 is kept");
let thin: Vec<ParsedEdition> = editions.iter().filter(|e| e.self_hash != m1).cloned().collect();
assert_eq!(head(&thin), Some((3, false)), "without v1, A2's v2 is no target either");
}
/// The content of the edition `signer` published for `entity` at `version`.
fn content_at(editions: &[ParsedEdition], entity: &[u8; 32], version: u64, signer: &PublicKey) -> (String, Option<[u8; 32]>, [u8; 32]) {
let e = editions.iter().find(|e| e.entity_id == *entity && e.version == version && e.author == *signer).expect("the edition");
(e.content.clone(), e.prev_hash, e.inner_id)
}
#[tokio::test]
async fn a_re_signed_copy_never_stands_in_for_a_withheld_grant() {
// A chain link names content, not a signer, so anyone writing the plane can serve a
// copy of an edition under their own key. It must count for nothing in place of the
// genuine one: neither a refused held head to fall back from, nor a predecessor's rank.
let (_tmp, _guard, owner) = init_test_db();
let full = MemoryRelay::new();
let community = create_community(&full, "Copies", vec!["wss://r".into()], None).await.unwrap();
let (a, mgr, senior) = (Keys::generate(), Keys::generate(), Keys::generate().public_key());
let (radm, rsen, rmgr, rlow) = ("a1".repeat(32), "a2".repeat(32), "a5".repeat(32), "a9".repeat(32));
publish_role(&full, &community, &owner, &role_at(&radm, "Adm", 1, Permissions::MANAGE_ROLES), 1).await;
publish_role(&full, &community, &owner, &role_at(&rsen, "Senior", 2, 0), 1).await;
publish_role(&full, &community, &owner, &role_at(&rmgr, "Mgr", 5, Permissions::MANAGE_ROLES), 1).await;
publish_role(&full, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
publish_grant(&full, &community, &owner, &mgr.public_key(), vec![rmgr.clone()], 1).await;
let (ga, gs) = (
crate::community::v2::derive::grant_locator(community.id(), &a.public_key().to_bytes()),
crate::community::v2::derive::grant_locator(community.id(), &senior.to_bytes()),
);
publish_grant(&full, &community, &owner, &a.public_key(), vec![radm.clone()], 1).await;
publish_grant(&full, &community, &owner, &a.public_key(), vec![], 2).await;
publish_grant(&full, &community, &owner, &senior, vec![rlow.clone()], 1).await;
publish_grant(&full, &community, &owner, &senior, vec![rsen.clone()], 2).await;
follow_control(&full, &community).await.unwrap();
assert_eq!((floor_of(&community, &ga).0, floor_of(&community, &gs).0), (2, 2));
// A re-signs the owner's strip of A; the manager re-signs the senior grant and builds
// a demotion on it. Relays withhold both genuine editions.
let editions = fetch_control(&full, &community).await;
let (strip, strip_prev, strip_id) = content_at(&editions, &ga, 2, &owner.public_key());
let (sen, sen_prev, sen_id) = content_at(&editions, &gs, 2, &owner.public_key());
let thin = MemoryRelay::new();
mirror_control_except(&full, &thin, &community, &|e| e.inner_id == strip_id || e.inner_id == sen_id).await;
publish_fork(&[&thin], &community, &a, vsk::GRANT, &ga, 2, strip_prev, &strip, None).await;
let copy = publish_fork(&[&thin], &community, &mgr, vsk::GRANT, &gs, 2, sen_prev, &sen, None).await;
let copied = fetch_control(&thin, &community).await;
let copy_hash = copied.iter().find(|e| e.inner_id == copy).unwrap().self_hash;
assert_eq!(copy_hash, editions.iter().find(|e| e.inner_id == sen_id).unwrap().self_hash, "the copy is the same link");
let demote = crate::community::v2::roles::grant_content_json(&MemberGrant { member: senior.to_hex(), role_ids: vec![rlow.clone()] }).unwrap();
publish_fork(&[&thin], &community, &mgr, vsk::GRANT, &gs, 3, Some(copy_hash), &demote, None).await;
let t = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
assert!(!t.roles.is_admin(&a.public_key().to_hex()), "the strip stands");
assert_ne!(t.roles.highest_position(&senior.to_hex()), Some(9), "and the copy carries no demotion");
assert!(!t.complete, "a copy is not the edition the device holds");
let ga_hex = crate::simd::hex::bytes_to_hex_32(&ga);
let gs_hex = crate::simd::hex::bytes_to_hex_32(&gs);
assert!(!t.heads.iter().any(|h| h.entity_hex == ga_hex || h.entity_hex == gs_hex), "neither entity moves");
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
follow_control(&thin, &held).await.unwrap();
assert_eq!((floor_of(&community, &ga).0, floor_of(&community, &gs).0), (2, 2), "the floors hold");
let cached = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
assert_eq!(cached.highest_position(&senior.to_hex()), Some(2), "and the cache keeps the senior member");
assert!(!cached.is_admin(&a.public_key().to_hex()));
}
#[tokio::test]
async fn a_re_signed_copy_never_stands_in_for_a_withheld_channel_edit() {
let (_tmp, _guard, owner) = init_test_db();
let full = MemoryRelay::new();
let community = create_community(&full, "ChanCopy", vec!["wss://r".into()], None).await.unwrap();
let ch = community.channels[0].id;
let v1 = head_hash_on_relay(&full, &community, &ch.0).await;
let real = publish_fork(&[&full], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("real"), None).await;
follow_control(&full, &community).await.unwrap();
let thin = MemoryRelay::new();
mirror_control_except(&full, &thin, &community, &|e| e.inner_id == real).await;
let stranger = Keys::generate();
publish_fork(&[&thin], &community, &stranger, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("real"), None).await;
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
follow_control(&thin, &held).await.unwrap();
let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(after.channel(&ch).unwrap().name, "real", "no rollback to the name before");
assert_eq!(floor_of(&community, &ch.0).0, 2);
}
#[tokio::test]
async fn a_sibling_that_fails_on_its_own_cannot_veto_the_version() {
// Siblings are judged at the strictest rank among them, but only among siblings that
// could stand: a stranger's sibling claiming the top rank must not refuse the rest.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Veto", vec!["wss://r".into()], None).await.unwrap();
let (a, z, member) = (Keys::generate(), Keys::generate(), Keys::generate().public_key());
let (rtop, radm, rmid, rlow) = ("b1".repeat(32), "b3".repeat(32), "b6".repeat(32), "b9".repeat(32));
publish_role(&relay, &community, &owner, &role_at(&rtop, "Top", 1, 0), 1).await;
publish_role(&relay, &community, &owner, &role_at(&radm, "Adm", 3, Permissions::MANAGE_ROLES), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rmid, "Mid", 6, 0), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![radm.clone()], 1).await;
let geid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
publish_grant(&relay, &community, &owner, &member, vec![rlow.clone()], 1).await;
let v1 = head_hash_on_relay(&relay, &community, &geid).await;
publish_grant(&relay, &community, &a, &member, vec![rmid.clone()], 2).await;
follow_control(&relay, &community).await.unwrap();
let claim_top = crate::community::v2::roles::grant_content_json(&MemberGrant { member: member.to_hex(), role_ids: vec![rtop.clone()] }).unwrap();
publish_fork(&[&relay], &community, &z, vsk::GRANT, &geid, 2, v1, &claim_top, None).await;
let editions = fetch_control(&relay, &community).await;
let gid = crate::simd::hex::bytes_to_hex_32(&geid);
for floors in [Floors::default(), load_floors(&community)] {
let f = fold_authority(&community, &editions, &floors);
assert!(f.converged);
assert_eq!(f.roles.highest_position(&member.to_hex()), Some(6), "A's edit stands");
let head = f.heads.iter().find(|h| h.entity_hex == gid).unwrap();
assert_eq!((head.version, head.author, head.rebased), (2, a.public_key().to_bytes(), false));
}
}
#[tokio::test]
async fn a_citation_settles_with_the_heads_it_reads() {
// A citation is checked against the heads of the round before, so a round where only
// a head moved isn't settled: A's role cites a re-issued grant whose content matches
// the original, and the fold must run one more round to admit it.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Heads", vec!["wss://r".into()], None).await.unwrap();
let (a, b, c) = (Keys::generate(), Keys::generate(), Keys::generate());
let (rc, rb, radm, rr) = ("c1".repeat(32), "c2".repeat(32), "c3".repeat(32), "c5".repeat(32));
let mr = Permissions::MANAGE_ROLES;
publish_role(&relay, &community, &owner, &role_at(&rc, "C", 1, mr), 1).await;
publish_grant(&relay, &community, &owner, &c.public_key(), vec![rc.clone()], 1).await;
publish_role(&relay, &community, &c, &role_at(&rb, "B", 2, mr), 1).await;
publish_grant(&relay, &community, &owner, &b.public_key(), vec![rb.clone()], 1).await;
publish_role(&relay, &community, &owner, &role_at(&radm, "Adm", 3, mr), 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![radm.clone()], 1).await;
publish_grant(&relay, &community, &b, &a.public_key(), vec![radm.clone()], 2).await;
publish_role(&relay, &community, &a, &role_at(&rr, "R", 5, 0), 1).await;
let editions = fetch_control(&relay, &community).await;
let reversed: Vec<ParsedEdition> = editions.iter().rev().cloned().collect();
for eds in [&editions, &reversed] {
let f = fold_authority(&community, eds, &Floors::default());
assert!(f.converged);
assert!(f.roles.role(&rr).is_some(), "the role citing the re-issued grant folds");
}
}
#[tokio::test]
async fn an_admin_edit_advances_a_head_whose_history_is_gone() {
// After a compaction the held head's predecessor is gone: the held edition is the
// device's baseline, so an admin's next edit is judged against it and advances.
let (_tmp, _guard, owner) = init_test_db();
let full = MemoryRelay::new();
let community = create_community(&full, "Baseline", vec!["wss://r".into()], None).await.unwrap();
let a = Keys::generate();
let (radm, rx) = ("d1".repeat(32), "d6".repeat(32));
publish_role(&full, &community, &owner, &role_at(&radm, "Adm", 1, Permissions::MANAGE_ROLES), 1).await;
publish_grant(&full, &community, &owner, &a.public_key(), vec![radm.clone()], 1).await;
publish_role(&full, &community, &owner, &role_at(&rx, "X", 6, 0), 1).await;
let x1 = head_hash_on_relay(&full, &community, &eid_of(&rx)).await.unwrap();
publish_role(&full, &community, &a, &role_at(&rx, "X2", 6, 0), 2).await;
follow_control(&full, &community).await.unwrap();
let thin = MemoryRelay::new();
mirror_control_except(&full, &thin, &community, &|e| e.self_hash == x1).await;
publish_role(&thin, &community, &a, &role_at(&rx, "X3", 6, 0), 3).await;
let f = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
assert_eq!(f.roles.role(&rx).map(|r| r.name.as_str()), Some("X3"));
assert!(f.heads.iter().any(|h| h.entity_hex == rx && h.version == 3 && !h.rebased));
}
#[tokio::test]
async fn an_uncited_strip_naming_a_made_up_role_is_still_a_strip() {
// An uncited grant may add a Role, never take one away, and naming a Role nobody
// published doesn't turn a strip into an addition.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Uncited", vec!["wss://r".into()], None).await.unwrap();
let mgr = Keys::generate();
let (m1, m2) = (Keys::generate().public_key(), Keys::generate().public_key());
let (rmgr, rlow, rlower) = ("e5".repeat(32), "e9".repeat(32), "ea".repeat(32));
publish_role(&relay, &community, &owner, &role_at(&rmgr, "Mgr", 5, Permissions::MANAGE_ROLES), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rlower, "Lower", 10, 0), 1).await;
publish_grant(&relay, &community, &owner, &mgr.public_key(), vec![rmgr.clone()], 1).await;
publish_grant(&relay, &community, &owner, &m1, vec![rlow.clone()], 1).await;
publish_grant(&relay, &community, &owner, &m2, vec![rlow.clone()], 1).await;
publish_grant_citing(&relay, &community, &mgr, &m1, vec!["ff".repeat(32)], 2, None).await;
publish_grant_citing(&relay, &community, &mgr, &m2, vec![rlow.clone(), rlower.clone()], 2, None).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
assert_eq!(f.roles.highest_position(&m1.to_hex()), Some(9), "the made-up role strips nothing");
assert_eq!(f.roles.roles_of(&m2.to_hex()).count(), 2, "an uncited addition stands");
}
#[tokio::test]
async fn an_edition_off_the_floors_chain_waits_for_its_link() {
// Above the floor only what the held edition's chain reaches folds: an edit naming a
// predecessor nobody serves is a gap, even from the owner, and the device pages for it.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Reach", vec!["wss://r".into()], None).await.unwrap();
let member = Keys::generate().public_key();
let (rmid, rlow) = ("f6".repeat(32), "f9".repeat(32));
publish_role(&relay, &community, &owner, &role_at(&rmid, "Mid", 6, 0), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
publish_grant(&relay, &community, &owner, &member, vec![rlow.clone()], 1).await;
publish_grant(&relay, &community, &owner, &member, vec![rmid.clone()], 2).await;
follow_control(&relay, &community).await.unwrap();
let geid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
let off = crate::community::v2::roles::grant_content_json(&MemberGrant { member: member.to_hex(), role_ids: vec![rlow.clone()] }).unwrap();
publish_fork(&[&relay], &community, &owner, vsk::GRANT, &geid, 3, Some([7u8; 32]), &off, None).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
let gid = crate::simd::hex::bytes_to_hex_32(&geid);
assert!(f.heads.iter().any(|h| h.entity_hex == gid && h.version == 2), "the held head stands");
assert_eq!(f.roles.highest_position(&member.to_hex()), Some(6));
assert!(f.gapped, "and the device pages for the missing link");
// A link names the version directly beneath it: skipping versions reaches nothing.
let skip = crate::community::v2::roles::grant_content_json(&MemberGrant { member: member.to_hex(), role_ids: vec![] }).unwrap();
let held = floor_of(&community, &geid);
assert_eq!(held.0, 2);
let eds = fetch_control(&relay, &community).await;
let h2 = eds.iter().find(|e| e.entity_id == geid && e.version == 2).unwrap().self_hash;
publish_fork(&[&relay], &community, &owner, vsk::GRANT, &geid, 5, Some(h2), &skip, None).await;
let g = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
assert!(g.heads.iter().any(|h| h.entity_hex == gid && h.version == 2), "a skipped version links nothing");
}
#[tokio::test]
async fn a_refounding_carries_the_genuine_head_never_a_newer_copy() {
// A copy re-signed under another key shares the head's hash and is served first.
// Compaction must carry the edition the floor records, or fresh joiners judge
// every head on the copier's authority.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "CopyCompact", bed.relays.clone(), None).await.unwrap();
let rid = crate::simd::hex::bytes_to_hex_32(&[0xa2; 32]);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid.clone()], 1).await;
follow_control(&bed.relay, &community).await.unwrap();
let copier = Keys::generate();
for e in fetch_control(&bed.relay, &community).await {
if e.vsk == vsk::ROLE || e.vsk == vsk::GRANT {
publish_fork(&[&bed.relay], &community, &copier, &e.vsk, &e.entity_id, e.version, e.prev_hash, &e.content, None).await;
}
}
let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
let fresh = fetch_control(&bed.relay, &refounded).await;
assert!(fresh.iter().filter(|e| e.vsk == vsk::ROLE || e.vsk == vsk::GRANT).all(|e| e.author == owner.keys.public_key()), "only the owner's editions are carried");
let joiner = fold_authority(&refounded, &fresh, &Floors::default());
assert!(joiner.roles.is_admin(&member.keys.public_key().to_hex()), "a fresh joiner folds the roster");
}
#[tokio::test]
async fn a_demoted_link_in_a_roles_chain_strands_no_device() {
// A edits R, B edits on top, then A is demoted. Whatever version a device holds, and
// a reader holding nothing, all land on B's edit.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Strand", vec!["wss://r".into()], None).await.unwrap();
let (a, b) = (Keys::generate(), Keys::generate());
let (ra, rb, rr) = ("b1".repeat(32), "b2".repeat(32), "b5".repeat(32));
let mr = Permissions::MANAGE_ROLES;
publish_role(&relay, &community, &owner, &role_at(&ra, "A", 1, mr), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rb, "B", 2, mr), 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
publish_grant(&relay, &community, &owner, &b.public_key(), vec![rb.clone()], 1).await;
publish_role(&relay, &community, &owner, &role_at(&rr, "R", 5, 0), 1).await;
publish_role(&relay, &community, &a, &role_at(&rr, "R2", 5, 0), 2).await;
publish_role(&relay, &community, &b, &role_at(&rr, "R3", 5, 0), 3).await;
follow_control(&relay, &community).await.unwrap();
publish_grant(&relay, &community, &owner, &a.public_key(), vec![], 2).await;
let editions = fetch_control(&relay, &community).await;
let base = load_floors(&community);
let at = |v: u64| {
let e = editions.iter().find(|e| crate::simd::hex::bytes_to_hex_32(&e.entity_id) == rr && e.version == v).unwrap();
let mut f = base.clone();
f.insert(rr.clone(), (v, e.self_hash, Some(e.inner_id), Some(e.author.to_bytes()), None));
f
};
for floors in [Floors::default(), at(1), at(2), at(3)] {
let f = fold_authority(&community, &editions, &floors);
assert_eq!(f.roles.role(&rr).map(|r| r.name.as_str()), Some("R3"), "every device lands on B's edit");
}
}
#[tokio::test]
async fn a_demoted_link_strands_no_channel_or_banlist() {
// The same for entities judged on their author alone: a refused edition still links
// what was built on it, so the floor reaches B's edit and nothing is left to page for.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "StrandChan", vec!["wss://r".into()], None).await.unwrap();
let (a, b) = (Keys::generate(), Keys::generate());
let (ra, rb) = ("c1".repeat(32), "c2".repeat(32));
let staff = Permissions::MANAGE_CHANNELS | Permissions::BAN;
publish_role(&relay, &community, &owner, &role_at(&ra, "A", 1, staff), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rb, "B", 2, staff), 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
publish_grant(&relay, &community, &owner, &b.public_key(), vec![rb.clone()], 1).await;
let (x, y, z) = (Keys::generate().public_key().to_hex(), Keys::generate().public_key().to_hex(), Keys::generate().public_key().to_hex());
publish_banlist(&relay, &community, &owner, &[x.clone()], 1).await;
follow_control(&relay, &community).await.unwrap();
let ch = community.channels[0].id;
// The refused link sits above the version that links straight to the floor.
let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
let hash_of = |id: [u8; 32], eds: Vec<ParsedEdition>| eds.into_iter().find(|e| e.inner_id == id).unwrap().self_hash;
let i2 = publish_fork(&[&relay], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("by-owner"), None).await;
let h2 = hash_of(i2, fetch_control(&relay, &community).await);
let i3 = publish_fork(&[&relay], &community, &a, vsk::CHANNEL_METADATA, &ch.0, 3, Some(h2), &channel_meta_json("by-a"), None).await;
let h3 = hash_of(i3, fetch_control(&relay, &community).await);
publish_fork(&[&relay], &community, &b, vsk::CHANNEL_METADATA, &ch.0, 4, Some(h3), &channel_meta_json("by-b"), None).await;
publish_banlist(&relay, &community, &a, &[x.clone(), y.clone()], 2).await;
publish_banlist(&relay, &community, &b, &[x.clone(), y.clone(), z.clone()], 3).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![], 2).await;
// An unlinked edition above everything, from someone without the bit, is no gap.
publish_fork(&[&relay], &community, &Keys::generate(), vsk::CHANNEL_METADATA, &ch.0, 9, Some([9u8; 32]), &channel_meta_json("junk"), None).await;
let editions = fetch_control(&relay, &community).await;
let floors = load_floors(&community);
assert_eq!(floors[&crate::simd::hex::bytes_to_hex_32(&ch.0)].0, 1, "the device holds the channel at v1");
let authority = fold_authority(&community, &editions, &floors);
assert!(authority.banned.contains(&z), "the banlist reaches B's edit");
let fold = apply_control_fold(&community, &editions, &floors, &authority);
assert_eq!(fold.updated.as_ref().and_then(|c| c.channel(&ch)).map(|c| c.name.as_str()), Some("by-b"));
assert!(!fold.gapped && !authority.gapped, "and nothing is left to page for");
}
#[tokio::test]
async fn a_future_stamp_never_freezes_the_roster_cache() {
// Signers pick their own `created_at`: the cache stamps from authorized heads only,
// clamped, and a stamp past any clock (an older build's) doesn't hold the cache back.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Stamp", vec!["wss://r".into()], None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let r1 = "d1".repeat(32);
publish_role(&relay, &community, &owner, &role_at(&r1, "R1", 3, 0), 1).await;
let year_2100 = 4_102_444_800u64;
publish_role_at(&relay, &community, &Keys::generate(), &role_at(&"d2".repeat(32), "Junk", 4, 0), 1, year_2100).await;
let soon = now_ms() / 1000 + 300;
publish_role_at(&relay, &community, &Keys::generate(), &role_at(&"d4".repeat(32), "Junk soon", 4, 0), 1, soon).await;
follow_control(&relay, &community).await.unwrap();
assert_eq!(crate::db::community::get_community_roles_at(&cid_hex).unwrap(), 1_000, "only authorized heads set the stamp");
let stored = crate::db::community::get_community_roles(&cid_hex).unwrap();
crate::db::community::set_community_roles(&cid_hex, &stored, year_2100 as i64).unwrap();
let r2 = "d3".repeat(32);
publish_role(&relay, &community, &owner, &role_at(&r2, "R2", 5, 0), 1).await;
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
follow_control(&relay, &held).await.unwrap();
assert!(crate::db::community::get_community_roles(&cid_hex).unwrap().role(&r2).is_some(), "the cache moves past it");
// An authorized head dated far ahead is clamped too.
publish_role_at(&relay, &community, &owner, &role_at(&"d5".repeat(32), "Ahead", 6, 0), 1, year_2100).await;
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
follow_control(&relay, &held).await.unwrap();
assert!(crate::db::community::get_community_roles_at(&cid_hex).unwrap() <= (now_ms() / 1000) as i64 + 600);
}
#[tokio::test]
async fn a_floor_without_its_signers_id_never_falls_back_from_a_copy() {
// A floor recorded before rumor ids were can't tell its edition from a copy, so a
// refused copy standing in for it never moves the entity down.
let (_tmp, _guard, owner) = init_test_db();
let full = MemoryRelay::new();
let community = create_community(&full, "Legacy", vec!["wss://r".into()], None).await.unwrap();
let member = Keys::generate().public_key();
let (rsen, rlow) = ("a2".repeat(32), "a9".repeat(32));
publish_role(&full, &community, &owner, &role_at(&rsen, "Senior", 2, 0), 1).await;
publish_role(&full, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
let gm = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
publish_grant(&full, &community, &owner, &member, vec![rlow.clone()], 1).await;
publish_grant(&full, &community, &owner, &member, vec![rsen.clone()], 2).await;
let ch = community.channels[0].id;
let v1 = head_hash_on_relay(&full, &community, &ch.0).await;
publish_fork(&[&full], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("real"), None).await;
follow_control(&full, &community).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let editions = fetch_control(&full, &community).await;
let (g2, ch2) = (
editions.iter().find(|e| e.entity_id == gm && e.version == 2).unwrap().clone(),
editions.iter().find(|e| e.entity_id == ch.0 && e.version == 2).unwrap().clone(),
);
let stranger = Keys::generate();
let thin = MemoryRelay::new();
mirror_control_except(&full, &thin, &community, &|e| e.inner_id == g2.inner_id || e.inner_id == ch2.inner_id).await;
publish_fork(&[&thin], &community, &stranger, vsk::GRANT, &gm, 2, g2.prev_hash, &g2.content, None).await;
publish_fork(&[&thin], &community, &stranger, vsk::CHANNEL_METADATA, &ch.0, 2, ch2.prev_hash, &ch2.content, None).await;
let mut floors = load_floors(&community);
for e in [&g2, &ch2] {
floors.insert(crate::simd::hex::bytes_to_hex_32(&e.entity_id), (2, e.self_hash, None, None, None));
}
let thin_eds = fetch_control(&thin, &community).await;
let a = fold_authority(&held, &thin_eds, &floors);
assert!(a.complete);
assert_eq!(a.roles.highest_position(&member.to_hex()), Some(2), "no step down to v1");
let fold = apply_control_fold(&held, &thin_eds, &floors, &a);
assert!(!fold.heads.iter().any(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(&ch.0) && h.rebased), "nor for the channel");
assert_eq!(fold.updated.as_ref().unwrap_or(&held).channel(&ch).unwrap().name, "real");
}
#[tokio::test]
async fn a_side_branch_cannot_start_a_role_or_grant_over_from_nothing() {
// An edition acts on what the newest admitted version left, not on what its own
// `prev` names: a manager naming no predecessor at a high version is judged against
// the role and the member as they stand.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Branch", vec!["wss://r".into()], None).await.unwrap();
let w = Keys::generate();
let senior = Keys::generate().public_key();
let (radm, rsen, rw, rlow) = ("a2".repeat(32), "a3".repeat(32), "a8".repeat(32), "a9".repeat(32));
let mr = Permissions::MANAGE_ROLES;
publish_role(&relay, &community, &owner, &role_at(&radm, "Admin", 2, mr | Permissions::BAN), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rsen, "Senior", 3, 0), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rw, "W", 8, mr), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
publish_grant(&relay, &community, &owner, &w.public_key(), vec![rw.clone()], 1).await;
publish_grant(&relay, &community, &owner, &senior, vec![rsen.clone()], 1).await;
follow_control(&relay, &community).await.unwrap();
let gs = crate::community::v2::derive::grant_locator(community.id(), &senior.to_bytes());
let neutered = crate::community::v2::roles::role_content_json(&role_at(&radm, "Admin", 50, 0)).unwrap();
publish_fork(&[&relay], &community, &w, vsk::ROLE, &eid_of(&radm), 1_000_000, None, &neutered, None).await;
let strip = crate::community::v2::roles::grant_content_json(&MemberGrant { member: senior.to_hex(), role_ids: vec![rlow.clone()] }).unwrap();
publish_fork(&[&relay], &community, &w, vsk::GRANT, &gs, 1_000_000, None, &strip, None).await;
// On a tracker, a branch at the held version with a successor on top.
let s_id = publish_fork(&[&relay], &community, &w, vsk::ROLE, &eid_of(&radm), 1, None, &neutered, None).await;
let s_hash = fetch_control(&relay, &community).await.into_iter().find(|e| e.inner_id == s_id).unwrap().self_hash;
publish_fork(&[&relay], &community, &w, vsk::ROLE, &eid_of(&radm), 2, Some(s_hash), &neutered, None).await;
let editions = fetch_control(&relay, &community).await;
for floors in [Floors::default(), load_floors(&community)] {
let f = fold_authority(&community, &editions, &floors);
assert_eq!(f.roles.role(&radm).map(|r| r.position), Some(2), "the Admin role stands");
assert_eq!(f.roles.highest_position(&senior.to_hex()), Some(3), "and so does the senior member");
}
}
#[tokio::test]
async fn an_owner_edit_on_a_refused_channel_head_moves_it_on() {
// A demoted admin's channel edit is the device's held head; the owner then edits on
// top of it. The owner's edit is the head, with no step down and nothing to page for.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "OnTop", vec!["wss://r".into()], None).await.unwrap();
let a = Keys::generate();
let ra = "c1".repeat(32);
publish_role(&relay, &community, &owner, &role_at(&ra, "A", 1, Permissions::MANAGE_CHANNELS), 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
let ch = community.channels[0].id;
let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
publish_fork(&[&relay], &community, &a, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("by-a"), None).await;
follow_control(&relay, &community).await.unwrap();
assert_eq!(floor_of(&community, &ch.0).0, 2);
publish_grant(&relay, &community, &owner, &a.public_key(), vec![], 2).await;
let v2 = head_hash_on_relay(&relay, &community, &ch.0).await;
publish_fork(&[&relay], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 3, v2, &channel_meta_json("by-owner"), None).await;
let editions = fetch_control(&relay, &community).await;
let floors = load_floors(&community);
let authority = fold_authority(&community, &editions, &floors);
assert!(authority.complete);
let fold = apply_control_fold(&community, &editions, &floors, &authority);
let head = fold.heads.iter().find(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(&ch.0)).unwrap();
assert_eq!((head.version, head.rebased), (3, false), "the owner's edit, not a step down");
assert_eq!(fold.updated.as_ref().and_then(|c| c.channel(&ch)).map(|c| c.name.as_str()), Some("by-owner"));
assert!(!fold.gapped);
}
#[tokio::test]
async fn copies_of_compacted_history_never_veto_the_head() {
// After a compaction the head's history is gone; copies of it re-signed by someone
// else prove nothing, so they can't make the head stricter than it is on its own.
let (_tmp, _guard, owner) = init_test_db();
let full = MemoryRelay::new();
let community = create_community(&full, "NoVeto", vec!["wss://r".into()], None).await.unwrap();
let a = Keys::generate();
let m = Keys::generate().public_key();
let (radm, ra, rmod, rhelp) = ("d2".repeat(32), "d5".repeat(32), "da".repeat(32), "d7".repeat(32));
publish_role(&full, &community, &owner, &role_at(&radm, "Admin", 2, 0), 1).await;
publish_role(&full, &community, &owner, &role_at(&ra, "A", 5, Permissions::MANAGE_ROLES), 1).await;
publish_role(&full, &community, &owner, &role_at(&rhelp, "Helper", 7, 0), 1).await;
publish_role(&full, &community, &owner, &role_at(&rmod, "Mod", 10, 0), 1).await;
publish_grant(&full, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
let gm = crate::community::v2::derive::grant_locator(community.id(), &m.to_bytes());
publish_grant(&full, &community, &owner, &m, vec![radm.clone()], 1).await;
publish_grant(&full, &community, &owner, &m, vec![rmod.clone()], 2).await;
publish_grant(&full, &community, &a, &m, vec![rhelp.clone()], 3).await;
let editions = fetch_control(&full, &community).await;
let history: Vec<&ParsedEdition> = editions.iter().filter(|e| e.entity_id == gm && e.version < 3).collect();
let thin = MemoryRelay::new();
mirror_control_except(&full, &thin, &community, &|e| e.entity_id == gm && e.version < 3).await;
let copier = Keys::generate();
for e in &history {
publish_fork(&[&thin], &community, &copier, vsk::GRANT, &gm, e.version, e.prev_hash, &e.content, None).await;
}
let f = fold_authority(&community, &fetch_control(&thin, &community).await, &Floors::default());
assert_eq!(f.roles.highest_position(&m.to_hex()), Some(7), "the head stands on its own claims");
}
#[tokio::test]
async fn refused_or_unauthorized_editions_leave_nothing_to_page_for() {
// A banlist held from a since-demoted moderator, with nothing newer to reach, and a
// stranger's unlinked junk above a tracked role: neither is a gap.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "NoGap", vec!["wss://r".into()], None).await.unwrap();
let moder = Keys::generate();
let (rm, rr) = ("e1".repeat(32), "e6".repeat(32));
publish_role(&relay, &community, &owner, &role_at(&rm, "Mod", 1, Permissions::BAN), 1).await;
publish_grant(&relay, &community, &owner, &moder.public_key(), vec![rm.clone()], 1).await;
publish_role(&relay, &community, &owner, &role_at(&rr, "R", 6, 0), 1).await;
let x = Keys::generate().public_key().to_hex();
publish_banlist(&relay, &community, &owner, &[], 1).await;
publish_banlist(&relay, &community, &moder, &[x.clone()], 2).await;
follow_control(&relay, &community).await.unwrap();
publish_grant(&relay, &community, &owner, &moder.public_key(), vec![], 2).await;
let junk = crate::community::v2::roles::role_content_json(&role_at(&rr, "Junk", 6, 0)).unwrap();
publish_fork(&[&relay], &community, &Keys::generate(), vsk::ROLE, &eid_of(&rr), 9, Some([3u8; 32]), &junk, None).await;
let a = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
assert!(!a.gapped, "nothing to page for");
assert_eq!(a.roles.role(&rr).map(|r| r.name.as_str()), Some("R"));
}
#[tokio::test]
async fn only_the_owner_stands_in_for_a_withheld_held_role_edit() {
// Without the held edition its claims are unknown, so a better-ranked rival can't be
// judged against them: a relay withholding C's move can't swap in P's.
let (_tmp, _guard, owner) = init_test_db();
let full = MemoryRelay::new();
let community = create_community(&full, "Rival", vec!["wss://r".into()], None).await.unwrap();
let (c, p) = (Keys::generate(), Keys::generate());
let (rcos, rc, rpm, rr) = ("f1".repeat(32), "f2".repeat(32), "f7".repeat(32), "fa".repeat(32));
let mr = Permissions::MANAGE_ROLES;
publish_role(&full, &community, &owner, &role_at(&rcos, "Cosmetic", 1, 0), 1).await;
publish_role(&full, &community, &owner, &role_at(&rc, "C", 2, mr), 1).await;
publish_role(&full, &community, &owner, &role_at(&rpm, "P", 7, mr), 1).await;
publish_grant(&full, &community, &owner, &c.public_key(), vec![rc.clone()], 1).await;
publish_grant(&full, &community, &owner, &p.public_key(), vec![rcos.clone(), rpm.clone()], 1).await;
publish_role(&full, &community, &owner, &role_at(&rr, "R", 10, 0), 1).await;
let v1 = head_hash_on_relay(&full, &community, &eid_of(&rr)).await;
let moved = crate::community::v2::roles::role_content_json(&role_at(&rr, "R", 5, 0)).unwrap();
let held = publish_fork(&[&full], &community, &c, vsk::ROLE, &eid_of(&rr), 2, v1, &moved, None).await;
follow_control(&full, &community).await.unwrap();
assert_eq!(floor_of(&community, &eid_of(&rr)).1, Some(held));
let thin = MemoryRelay::new();
mirror_control_except(&full, &thin, &community, &|e| e.inner_id == held).await;
let down = crate::community::v2::roles::role_content_json(&role_at(&rr, "R", 11, 0)).unwrap();
publish_fork(&[&thin], &community, &p, vsk::ROLE, &eid_of(&rr), 2, v1, &down, None).await;
let a = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
assert_ne!(a.roles.role(&rr).map(|r| r.position), Some(11), "P's rival does not stand in");
let held_c = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
follow_control(&thin, &held_c).await.unwrap();
assert_eq!(floor_of(&community, &eid_of(&rr)).1, Some(held), "and the floor keeps C's edit");
}
#[tokio::test]
async fn a_refounding_never_launders_a_kept_head() {
// E's rename chain is the tracker's held head until S's sibling makes it refused; the
// tracker keeps it. A Refounding must carry what a floorless reader folds, S's move,
// or the new epoch reads E's rename on its own and S's decision is lost.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Launder", bed.relays.clone(), None).await.unwrap();
let (e, sk) = (Keys::generate(), Keys::generate());
let (rs, re, rr) = ("a2".repeat(32), "a4".repeat(32), "a6".repeat(32));
let mr = Permissions::MANAGE_ROLES;
publish_role(&bed.relay, &community, &owner.keys, &role_at(&rs, "S", 2, mr), 1).await;
publish_role(&bed.relay, &community, &owner.keys, &role_at(&re, "E", 4, mr), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &sk.public_key(), vec![rs.clone()], 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &e.public_key(), vec![re.clone()], 1).await;
publish_role(&bed.relay, &community, &owner.keys, &role_at(&rr, "R", 6, 0), 1).await;
let v1 = head_hash_on_relay(&bed.relay, &community, &eid_of(&rr)).await;
publish_role(&bed.relay, &community, &e, &role_at(&rr, "R by E", 6, 0), 2).await;
publish_role(&bed.relay, &community, &e, &role_at(&rr, "R by E again", 6, 0), 3).await;
follow_control(&bed.relay, &community).await.unwrap();
assert_eq!(floor_of(&community, &eid_of(&rr)).0, 3);
let up = crate::community::v2::roles::role_content_json(&role_at(&rr, "R by S", 3, 0)).unwrap();
publish_fork(&[&bed.relay], &community, &sk, vsk::ROLE, &eid_of(&rr), 2, v1, &up, None).await;
let a = fold_authority(&community, &fetch_control(&bed.relay, &community).await, &load_floors(&community));
assert!(a.carried.contains(&rr), "the tracker keeps E's refused head");
let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
let fresh = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &Floors::default());
assert_eq!(fresh.roles.role(&rr).map(|r| r.name.as_str()), Some("R by S"), "the new epoch carries S's move");
}
#[tokio::test]
async fn a_refounding_never_carries_a_refused_control_head_it_keeps() {
// A Mod renamed the Community twice and then lost the bit: the tracker keeps the second
// rename, its predecessor refused too. The new epoch must read the owner's name, never
// the kept rename re-wrapped as if it stood (CORD-06 §3).
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Original", bed.relays.clone(), None).await.unwrap();
let mod_key = Keys::generate();
let rm = "d2".repeat(32);
let bits = Permissions::MANAGE_METADATA | Permissions::MANAGE_CHANNELS;
publish_role(&bed.relay, &community, &owner.keys, &role_at(&rm, "Mod", 2, bits), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &mod_key.public_key(), vec![rm.clone()], 1).await;
publish_community_meta(&bed.relay, &community, &mod_key, "By Mod", 2).await;
publish_community_meta(&bed.relay, &community, &mod_key, "By Mod again", 3).await;
let channel = ChannelId([0xd7; 32]);
publish_fork(&[&bed.relay], &community, &mod_key, vsk::CHANNEL_METADATA, &channel.0, 1, None, &channel_meta_json("mods"), None).await;
follow_control(&bed.relay, &community).await.unwrap();
assert_eq!(floor_of(&community, &community.id().0).0, 3);
assert_eq!(floor_of(&community, &channel.0).0, 1);
publish_grant(&bed.relay, &community, &owner.keys, &mod_key.public_key(), vec![], 2).await;
follow_control(&bed.relay, &community).await.unwrap();
let eds = fetch_control(&bed.relay, &community).await;
let floors = load_floors(&community);
let tracked = apply_control_fold(&community, &eds, &floors, &fold_authority(&community, &eds, &floors));
assert!(tracked.kept.contains(&crate::simd::hex::bytes_to_hex_32(&community.id().0)), "the tracker keeps the refused rename");
assert!(tracked.kept.contains(&crate::simd::hex::bytes_to_hex_32(&channel.0)), "and the refused Channel");
let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
let carried = fetch_control(&bed.relay, &refounded).await;
assert!(carried.iter().all(|e| e.author != mod_key.public_key()), "nothing the Roster refuses crosses");
let fresh = apply_control_fold(&refounded, &carried, &Floors::default(), &fold_authority(&refounded, &carried, &Floors::default()));
let meta = fresh.heads.iter().find(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(&community.id().0)).expect("a metadata head crosses");
let content = &carried.iter().find(|e| e.inner_id == meta.inner_id).unwrap().content;
assert_eq!(serde_json::from_str::<control::CommunityMetadata>(content).unwrap().name, "Original", "the head a floorless reader folds");
}
#[tokio::test]
async fn a_demoted_mods_rename_stands_through_a_refounding() {
// A demotion seals what the Mod decided before it lands (CORD-04 §9), so the rename stands
// for every reader, a fresh joiner of the next epoch included.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Original", bed.relays.clone(), None).await.unwrap();
publish_everyone(&bed.relay, &community, &owner.keys, 0, 1).await;
let mod_key = Keys::generate();
let rm = "d6".repeat(32);
publish_role_v2(&bed.relay, &community, &owner.keys, &role_v2(&rm, "Mod", "F", Permissions::MANAGE_METADATA), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &mod_key.public_key(), vec![rm.clone()], 1).await;
publish_community_meta(&bed.relay, &community, &mod_key, "By Mod", 2).await;
publish_community_meta(&bed.relay, &community, &mod_key, "By Mod again", 3).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(held().name, "By Mod again");
grant_roles(&bed.relay, &held(), &mod_key.public_key(), vec![]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let eds = fetch_control(&bed.relay, &held()).await;
assert!(eds.iter().any(|e| e.vsk == vsk::TENURE), "the demotion wrote a Tenure");
assert_eq!(fold_authority(&held(), &eds, &load_floors(&held())).roles.roles_of(&mod_key.public_key().to_hex()).count(), 0, "the Mod holds no Role");
assert_eq!(held().name, "By Mod again", "and the rename stands for this member");
let refounded = refound_community(&bed.relay, &held(), &[]).await.unwrap();
let carried = fetch_control(&bed.relay, &refounded).await;
let fresh = apply_control_fold(&refounded, &carried, &Floors::default(), &fold_authority(&refounded, &carried, &Floors::default()));
let meta = fresh.heads.iter().find(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(&community.id().0)).expect("a metadata head crosses");
let head = carried.iter().find(|e| e.inner_id == meta.inner_id).unwrap();
assert_eq!(head.author, mod_key.public_key());
assert_eq!(serde_json::from_str::<control::CommunityMetadata>(&head.content).unwrap().name, "By Mod again", "and for a fresh joiner of the new epoch");
}
/// Every edition a follow's read holds, against a fresh open of the same wrap.
async fn read_as_fresh_opens_read(relay: &MemoryRelay, community: &CommunityV2, step: &str) {
let read = read_control(relay, community).await.unwrap();
let fresh: std::collections::HashMap<[u8; 32], String> = fetch_control(relay, community).await.iter().map(|e| (e.inner_id, format!("{e:?}"))).collect();
assert!(!read.editions.is_empty(), "{step}: the read found the plane");
for e in &read.editions {
assert_eq!(fresh.get(&e.inner_id), Some(&format!("{e:?}")), "{step}: an edition the follow read differs from its fresh open");
}
}
#[tokio::test]
async fn a_follow_reads_what_fresh_opens_read_through_every_kind_of_change() {
// Each change arrives as new wraps; the memo serves only wraps the relay serves again,
// as their own open would. So after any change a follow sees what a cold read does.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Churn", bed.relays.clone(), None).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
follow_control(&bed.relay, &held()).await.unwrap();
read_as_fresh_opens_read(&bed.relay, &held(), "created").await;
let view = control::ControlPlane::of(&held());
let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![view.pk().to_hex()], limit: Some(500), ..Default::default() };
let before = bed.relay.fetch(&q, &held().relays).await.unwrap();
assert!(before.iter().all(|w| control::opened_held(&view, w)), "the follow kept every open");
grant_admin(&bed.relay, &held(), &a).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
read_as_fresh_opens_read(&bed.relay, &held(), "granted").await;
assert!(crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap().grants.iter().any(|g| g.member == a.to_hex()));
let renamed = control::CommunityMetadata { name: "Churned".into(), ..held().metadata() };
edit_community_metadata(&bed.relay, &held(), &renamed).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
read_as_fresh_opens_read(&bed.relay, &held(), "renamed").await;
assert_eq!(held().name, "Churned");
let ch = create_channel_in(&bed.relay, &held(), "side", false, None).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
read_as_fresh_opens_read(&bed.relay, &held(), "channel created").await;
assert!(held().channel(&ch).is_some());
set_banlist(&bed.relay, &held(), &[b.to_hex()]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
read_as_fresh_opens_read(&bed.relay, &held(), "banned").await;
assert!(crate::db::community::get_community_banlist(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap().contains(&b.to_hex()));
kick_member(&bed.relay, &held(), &a).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
read_as_fresh_opens_read(&bed.relay, &held(), "kicked").await;
grant_roles(&bed.relay, &held(), &a, vec![]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
read_as_fresh_opens_read(&bed.relay, &held(), "revoked").await;
assert!(crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap().grants.iter().all(|g| g.member != a.to_hex() || g.role_ids.is_empty()));
delete_channel(&bed.relay, &held(), &ch, "side").await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
read_as_fresh_opens_read(&bed.relay, &held(), "channel deleted").await;
assert!(held().channel(&ch).is_none());
set_banlist(&bed.relay, &held(), &[]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
read_as_fresh_opens_read(&bed.relay, &held(), "unbanned").await;
assert!(crate::db::community::get_community_banlist(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap().is_empty());
// And the fold over what the follow read equals one over fresh opens, end to end.
let floors = load_floors(&held());
let read = read_control(&bed.relay, &held()).await.unwrap();
control::forget_opened();
let cold = read_control(&bed.relay, &held()).await.unwrap();
assert_eq!(authority_whole(&read.authority), authority_whole(&cold.authority));
assert_eq!(format!("{:?}", read.fold.updated.map(|c| c.metadata())), format!("{:?}", cold.fold.updated.map(|c| c.metadata())));
assert_eq!(authority_whole(&fold_authority(&held(), &read.editions, &floors)), authority_whole(&fold_authority(&held(), &cold.editions, &floors)));
}
#[tokio::test]
async fn opened_control_editions_stay_with_the_account_that_opened_them() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Mine", bed.relays.clone(), None).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let view = control::ControlPlane::of(&community);
let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![view.pk().to_hex()], limit: Some(500), ..Default::default() };
let wraps = bed.relay.fetch(&q, &community.relays).await.unwrap();
assert!(wraps.iter().any(|w| control::opened_held(&view, w)));
bed.swap_to(&member);
assert!(!wraps.iter().any(|w| control::opened_held(&view, w)), "another account's session holds none of them");
}
#[tokio::test]
async fn a_roster_fold_that_runs_out_its_bound_keeps_nothing_it_judged() {
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Bound", bed.relays.clone(), None).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let cid = community.id().0;
let before = floor_of(&community, &cid);
publish_community_meta(&bed.relay, &community, &owner.keys, "Renamed", 2).await;
FOLD_BOUND.with(|b| b.set(Some(0)));
let follow = follow_control(&bed.relay, &community).await;
FOLD_BOUND.with(|b| b.set(None));
assert!(follow.unwrap().updated.is_none(), "nothing adopted");
assert_eq!(floor_of(&community, &cid), before, "no floor moves");
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(held().name, "Bound");
follow_control(&bed.relay, &community).await.unwrap();
assert_eq!(held().name, "Renamed", "the next settled fold keeps it");
assert_eq!(floor_of(&community, &cid).0, 2);
}
#[tokio::test]
async fn a_join_seeds_nothing_from_a_roster_fold_that_runs_out_its_bound() {
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "BoundJoin", bed.relays.clone(), None).await.unwrap();
let rm = "d4".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &role_at(&rm, "Mod", 2, Permissions::BAN), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &Keys::generate().public_key(), vec![rm.clone()], 1).await;
publish_banlist(&bed.relay, &community, &owner.keys, &[Keys::generate().public_key().to_hex()], 1).await;
let settled = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
assert!(settled.roles.is_some() && settled.banlist_persist.is_some() && !settled.authority_heads.is_empty());
FOLD_BOUND.with(|b| b.set(Some(0)));
let guessed = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await;
FOLD_BOUND.with(|b| b.set(None));
let guessed = guessed.unwrap();
assert!(guessed.roles.is_none() && guessed.banlist_persist.is_none() && guessed.authority_heads.is_empty(), "no Roster, banlist or floor from a guess");
assert_eq!(guessed.community.name, settled.community.name, "the owner's own document still folds");
}
#[tokio::test]
async fn keeping_or_stepping_down_never_oscillates() {
// Whether A's grant keeps B's refused v3 or steps down to C's v2 depends on C, whose
// authority comes from A. Judged only on authority above A's grant, it settles.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Settle", vec!["wss://r".into()], None).await.unwrap();
let (a, b, c) = (Keys::generate(), Keys::generate(), Keys::generate());
let (rz, rp, rk, rq, rq2) = ("b2".repeat(32), "b3".repeat(32), "b4".repeat(32), "b5".repeat(32), "b6".repeat(32));
let mr = Permissions::MANAGE_ROLES;
publish_role(&relay, &community, &owner, &role_at(&rz, "Z", 2, mr | Permissions::BAN), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rp, "P", 3, mr), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rk, "K", 4, mr), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rq, "Q", 5, 0), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rq2, "Q2", 6, 0), 1).await;
publish_grant(&relay, &community, &owner, &b.public_key(), vec![rz.clone()], 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![rq2.clone()], 1).await;
publish_grant(&relay, &community, &c, &a.public_key(), vec![rq.clone()], 2).await;
publish_grant(&relay, &community, &b, &a.public_key(), vec![rp.clone()], 3).await;
publish_grant(&relay, &community, &a, &c.public_key(), vec![rk.clone()], 1).await;
follow_control(&relay, &community).await.unwrap();
publish_grant(&relay, &community, &owner, &b.public_key(), vec![], 2).await;
let editions = fetch_control(&relay, &community).await;
let floors = load_floors(&community);
let one = fold_authority(&community, &editions, &floors);
assert!(one.converged, "the fold settles");
let reversed: Vec<ParsedEdition> = editions.iter().rev().cloned().collect();
let two = fold_authority(&community, &reversed, &floors);
assert_eq!(authority_fingerprint(&one), authority_fingerprint(&two), "in any order");
// Unrelated extra entities don't flip it either.
publish_role(&relay, &community, &owner, &role_at(&"b9".repeat(32), "Extra", 9, 0), 1).await;
let three = fold_authority(&community, &fetch_control(&relay, &community).await, &floors);
assert!(three.converged);
assert_eq!(three.roles.highest_position(&a.public_key().to_hex()), one.roles.highest_position(&a.public_key().to_hex()));
}
#[tokio::test]
async fn an_edit_its_author_could_not_make_is_never_a_gap() {
// The lowest manager publishing far above a role they can't touch, linked to nothing:
// refused, so nothing to page for.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "NoPage", vec!["wss://r".into()], None).await.unwrap();
let low = Keys::generate();
let (rlow, rr) = ("c9".repeat(32), "c3".repeat(32));
publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 9, Permissions::MANAGE_ROLES), 1).await;
publish_grant(&relay, &community, &owner, &low.public_key(), vec![rlow.clone()], 1).await;
publish_role(&relay, &community, &owner, &role_at(&rr, "R", 3, 0), 1).await;
follow_control(&relay, &community).await.unwrap();
let junk = crate::community::v2::roles::role_content_json(&role_at(&rr, "R", 50, 0)).unwrap();
let f1 = head_hash_on_relay(&relay, &community, &eid_of(&rr)).await;
publish_fork(&[&relay], &community, &low, vsk::ROLE, &eid_of(&rr), 6, f1, &junk, None).await;
let a = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
assert!(!a.gapped);
assert_eq!(a.roles.role(&rr).map(|r| r.position), Some(3));
}
#[tokio::test]
async fn a_ban_then_refounding_keeps_the_owners_edition_under_the_banned_one() {
// X renamed R; the owner bans X and re-founds at once, with no follow between. The
// re-founding carries the fold's decision, the owner's v1, not X's floored edition.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "BanRefound", bed.relays.clone(), None).await.unwrap();
let x = Keys::generate();
let (rx, rr) = ("a1".repeat(32), "a6".repeat(32));
publish_role(&bed.relay, &community, &owner.keys, &role_at(&rx, "X", 1, Permissions::MANAGE_ROLES), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &x.public_key(), vec![rx.clone()], 1).await;
publish_role(&bed.relay, &community, &owner.keys, &role_at(&rr, "R", 6, 0), 1).await;
publish_role(&bed.relay, &community, &x, &role_at(&rr, "R by X", 6, 0), 2).await;
let own = "a8".repeat(32);
publish_role(&bed.relay, &community, &x, &role_at(&own, "X's own", 8, 0), 1).await;
follow_control(&bed.relay, &community).await.unwrap();
assert_eq!(floor_of(&community, &eid_of(&rr)).0, 2);
publish_banlist(&bed.relay, &community, &owner.keys, &[x.public_key().to_hex()], 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &x.public_key(), vec![], 2).await;
let refounded = refound_community(&bed.relay, &community, &[x.public_key()]).await.unwrap();
let fresh = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &Floors::default());
assert_eq!(fresh.roles.role(&rr).map(|r| r.name.as_str()), Some("R"), "the owner's edition survives the re-founding");
assert!(fresh.banned.contains(&x.public_key().to_hex()), "and so does the ban, floored here or not");
assert!(!fetch_control(&bed.relay, &refounded).await.iter().any(|e| e.entity_id == eid_of(&own)), "a role settled as absent isn't carried");
}
#[tokio::test]
async fn a_ban_falls_back_to_what_stood_before_the_banned_signer() {
// A ban takes every edition its target wrote, the held one included: the entity is
// read as if they never wrote, and pages for what stood before them when that is unread.
let (_tmp, _guard, owner) = init_test_db();
let full = MemoryRelay::new();
let community = create_community(&full, "BanBack", vec!["wss://r".into()], None).await.unwrap();
let x = Keys::generate();
let (rx, r1, r2, r3) = ("b1".repeat(32), "b5".repeat(32), "b6".repeat(32), "b7".repeat(32));
publish_role(&full, &community, &owner, &role_at(&rx, "X", 1, Permissions::MANAGE_ROLES), 1).await;
publish_grant(&full, &community, &owner, &x.public_key(), vec![rx.clone()], 1).await;
// R1: the owner's v1 under two of X's edits. R2: X's own from the genesis.
publish_role(&full, &community, &owner, &role_at(&r1, "R1", 5, 0), 1).await;
publish_role(&full, &community, &x, &role_at(&r1, "R1 x", 5, 0), 2).await;
publish_role(&full, &community, &x, &role_at(&r1, "R1 xx", 5, 0), 3).await;
publish_role(&full, &community, &x, &role_at(&r2, "R2", 6, 0), 1).await;
publish_role(&full, &community, &x, &role_at(&r2, "R2 x", 6, 0), 2).await;
// R3: the owner's v1 under one X edit, with v1 not served below.
publish_role(&full, &community, &owner, &role_at(&r3, "R3", 7, 0), 1).await;
let r3v1 = head_hash_on_relay(&full, &community, &eid_of(&r3)).await.unwrap();
publish_role(&full, &community, &x, &role_at(&r3, "R3 x", 7, 0), 2).await;
follow_control(&full, &community).await.unwrap();
publish_banlist(&full, &community, &owner, &[x.public_key().to_hex()], 1).await;
let a = fold_authority(&community, &fetch_control(&full, &community).await, &load_floors(&community));
assert_eq!(a.roles.role(&r1).map(|r| r.name.as_str()), Some("R1"), "back to the owner's v1");
assert!(a.heads.iter().any(|h| h.entity_hex == r1 && h.version == 1 && h.rebased));
assert!(a.refused.contains(&r2) && a.roles.role(&r2).is_none(), "X's own role goes");
assert!(!a.gapped, "with every link read, nothing to page for");
let thin = MemoryRelay::new();
mirror_control_except(&full, &thin, &community, &|e| e.self_hash == r3v1).await;
let t = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
assert!(t.refused.contains(&r3) && t.gapped, "with what stood before unread, it settles as a floorless reader does and pages for the rest");
}
#[tokio::test]
async fn a_junk_edition_never_poisons_the_proof_of_the_next_one() {
// A link proof depends on the version it is made from: junk naming the held hash at
// the held version must not decide the proof of the real next edition.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Poison", vec!["wss://r".into()], None).await.unwrap();
let (a, m) = (Keys::generate(), Keys::generate());
let (ra, rr) = ("c1".repeat(32), "c6".repeat(32));
publish_role(&relay, &community, &owner, &role_at(&ra, "A", 1, Permissions::MANAGE_ROLES), 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
publish_role(&relay, &community, &owner, &role_at(&rr, "R", 6, 0), 1).await;
publish_role(&relay, &community, &a, &role_at(&rr, "R2", 6, 0), 2).await;
follow_control(&relay, &community).await.unwrap();
let h2 = head_hash_on_relay(&relay, &community, &eid_of(&rr)).await;
let junk = crate::community::v2::roles::role_content_json(&role_at(&rr, "junk", 6, 0)).unwrap();
publish_fork(&[&relay], &community, &m, vsk::ROLE, &eid_of(&rr), 2, h2, &junk, None).await;
let next = crate::community::v2::roles::role_content_json(&role_at(&rr, "R3", 6, 0)).unwrap();
publish_fork(&[&relay], &community, &a, vsk::ROLE, &eid_of(&rr), 3, h2, &next, None).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
assert_eq!(f.roles.role(&rr).map(|r| r.name.as_str()), Some("R3"), "A's next edit advances");
}
#[tokio::test]
async fn an_edition_at_the_last_version_folds_without_overflow() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Overflow", vec!["wss://r".into()], None).await.unwrap();
let rr = "d6".repeat(32);
publish_role(&relay, &community, &owner, &role_at(&rr, "R", 6, 0), 1).await;
follow_control(&relay, &community).await.unwrap();
let junk = crate::community::v2::roles::role_content_json(&role_at(&rr, "top", 6, 0)).unwrap();
let top = publish_fork(&[&relay], &community, &Keys::generate(), vsk::ROLE, &eid_of(&rr), u64::MAX, None, &junk, None).await;
let top_hash = fetch_control(&relay, &community).await.into_iter().find(|e| e.inner_id == top).unwrap().self_hash;
publish_fork(&[&relay], &community, &Keys::generate(), vsk::ROLE, &eid_of(&rr), 2, Some(top_hash), &junk, None).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
assert_eq!(f.roles.role(&rr).map(|r| r.name.as_str()), Some("R"));
}
#[tokio::test]
async fn a_channel_edition_at_the_banlists_coordinate_is_no_channel() {
// A channel id is random, so one at the banlist's coordinate is aimed at the banlist:
// it folds no head, and a re-founding still carries the real banlist.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Squat", bed.relays.clone(), None).await.unwrap();
let staff = Keys::generate();
let rs = "e1".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &role_at(&rs, "Staff", 1, Permissions::MANAGE_CHANNELS), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &staff.public_key(), vec![rs.clone()], 1).await;
let x = Keys::generate().public_key().to_hex();
set_banlist(&bed.relay, &community, &[x.clone()]).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let bl = crate::community::v2::derive::banlist_locator(community.id());
let head = head_hash_on_relay(&bed.relay, &community, &bl).await;
let v = floor_of(&community, &bl).0;
publish_fork(&[&bed.relay], &community, &staff, vsk::CHANNEL_METADATA, &bl, v + 1, head, &channel_meta_json("phantom"), None).await;
let editions = fetch_control(&bed.relay, &community).await;
let floors = load_floors(&community);
let authority = fold_authority(&community, &editions, &floors);
let fold = apply_control_fold(&community, &editions, &floors, &authority);
assert!(!fold.heads.iter().any(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(&bl)), "no channel head at the banlist's coordinate");
let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
let fresh = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &Floors::default());
assert!(fresh.banned.contains(&x), "the real banlist is carried");
}
#[tokio::test]
async fn a_ban_after_a_refounding_settles_the_banned_signers_edition() {
// After a compaction the held edition's history is gone, so a ban that voids it reads
// down to nothing it can name. The grant settles as absent rather than freezing the roster.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "BanAfter", bed.relays.clone(), None).await.unwrap();
let x = Keys::generate();
let m = Keys::generate().public_key();
let (rx, rmid, rlow) = ("f1".repeat(32), "f6".repeat(32), "f9".repeat(32));
publish_role(&bed.relay, &community, &owner.keys, &role_at(&rx, "X", 1, Permissions::MANAGE_ROLES), 1).await;
publish_role(&bed.relay, &community, &owner.keys, &role_at(&rmid, "Mid", 6, 0), 1).await;
publish_role(&bed.relay, &community, &owner.keys, &role_at(&rlow, "Low", 9, 0), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &x.public_key(), vec![rx.clone()], 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &m, vec![rlow.clone()], 1).await;
publish_grant(&bed.relay, &community, &x, &m, vec![rmid.clone()], 2).await;
follow_control(&bed.relay, &community).await.unwrap();
let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
follow_control(&bed.relay, &refounded).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
set_banlist(&bed.relay, &held, &[x.public_key().to_hex()]).await.unwrap();
let gm = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::grant_locator(community.id(), &m.to_bytes()));
let a = fold_authority(&held, &fetch_control(&bed.relay, &held).await, &load_floors(&held));
assert!(a.refused.contains(&gm), "the banned signer's grant settles as absent");
follow_control(&bed.relay, &held).await.unwrap();
let cached = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
assert_eq!(cached.roles_of(&m.to_hex()).count(), 0, "and the roster cache moves on");
}
#[tokio::test]
async fn a_refounding_never_carries_what_this_device_refuses() {
// R is kept on this device, and a floorless reader would take A's edit on top of it.
// This device's own evidence refuses that edit, so the re-founding doesn't carry it.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "NoCarry", bed.relays.clone(), None).await.unwrap();
let (a, b, c) = (Keys::generate(), Keys::generate(), Keys::generate());
let (rc, rb, ra, rr) = ("a1".repeat(32), "a2".repeat(32), "a3".repeat(32), "a7".repeat(32));
let mr = Permissions::MANAGE_ROLES;
publish_role(&bed.relay, &community, &owner.keys, &role_at(&rc, "C", 1, mr), 1).await;
publish_role(&bed.relay, &community, &owner.keys, &role_at(&rb, "B", 1, mr), 1).await;
publish_role(&bed.relay, &community, &owner.keys, &role_at(&ra, "A", 3, mr), 1).await;
for (k, r) in [(&c, &rc), (&b, &rb), (&a, &ra)] {
publish_grant(&bed.relay, &community, &owner.keys, &k.public_key(), vec![r.clone()], 1).await;
}
publish_role(&bed.relay, &community, &c, &role_at(&rr, "R", 2, 0), 1).await;
publish_role(&bed.relay, &community, &b, &role_at(&rr, "R by B", 2, 0), 2).await;
follow_control(&bed.relay, &community).await.unwrap();
publish_grant(&bed.relay, &community, &owner.keys, &c.public_key(), vec![], 2).await;
publish_grant(&bed.relay, &community, &owner.keys, &b.public_key(), vec![], 2).await;
publish_role(&bed.relay, &community, &a, &role_at(&rr, "R by A", 5, 0), 3).await;
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let t = fold_authority(&held, &fetch_control(&bed.relay, &held).await, &load_floors(&held));
assert!(t.carried.contains(&rr), "kept on this device");
let refounded = refound_community(&bed.relay, &held, &[]).await.unwrap();
let fresh = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &Floors::default());
assert_ne!(fresh.roles.role(&rr).map(|r| r.name.as_str()), Some("R by A"), "A's edit isn't carried");
}
#[tokio::test]
async fn an_uncited_demotion_to_a_role_the_member_minted_settles() {
// The uncited-strip gate reads what a grant names, never what resolves: keyed on the
// latter, refusing the grant brings back the predecessor whose roles admit the named
// role, which admits the grant, and the fold cycles.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "UncitedDemote", vec!["wss://r".into()], None).await.unwrap();
let (a, z) = (Keys::generate(), Keys::generate());
let (rz, r1, rmod) = ("f0".repeat(32), "f1".repeat(32), "f5".repeat(32));
let mr = Permissions::MANAGE_ROLES;
publish_role(&relay, &community, &owner, &role_at(&rz, "Z", 1, mr), 1).await;
publish_role(&relay, &community, &owner, &role_at(&r1, "R1", 2, mr), 1).await;
publish_grant(&relay, &community, &owner, &z.public_key(), vec![rz.clone()], 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![r1.clone()], 1).await;
publish_role(&relay, &community, &a, &role_at(&rmod, "Mod", 5, mr), 1).await;
publish_grant_citing(&relay, &community, &z, &a.public_key(), vec![rmod.clone()], 2, None).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
assert!(f.converged, "the fold settles");
assert_eq!(f.roles.roles_of(&a.public_key().to_hex()).count(), 0);
}
#[tokio::test]
async fn a_link_to_a_sibling_that_lost_the_version_still_binds() {
// Two siblings stand at v2; the owner's wins it. An edit built on the other one acts on
// the member as that sibling left them.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Sibling", vec!["wss://r".into()], None).await.unwrap();
let (a, m) = (Keys::generate(), Keys::generate());
let member = Keys::generate().public_key();
let (ra, rsen, rm, rlow, rlower) = ("a1".repeat(32), "a2".repeat(32), "a5".repeat(32), "a9".repeat(32), "aa".repeat(32));
let mr = Permissions::MANAGE_ROLES;
publish_role(&relay, &community, &owner, &role_at(&ra, "A", 1, mr), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rsen, "Senior", 2, 0), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rm, "M", 5, mr), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rlower, "Lower", 10, 0), 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
publish_grant(&relay, &community, &owner, &m.public_key(), vec![rm.clone()], 1).await;
let gm = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
publish_grant(&relay, &community, &owner, &member, vec![rlow.clone()], 1).await;
let v1 = head_hash_on_relay(&relay, &community, &gm).await;
let json = |ids: Vec<String>| crate::community::v2::roles::grant_content_json(&MemberGrant { member: member.to_hex(), role_ids: ids }).unwrap();
publish_fork(&[&relay], &community, &owner, vsk::GRANT, &gm, 2, v1, &json(vec![rlow.clone()]), None).await;
let b_id = publish_fork(&[&relay], &community, &a, vsk::GRANT, &gm, 2, v1, &json(vec![rsen.clone()]), None).await;
let b_hash = fetch_control(&relay, &community).await.into_iter().find(|e| e.inner_id == b_id).unwrap().self_hash;
publish_fork(&[&relay], &community, &m, vsk::GRANT, &gm, 3, Some(b_hash), &json(vec![rlower.clone()]), None).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
assert_eq!(f.roles.highest_position(&member.to_hex()), Some(9), "M can't act on a member A's sibling made senior");
}
#[tokio::test]
async fn a_reader_holding_nothing_never_takes_an_unauthorized_channel_edit() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "ColdChan", vec!["wss://r".into()], None).await.unwrap();
let ch = community.channels[0].id;
let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
let before = community.channel(&ch).unwrap().name.clone();
publish_fork(&[&relay], &community, &Keys::generate(), vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("stranger"), None).await;
let _ = owner;
let editions = fetch_control(&relay, &community).await;
let authority = fold_authority(&community, &editions, &Floors::default());
let fold = apply_control_fold(&community, &editions, &Floors::default(), &authority);
assert_eq!(fold.updated.as_ref().unwrap_or(&community).channel(&ch).unwrap().name, before);
}
#[tokio::test]
async fn a_step_down_lands_only_on_an_edition_decided_on_evidence() {
// With the owner's v1 unread, A2's v2 was judged blind (one as a branch of its own,
// one on a link nobody serves), so B's refused v3 is kept rather than stepped down.
let (_tmp, _guard, owner) = init_test_db();
let full = MemoryRelay::new();
let community = create_community(&full, "Blind", vec!["wss://r".into()], None).await.unwrap();
let (a2, b) = (Keys::generate(), Keys::generate());
let (rb, rsen, ra2, rhelp, rlow) = ("b1".repeat(32), "b2".repeat(32), "b3".repeat(32), "b8".repeat(32), "b9".repeat(32));
let mr = Permissions::MANAGE_ROLES;
for (id, name, pos, bits) in [(&rb, "B", 1, mr), (&rsen, "Senior", 2, 0), (&ra2, "A2", 3, mr), (&rhelp, "Helper", 8, 0), (&rlow, "Low", 9, 0)] {
publish_role(&full, &community, &owner, &role_at(id, name, pos, bits), 1).await;
}
publish_grant(&full, &community, &owner, &b.public_key(), vec![rb.clone()], 1).await;
publish_grant(&full, &community, &owner, &a2.public_key(), vec![ra2.clone()], 1).await;
let (m1, m2) = (Keys::generate().public_key(), Keys::generate().public_key());
let json = |m: &PublicKey, ids: Vec<String>| crate::community::v2::roles::grant_content_json(&MemberGrant { member: m.to_hex(), role_ids: ids }).unwrap();
let mut withheld = Vec::new();
for (m, side) in [(&m1, true), (&m2, false)] {
let gm = crate::community::v2::derive::grant_locator(community.id(), &m.to_bytes());
publish_grant(&full, &community, &owner, m, vec![rsen.clone()], 1).await;
let h1 = head_hash_on_relay(&full, &community, &gm).await;
withheld.push(h1.unwrap());
let i2 = publish_fork(&[&full], &community, &a2, vsk::GRANT, &gm, 2, if side { None } else { h1 }, &json(m, vec![rlow.clone()]), None).await;
let h2 = fetch_control(&full, &community).await.into_iter().find(|e| e.inner_id == i2).unwrap().self_hash;
publish_fork(&[&full], &community, &b, vsk::GRANT, &gm, 3, Some(h2), &json(m, vec![rlow.clone(), rhelp.clone()]), None).await;
}
follow_control(&full, &community).await.unwrap();
publish_grant(&full, &community, &owner, &b.public_key(), vec![], 2).await;
let thin = MemoryRelay::new();
mirror_control_except(&full, &thin, &community, &|e| withheld.contains(&e.self_hash)).await;
let f = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
for m in [&m1, &m2] {
let gm = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::grant_locator(community.id(), &m.to_bytes()));
let head = f.heads.iter().find(|h| h.entity_hex == gm).map(|h| (h.version, h.rebased));
assert_eq!(head, Some((3, false)), "B's v3 is kept, not stepped down to a blind v2");
}
}
#[tokio::test]
async fn a_link_that_skips_a_version_binds_nothing() {
// A link names the version directly beneath it, so an edit naming v1 past v2 is judged
// only on what v2 left.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Skip", vec!["wss://r".into()], None).await.unwrap();
let m = Keys::generate();
let member = Keys::generate().public_key();
let (rsen, rm, rlow, rlower) = ("c2".repeat(32), "c5".repeat(32), "c9".repeat(32), "ca".repeat(32));
publish_role(&relay, &community, &owner, &role_at(&rsen, "Senior", 2, 0), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rm, "M", 5, Permissions::MANAGE_ROLES), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rlower, "Lower", 10, 0), 1).await;
publish_grant(&relay, &community, &owner, &m.public_key(), vec![rm.clone()], 1).await;
let gm = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
publish_grant(&relay, &community, &owner, &member, vec![rsen.clone()], 1).await;
let v1 = head_hash_on_relay(&relay, &community, &gm).await;
publish_grant(&relay, &community, &owner, &member, vec![rlow.clone()], 2).await;
let json = crate::community::v2::roles::grant_content_json(&MemberGrant { member: member.to_hex(), role_ids: vec![rlower.clone()] }).unwrap();
publish_fork(&[&relay], &community, &m, vsk::GRANT, &gm, 3, v1, &json, None).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
assert_eq!(f.roles.highest_position(&member.to_hex()), Some(10), "M acts on the member v2 left at Low");
}
#[tokio::test]
async fn a_refounding_carries_an_invite_registry_signed_by_its_creator() {
// Compaction falls back to the floor for entities no fold covers; a re-signed copy of
// that edition must not take its place.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "RegistryCopy", bed.relays.clone(), None).await.unwrap();
mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
assert!(community_is_public(&bed.relay, &community).await);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let reg = crate::community::v2::derive::invite_links_locator(community.id(), &owner.keys.public_key().to_bytes());
let eds = fetch_control(&bed.relay, &held).await;
let head = eds.iter().filter(|e| e.entity_id == reg).max_by_key(|e| e.version).unwrap().clone();
// A copy stamped newer, so a reader taking the first served edition by hash takes it.
let copier = Keys::generate();
let ts = now_ms() / 1000 + 100;
let group = control::ControlPlane::of(&held).write_group().unwrap();
let rumor = control::build_edition_rumor(copier.public_key(), &head.vsk, ®, head.version, head.prev_hash.as_ref(), &head.content, ts, None);
let (wrap, _) = control::seal_control_edition(&rumor, &group, &copier, Timestamp::from_secs(ts)).unwrap();
bed.relay.publish(&wrap, &held.relays).await.unwrap();
assert!(load_floors(&held).contains_key(&crate::simd::hex::bytes_to_hex_32(®)), "the creator's registry is floored here");
let refounded = refound_community(&bed.relay, &held, &[]).await.unwrap();
let carried: Vec<ParsedEdition> = fetch_control(&bed.relay, &refounded).await.into_iter().filter(|e| e.entity_id == reg).collect();
assert!(!carried.is_empty() && carried.iter().all(|e| e.author == owner.keys.public_key()), "the creator's registry is carried, not the copy");
}
fn role_v2(id: &str, name: &str, rank: &str, bits: u64) -> Role {
Role { role_id: id.into(), name: name.into(), position: u32::MAX, permissions: Permissions(bits), scope: RoleScope::Server, color: 0, rank: Some(rank.into()), display: false, mentionable: false, extra: Default::default() }
}
/// Publish a vsk-13 edition with `content` at `eid`, chained to the relay's head there.
async fn publish_v2(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, eid: &[u8; 32], content: &str, version: u64) {
let group = control::ControlPlane::of(community).write_group().unwrap();
let prev = head_hash_on_relay(relay, community, eid).await;
let cite = cite_on_relay(relay, community, signer).await;
let binding = Some(crate::community::v2::derive::edition_binding(community.id()));
let rumor = control::build_edition_rumor_bound(signer.public_key(), vsk::ROLE_V2, eid, version, prev.as_ref(), content, 1_000, cite.as_ref(), binding);
let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
async fn publish_role_v2(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, role: &Role, version: u64) {
let content = crate::community::v2::roles::role_v2_content_json(role).unwrap();
publish_v2(relay, community, signer, &eid_of(&role.role_id), &content, version).await;
}
async fn publish_everyone(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, bits: u64, version: u64) {
let eid = crate::community::v2::derive::everyone_locator(community.id());
publish_v2(relay, community, signer, &eid, &crate::community::v2::roles::everyone_content_json(bits), version).await;
}
#[tokio::test]
async fn roles_v2_activate_when_the_owner_publishes_everyone() {
// Before @everyone, vsk 13 is noise and the legacy roster stands; after, Roles fold from
// vsk 13 alone and a vsk-1 Role is history.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Activate", vec!["wss://r".into()], None).await.unwrap();
let m = Keys::generate().public_key();
let (legacy, fresh) = ("a1".repeat(32), "a2".repeat(32));
publish_role(&relay, &community, &owner, &role_at(&legacy, "Legacy", 3, Permissions::KICK), 1).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&fresh, "Fresh", "V", Permissions::KICK), 1).await;
publish_grant(&relay, &community, &owner, &m, vec![legacy.clone(), fresh.clone()], 1).await;
let before = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
assert!(before.roles.role(&legacy).is_some() && before.roles.role(&fresh).is_none() && before.roles.everyone.is_none());
// A non-owner's @everyone activates nothing.
let stranger = Keys::generate();
publish_everyone(&relay, &community, &stranger, crate::community::v2::roles::EVERYONE_DEFAULT, 1).await;
let still = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
assert!(still.roles.role(&legacy).is_some() && still.roles.everyone.is_none());
publish_everyone(&relay, &community, &owner, crate::community::v2::roles::EVERYONE_DEFAULT | Permissions::CREATE_INVITE, 2).await;
let after = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
assert!(after.converged);
assert!(after.roles.role(&legacy).is_none(), "vsk 1 is history");
assert!(after.roles.role(&fresh).is_some(), "vsk 13 folds");
assert_eq!(after.roles.everyone.map(|p| p.0), Some(crate::community::v2::roles::EVERYONE_DEFAULT | Permissions::CREATE_INVITE));
assert!(after.roles.effective_permissions(&Keys::generate().public_key().to_hex()).contains(Permissions::CREATE_INVITE), "every member holds @everyone");
assert_eq!(after.roles.roles_of(&m.to_hex()).count(), 1, "the grant resolves against vsk 13");
// Once seen, activation outlives the edition that made it: a relay dropping @everyone
// can't flip a tracker back to the legacy roster.
follow_control(&relay, &community).await.unwrap();
let thin = MemoryRelay::new();
let everyone_eid = crate::community::v2::derive::everyone_locator(community.id());
mirror_control_except(&relay, &thin, &community, &|e| e.entity_id == everyone_eid).await;
let tracked = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
assert!(tracked.roles.role(&legacy).is_none() && tracked.roles.role(&fresh).is_some(), "still Roles v2");
}
#[tokio::test]
async fn legacy_ranks_bind_nothing_after_activation() {
// An admin carries a legacy Role that sat at position 1 across to vsk 13. Legacy
// positions mean nothing once Roles v2 is active, so only vsk-13 ranks judge the edit.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "LegacyRank", vec!["wss://r".into()], None).await.unwrap();
let admin = Keys::generate();
let (radm, rr) = ("f1".repeat(32), "f2".repeat(32));
publish_role(&relay, &community, &owner, &role_at(&rr, "R", 1, 0), 1).await;
// A device holding the legacy edition reads the same.
follow_control(&relay, &community).await.unwrap();
publish_everyone(&relay, &community, &owner, 0, 1).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&radm, "Admin", "B", Permissions::MANAGE_ROLES), 1).await;
publish_grant(&relay, &community, &owner, &admin.public_key(), vec![radm.clone()], 1).await;
publish_role_v2(&relay, &community, &admin, &role_v2(&rr, "R carried", "V", 0), 2).await;
let editions = fetch_control(&relay, &community).await;
for floors in [Floors::default(), load_floors(&community)] {
let f = fold_authority(&community, &editions, &floors);
assert_eq!(f.roles.role(&rr).map(|r| r.name.as_str()), Some("R carried"));
}
}
#[tokio::test]
async fn a_floor_steps_down_to_a_deletion_it_learns_of_late() {
// A device that took the owner's v3 before it saw the deletion at v2 beneath it: the
// deletion stands, and the floor moves down to it.
let (_tmp, _guard, owner) = init_test_db();
let full = MemoryRelay::new();
let community = create_community(&full, "LateDelete", vec!["wss://r".into()], None).await.unwrap();
publish_everyone(&full, &community, &owner, 0, 1).await;
let rr = "f6".repeat(32);
publish_role_v2(&full, &community, &owner, &role_v2(&rr, "R", "V", 0), 1).await;
publish_v2(&full, &community, &owner, &eid_of(&rr), &crate::community::v2::roles::role_v2_deleted_json(&rr), 2).await;
let d = head_hash_on_relay(&full, &community, &eid_of(&rr)).await.unwrap();
publish_role_v2(&full, &community, &owner, &role_v2(&rr, "R again", "V", 0), 3).await;
let thin = MemoryRelay::new();
mirror_control_except(&full, &thin, &community, &|e| e.self_hash == d).await;
follow_control(&thin, &community).await.unwrap();
assert_eq!(floor_of(&community, &eid_of(&rr)).0, 3);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
follow_control(&full, &held).await.unwrap();
assert_eq!(floor_of(&community, &eid_of(&rr)).0, 2, "the floor moves down to the deletion");
let cached = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
assert!(cached.role(&rr).is_none());
}
#[tokio::test]
async fn rank_keys_order_authority_and_equal_keys_are_peers() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Ranks", vec!["wss://r".into()], None).await.unwrap();
publish_everyone(&relay, &community, &owner, 0, 1).await;
let (hi, lo, peer) = (Keys::generate(), Keys::generate(), Keys::generate());
let mr = Permissions::MANAGE_ROLES;
let (rhi, rlo, rpeer, rtarget) = ("b1".repeat(32), "b2".repeat(32), "b3".repeat(32), "b4".repeat(32));
publish_role_v2(&relay, &community, &owner, &role_v2(&rhi, "Hi", "B", mr), 1).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&rlo, "Lo", "V", mr), 1).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&rpeer, "Peer", "V", mr), 1).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&rtarget, "Target", "VV", 0), 1).await;
for (k, r) in [(&hi, &rhi), (&lo, &rlo), (&peer, &rpeer)] {
publish_grant(&relay, &community, &owner, &k.public_key(), vec![r.clone()], 1).await;
}
// Lo renames the role beneath it, and tries to rename Hi's and its peer's.
publish_role_v2(&relay, &community, &lo, &role_v2(&rtarget, "Target by Lo", "VV", 0), 2).await;
publish_role_v2(&relay, &community, &lo, &role_v2(&rhi, "Hi by Lo", "B", mr), 2).await;
publish_role_v2(&relay, &community, &lo, &role_v2(&rpeer, "Peer by Lo", "V", mr), 2).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
let name = |id: &String| f.roles.role(id).map(|r| r.name.clone());
assert_eq!(name(&rtarget).as_deref(), Some("Target by Lo"), "a lower key is beneath");
assert_eq!(name(&rhi).as_deref(), Some("Hi"), "a higher key isn't");
assert_eq!(name(&rpeer).as_deref(), Some("Peer"), "equal keys are peers");
let (p_hi, p_lo, p_peer) = (f.roles.role(&rhi).unwrap().position, f.roles.role(&rlo).unwrap().position, f.roles.role(&rpeer).unwrap().position);
assert!(p_hi < p_lo && p_lo == p_peer, "positions follow the keys");
}
#[tokio::test]
async fn a_migrated_role_continues_its_legacy_chain() {
// The owner carries a vsk-1 Role across as vsk 13 on top of its last legacy edition: a
// tracker holding that edition advances, and the role's grants keep resolving.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Migrate", vec!["wss://r".into()], None).await.unwrap();
let (admin, m) = (Keys::generate(), Keys::generate().public_key());
let (radm, rr) = ("c1".repeat(32), "c5".repeat(32));
publish_role(&relay, &community, &owner, &role_at(&radm, "Admin", 1, Permissions::MANAGE_ROLES | Permissions::KICK), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rr, "R", 5, Permissions::KICK), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rr, "R renamed", 5, Permissions::KICK), 2).await;
publish_grant(&relay, &community, &owner, &admin.public_key(), vec![radm.clone()], 1).await;
publish_grant(&relay, &community, &owner, &m, vec![rr.clone()], 1).await;
follow_control(&relay, &community).await.unwrap();
assert_eq!(floor_of(&community, &eid_of(&rr)).0, 2);
publish_role_v2(&relay, &community, &owner, &role_v2(&radm, "Admin", "B", Permissions::MANAGE_ROLES | Permissions::KICK), 2).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&rr, "R renamed", "V", Permissions::KICK), 3).await;
publish_everyone(&relay, &community, &owner, crate::community::v2::roles::EVERYONE_DEFAULT, 1).await;
// The migrated admin edits on top.
publish_role_v2(&relay, &community, &admin, &role_v2(&rr, "R by admin", "V", Permissions::KICK), 4).await;
let editions = fetch_control(&relay, &community).await;
for floors in [load_floors(&community), Floors::default()] {
let f = fold_authority(&community, &editions, &floors);
assert!(f.converged);
assert_eq!(f.roles.role(&rr).map(|r| r.name.as_str()), Some("R by admin"));
assert_eq!(f.roles.roles_of(&m.to_hex()).count(), 1, "the grant keeps resolving");
}
}
#[tokio::test]
async fn a_deleted_role_is_gone_whatever_comes_after() {
// Deletion is terminal over the authorized chain; it takes authority over the rank the
// Role stood at, so someone beneath it can't delete it.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Delete", vec!["wss://r".into()], None).await.unwrap();
publish_everyone(&relay, &community, &owner, 0, 1).await;
let (adm, low) = (Keys::generate(), Keys::generate());
let mr = Permissions::MANAGE_ROLES;
let (radm, rlow, gone, kept) = ("d1".repeat(32), "d9".repeat(32), "d5".repeat(32), "d6".repeat(32));
publish_role_v2(&relay, &community, &owner, &role_v2(&radm, "Adm", "B", mr), 1).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&rlow, "Low", "y", mr), 1).await;
publish_grant(&relay, &community, &owner, &adm.public_key(), vec![radm.clone()], 1).await;
publish_grant(&relay, &community, &owner, &low.public_key(), vec![rlow.clone()], 1).await;
let m = Keys::generate().public_key();
for id in [&gone, &kept] {
publish_role_v2(&relay, &community, &owner, &role_v2(id, "R", "V", 0), 1).await;
}
publish_grant(&relay, &community, &owner, &m, vec![gone.clone(), kept.clone()], 1).await;
let del = |id: &str| crate::community::v2::roles::role_v2_deleted_json(id);
publish_v2(&relay, &community, &adm, &eid_of(&gone), &del(&gone), 2).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&gone, "R again", "V", 0), 3).await;
publish_v2(&relay, &community, &low, &eid_of(&kept), &del(&kept), 2).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
assert!(f.roles.role(&gone).is_none(), "deleted, and the later edition doesn't revive it");
assert!(f.heads.iter().any(|h| h.entity_hex == gone && h.version == 2), "the deletion is the head");
assert!(f.roles.role(&kept).is_some(), "a Role above its deleter stands");
assert_eq!(f.roles.roles_of(&m.to_hex()).count(), 1, "the grant naming the deleted Role confers the rest");
}
#[tokio::test]
async fn everyone_carries_only_bits_its_editor_holds_and_no_grant_names_it() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Everyone", vec!["wss://r".into()], None).await.unwrap();
let base = crate::community::v2::roles::EVERYONE_DEFAULT;
publish_everyone(&relay, &community, &owner, base, 1).await;
let (full, partial) = (Keys::generate(), Keys::generate());
let (rfull, rpart) = ("e1".repeat(32), "e2".repeat(32));
publish_role_v2(&relay, &community, &owner, &role_v2(&rfull, "Full", "B", Permissions::MANAGE_ROLES | base | Permissions::PIN_MESSAGES), 1).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&rpart, "Partial", "C", Permissions::MANAGE_ROLES | Permissions::VIEW_CHANNEL), 1).await;
publish_grant(&relay, &community, &owner, &full.public_key(), vec![rfull.clone()], 1).await;
publish_grant(&relay, &community, &owner, &partial.public_key(), vec![rpart.clone()], 1).await;
// Partial can't carry bits it lacks; Full can add a bit it holds.
publish_everyone(&relay, &community, &partial, base & !Permissions::VIDEO, 2).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
assert_eq!(f.roles.everyone.map(|p| p.0), Some(base), "the partial manager's edit carries bits it lacks");
publish_everyone(&relay, &community, &full, base | Permissions::PIN_MESSAGES, 2).await;
let g = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
assert_eq!(g.roles.everyone.map(|p| p.0), Some(base | Permissions::PIN_MESSAGES));
// A grant naming @everyone's coordinate confers nothing.
let everyone_hex = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::everyone_locator(community.id()));
let m = Keys::generate().public_key();
publish_grant(&relay, &community, &owner, &m, vec![everyone_hex], 1).await;
let h = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
assert_eq!(h.roles.roles_of(&m.to_hex()).count(), 0);
assert!(!h.roles.roles.iter().any(|r| r.name == "@everyone"), "@everyone is no Role in the list");
}
#[tokio::test]
async fn the_owner_carries_a_legacy_roster_across_to_roles_v2() {
// Order, names, colours, bits and peers survive; Grants keep resolving; nothing reads
// vsk 13 until @everyone lands last; and a channel access role becomes overwrites.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Carry", bed.relays.clone(), None).await.unwrap();
let mr = Permissions::MANAGE_ROLES;
let (radm, rmod, rpeer, rlow) = ("a1".repeat(32), "a3".repeat(32), "a4".repeat(32), "a9".repeat(32));
publish_role(&bed.relay, &community, &owner.keys, &role_at(&radm, "Admin", 1, mr | Permissions::KICK), 1).await;
publish_role(&bed.relay, &community, &owner.keys, &role_at(&rmod, "Mod", 3, Permissions::KICK), 1).await;
publish_role(&bed.relay, &community, &owner.keys, &role_at(&rpeer, "Peer", 3, Permissions::KICK), 1).await;
publish_role(&bed.relay, &community, &owner.keys, &role_at(&rlow, "Low", 9, 0), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rmod.clone(), rlow.clone()], 1).await;
follow_control(&bed.relay, &community).await.unwrap();
let before = fetch_authority(&bed.relay, &community).await;
assert!(!before.activated);
let carried = activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
assert_eq!(carried, 4);
let after = fetch_authority(&bed.relay, &community).await;
assert!(after.activated);
assert_eq!(after.roles.everyone.map(|p| p.0), Some(crate::community::v2::roles::EVERYONE_DEFAULT));
let pos = |id: &str| after.roles.role(id).map(|r| r.position).unwrap();
assert!(pos(&radm) < pos(&rmod) && pos(&rmod) == pos(&rpeer) && pos(&rpeer) < pos(&rlow), "order and peers kept");
for id in [&radm, &rmod, &rpeer, &rlow] {
let (b, a) = (before.roles.role(id).unwrap(), after.roles.role(id).unwrap());
// A managing Role gains the channel basics, so it can keep managing channel access.
let gained = if b.permissions.contains(Permissions::MANAGE_ROLES) { crate::community::v2::roles::EVERYONE_DEFAULT } else { 0 };
assert_eq!((&b.name, b.permissions.0 | gained, b.color), (&a.name, a.permissions.0, a.color));
assert!(a.rank.is_some());
assert_eq!(a.display, b.permissions.is_management(), "managing roles stay apart in the member list, as they were");
}
assert_eq!(after.roles.roles_of(&member.keys.public_key().to_hex()).count(), 2, "grants keep resolving");
assert!(activate_roles_v2(&bed.relay, &community, 0).await.is_err(), "once is enough");
let other = create_community(&bed.relay, "Scoped", bed.relays.clone(), None).await.unwrap();
let scoped = Role { role_id: "b1".repeat(32), name: "Access".into(), position: 5, permissions: Permissions(0), scope: RoleScope::Channel(crate::simd::hex::bytes_to_hex_32(&other.channels[0].id.0)), color: 0, rank: None, display: false, mentionable: false, extra: Default::default() };
publish_role(&bed.relay, &other, &owner.keys, &scoped, 1).await;
follow_control(&bed.relay, &other).await.unwrap();
activate_roles_v2(&bed.relay, &other, 0).await.unwrap();
let moved = fetch_authority(&bed.relay, &other).await;
let access = moved.roles.role(&scoped.role_id).unwrap();
assert_eq!(access.scope, RoleScope::Server, "an access role carries across unscoped");
assert_eq!(moved.roles.overwrites.len(), 1, "its private Channel lets the role through");
}
#[tokio::test]
async fn the_roles_v2_editor_refuses_exactly_what_readers_would_drop() {
let (bed, owner, mgr) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "V2Editor", bed.relays.clone(), None).await.unwrap();
publish_everyone(&bed.relay, &community, &owner.keys, Permissions::VIEW_CHANNEL, 1).await;
let mr = Permissions::MANAGE_ROLES;
let (rtop, rmgr) = ("c1".repeat(32), "c2".repeat(32));
publish_role_v2(&bed.relay, &community, &owner.keys, &role_v2(&rtop, "Top", "B", Permissions::BAN), 1).await;
publish_role_v2(&bed.relay, &community, &owner.keys, &role_v2(&rmgr, "Mgr", "F", mr | Permissions::KICK | Permissions::VIEW_CHANNEL), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &mgr.keys.public_key(), vec![rmgr.clone()], 1).await;
follow_control(&bed.relay, &community).await.unwrap();
bed.swap_to(&mgr);
crate::db::community::save_community_v2(&community).unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let a = create_role_v2(&bed.relay, &community, "A", 0, Permissions::KICK).await.unwrap();
let b = create_role_v2(&bed.relay, &community, "B", 0, 0).await.unwrap();
assert!(create_role_v2(&bed.relay, &community, "Banner", 0, Permissions::BAN).await.unwrap_err().contains("don't hold"));
let v = fetch_authority(&bed.relay, &community).await;
let pos = |v: &AuthorityView, id: &str| v.roles.role(id).map(|r| r.position).unwrap();
assert!(pos(&v, &rmgr) < pos(&v, &a) && pos(&v, &a) < pos(&v, &b), "new roles go to the bottom, in order");
// Moving B above A is one edition, on B alone.
move_role_v2(&bed.relay, &community, &b, 2).await.unwrap();
let w = fetch_authority(&bed.relay, &community).await;
assert!(pos(&w, &b) < pos(&w, &a) && pos(&w, &rmgr) < pos(&w, &b));
assert_eq!(w.roles.role(&a).unwrap().rank, v.roles.role(&a).unwrap().rank, "A wasn't touched");
// Not above itself, and not the role above it.
assert!(move_role_v2(&bed.relay, &community, &b, 0).await.is_err());
assert!(move_role_v2(&bed.relay, &community, &rtop, 3).await.is_err());
assert!(edit_role_v2(&bed.relay, &community, &rtop, "Top!", 0, Permissions::BAN, false, false).await.is_err());
// @everyone carries only what the manager holds.
assert!(set_everyone(&bed.relay, &community, Permissions::VIEW_CHANNEL | Permissions::SEND_MESSAGES).await.unwrap_err().contains("don't hold"));
set_everyone(&bed.relay, &community, Permissions::VIEW_CHANNEL | Permissions::KICK).await.unwrap();
// Delete beneath, never above.
delete_role_v2(&bed.relay, &community, &a).await.unwrap();
assert!(delete_role_v2(&bed.relay, &community, &rtop).await.is_err());
let x = fetch_authority(&bed.relay, &community).await;
assert!(x.roles.role(&a).is_none() && x.roles.role(&rtop).is_some());
assert_eq!(x.roles.everyone.map(|p| p.0), Some(Permissions::VIEW_CHANNEL | Permissions::KICK));
edit_role_v2(&bed.relay, &community, &b, "B shown", 7, 0, true, true).await.unwrap();
let y = fetch_authority(&bed.relay, &community).await;
let rb = y.roles.role(&b).unwrap();
assert!(rb.display && rb.mentionable && rb.name == "B shown" && rb.color == 7);
}
#[tokio::test]
async fn a_marked_edition_is_its_signers_and_its_communitys_alone() {
// SC-6: a marked edition's hash covers its signer, so a re-signed copy is a different
// edition; an unmarked one keeps the content hash. A marked edition re-wrapped into
// another Community is refused there.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let a = create_community(&relay, "A", vec!["wss://r".into()], None).await.unwrap();
let b = create_community(&relay, "B", vec!["wss://r".into()], None).await.unwrap();
let rid = eid_of(&"a1".repeat(32));
let content = crate::community::v2::roles::role_v2_content_json(&role_v2(&"a1".repeat(32), "R", "V", 0)).unwrap();
let bind_a = Some(crate::community::v2::derive::edition_binding(a.id()));
let copier = Keys::generate();
let seal = |c: &CommunityV2, signer: &Keys, binding: Option<[u8; 32]>| {
let group = control::ControlPlane::of(c).write_group().unwrap();
let rumor = control::build_edition_rumor_bound(signer.public_key(), vsk::ROLE_V2, &rid, 1, None, &content, 1_000, None, binding);
control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap().0
};
let (genuine, _) = control::ControlPlane::of(&a).open(&seal(&a, &owner, bind_a)).unwrap();
let (copy, _) = control::ControlPlane::of(&a).open(&seal(&a, &copier, bind_a)).unwrap();
assert_ne!(genuine.self_hash, copy.self_hash, "a copy under another key is another edition");
let (plain, _) = control::ControlPlane::of(&a).open(&seal(&a, &owner, None)).unwrap();
let (plain_copy, _) = control::ControlPlane::of(&a).open(&seal(&a, &copier, None)).unwrap();
assert_eq!(plain.self_hash, plain_copy.self_hash, "unmarked editions keep the content hash");
// Bound to A, wrapped at B: refused at B.
let mut wrong = a.clone();
wrong.community_root = b.community_root;
wrong.control_pk = b.control_pk;
wrong.control_root = b.control_root;
let foreign = {
let group = control::ControlPlane::of(&b).write_group().unwrap();
let rumor = control::build_edition_rumor_bound(owner.public_key(), vsk::ROLE_V2, &rid, 1, None, &content, 1_000, None, bind_a);
control::seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(1_000)).unwrap().0
};
assert!(control::ControlPlane::of(&b).open(&foreign).is_err(), "A's edition is no edition of B");
let _ = wrong;
}
#[tokio::test]
async fn on_roles_v2_every_edition_is_marked_and_an_unmarked_role_is_none() {
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Marked", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = held.channels[0].id;
edit_channel_metadata(&bed.relay, &held, &ch, &control::ChannelMetadata { name: "renamed".into(), private: false, ..Default::default() }).await.unwrap();
let eds = fetch_control(&bed.relay, &held).await;
let rename = eds.iter().filter(|e| e.entity_id == ch.0).max_by_key(|e| e.version).unwrap();
assert!(rename.binding.is_some(), "a channel edit after activation is marked");
assert!(eds.iter().filter(|e| e.vsk == vsk::ROLE_V2).all(|e| e.binding.is_some()));
// An unmarked vsk-13 Role from a writer that skipped the mark folds nothing.
let rid = "b1".repeat(32);
let content = crate::community::v2::roles::role_v2_content_json(&role_v2(&rid, "Unmarked", "x", 0)).unwrap();
let group = control::ControlPlane::of(&held).write_group().unwrap();
let rumor = control::build_edition_rumor(owner.keys.public_key(), vsk::ROLE_V2, &eid_of(&rid), 1, None, &content, 1_000, None);
let (wrap, _) = control::seal_control_edition(&rumor, &group, &owner.keys, Timestamp::from_secs(1_000)).unwrap();
bed.relay.publish(&wrap, &held.relays).await.unwrap();
let f = fold_authority(&held, &fetch_control(&bed.relay, &held).await, &load_floors(&held));
assert!(f.roles.role(&rid).is_none());
}
#[tokio::test]
async fn a_backdated_deletion_never_reaches_above_its_signer() {
// A deletion acts on the Role at every rank it holds from the deletion on: published as
// an early version beneath a Role's later life, it doesn't reach above its signer.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Backdate", vec!["wss://r".into()], None).await.unwrap();
let m = Keys::generate();
let mr = Permissions::MANAGE_ROLES;
let (rtop, rm, rlegacy) = ("a1".repeat(32), "a5".repeat(32), "a7".repeat(32));
// A legacy Role carried across at the top, and a v2 Role moved to the top by the owner.
publish_role(&relay, &community, &owner, &role_at(&rlegacy, "Legacy", 2, 0), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rlegacy, "Legacy", 2, 0), 2).await;
publish_everyone(&relay, &community, &owner, 0, 1).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&rlegacy, "Legacy", "1", 0), 3).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&rtop, "Top", "z", 0), 1).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&rtop, "Top", "2", 0), 2).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&rm, "M", "V", mr), 1).await;
publish_grant(&relay, &community, &owner, &m.public_key(), vec![rm.clone()], 1).await;
let del = |id: &str| crate::community::v2::roles::role_v2_deleted_json(id);
// Each deletion is a genesis, beneath the Role's whole later life.
let group = control::ControlPlane::of(&community).write_group().unwrap();
for id in [&rtop, &rlegacy] {
let rumor = control::build_edition_rumor_bound(m.public_key(), vsk::ROLE_V2, &eid_of(id), 1, None, &del(id), 9_000, cite_on_relay(&relay, &community, &m).await.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())));
let (wrap, _) = control::seal_control_edition(&rumor, &group, &m, Timestamp::from_secs(9_000)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
assert!(f.roles.role(&rtop).is_some(), "M can't delete the Role the owner moved above it");
assert!(f.roles.role(&rlegacy).is_some(), "nor the one carried across above it");
}
#[tokio::test]
async fn only_everyone_activates_and_nothing_squats_its_coordinate() {
// A manager's legacy Role or channel at @everyone's coordinate floors nothing there, so
// no tracker reads the Community as Roles v2 before the owner moves it.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Squat2", vec!["wss://r".into()], None).await.unwrap();
let staff = Keys::generate();
let rs = "b1".repeat(32);
publish_role(&relay, &community, &owner, &role_at(&rs, "Staff", 1, Permissions::MANAGE_ROLES | Permissions::MANAGE_CHANNELS), 1).await;
publish_grant(&relay, &community, &owner, &staff.public_key(), vec![rs.clone()], 1).await;
let everyone_hex = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::everyone_locator(community.id()));
// Each squat on its own: either one alone would floor the coordinate.
let other = create_community(&relay, "Squat3", vec!["wss://r".into()], None).await.unwrap();
publish_role(&relay, &other, &owner, &role_at(&rs, "Staff", 1, Permissions::MANAGE_ROLES | Permissions::MANAGE_CHANNELS), 1).await;
publish_grant(&relay, &other, &owner, &staff.public_key(), vec![rs.clone()], 1).await;
let other_everyone = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::everyone_locator(other.id()));
publish_role(&relay, &community, &staff, &role_at(&everyone_hex, "Squat", 5, 0), 1).await;
publish_fork(&[&relay], &other, &staff, vsk::CHANNEL_METADATA, &eid_of(&other_everyone), 1, None, &channel_meta_json("squat"), None).await;
for (c, e) in [(&community, &everyone_hex), (&other, &other_everyone)] {
follow_control(&relay, c).await.unwrap();
assert!(!load_floors(c).contains_key(e), "nothing floors @everyone's coordinate");
let held = crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
let a = fold_authority(&held, &fetch_control(&relay, &held).await, &load_floors(&held));
assert!(!a.activated && a.roles.role(&rs).is_some());
}
}
#[tokio::test]
async fn roles_v2_survives_a_refounding_after_an_admin_edits_everyone() {
// Compaction carries @everyone's head, here an admin's: a reader at the new epoch
// still folds Roles v2, since activation reads the head the vsk-13 fold admits.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Survive", bed.relays.clone(), None).await.unwrap();
let admin = Keys::generate();
let ra = "c1".repeat(32);
publish_everyone(&bed.relay, &community, &owner.keys, Permissions::VIEW_CHANNEL, 1).await;
publish_role_v2(&bed.relay, &community, &owner.keys, &role_v2(&ra, "Admin", "B", Permissions::MANAGE_ROLES | Permissions::VIEW_CHANNEL | Permissions::SEND_MESSAGES | Permissions::BAN), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![ra.clone()], 1).await;
publish_everyone(&bed.relay, &community, &admin, Permissions::VIEW_CHANNEL | Permissions::SEND_MESSAGES, 2).await;
follow_control(&bed.relay, &community).await.unwrap();
let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
let fresh = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &Floors::default());
assert!(fresh.activated, "still Roles v2 at the new epoch");
assert!(fresh.roles.role(&ra).is_some() && fresh.roles.is_admin(&admin.public_key().to_hex()));
}
#[tokio::test]
async fn a_kept_legacy_head_stands_for_nothing_after_activation() {
// A device holding a legacy Role whose migration it can't read keeps that edition as the
// head, but a vsk-1 Role confers nothing once Roles v2 is active.
let (_tmp, _guard, owner) = init_test_db();
let full = MemoryRelay::new();
let community = create_community(&full, "KeptLegacy", vec!["wss://r".into()], None).await.unwrap();
let m = Keys::generate().public_key();
let rr = "d3".repeat(32);
publish_role(&full, &community, &owner, &role_at(&rr, "Legacy", 3, Permissions::BAN), 1).await;
publish_role(&full, &community, &owner, &role_at(&rr, "Legacy", 3, Permissions::BAN), 2).await;
publish_grant(&full, &community, &owner, &m, vec![rr.clone()], 1).await;
follow_control(&full, &community).await.unwrap();
publish_role_v2(&full, &community, &owner, &role_v2(&rr, "Legacy", "V", Permissions::BAN), 3).await;
let migrated = head_hash_on_relay(&full, &community, &eid_of(&rr)).await.unwrap();
publish_everyone(&full, &community, &owner, 0, 1).await;
let thin = MemoryRelay::new();
mirror_control_except(&full, &thin, &community, &|e| e.self_hash == migrated).await;
let a = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
assert!(a.activated && a.carried.contains(&rr), "kept, with nothing proven to step down to");
assert!(a.roles.role(&rr).is_none() && !a.roles.has_permission(&m.to_hex(), Permissions::BAN), "the legacy edition confers nothing");
}
#[tokio::test]
async fn everyones_bits_author_no_banlist() {
// Removals from a banlist aren't checked by rank, so who may author one is read from
// Roles alone: @everyone holding BAN doesn't let any member lift every ban.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "EveryoneBan", vec!["wss://r".into()], None).await.unwrap();
publish_everyone(&relay, &community, &owner, Permissions::BAN, 1).await;
let x = Keys::generate().public_key().to_hex();
publish_banlist(&relay, &community, &owner, &[x.clone()], 1).await;
let member = Keys::generate();
let rc = "e7".repeat(32);
publish_role_v2(&relay, &community, &owner, &role_v2(&rc, "Cosmetic", "V", 0), 1).await;
publish_grant(&relay, &community, &owner, &member.public_key(), vec![rc.clone()], 1).await;
publish_banlist(&relay, &community, &member, &[], 2).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
assert!(f.banned.contains(&x), "a member without BAN in a Role unbans nobody");
}
#[tokio::test]
async fn an_uncited_grant_naming_only_everyone_is_a_strip() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "UncitedEveryone", vec!["wss://r".into()], None).await.unwrap();
publish_everyone(&relay, &community, &owner, 0, 1).await;
let mgr = Keys::generate();
let m = Keys::generate().public_key();
let (rmgr, rlow) = ("e5".repeat(32), "e9".repeat(32));
publish_role_v2(&relay, &community, &owner, &role_v2(&rmgr, "Mgr", "F", Permissions::MANAGE_ROLES), 1).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&rlow, "Low", "V", 0), 1).await;
publish_grant(&relay, &community, &owner, &mgr.public_key(), vec![rmgr.clone()], 1).await;
publish_grant(&relay, &community, &owner, &m, vec![rlow.clone()], 1).await;
let everyone_hex = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::everyone_locator(community.id()));
publish_grant_citing(&relay, &community, &mgr, &m, vec![everyone_hex], 2, None).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
assert_eq!(f.roles.roles_of(&m.to_hex()).count(), 1, "the member keeps Low");
}
async fn publish_tenure(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, member: &PublicKey, sealed: Vec<crate::community::v2::roles::TenureEntry>, version: u64) {
let eid = crate::community::v2::derive::tenure_locator(community.id(), &member.to_bytes(), &signer.public_key().to_bytes());
let content = crate::community::v2::roles::tenure_content_json(&crate::community::v2::roles::TenureContent { member: member.to_hex(), sealed }).unwrap();
let group = control::ControlPlane::of(community).write_group().unwrap();
let prev = head_hash_on_relay(relay, community, &eid).await;
let cite = cite_on_relay(relay, community, signer).await;
let binding = Some(crate::community::v2::derive::edition_binding(community.id()));
let rumor = control::build_edition_rumor_bound(signer.public_key(), vsk::TENURE, &eid, version, prev.as_ref(), &content, 1_000, cite.as_ref(), binding);
let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
fn entry(rank: &str, bits: u64, heads: &[[u8; 32]]) -> crate::community::v2::roles::TenureEntry {
crate::community::v2::roles::TenureEntry { rank: rank.into(), permissions: bits, heads: heads.iter().map(crate::simd::hex::bytes_to_hex_32).collect() }
}
#[tokio::test]
async fn a_tenure_keeps_what_a_demoted_admin_decided_and_nothing_after() {
// CORD-04 §9: the listed editions are judged at the sealed standing; anything else the
// member signs is judged on where they stand now.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Tenure", vec!["wss://r".into()], None).await.unwrap();
publish_everyone(&relay, &community, &owner, 0, 1).await;
let a = Keys::generate();
let bits = Permissions::MANAGE_ROLES | Permissions::MANAGE_CHANNELS;
let (ra, made, late) = ("a1".repeat(32), "a6".repeat(32), "a7".repeat(32));
publish_role_v2(&relay, &community, &owner, &role_v2(&ra, "Admin", "F", bits), 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
publish_role_v2(&relay, &community, &a, &role_v2(&made, "Made by A", "V", 0), 1).await;
let ch = community.channels[0].id;
let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
let renamed = publish_fork(&[&relay], &community, &a, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("by A"), None).await;
let eds = fetch_control(&relay, &community).await;
let hash = |id: [u8; 32]| eds.iter().find(|e| e.inner_id == id).unwrap().self_hash;
let role_hash = eds.iter().find(|e| e.entity_id == eid_of(&made)).unwrap().self_hash;
publish_tenure(&relay, &community, &owner, &a.public_key(), vec![entry("F", bits, &[role_hash, hash(renamed)])], 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![], 2).await;
// After the strip, A signs something new: nothing seals it.
publish_role_v2(&relay, &community, &a, &role_v2(&late, "Late", "W", 0), 1).await;
let editions = fetch_control(&relay, &community).await;
let f = fold_authority(&community, &editions, &Floors::default());
assert!(f.roles.role(&made).is_some(), "A's role stands on the sealed standing");
assert!(f.roles.role(&late).is_none(), "A's later role doesn't");
let fold = apply_control_fold(&community, &editions, &Floors::default(), &f);
assert_eq!(fold.updated.as_ref().unwrap_or(&community).channel(&ch).unwrap().name, "by A", "and so does A's channel edit");
}
#[tokio::test]
async fn a_tenure_seals_only_what_its_writer_could_grant() {
// Beneath the writer, with bits the writer holds above it; and never by the member
// themselves, or anyone could pre-seal against their own demotion.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "TenureLimit", vec!["wss://r".into()], None).await.unwrap();
publish_everyone(&relay, &community, &owner, 0, 1).await;
let (a, m) = (Keys::generate(), Keys::generate());
let mr = Permissions::MANAGE_ROLES;
let (ra, rm, made) = ("b1".repeat(32), "b2".repeat(32), "b6".repeat(32));
publish_role_v2(&relay, &community, &owner, &role_v2(&ra, "A", "C", mr), 1).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&rm, "M", "F", mr), 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
publish_grant(&relay, &community, &owner, &m.public_key(), vec![rm.clone()], 1).await;
publish_role_v2(&relay, &community, &a, &role_v2(&made, "Made", "V", 0), 1).await;
let role_hash = fetch_control(&relay, &community).await.into_iter().find(|e| e.entity_id == eid_of(&made)).unwrap().self_hash;
// M seals A at A's rank, above M: refused. A seals themselves: refused.
publish_tenure(&relay, &community, &m, &a.public_key(), vec![entry("C", mr, &[role_hash])], 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![], 2).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
assert!(f.roles.role(&made).is_none(), "a Tenure above its writer seals nothing");
// A seal lends nothing at its own rank: A's role at A's rank stays refused.
let peer_c = create_community(&relay, "PeerSeal", vec!["wss://r".into()], None).await.unwrap();
publish_everyone(&relay, &peer_c, &owner, 0, 1).await;
let peer = "b7".repeat(32);
publish_role_v2(&relay, &peer_c, &owner, &role_v2(&ra, "A", "C", mr), 1).await;
publish_grant(&relay, &peer_c, &owner, &a.public_key(), vec![ra.clone()], 1).await;
publish_role_v2(&relay, &peer_c, &a, &role_v2(&peer, "Peer", "C", 0), 1).await;
let peer_hash = fetch_control(&relay, &peer_c).await.into_iter().find(|e| e.entity_id == eid_of(&peer)).unwrap().self_hash;
publish_tenure(&relay, &peer_c, &owner, &a.public_key(), vec![entry("C", mr, &[peer_hash])], 1).await;
publish_grant(&relay, &peer_c, &owner, &a.public_key(), vec![], 2).await;
let p = fold_authority(&peer_c, &fetch_control(&relay, &peer_c).await, &Floors::default());
assert!(p.roles.role(&peer).is_none(), "sealed at C, A still can't stand a role at C");
let other = create_community(&relay, "SelfSeal", vec!["wss://r".into()], None).await.unwrap();
publish_everyone(&relay, &other, &owner, 0, 1).await;
publish_role_v2(&relay, &other, &owner, &role_v2(&ra, "A", "C", mr), 1).await;
publish_grant(&relay, &other, &owner, &a.public_key(), vec![ra.clone()], 1).await;
publish_role_v2(&relay, &other, &a, &role_v2(&made, "Made", "V", 0), 1).await;
let role_hash = fetch_control(&relay, &other).await.into_iter().find(|e| e.entity_id == eid_of(&made)).unwrap().self_hash;
publish_tenure(&relay, &other, &a, &a.public_key(), vec![entry("V", 0, &[role_hash])], 1).await;
publish_grant(&relay, &other, &owner, &a.public_key(), vec![], 2).await;
let g = fold_authority(&other, &fetch_control(&relay, &other).await, &Floors::default());
assert!(g.roles.role(&made).is_none(), "nor a Tenure its own member wrote");
}
#[tokio::test]
async fn a_tenure_written_by_a_later_demoted_admin_still_stands() {
// X demoted Y and sealed Y's standing; then the owner banned X, sealing X's. Y's
// decisions hold through X's sealed standing.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Chain", vec!["wss://r".into()], None).await.unwrap();
publish_everyone(&relay, &community, &owner, 0, 1).await;
let (x, y) = (Keys::generate(), Keys::generate());
let mr = Permissions::MANAGE_ROLES;
let (rx, ry, made) = ("e1".repeat(32), "e2".repeat(32), "e6".repeat(32));
publish_role_v2(&relay, &community, &owner, &role_v2(&rx, "X", "C", mr), 1).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&ry, "Y", "F", mr), 1).await;
publish_grant(&relay, &community, &owner, &x.public_key(), vec![rx.clone()], 1).await;
publish_grant(&relay, &community, &owner, &y.public_key(), vec![ry.clone()], 1).await;
publish_role_v2(&relay, &community, &y, &role_v2(&made, "Made by Y", "V", 0), 1).await;
let hash_at = |eds: &[ParsedEdition], eid: [u8; 32]| eds.iter().filter(|e| e.entity_id == eid).max_by_key(|e| e.version).unwrap().self_hash;
let eds = fetch_control(&relay, &community).await;
publish_tenure(&relay, &community, &x, &y.public_key(), vec![entry("F", mr, &[hash_at(&eds, eid_of(&made))])], 1).await;
publish_grant(&relay, &community, &x, &y.public_key(), vec![], 2).await;
let eds = fetch_control(&relay, &community).await;
let tenure_y = crate::community::v2::derive::tenure_locator(community.id(), &y.public_key().to_bytes(), &x.public_key().to_bytes());
let strip_y = crate::community::v2::derive::grant_locator(community.id(), &y.public_key().to_bytes());
publish_tenure(&relay, &community, &owner, &x.public_key(), vec![entry("C", mr, &[hash_at(&eds, tenure_y), hash_at(&eds, strip_y)])], 1).await;
publish_banlist(&relay, &community, &owner, &[x.public_key().to_hex()], 1).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
assert!(f.banned.contains(&x.public_key().to_hex()) && f.roles.roles_of(&x.public_key().to_hex()).next().is_none());
assert!(f.roles.roles_of(&y.public_key().to_hex()).next().is_none(), "X's strip of Y stands though X is banned");
assert!(f.roles.role(&made).is_some(), "and so does what Y decided, through X's sealed standing");
}
#[tokio::test]
async fn a_sealed_banlist_keeps_its_bans_after_its_editor_is_demoted() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "SealedBans", vec!["wss://r".into()], None).await.unwrap();
publish_everyone(&relay, &community, &owner, 0, 1).await;
let (a, t) = (Keys::generate(), Keys::generate());
let bits = Permissions::MANAGE_ROLES | Permissions::BAN;
let ra = "f1".repeat(32);
publish_role_v2(&relay, &community, &owner, &role_v2(&ra, "Mod", "C", bits), 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
publish_banlist(&relay, &community, &a, &[t.public_key().to_hex()], 1).await;
let eds = fetch_control(&relay, &community).await;
let banlist = eds.iter().find(|e| e.entity_id == crate::community::v2::derive::banlist_locator(community.id())).unwrap().self_hash;
publish_tenure(&relay, &community, &owner, &a.public_key(), vec![entry("C", bits, &[banlist])], 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![], 2).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
assert!(f.banned.contains(&t.public_key().to_hex()), "the ban A made stands on A's sealed standing");
}
fn folded(base: &CommunityV2, eds: &[ParsedEdition]) -> CommunityV2 {
let f = fold_authority(base, eds, &Floors::default());
apply_control_fold(base, eds, &Floors::default(), &f).updated.unwrap_or_else(|| base.clone())
}
fn sidebar_names(c: &CommunityV2) -> Vec<(Option<String>, Vec<String>)> {
c.sidebar().into_iter().map(|(k, chans)| (k.map(|k| k.name.clone()), chans.into_iter().map(|c| c.name.clone()).collect())).collect()
}
fn held_of(c: &CommunityV2) -> CommunityV2 {
crate::db::community::load_community_v2(c.id()).unwrap().unwrap()
}
/// Every channel of a thirty-channel community, one message each, backfilled twice over a
/// real socket: more planes than the plane pool holds. Returns the connections it took.
async fn backfill_sockets() -> usize {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Many", vec!["wss://r".into()], None).await.unwrap();
for i in 1..30 {
create_public_channel(&relay, &held_of(&community), &format!("channel {i}")).await.unwrap();
}
let mut community = held_of(&community);
assert_eq!(community.channels.len(), 30);
for ch in &community.channels {
send_message(&relay, &community, &ch.id, &format!("hello {}", ch.name)).await.unwrap();
}
let wire = crate::community::transport::wire::WireRelay::start().await;
wire.hold(relay.fetch(&Query { kinds: vec![stream::KIND_WRAP], ..Default::default() }, &community.relays).await.unwrap());
community.relays = vec![wire.url()];
crate::transport::set_preference(Some(crate::transport::Kind::Clearnet));
let live = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(5));
for _ in 0..2 {
for ch in &community.channels {
let read = fetch_channel_history(&live, &community, &ch.id, 50, 1, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default());
assert_eq!(read.await.unwrap().len(), 1, "#{} backfilled", ch.name);
}
}
crate::community::transport::clear_plane_pool();
wire.opened()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_backfill_of_many_channels_holds_one_connection_to_a_relay_without_auth() {
assert_eq!(backfill_sockets().await, 1, "connections opened to the relay");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_relay_found_gating_plane_reads_is_recorded_for_the_account() {
use nostr_sdk::prelude::FinalizeEvent;
let (_tmp, _guard, _owner) = init_test_db();
let relay = crate::community::transport::wire::WireRelay::start().await;
relay.gate(true);
crate::transport::set_preference(Some(crate::transport::Kind::Clearnet));
let plane = Keys::generate();
let wrap = nostr_sdk::prelude::EventBuilder::new(nostr_sdk::prelude::Kind::Custom(stream::KIND_WRAP), "sealed").finalize(&plane).unwrap();
relay.hold([wrap]);
let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![plane.public_key().to_hex()], ..Default::default() };
let live = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(5));
live.fetch_plane(&plane, &query, &[relay.url()]).await.unwrap();
assert!(crate::community::transport::auth_gate_live(&relay.url()));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_relay_the_account_saw_challenge_goes_straight_to_authed_plane_reads() {
use nostr_sdk::prelude::FinalizeEvent;
let (_tmp, _guard, _owner) = init_test_db();
let relay = crate::community::transport::wire::WireRelay::start().await;
relay.gate(true);
crate::community::transport::note_auth_gate(&relay.url());
crate::transport::set_preference(Some(crate::transport::Kind::Clearnet));
let plane = Keys::generate();
let wrap = nostr_sdk::prelude::EventBuilder::new(nostr_sdk::prelude::Kind::Custom(stream::KIND_WRAP), "sealed").finalize(&plane).unwrap();
relay.hold([wrap.clone()]);
let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![plane.public_key().to_hex()], ..Default::default() };
let live = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(5));
let read = live.fetch_plane(&plane, &query, &[relay.url()]).await.unwrap();
assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id]);
assert_eq!(relay.opened(), 1, "no open read first");
}
#[tokio::test]
async fn categories_order_and_delete_terminally() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Cats", vec!["wss://r".into()], None).await.unwrap();
let staff = create_category(&relay, &held_of(&community), "Staff").await.unwrap();
let social = create_category(&relay, &held_of(&community), "Social").await.unwrap();
move_category(&relay, &held_of(&community), social, 0).await.unwrap();
rename_category(&relay, &held_of(&community), staff, "Mods").await.unwrap();
let peer = folded(&community, &fetch_control(&relay, &community).await);
assert_eq!(sidebar_names(&peer), vec![(None, vec!["general".into()]), (Some("Social".into()), vec![]), (Some("Mods".into()), vec![])]);
assert_eq!(sidebar_names(&held_of(&community)), sidebar_names(&peer), "this device shows what a peer folds, and keeps it across a reload");
delete_category(&relay, &held_of(&community), social).await.unwrap();
// A later edition can't bring a deleted Category back.
let eds = fetch_control(&relay, &community).await;
let head = eds.iter().filter(|e| e.entity_id == social).max_by_key(|e| e.version).unwrap();
let revive = serde_json::to_string(&control::CategoryMetadata { name: "Back".into(), position: Some("V".into()), ..Default::default() }).unwrap();
publish_marked(&relay, &community, &owner, vsk::CATEGORY, &social, head.version + 1, Some(head.self_hash), &revive).await;
let peer = folded(&community, &fetch_control(&relay, &community).await);
assert_eq!(peer.categories.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), vec!["Mods"]);
}
/// One marked edition at an explicit version and predecessor.
async fn publish_marked(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, vsk_code: &str, eid: &[u8; 32], version: u64, prev: Option<[u8; 32]>, content: &str) {
let group = control::ControlPlane::of(community).write_group().unwrap();
let cite = cite_on_relay(relay, community, signer).await;
let binding = Some(crate::community::v2::derive::edition_binding(community.id()));
let rumor = control::build_edition_rumor_bound(signer.public_key(), vsk_code, eid, version, prev.as_ref(), content, 2_000 + version, cite.as_ref(), binding);
let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(2_000 + version)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
#[tokio::test]
async fn a_category_needs_manage_channels_the_mark_and_its_own_coordinate() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "CatGate", vec!["wss://r".into()], None).await.unwrap();
let cat = |name: &str| serde_json::to_string(&control::CategoryMetadata { name: name.into(), position: Some("V".into()), ..Default::default() }).unwrap();
let stranger = Keys::generate();
publish_marked(&relay, &community, &stranger, vsk::CATEGORY, &[0x31; 32], 1, None, &cat("Stranger's")).await;
// Unmarked: nothing older ever wrote a Category, so an unmarked one is forged.
publish_fork(&[&relay], &community, &owner, vsk::CATEGORY, &[0x32; 32], 1, None, &cat("Unmarked"), None).await;
// At another entity's coordinate.
let general = community.channels[0].id.0;
publish_marked(&relay, &community, &owner, vsk::CATEGORY, &general, 1, None, &cat("On a channel")).await;
publish_marked(&relay, &community, &owner, vsk::CATEGORY, &crate::community::v2::derive::banlist_locator(community.id()), 1, None, &cat("On the banlist")).await;
publish_marked(&relay, &community, &owner, vsk::CATEGORY, &[0x33; 32], 1, None, &cat("Real")).await;
// A stranger's deletion deletes nothing.
let real = fetch_control(&relay, &community).await.into_iter().find(|e| e.entity_id == [0x33; 32]).unwrap();
let gone = serde_json::to_string(&control::CategoryMetadata { deleted: Some(true), ..Default::default() }).unwrap();
publish_marked(&relay, &community, &stranger, vsk::CATEGORY, &[0x33; 32], 2, Some(real.self_hash), &gone).await;
let peer = folded(&community, &fetch_control(&relay, &community).await);
assert_eq!(peer.categories.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), vec!["Real"]);
}
#[tokio::test]
async fn a_channel_moves_in_one_edition_once_its_group_is_keyed() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Moves", vec!["wss://r".into()], None).await.unwrap();
let alpha = create_public_channel(&relay, &held_of(&community), "alpha").await.unwrap();
let beta = create_public_channel(&relay, &held_of(&community), "beta").await.unwrap();
let gamma = create_public_channel(&relay, &held_of(&community), "gamma").await.unwrap();
let names = |c: &CommunityV2| sidebar_names(c)[0].1.clone();
assert_eq!(names(&held_of(&community)), vec!["alpha", "beta", "gamma", "general"], "keyless channels sort by name");
// The first move keys the group as it shows, then places gamma.
move_channel(&relay, &held_of(&community), &gamma, None, 0).await.unwrap();
assert_eq!(names(&held_of(&community)), vec!["gamma", "alpha", "beta", "general"]);
let before = fetch_control(&relay, &community).await.len();
move_channel(&relay, &held_of(&community), &gamma, None, 2).await.unwrap();
assert_eq!(fetch_control(&relay, &community).await.len(), before + 1, "a later move is one edition");
assert_eq!(names(&held_of(&community)), vec!["alpha", "beta", "gamma", "general"]);
let staff = create_category(&relay, &held_of(&community), "Staff").await.unwrap();
move_channel(&relay, &held_of(&community), &beta, Some(staff), 0).await.unwrap();
let delta = create_channel_in(&relay, &held_of(&community), "delta", false, Some(staff)).await.unwrap();
let peer = folded(&community, &fetch_control(&relay, &community).await);
assert_eq!(sidebar_names(&peer), vec![(None, vec!["alpha".into(), "gamma".into(), "general".into()]), (Some("Staff".into()), vec!["beta".into(), "delta".into()])]);
assert_eq!(sidebar_names(&held_of(&community)), sidebar_names(&peer));
move_channel(&relay, &held_of(&community), &delta, None, usize::MAX).await.unwrap();
// A deleted Category unfiles its Channels, which keep pointing at it.
delete_category(&relay, &held_of(&community), staff).await.unwrap();
let peer = folded(&community, &fetch_control(&relay, &community).await);
// Its key from inside Staff ties alpha's out here, and the name breaks the tie.
assert_eq!(sidebar_names(&peer), vec![(None, vec!["alpha".into(), "beta".into(), "gamma".into(), "general".into(), "delta".into()])]);
assert_eq!(peer.channel(&beta).unwrap().category(), Some(staff));
assert!(move_channel(&relay, &held_of(&community), &alpha, Some(staff), 0).await.is_err(), "nothing files under a deleted Category");
}
#[tokio::test]
async fn channel_details_round_trip_and_keep_what_others_wrote() {
use crate::community::v2::community::ChannelView;
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Details", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
// Another client's field, and its legacy voice flag.
let mut foreign = community.channels[0].metadata();
foreign.extra.insert("vnd".into(), 7.into());
foreign.voice = Some(true);
let v1 = head_hash_on_relay(&relay, &community, &general.0).await;
publish_fork(&[&relay], &community, &owner, vsk::CHANNEL_METADATA, &general.0, 2, v1, &serde_json::to_string(&foreign).unwrap(), None).await;
follow_control(&relay, &community).await.unwrap();
assert_eq!(held_of(&community).channel(&general).unwrap().view(), ChannelView::Voice, "the legacy flag reads as a voice view");
edit_channel_details(&relay, &held_of(&community), &general, "lobby", Some(" Say hi "), ChannelView::Forum).await.unwrap();
let peer = folded(&community, &fetch_control(&relay, &community).await);
let ch = peer.channel(&general).unwrap();
assert_eq!((ch.name.as_str(), ch.topic(), ch.view()), ("lobby", Some("Say hi"), ChannelView::Forum));
assert_eq!(ch.meta_extra.get("vnd"), Some(&serde_json::Value::from(7)), "a field Vector doesn't drive rides through");
edit_channel_details(&relay, &held_of(&community), &general, "lobby", None, ChannelView::Chat).await.unwrap();
let ch = folded(&community, &fetch_control(&relay, &community).await).channel(&general).unwrap().clone();
assert_eq!((ch.topic(), ch.view()), (None, ChannelView::Chat), "chat over a legacy voice flag is written, not implied");
assert!(edit_channel_details(&relay, &held_of(&community), &general, "lobby", Some(&"x".repeat(1025)), ChannelView::Chat).await.is_err(), "the topic cap");
}
#[tokio::test]
async fn a_refounding_carries_categories_and_filing() {
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "CarryCats", bed.relays.clone(), None).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let staff = create_category(&bed.relay, &held_of(&community), "Staff").await.unwrap();
let general = community.channels[0].id;
move_channel(&bed.relay, &held_of(&community), &general, Some(staff), 0).await.unwrap();
follow_control(&bed.relay, &held_of(&community)).await.unwrap();
set_members_banned(&bed.relay, community.id(), &[Keys::generate().public_key()], true).await.unwrap();
let now = held_of(&community);
assert_ne!(now.root_epoch, community.root_epoch, "the ban re-founded");
let mut fresh = now.clone();
fresh.categories.clear();
let peer = folded(&fresh, &fetch_control(&bed.relay, &now).await);
assert_eq!(sidebar_names(&peer), vec![(None, vec![]), (Some("Staff".into()), vec!["general".into()])]);
}
#[tokio::test]
async fn a_ban_spares_the_floor_of_a_sealed_head() {
// A ban voids a floor its target recorded, unless a Tenure sealed that head: then
// the floor holds, and with the held edition withheld no admin's rival stands in.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "SealedFloor", vec!["wss://r".into()], None).await.unwrap();
publish_everyone(&relay, &community, &owner, 0, 1).await;
let (b, c) = (Keys::generate(), Keys::generate());
let mr = Permissions::MANAGE_ROLES;
let (rb, rc, made) = ("a2".repeat(32), "a3".repeat(32), "a8".repeat(32));
publish_role_v2(&relay, &community, &owner, &role_v2(&rb, "B", "C", mr), 1).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&rc, "C", "D", mr), 1).await;
publish_grant(&relay, &community, &owner, &b.public_key(), vec![rb.clone()], 1).await;
publish_grant(&relay, &community, &owner, &c.public_key(), vec![rc.clone()], 1).await;
publish_role_v2(&relay, &community, &b, &role_v2(&made, "by B", "V", 0), 1).await;
let held = fetch_control(&relay, &community).await.into_iter().find(|e| e.entity_id == eid_of(&made)).unwrap();
publish_tenure(&relay, &community, &owner, &b.public_key(), vec![entry("C", mr, &[held.self_hash])], 1).await;
publish_banlist(&relay, &community, &owner, &[b.public_key().to_hex()], 1).await;
// C, an admin in good standing, serves a rival genesis at B's coordinate.
let group = control::ControlPlane::of(&community).write_group().unwrap();
let cite = cite_on_relay(&relay, &community, &c).await;
let content = crate::community::v2::roles::role_v2_content_json(&role_v2(&made, "by C", "W", 0)).unwrap();
let binding = Some(crate::community::v2::derive::edition_binding(community.id()));
let rumor = control::build_edition_rumor_bound(c.public_key(), vsk::ROLE_V2, &eid_of(&made), 1, None, &content, 1_000, cite.as_ref(), binding);
let (wrap, _) = control::seal_control_edition(&rumor, &group, &c, Timestamp::from_secs(1_000)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
let served: Vec<ParsedEdition> = fetch_control(&relay, &community).await.into_iter().filter(|e| e.inner_id != held.inner_id).collect();
let floors: Floors = [(crate::simd::hex::bytes_to_hex_32(&held.entity_id), (1, held.self_hash, Some(held.inner_id), Some(b.public_key().to_bytes()), None))].into_iter().collect();
assert_eq!(fold_authority(&community, &served, &Floors::default()).roles.role(&made).map(|r| r.name.as_str()), Some("by C"), "read floorless, C's stands");
let f = fold_authority(&community, &served, &floors);
assert!(f.roles.role(&made).is_none_or(|r| r.name != "by C"), "the sealed floor holds against a non-owner rival");
// Withheld is not refused: a relay that drops a sealed head can't settle it absent.
assert!(!f.refused.contains(&crate::simd::hex::bytes_to_hex_32(&held.entity_id)), "the withheld sealed head isn't settled absent");
}
/// Serves everything but the wraps whose edition `hide` picks.
struct Hiding<'a> {
inner: &'a MemoryRelay,
group: crate::community::v2::derive::GroupKey,
hide: Box<dyn Fn(&ParsedEdition) -> bool + Send + Sync + 'a>,
}
#[async_trait::async_trait]
impl Transport for Hiding<'_> {
async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
Ok(crate::community::transport::PlaneFetch::whole(self.fetch(query, relays).await?))
}
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.inner.publish(e, r).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.inner.publish_durable(e, r).await
}
async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
let all = self.inner.fetch(q, r).await?;
Ok(all.into_iter().filter(|w| control::open_control_edition(w, &self.group).ok().is_none_or(|(ed, _)| !(self.hide)(&ed))).collect())
}
}
#[tokio::test]
async fn a_withheld_tenure_leaves_what_it_seals_unsettled() {
// A device tracking a Tenure must not read its absence as evidence: what it sealed
// is neither refused nor stepped down while a relay withholds it.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Withheld", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, 0).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let a = Keys::generate();
let admin = create_role_v2(&bed.relay, &held(), "Admin", 0, Permissions::MANAGE_ROLES).await.unwrap();
set_member_roles(&bed.relay, &held(), &a.public_key(), vec![admin]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let made = "a9".repeat(32);
publish_role_v2(&bed.relay, &held(), &a, &role_v2(&made, "by A", "z", 0), 1).await;
follow_control(&bed.relay, &held()).await.unwrap();
set_member_roles(&bed.relay, &held(), &a.public_key(), vec![]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex).unwrap().into_iter().filter(|(_, f)| f.0 == held().root_epoch.0).map(|(e, f)| (e, (f.1, f.2, f.3, f.4, f.5))).collect();
let served: Vec<ParsedEdition> = fetch_control(&bed.relay, &held()).await.into_iter().filter(|e| e.vsk != vsk::TENURE).collect();
let f = fold_authority(&held(), &served, &floors);
let entity = crate::simd::hex::bytes_to_hex_32(&eid_of(&made));
assert!(!f.refused.contains(&entity), "not settled absent");
assert!(f.heads.iter().any(|h| h.entity_hex == entity && !h.rebased), "the held head stays the head");
assert!(!f.complete, "and the fold knows it read short");
}
#[tokio::test]
async fn a_writer_never_replaces_a_tenure_it_cant_see() {
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Clobber", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, 0).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let a = Keys::generate();
let r1 = create_role_v2(&bed.relay, &held(), "One", 0, Permissions::MANAGE_ROLES).await.unwrap();
let r2 = create_role_v2(&bed.relay, &held(), "Two", 0, Permissions::MANAGE_ROLES).await.unwrap();
set_member_roles(&bed.relay, &held(), &a.public_key(), vec![r1.clone(), r2.clone()]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
publish_role_v2(&bed.relay, &held(), &a, &role_v2(&"b9".repeat(32), "by A", "z", 0), 1).await;
follow_control(&bed.relay, &held()).await.unwrap();
set_member_roles(&bed.relay, &held(), &a.public_key(), vec![r2.clone()]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let hiding = Hiding { inner: &bed.relay, group: control::ControlPlane::of(&held()).write_group().unwrap(), hide: Box::new(|e| e.vsk == vsk::TENURE) };
let before = fetch_control(&bed.relay, &held()).await.len();
forget_held(&held());
let err = set_member_roles(&hiding, &held(), &a.public_key(), vec![]).await.unwrap_err();
assert!(err.contains("isn't being served"), "{err}");
assert_eq!(fetch_control(&bed.relay, &held()).await.len(), before, "nothing was published");
// A removal goes ahead, leaving the unseen Tenure as it was.
kick_member(&hiding, &held(), &a.public_key()).await.unwrap();
let eds = fetch_control(&bed.relay, &held()).await;
assert_eq!(eds.iter().filter(|e| e.vsk == vsk::TENURE).count(), 1, "the earlier Tenure stands alone");
}
#[tokio::test]
async fn a_weaker_writer_seals_beside_a_stronger_one() {
// The owner demoted M from the top; later an admin beneath M's old rank strips M's
// last role. Each seals in a Tenure of their own, so both standings hold.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "TwoWriters", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, 0).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let mr = Permissions::MANAGE_ROLES;
let (m, x) = (Keys::generate(), Keys::generate());
let top = create_role_v2(&bed.relay, &held(), "Top", 0, mr | Permissions::BAN).await.unwrap();
let admin = create_role_v2(&bed.relay, &held(), "Admin", 0, mr).await.unwrap();
let helper = create_role_v2(&bed.relay, &held(), "Helper", 0, mr).await.unwrap();
set_member_roles(&bed.relay, &held(), &m.public_key(), vec![top.clone()]).await.unwrap();
set_member_roles(&bed.relay, &held(), &x.public_key(), vec![admin]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let (early, late) = ("c7".repeat(32), "c8".repeat(32));
publish_role_v2(&bed.relay, &held(), &m, &role_v2(&early, "early", "z", 0), 1).await;
follow_control(&bed.relay, &held()).await.unwrap();
set_member_roles(&bed.relay, &held(), &m.public_key(), vec![helper.clone()]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
publish_role_v2(&bed.relay, &held(), &m, &role_v2(&late, "late", "z", 0), 1).await;
follow_control(&bed.relay, &held()).await.unwrap();
crate::state::MY_SECRET_KEY.store_from_keys(&x, &[]);
crate::state::set_my_public_key(x.public_key());
set_member_roles(&bed.relay, &held(), &m.public_key(), vec![]).await.unwrap();
let eds = fetch_control(&bed.relay, &held()).await;
assert_eq!(eds.iter().filter(|e| e.vsk == vsk::TENURE).count(), 2, "one Tenure per writer");
let f = fold_authority(&held(), &eds, &Floors::default());
assert!(f.roles.role(&early).is_some() && f.roles.role(&late).is_some(), "both standings hold");
}
#[tokio::test]
async fn a_tenure_at_another_writers_coordinate_is_ignored() {
// Each writer's Tenure lives at a coordinate naming them: an admin can't replace the
// owner's Tenure of a member with one of their own.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Squat", vec!["wss://r".into()], None).await.unwrap();
publish_everyone(&relay, &community, &owner, 0, 1).await;
let (a, x) = (Keys::generate(), Keys::generate());
let mr = Permissions::MANAGE_ROLES;
let (ra, rx, made) = ("d7".repeat(32), "d8".repeat(32), "d9".repeat(32));
publish_role_v2(&relay, &community, &owner, &role_v2(&rx, "X", "B", mr), 1).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&ra, "A", "C", mr), 1).await;
publish_grant(&relay, &community, &owner, &x.public_key(), vec![rx.clone()], 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
publish_role_v2(&relay, &community, &a, &role_v2(&made, "by A", "V", 0), 1).await;
let hash = fetch_control(&relay, &community).await.into_iter().find(|e| e.entity_id == eid_of(&made)).unwrap().self_hash;
publish_tenure(&relay, &community, &owner, &a.public_key(), vec![entry("C", mr, &[hash])], 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![], 2).await;
// X writes v2 at the owner's coordinate, sealing nothing of note.
let eid = crate::community::v2::derive::tenure_locator(community.id(), &a.public_key().to_bytes(), &owner.public_key().to_bytes());
let prev = head_hash_on_relay(&relay, &community, &eid).await;
let content = crate::community::v2::roles::tenure_content_json(&crate::community::v2::roles::TenureContent { member: a.public_key().to_hex(), sealed: vec![entry("V", 0, &[[0x11; 32]])] }).unwrap();
publish_marked(&relay, &community, &x, vsk::TENURE, &eid, 2, prev, &content).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
assert!(f.roles.role(&made).is_some(), "the owner's seal still holds");
}
#[tokio::test]
async fn a_reorder_moves_only_what_left_its_run() {
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Reorder", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, 0).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let mut ids = Vec::new();
for name in ["A", "B", "C", "D", "E"] {
ids.push(create_role_v2(&bed.relay, &held(), name, 0, 0).await.unwrap());
}
let order = |eds: &[ParsedEdition]| {
let f = fold_authority(&held(), eds, &Floors::default());
let mut roles: Vec<&crate::community::roles::Role> = f.roles.roles.iter().collect();
roles.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.role_id.cmp(&b.role_id)));
roles.into_iter().map(|r| r.name.clone()).collect::<Vec<_>>()
};
let pick = |names: &str| names.chars().map(|c| ids[(c as u8 - b'A') as usize].clone()).collect::<Vec<_>>();
let before = fetch_control(&bed.relay, &held()).await.len();
assert_eq!(reorder_roles_v2(&bed.relay, &held(), &pick("EABCD")).await.unwrap(), 1, "one Role left its run");
assert_eq!(fetch_control(&bed.relay, &held()).await.len(), before + 1);
assert_eq!(order(&fetch_control(&bed.relay, &held()).await), ["E", "A", "B", "C", "D"]);
assert_eq!(reorder_roles_v2(&bed.relay, &held(), &pick("DBAEC")).await.unwrap(), 3);
assert_eq!(order(&fetch_control(&bed.relay, &held()).await), ["D", "B", "A", "E", "C"]);
assert_eq!(reorder_roles_v2(&bed.relay, &held(), &pick("DBAEC")).await.unwrap(), 0, "nothing to do");
}
#[tokio::test]
async fn moving_a_role_up_past_its_grantor_keeps_it_with_its_holders() {
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "MoveUp", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, 0).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let (x, m) = (Keys::generate(), Keys::generate());
let admin = create_role_v2(&bed.relay, &held(), "Admin", 0, Permissions::MANAGE_ROLES).await.unwrap();
let vip = create_role_v2(&bed.relay, &held(), "VIP", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(), &x.public_key(), vec![admin]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
crate::state::MY_SECRET_KEY.store_from_keys(&x, &[]);
crate::state::set_my_public_key(x.public_key());
set_member_roles(&bed.relay, &held(), &m.public_key(), vec![vip.clone()]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
bed.swap_to(&owner);
move_role_v2(&bed.relay, &held(), &vip, 0).await.unwrap();
let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
assert_eq!(f.roles.highest_position(&m.public_key().to_hex()), Some(1), "M still holds VIP, now at the top");
}
#[tokio::test]
async fn a_seal_lends_every_standing_above_what_it_touches() {
// Two entries list one Banlist edition: MANAGE_ROLES high, BAN lower. A target beneath
// both is banned on the union, as Roles above it would lend.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Union", vec!["wss://r".into()], None).await.unwrap();
publish_everyone(&relay, &community, &owner, 0, 1).await;
let (a, t) = (Keys::generate(), Keys::generate());
let ra = "d3".repeat(32);
publish_role_v2(&relay, &community, &owner, &role_v2(&ra, "Mod", "C", Permissions::MANAGE_ROLES | Permissions::BAN), 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
publish_banlist(&relay, &community, &a, &[t.public_key().to_hex()], 1).await;
let banlist = fetch_control(&relay, &community).await.into_iter().find(|e| e.entity_id == crate::community::v2::derive::banlist_locator(community.id())).unwrap().self_hash;
publish_tenure(&relay, &community, &owner, &a.public_key(), vec![entry("C", Permissions::MANAGE_ROLES, &[banlist]), entry("F", Permissions::BAN, &[banlist])], 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![], 2).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
assert!(f.banned.contains(&t.public_key().to_hex()));
}
#[tokio::test]
async fn a_strip_to_nothing_seals_even_on_a_stale_roster() {
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Stale", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, 0).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let a = Keys::generate();
// Granted on the plane, never folded here.
let ra = "d5".repeat(32);
publish_role_v2(&bed.relay, &held(), &owner.keys, &role_v2(&ra, "Admin", "C", Permissions::MANAGE_ROLES), 1).await;
publish_grant(&bed.relay, &held(), &owner.keys, &a.public_key(), vec![ra], 1).await;
publish_role_v2(&bed.relay, &held(), &a, &role_v2(&"d6".repeat(32), "by A", "z", 0), 1).await;
grant_roles(&bed.relay, &held(), &a.public_key(), vec![]).await.unwrap();
assert_eq!(fetch_control(&bed.relay, &held()).await.iter().filter(|e| e.vsk == vsk::TENURE).count(), 1);
let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
assert!(f.roles.role(&"d6".repeat(32)).is_some(), "what they made stands on the seal");
}
#[test]
fn a_seal_keeps_a_members_deletions_ahead_of_everything_else() {
let head = |n: u8, author: u8| FoldedHead { entity_hex: String::new(), version: 1, self_hash: [n; 32], inner_id: [n; 32], author: [author; 32], rebased: false };
let (grant, edit, deletion, theirs_not) = (head(1, 9), head(2, 9), head(3, 9), head(4, 8));
let order = seal_order(&[grant.clone()], &[edit.clone(), deletion.clone(), theirs_not], |h| h.author == [9; 32], |h| h.self_hash == [3; 32]);
assert_eq!(order, vec![[3; 32], [1; 32], [2; 32]], "a budget cut takes a channel edit, never a deletion");
}
#[tokio::test]
async fn a_tenure_goes_to_every_relay() {
struct Counting<'a> {
inner: &'a MemoryRelay,
durable: std::sync::atomic::AtomicUsize,
}
#[async_trait::async_trait]
impl Transport for Counting<'_> {
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
self.inner.fetch_plane(plane, query, relays).await
}
async fn publish(&self, event: &Event, relays: &[String]) -> Result<(), String> {
self.inner.publish(event, relays).await
}
async fn publish_durable(&self, event: &Event, relays: &[String]) -> Result<(), String> {
self.durable.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
self.inner.publish_durable(event, relays).await
}
async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
self.inner.fetch(query, relays).await
}
}
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Durable", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, 0).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let a = Keys::generate();
let ra = "e5".repeat(32);
publish_role_v2(&bed.relay, &held(), &owner.keys, &role_v2(&ra, "Admin", "C", Permissions::MANAGE_ROLES), 1).await;
publish_grant(&bed.relay, &held(), &owner.keys, &a.public_key(), vec![ra], 1).await;
publish_role_v2(&bed.relay, &held(), &a, &role_v2(&"e6".repeat(32), "by A", "z", 0), 1).await;
let counting = Counting { inner: &bed.relay, durable: Default::default() };
grant_roles(&counting, &held(), &a.public_key(), vec![]).await.unwrap();
assert_eq!(fetch_control(&bed.relay, &held()).await.iter().filter(|e| e.vsk == vsk::TENURE).count(), 1);
assert_eq!(counting.durable.load(std::sync::atomic::Ordering::Relaxed), 1, "the Tenure, and only it, went out durably");
}
#[tokio::test]
async fn every_reduction_seals_what_the_member_decided() {
// The writer side: a strip, a deletion, a bit dropped, a move down and a ban each
// publish the member's Tenure first, so what they decided stands for every reader.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Duty", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, 0).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let bits = Permissions::MANAGE_ROLES | Permissions::BAN | Permissions::MANAGE_CHANNELS;
let members: Vec<Keys> = (0..5).map(|_| Keys::generate()).collect();
let mut roles = Vec::new();
for (i, k) in members.iter().enumerate() {
let rid = create_role_v2(&bed.relay, &held(), &format!("Admin {i}"), 0, bits).await.unwrap();
set_member_roles(&bed.relay, &held(), &k.public_key(), vec![rid.clone()]).await.unwrap();
roles.push(rid);
}
follow_control(&bed.relay, &held()).await.unwrap();
let made: Vec<String> = ["c1", "c2", "c3", "c4", "c5"].iter().map(|p| p.repeat(32)).collect();
for (k, id) in members.iter().zip(&made) {
publish_role_v2(&bed.relay, &held(), k, &role_v2(id, "Made", "z", 0), 1).await;
}
follow_control(&bed.relay, &held()).await.unwrap();
let granted = Keys::generate();
publish_grant(&bed.relay, &held(), &members[4], &granted.public_key(), vec![made[4].clone()], 1).await;
let ch = community.channels[0].id;
let v1 = head_hash_on_relay(&bed.relay, &held(), &ch.0).await;
publish_fork(&[&bed.relay], &held(), &members[4], vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("by the banned"), None).await;
follow_control(&bed.relay, &held()).await.unwrap();
let standing = |at: &CommunityV2, eds: &[ParsedEdition]| {
let f = fold_authority(at, eds, &Floors::default());
made.iter().map(|id| f.roles.role(id).is_some()).collect::<Vec<bool>>()
};
assert_eq!(standing(&held(), &fetch_control(&bed.relay, &held()).await), vec![true; 5]);
set_member_roles(&bed.relay, &held(), &members[0].public_key(), vec![]).await.unwrap();
delete_role_v2(&bed.relay, &held(), &roles[1]).await.unwrap();
edit_role_v2(&bed.relay, &held(), &roles[2], "Admin 2", 0, Permissions::BAN, false, false).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
move_role_v2(&bed.relay, &held(), &roles[3], usize::MAX).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let eds = fetch_control(&bed.relay, &held()).await;
let f = fold_authority(&held(), &eds, &Floors::default());
for (k, r) in members.iter().zip(&roles).take(4) {
assert!(!f.roles.permissions_above(&k.public_key().to_hex(), u32::MAX).contains(Permissions::MANAGE_ROLES) || f.roles.role(r).is_some_and(|x| x.rank.as_deref() > Some("z")), "each reduction took");
}
assert_eq!(standing(&held(), &eds), vec![true; 5], "and each member's role stands on its Tenure");
// A ban re-founds the plane: the Tenures and what they seal are carried across.
set_members_banned(&bed.relay, held().id(), &[members[4].public_key()], true).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let now = held();
assert_ne!(now.root_epoch, community.root_epoch, "the ban re-founded");
let eds = fetch_control(&bed.relay, &now).await;
assert!(fold_authority(&now, &eds, &Floors::default()).banned.contains(&members[4].public_key().to_hex()));
assert_eq!(standing(&now, &eds), vec![true; 5], "the banned admin's role stands too");
let f = fold_authority(&now, &eds, &Floors::default());
assert!(f.roles.roles_of(&granted.public_key().to_hex()).any(|r| r.role_id == made[4]), "so does their Grant");
let fold = apply_control_fold(&now, &eds, &Floors::default(), &f);
assert_eq!(fold.updated.as_ref().unwrap_or(&now).channel(&ch).unwrap().name, "by the banned", "and their channel edit");
// This device's own read, on the floors it holds, agrees.
let cached = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&now.id().0)).unwrap();
assert!(made.iter().all(|id| cached.role(id).is_some()), "the followed roster keeps every sealed role");
}
#[tokio::test]
async fn a_reduction_its_writer_cant_seal_waits_but_a_ban_does_not() {
// A role edit that would drop decisions the writer couldn't have made is refused; a
// removal goes ahead, sealing what the writer can.
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Limits", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, 0).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let moderator = Keys::generate();
let (target, kicked) = (Keys::generate(), Keys::generate());
let mr = Permissions::MANAGE_ROLES;
let top = create_role_v2(&bed.relay, &held(), "Moderator", 0, mr | Permissions::BAN | Permissions::KICK).await.unwrap();
let below = create_role_v2(&bed.relay, &held(), "Channels", 0, mr | Permissions::MANAGE_CHANNELS).await.unwrap();
set_member_roles(&bed.relay, &held(), &moderator.public_key(), vec![top]).await.unwrap();
for k in [&target, &kicked] {
set_member_roles(&bed.relay, &held(), &k.public_key(), vec![below.clone()]).await.unwrap();
}
follow_control(&bed.relay, &held()).await.unwrap();
let (made, made_kicked) = ("d1".repeat(32), "d2".repeat(32));
publish_role_v2(&bed.relay, &held(), &target, &role_v2(&made, "Made", "z", 0), 1).await;
publish_role_v2(&bed.relay, &held(), &kicked, &role_v2(&made_kicked, "Made", "z", 0), 1).await;
follow_control(&bed.relay, &held()).await.unwrap();
crate::state::MY_SECRET_KEY.store_from_keys(&moderator, &[]);
crate::state::set_my_public_key(moderator.public_key());
let before = fetch_control(&bed.relay, &held()).await.len();
let err = set_member_roles(&bed.relay, &held(), &target.public_key(), vec![]).await.unwrap_err();
assert!(err.contains("permissions you don't"), "{err}");
assert_eq!(fetch_control(&bed.relay, &held()).await.len(), before, "nothing was published");
kick_member(&bed.relay, &held(), &kicked.public_key()).await.unwrap();
let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
assert!(f.roles.roles_of(&kicked.public_key().to_hex()).next().is_none(), "the kick stripped");
assert!(f.roles.role(&made_kicked).is_some(), "and sealed what it could");
set_members_banned(&bed.relay, held().id(), &[target.public_key()], true).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let eds = fetch_control(&bed.relay, &held()).await;
let f = fold_authority(&held(), &eds, &Floors::default());
assert!(f.banned.contains(&target.public_key().to_hex()), "the ban went ahead");
assert!(f.roles.role(&made).is_some(), "sealing the bits the moderator holds, which is enough for this role");
}
#[tokio::test]
async fn a_grant_draws_only_on_authority_above_what_it_touches() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "GrantSupport", vec!["wss://r".into()], None).await.unwrap();
let c = Keys::generate();
let (rtop, rlow, r5) = ("e1".repeat(32), "e2".repeat(32), "e3".repeat(32));
// C ranks at 2, but holds MANAGE_ROLES only through a role at 8.
publish_role(&relay, &community, &owner, &role_at(&rtop, "Top", 2, 0), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 8, Permissions::MANAGE_ROLES), 1).await;
publish_role(&relay, &community, &owner, &role_at(&r5, "Five", 5, Permissions::KICK), 1).await;
publish_grant(&relay, &community, &owner, &c.public_key(), vec![rtop.clone(), rlow.clone()], 1).await;
let (m1, m2) = (Keys::generate().public_key(), Keys::generate().public_key());
publish_grant(&relay, &community, &c, &m1, vec![r5.clone()], 1).await;
// Beneath 8 the same authority is enough.
let r9 = "e4".repeat(32);
publish_role(&relay, &community, &owner, &role_at(&r9, "Nine", 9, 0), 1).await;
publish_grant(&relay, &community, &c, &m2, vec![r9.clone()], 1).await;
// And nobody but the owner touches the owner's own grant.
publish_grant(&relay, &community, &c, &owner.public_key(), vec![r9.clone()], 1).await;
// Nor anyone their own grant: a manager taking a lower role that bans would gain BAN.
let mgr = Keys::generate();
let (rmgr, rban) = ("e5".repeat(32), "e6".repeat(32));
publish_role(&relay, &community, &owner, &role_at(&rmgr, "Mgr", 3, Permissions::MANAGE_ROLES), 1).await;
publish_role(&relay, &community, &owner, &role_at(&rban, "Ban", 7, Permissions::BAN), 1).await;
publish_grant(&relay, &community, &owner, &mgr.public_key(), vec![rmgr.clone()], 1).await;
publish_grant(&relay, &community, &mgr, &mgr.public_key(), vec![rmgr.clone(), rban.clone()], 2).await;
let a = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
assert!(!a.roles.has_permission(&mgr.public_key().to_hex(), Permissions::BAN), "a self-grant confers nothing");
assert!(a.roles.roles_of(&m1.to_hex()).next().is_none(), "MANAGE_ROLES from a role beneath 5 can't grant at 5");
assert!(a.roles.roles_of(&m2.to_hex()).any(|r| r.role_id == r9), "it can beneath 8");
assert!(a.roles.roles_of(&owner.public_key().to_hex()).next().is_none(), "the owner is never a target");
}
#[tokio::test]
async fn a_refused_channel_head_falls_back_only_on_a_complete_fold() {
let (_tmp, _guard, owner) = init_test_db();
let full = MemoryRelay::new();
let (community, admin) = with_admin(&full, "ChannelFallback", &owner, Permissions::MANAGE_CHANNELS).await;
let thin = MemoryRelay::new();
mirror_control(&full, &thin, &community).await;
// A role only the full relay serves: floored, so a thin read is incomplete.
publish_role(&full, &community, &owner, &role_at(&"f9".repeat(32), "Kept", 9, 0), 1).await;
let ch = community.channels[0].id;
let v1 = head_hash_on_relay(&full, &community, &ch.0).await;
publish_fork(&[&full, &thin], &community, &admin, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("admin-name"), None).await;
follow_control(&full, &community).await.unwrap();
assert_eq!(floor_of(&community, &ch.0).0, 2);
// The owner strips the admin on both relays: the v2 head is now refused.
let geid = crate::community::v2::derive::grant_locator(community.id(), &admin.public_key().to_bytes());
let gv1 = head_hash_on_relay(&full, &community, &geid).await;
let strip = crate::community::v2::roles::grant_content_json_with_wrap(&MemberGrant { member: admin.public_key().to_hex(), role_ids: vec![] }, None).unwrap();
publish_fork(&[&full, &thin], &community, &owner, vsk::GRANT, &geid, 2, gv1, &strip, None).await;
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
forget_held(&held);
follow_control(&thin, &held).await.unwrap();
assert_eq!(floor_of(&community, &ch.0).0, 2, "an incomplete read never moves a floor down");
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let updated = follow_control(&full, &held).await.unwrap().updated.expect("the refused head yields");
assert_eq!(updated.channel(&ch).unwrap().name, "general", "back to the newest admitted edition");
assert_eq!(floor_of(&community, &ch.0).0, 1);
}
#[tokio::test]
async fn the_role_editor_refuses_exactly_what_readers_would_drop() {
let (bed, owner, mgr) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "SubsetEditor", bed.relays.clone(), None).await.unwrap();
let rmgr = "a2".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &role_at(&rmgr, "Mgr", 2, Permissions::MANAGE_ROLES | Permissions::KICK), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &mgr.keys.public_key(), vec![rmgr], 1).await;
let guarded = create_role(&bed.relay, &community, "Guarded", 0, Permissions::BAN, RoleScope::Server).await.unwrap();
let stripped = create_role(&bed.relay, &community, "Stripped", 0, Permissions::BAN | Permissions::KICK, RoleScope::Server).await.unwrap();
let k1 = create_role(&bed.relay, &community, "K1", 0, Permissions::KICK, RoleScope::Server).await.unwrap();
let k2 = create_role(&bed.relay, &community, "K2", 0, Permissions::KICK, RoleScope::Server).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
bed.swap_to(&mgr);
crate::db::community::save_community_v2(&community).unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let pos = |v: &AuthorityView, id: &str| folded_role(v, id).position;
let before = fetch_authority(&bed.relay, &community).await;
let err = create_role(&bed.relay, &community, "Mine", 0, Permissions::BAN, RoleScope::Server).await.unwrap_err();
assert!(err.contains("don't hold"), "{err}");
let err = edit_role(&bed.relay, &community, &guarded, "Renamed", 0, Permissions::BAN, RoleScope::Server).await.unwrap_err();
assert!(err.contains("don't hold"), "keeping a bit you lack is carrying it: {err}");
// Stripping a bit you lack leaves a role you could have made: readers admit it.
edit_role(&bed.relay, &community, &stripped, "Stripped", 0, Permissions::KICK, RoleScope::Server).await.expect("a strip of what you lack");
let after_strip = fetch_authority(&bed.relay, &community).await;
assert_eq!(folded_role(&after_strip, &stripped).permissions.0, Permissions::KICK, "and the fold seats it");
// Moving the guarded role is refused, and nothing else moved on the way.
let err = reorder_roles(&bed.relay, &community, &[k1.clone(), guarded.clone(), stripped.clone(), k2.clone()]).await.unwrap_err();
assert!(err.contains("Guarded"), "{err}");
let mid = fetch_authority(&bed.relay, &community).await;
for id in [&guarded, &stripped, &k1, &k2] {
assert_eq!(pos(&mid, id), pos(&after_strip, id), "a refused reorder publishes nothing");
}
// Reordering roles of held bits beneath it works.
let moved = reorder_roles(&bed.relay, &community, &[guarded.clone(), stripped.clone(), k2.clone(), k1.clone()]).await.expect("beneath the guarded role");
assert!(moved > 0);
let after = fetch_authority(&bed.relay, &community).await;
assert!(pos(&after, &k2) < pos(&after, &k1));
assert_eq!(pos(&after, &guarded), pos(&before, &guarded));
// The editor's view marks exactly the role it can't touch.
follow_control(&bed.relay, &community).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let view = crate::VectorCore.community_roles_view(&cid_hex).unwrap();
let manageable = |id: &str| view["roles"].as_array().unwrap().iter().find(|r| r["role_id"] == id).map(|r| r["manageable"] == true);
assert_eq!(manageable(&guarded), Some(false));
assert_eq!(manageable(&k1), Some(true));
}
#[tokio::test]
async fn a_mid_rank_admin_cannot_demote_a_role_that_outranks_them() {
// CORD-04 §2 rank inversion. Minting at a position you outrank is
// necessary but NOT sufficient: an edition replaces the entity, so a
// gate that only reads the NEW position lets an admin at position 5
// rewrite the position-1 role to position 9. Every check passes (9 is
// beneath them), and the role that outranked them — plus everyone
// holding it — is now beneath them.
let (bed, owner, attacker) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Ranks", bed.relays.clone(), None).await.unwrap();
// A senior role at position 1, and a mid role at position 5 the attacker holds.
let senior = "a1".repeat(32);
let mid = "a5".repeat(32);
publish_role(&bed.relay, &community, &owner.keys,
&Role { role_id: senior.clone(), name: "Senior".into(), position: 1, permissions: Permissions(Permissions::BAN), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() }, 1).await;
publish_role(&bed.relay, &community, &owner.keys,
&Role { role_id: mid.clone(), name: "Mid".into(), position: 5, permissions: Permissions(Permissions::MANAGE_ROLES | Permissions::BAN), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() }, 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &attacker.keys.public_key(), vec![mid.clone()], 1).await;
// The attacker republishes the SENIOR role, dropping it beneath themselves.
publish_role(&bed.relay, &community, &attacker.keys,
&Role { role_id: senior.clone(), name: "Senior".into(), position: 9, permissions: Permissions(Permissions::BAN), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() }, 2).await;
let authority = fetch_authority(&bed.relay, &community).await;
let folded_senior = authority.roles.role(&senior).expect("the senior role survives the fold");
assert_eq!(
folded_senior.position, 1,
"a role may only be repositioned by someone who outranks where it STOOD, not just where it lands",
);
}
#[tokio::test]
async fn a_non_owner_admins_edition_cites_its_grant_and_the_owners_does_not() {
// CORD-04 §5. Armada's reader REQUIRES this on every non-owner control
// edition (`citationOk`: "a non-owner action MUST cite its grant"), so
// an uncited Vector admin's ban/role/channel edit was silently dropped
// by every Armada client — only the owner's actions crossed. The
// citation must name the actor's OWN grant coordinate, at the version
// and edition hash the verifier can match against a grant it holds.
let (bed, owner, admin) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Cited", bed.relays.clone(), None).await.unwrap();
let rid = "c1".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN | Permissions::MANAGE_METADATA), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin.keys.public_key(), vec![rid], 1).await;
// The owner's own edition carries NO citation: their rank is the id.
let owner_meta = control::CommunityMetadata { name: "By Owner".into(), relays: community.relays.clone(), ..Default::default() };
edit_community_metadata(&bed.relay, &community, &owner_meta).await.unwrap();
let owner_ed = fetch_control(&bed.relay, &community).await.into_iter()
.filter(|e| e.author == owner.keys.public_key() && e.vsk == vsk::COMMUNITY_METADATA)
.max_by_key(|e| e.version).expect("the owner's metadata edition");
assert!(owner_ed.authority.is_none(), "the owner cites nothing — rank comes from the community id");
// The admin JOINS and folds — the citation names the grant head their own
// client has actually synced, so the fold must have persisted it.
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&admin);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
set_banlist(&bed.relay, &joined, &["ee".repeat(32)]).await.unwrap();
let ban_ed = fetch_control(&bed.relay, &joined).await.into_iter()
.find(|e| e.author == admin.keys.public_key() && e.vsk == vsk::BANLIST)
.expect("the admin's banlist edition");
let cite = ban_ed.authority.as_ref().expect("a non-owner MUST cite its grant");
assert_eq!(
cite.entity_id,
crate::community::v2::derive::grant_locator(community.id(), &admin.keys.public_key().to_bytes()),
"the citation must name the ACTOR'S OWN grant coordinate",
);
assert!(cite.version >= 1, "pinned to a real grant version");
}
#[tokio::test]
async fn a_folded_metadata_edition_cannot_push_the_relay_set_past_the_cap() {
// `cap_relays` is the truncate-on-read invariant everywhere else, and the
// fold is a boundary like any other: MANAGE_METADATA makes an editor
// authorized, not trusted. An oversize list costs every member a fan-out
// per publish and the slowest of N per fetch — and Armada caps at 5, so
// an uncapped fold also splits the two clients' operative sets.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Fanout", vec!["wss://a".into()], None).await.unwrap();
let many: Vec<String> = (0..30).map(|i| format!("wss://r{i}")).collect();
let meta = control::CommunityMetadata { name: "Fanout".into(), relays: many, ..Default::default() };
edit_community_metadata(&relay, &community, &meta).await.unwrap();
let updated = follow_control(&relay, &community).await.unwrap().updated
.expect("the metadata edition is folded");
assert_eq!(
updated.relays.len(),
crate::community::MAX_COMMUNITY_RELAYS,
"a folded relay list must be truncated, never adopted whole",
);
// …and the fold must SETTLE: comparing an oversize edition against the
// capped working set would never be equal, so every later fold would
// report a change and re-save forever.
let again = follow_control(&relay, &updated).await.unwrap().updated;
assert!(again.is_none(), "re-folding the same oversize edition must be a no-op");
}
#[tokio::test]
async fn adopting_a_rotation_writes_no_registry_where_i_never_minted() {
// One Invite List spans every community, so "I hold links" must never be
// read as "I hold links HERE". A member with links elsewhere adopting a
// rotation would otherwise publish an empty Registry edition into this
// community — a control-plane write and a version bump on a coordinate
// they never owned, every rotation, forever.
let (bed, owner, me) = TestBed::new();
bed.swap_to(&owner);
let host = create_community(&bed.relay, "Host", bed.relays.clone(), None).await.unwrap();
let rid = "b2".repeat(32);
publish_role(&bed.relay, &host, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
publish_grant(&bed.relay, &host, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
let bundle = bundle_of(&host, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&me);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
// My only link lives in a DIFFERENT community — one I own, since minting
// is offer-gated on CREATE_INVITE.
let elsewhere = create_community(&bed.relay, "Elsewhere", bed.relays.clone(), None).await.unwrap();
mint_public_link(&bed.relay, &elsewhere, "https://other", None, None).await.unwrap();
let before = bed.relay.stored_count();
let new_root = [0xE1; 32];
publish_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await;
let rotation_events = bed.relay.stored_count() - before;
let after_adopt = bed.relay.stored_count();
follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
assert_eq!(
bed.relay.stored_count(),
after_adopt,
"adopting a rotation must publish NOTHING when I minted no links here",
);
assert!(rotation_events > 0, "the rotation itself did publish (guards the counter)");
}
#[tokio::test]
async fn an_expired_link_stops_keeping_the_community_public() {
// CORD-05 §1/§5: expiry is the one way a link dies with no user action.
// A joiner is refused by `InviteBundle::expired`, so leaving the link in
// the Registry states a door that isn't there — the aggregate never
// empties and the community reads Public forever, silently inverting
// every gate that hangs off that reading.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Lapsing", vec!["wss://r".into()], None).await.unwrap();
// A link that lapsed a minute ago.
let past = now_ms() - 60_000;
mint_public_link(&relay, &community, "https://x", Some(past), None).await.unwrap();
assert!(
!community_is_public(&relay, &community).await,
"an already-expired link must never read as a live door",
);
// …and one that hasn't, to prove the filter isn't just dropping everything.
mint_public_link(&relay, &community, "https://y", Some(now_ms() + 600_000), None).await.unwrap();
assert!(community_is_public(&relay, &community).await, "an unexpired link is still live");
}
#[tokio::test]
async fn minting_a_link_makes_the_community_public_and_revoke_makes_it_private() {
// CORD-05 §5: the Registry is the Public/Private source of truth. Minting a
// link publishes it (Public); retiring the last link empties it (Private).
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Invitable", vec!["wss://r".into()], None).await.unwrap();
assert!(!community_is_public(&relay, &community).await, "a fresh community is Private");
let minted = mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
assert!(community_is_public(&relay, &community).await, "a live link makes it Public");
let list = fetch_invite_list(&relay, &community.relays).await.unwrap().expect("the 13303 list was published");
assert_eq!(list.entries.len(), 1, "the minted link is recorded across devices");
let token_hex = crate::simd::hex::bytes_to_hex_16(&minted.token);
revoke_public_link(&relay, &community, &token_hex).await.unwrap();
assert!(!community_is_public(&relay, &community).await, "retiring the last link makes it Private again");
let after = fetch_invite_list(&relay, &community.relays).await.unwrap().unwrap();
assert!(after.entries.is_empty() && after.tombstones.len() == 1, "the link is tombstoned in the invite list");
}
#[tokio::test]
async fn the_registry_is_cached_locally_so_public_private_is_a_sync_read() {
// Every caller reads the `invite_registry` COLUMN, never the async fold. v2
// published the Registry to the plane but never mirrored it locally, so every
// v2 community read Private no matter how many live links it had.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Cached", vec!["wss://r".into()], None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let cached = || crate::db::community::get_community_invite_registry(&cid_hex).unwrap();
// The per-creator split is a SEPARATE table, and it drives the "first link flips
// the community Public" confirm — an empty one re-asks on every later link.
let per_creator = || crate::db::community::get_invite_link_sets(&cid_hex).unwrap();
assert!(cached().is_empty(), "a fresh community caches an empty registry");
assert!(per_creator().is_empty(), "…and no per-creator sets");
let minted = mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
assert!(!cached().is_empty(), "minting caches the registry, so the UI reads Public without folding");
let sets = per_creator();
assert_eq!(sets.len(), 1, "the minting creator gets a set");
assert_eq!(sets[0].locators.len(), 1, "carrying exactly their one live link");
// Both caches must SHRINK too — a union-only mirror would strand it Public.
let token_hex = crate::simd::hex::bytes_to_hex_16(&minted.token);
revoke_public_link(&relay, &community, &token_hex).await.unwrap();
assert!(cached().is_empty(), "retiring the last link empties the cache back to Private");
assert!(per_creator().is_empty(), "…and clears the per-creator sets");
}
#[tokio::test]
async fn a_rogue_registry_fork_cannot_retire_the_owners_live_link() {
// Registries are coordinate-bound to their creator, but `fold_head` picks an
// equal-version winner AUTHOR-BLIND, by lowest inner id — and an author grinds
// that freely by varying content. Folding before authorising would let any
// member occupy the owner's registry head, fail the authority check, and drop
// the whole registry: a live invite link silently retired, flipping the
// community to Private and steering a moderator into the wrong ban remedy.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Forked", vec!["wss://r".into()], None).await.unwrap();
mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
assert!(community_is_public(&relay, &community).await, "a live link makes it Public");
let cid = community.id();
let control = control::ControlPlane::of(&community).write_group().unwrap();
let eid = crate::community::v2::derive::invite_links_locator(cid, &owner.public_key().to_bytes());
let query = Query {
kinds: vec![stream::KIND_WRAP],
authors: vec![control.pk_hex()],
limit: Some(FOLLOW_PAGE),
..Default::default()
};
let wraps = relay.fetch(&query, &community.relays).await.unwrap();
let target = wraps
.iter()
.filter_map(|w| control::open_control_edition(w, &control).ok().map(|(e, _)| e))
.filter(|e| e.entity_id == eid)
.max_by_key(|e| e.version)
.expect("the owner published a registry");
// Grind a same-version fork under the owner's coordinate that OUTRANKS the
// real head on the tiebreak (~2 tries against a uniform id).
let rogue = Keys::generate();
let mut planted = false;
for n in 0..4_000u64 {
let content = format!("[{{\"token\":\"{n:032x}\",\"url\":\"https://evil\",\"expires_at\":0}}]");
let rumor = control::build_edition_rumor(
rogue.public_key(),
vsk::INVITE_LINKS,
&eid,
target.version,
target.prev_hash.as_ref(),
&content,
9_000,
None,
);
let (w, _) = control::seal_control_edition(&rumor, &control, &rogue, Timestamp::from_secs(9_000)).unwrap();
let (ed, _) = control::open_control_edition(&w, &control).unwrap();
if ed.inner_id < target.inner_id {
relay.publish(&w, &community.relays).await.unwrap();
planted = true;
break;
}
}
assert!(planted, "the test needs a fork that wins the tiebreak");
assert!(
community_is_public(&relay, &community).await,
"an unauthorised fork must not retire the owner's live link"
);
}
#[tokio::test]
async fn a_registry_from_a_non_create_invite_holder_does_not_make_it_public() {
// The CREATE_INVITE gate: a rogue publishing a registry can't fake Public.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Gated", vec!["wss://r".into()], None).await.unwrap();
let rogue = Keys::generate();
// Rogue publishes a registry edition at THEIR coordinate with a fake signer.
let eid = crate::community::v2::derive::invite_links_locator(community.id(), &rogue.public_key().to_bytes());
let content = crate::community::v2::invite::build_registry_content(&[Keys::generate().public_key()]);
let group = control::ControlPlane::of(&community).write_group().unwrap();
let rumor = control::build_edition_rumor(rogue.public_key(), vsk::INVITE_LINKS, &eid, 1, None, &content, 1_000, None);
let (wrap, _) = control::seal_control_edition(&rumor, &group, &rogue, Timestamp::from_secs(1_000)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
let _ = owner;
assert!(!community_is_public(&relay, &community).await, "a non-CREATE_INVITE registry is ignored");
}
#[tokio::test]
async fn full_lifecycle_e2e() {
// The whole stack end to end across two accounts: create -> Public link ->
// owner grants an admin -> member joins + reads history -> admin edits metadata
// (authorized fold) -> owner bans the member (CORD-04 §6: banlist + strip +
// Refounding) -> the banned member is severed AND stays banned across the new
// epoch -> pre-ban history still reads -> owner dissolves -> sealed.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Lifecycle", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
send_message(&bed.relay, &community, &general, "owner: welcome").await.unwrap();
// Public link → the community reads Public.
let _minted = mint_public_link(&bed.relay, &community, "https://x", None, None).await.unwrap();
assert!(community_is_public(&bed.relay, &community).await, "a live link makes it Public");
// Owner defines + grants an Admin role (MANAGE_METADATA among the bits).
let rid = "aa".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid], 1).await;
// Member joins from the bundle + reads the owner's message.
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&member);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
assert_eq!(texts_in(&bed.relay, &joined, &general).await, vec!["owner: welcome"]);
// The admin folds first — adopting the staff write key their Grant
// delivered (CORD-04 §3) — then renames the community.
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
assert!(joined.control_root.is_some(), "the Grant's control_wrap was adopted on fold");
publish_community_meta(&bed.relay, &joined, &member.keys, "Lifecycle Renamed", 2).await;
// Owner follows: the admin's rename folds (authorized).
bed.swap_to(&owner);
let updated = follow_control(&bed.relay, &community).await.unwrap().updated.expect("the admin edit folds");
assert_eq!(updated.name, "Lifecycle Renamed", "an authorized admin's metadata edit is honored");
// Ban the member (the three-removal composition, in order).
set_banlist(&bed.relay, &updated, &[member.keys.public_key().to_hex()]).await.unwrap();
grant_roles(&bed.relay, &updated, &member.keys.public_key(), vec![]).await.unwrap();
let refounded = refound_community(&bed.relay, &updated, &[member.keys.public_key()]).await.unwrap();
assert_eq!(refounded.root_epoch, Epoch(1), "the ban rolled the root");
// The ban survives the Refounding (the banlist head compacted forward).
let post = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &load_floors(&refounded));
assert!(post.banned.contains(&member.keys.public_key().to_hex()), "the ban survives the re-founding");
// Pre-ban history still reads across the new epoch.
assert!(
all_texts_in(&bed.relay, &refounded, &general).await.contains(&"owner: welcome".to_string()),
"pre-refounding history stays reachable by paging"
);
// The banned member's rekey-follow concludes they're severed. Guard captured AFTER
// the swap (the harness swap bumps the generation like production).
bed.swap_to(&member);
let session = crate::db::current_session();
let follow = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
assert!(follow.self_removed, "the banned member is cryptographically cut");
// Owner dissolves → sealed.
bed.swap_to(&owner);
dissolve_community(&bed.relay, &refounded).await.unwrap();
assert!(crate::db::community::load_community_v2(community.id()).unwrap().unwrap().dissolved, "the community is sealed");
}
/// The deep two-account e2e the way a real deployment runs: owner (A) + member (B)
/// over one shared relay, create → channels (public + private) → converse both ways →
/// persist (get_messages-level) → react/edit/delete → moderate (ban/unban) → dissolve.
/// Every account, community, channel, and action is LOGGED (run with --nocapture) so it
/// doubles as a reference transcript and a re-runnable regression.
#[tokio::test]
async fn a_forged_edition_cannot_suppress_a_role_across_a_refounding() {
// A member forges a higher-version role edition at the admin coordinate before a
// refounding. The compaction must carry the AUTHORIZED floor head, not the
// author-blind version tip — else the forgery is re-anchored, honest folders drop
// it, and the admin role vanishes at the new epoch (silent suppression).
let (bed, owner, member) = TestBed::new();
let attacker = Keys::generate();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "NoSuppress", bed.relays.clone(), None).await.unwrap();
let rid = crate::simd::hex::bytes_to_hex_32(&[0xa1; 32]);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid.clone()], 1).await;
// Owner folds → the authorized role/grant heads are floored.
follow_control(&bed.relay, &community).await.unwrap().updated;
assert!(fetch_authority(&bed.relay, &community).await.roles.is_admin(&member.keys.public_key().to_hex()), "member is admin pre-attack");
// The attacker (a non-owner) forges v2 of the admin role, chaining onto v1.
publish_role(&bed.relay, &community, &attacker, &Role { role_id: rid.clone(), name: "pwn".into(), position: 1, permissions: Permissions(0), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() }, 2).await;
// Owner refounds (keeping everyone).
let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
assert_eq!(refounded.root_epoch, Epoch(1), "root rolled");
// Post-refound, the admin role SURVIVES (the authorized floor head was carried).
let post = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &load_floors(&refounded));
assert!(post.roles.is_admin(&member.keys.public_key().to_hex()), "the admin role survives the refounding despite the forgery");
}
#[tokio::test]
async fn memberlist_survives_a_refounding_via_the_snapshot() {
// A silent survivor (didn't re-post at the new epoch) must stay in the memberlist
// after a refounding — the owner's 3312 snapshot re-seeds them (CORD-02 §5).
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Snapshot", bed.relays.clone(), None).await.unwrap();
// Member joins (a Guestbook Join at epoch 0).
let bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();
bed.swap_to(&member);
accept_parked_invite(&bed.relay, &bundle, None).await.unwrap();
bed.swap_to(&owner);
assert!(memberlist(&bed.relay, &community).await.unwrap().contains(&member.keys.public_key()), "member present pre-refound");
// Owner refounds keeping everyone (removed = []); survivors are snapshotted to epoch 1.
let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
assert_eq!(refounded.root_epoch, Epoch(1), "the root rolled");
// The member is STILL a member at epoch 1 purely via the snapshot (never re-posted).
let members = memberlist(&bed.relay, &refounded).await.unwrap();
assert!(members.contains(&member.keys.public_key()), "a silent survivor stays a member after the refounding");
assert!(members.contains(&owner.keys.public_key()), "owner is always a member");
}
#[tokio::test]
async fn e2e_two_accounts_channels_converse_moderate() {
use crate::community::v2::inbound::{apply_chat_to_state, persist_chat};
use nostr_sdk::prelude::ToBech32;
let (bed, a, b) = TestBed::new();
let (a_npub, b_npub) = (a.keys.public_key().to_bech32().unwrap(), b.keys.public_key().to_bech32().unwrap());
let (a_hex, b_hex) = (a.keys.public_key().to_hex(), b.keys.public_key().to_hex());
println!("\n===== Concord v2 deep e2e =====");
println!("[acct] A (owner) = {a_npub}");
println!("[acct] B (member) = {b_npub}");
// ── A creates the community + a PRIVATE channel + two extra PUBLIC channels ──
bed.swap_to(&a);
let mut community = create_community(&bed.relay, "Deep E2E", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
println!("[create] community {} · #general {}", crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
// A PRIVATE channel via the REAL create path: an independent key minted at
// channel-epoch 1, delivered over the rekey plane (A is the only member yet),
// then announced (vsk 2) — later carried to B in the join bundle.
let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let priv_ch = community.channel(&priv_id).unwrap();
assert!(priv_ch.private && priv_ch.key.is_some() && priv_ch.epoch == Epoch(1), "born-private: keyed at epoch 1");
println!("[channel] +private #mods {} (native create: key over the rekey plane)", crate::simd::hex::bytes_to_hex_32(&priv_id.0));
// Two more PUBLIC channels via the real create path.
let announcements = create_public_channel(&bed.relay, &community, "announcements").await.unwrap();
community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let random = create_public_channel(&bed.relay, &community, "random").await.unwrap();
community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
println!("[channel] +public #announcements {} · #random {}", crate::simd::hex::bytes_to_hex_32(&announcements.0), crate::simd::hex::bytes_to_hex_32(&random.0));
assert_eq!(community.channels.len(), 4, "general + mods + announcements + random");
// A talks in a few channels.
let m1 = send_message(&bed.relay, &community, &general, "A: welcome to the deep e2e").await.unwrap();
send_message(&bed.relay, &community, &announcements, "A: read the rules").await.unwrap();
send_message(&bed.relay, &community, &priv_id, "A: mods-only channel").await.unwrap();
println!("[msg] A posted in #general / #announcements / #mods");
// ── A grants B admin, mints a public link, B joins from the bundle ──
let admin_rid = crate::simd::hex::bytes_to_hex_32(&[0xa1; 32]);
publish_role(&bed.relay, &community, &a.keys, &admin_role(&admin_rid, Permissions::ADMIN_ALL), 1).await;
publish_grant(&bed.relay, &community, &a.keys, &b.keys.public_key(), vec![admin_rid], 1).await;
let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
assert!(community_is_public(&bed.relay, &community).await, "a live link makes it Public");
println!("[invite] granted B @admin · minted link {}", link.url);
// A private channel is readable only by granted role-holders (CORD-03), so
// B is added to its access list before the bundle is minted.
grant_channel_access(&bed.relay, &community, &priv_id, &b.keys.public_key()).await.unwrap();
let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Member(b.keys.public_key()), Some(a.keys.public_key()), None, None)).unwrap();
bed.swap_to(&b);
let mut b_view = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
println!("[join] B joined; sees {} channels", b_view.channels.len());
assert_eq!(b_view.channels.len(), 4, "B receives all four channels (incl. the private one's key) in the bundle");
assert!(b_view.channels.iter().any(|c| c.id.0 == priv_id.0 && c.private && c.key.is_some()), "B holds the private channel key");
assert!(texts_in(&bed.relay, &b_view, &general).await.contains(&"A: welcome to the deep e2e".to_string()), "B reads A's #general history");
assert!(texts_in(&bed.relay, &b_view, &priv_id).await.contains(&"A: mods-only channel".to_string()), "B reads the PRIVATE channel with the bundle key");
// B folds the control plane (persisting the roster) — the live worker does
// this right after any join; B's admin standing gates B's channel ops below.
if let Some(fresh) = follow_control(&bed.relay, &b_view).await.unwrap().updated {
b_view = fresh;
}
println!("[follow] B folded control (roster persisted: B is @admin)");
// ── Conversation both ways + persistence (get_messages-level) ──
send_message(&bed.relay, &b_view, &general, "B: thanks, glad to be here").await.unwrap();
send_message(&bed.relay, &b_view, &priv_id, "B: mods checking in").await.unwrap();
println!("[msg] B replied in #general + #mods");
// Persist B's own #general view into the shared store (what sync/live ingest does)
// and confirm it reads back via STATE — get_messages parity.
let my_pk = b.keys.public_key();
let gh = crate::simd::hex::bytes_to_hex_32(&general.0);
for f in fetch_channel(&bed.relay, &b_view, &general, 100).await.unwrap() {
let outcome = { let mut st = crate::state::STATE.lock().await; apply_chat_to_state(&mut st, &f.event, &gh, &my_pk) };
if let Some(o) = outcome { persist_chat(&gh, &o).await; }
}
assert!(crate::db::events::event_exists(&m1).unwrap(), "A's message persisted into B's shared store (get_messages backfill)");
println!("[persist] #general history persisted into the shared events store");
// B (admin) reacts to + the author edits/deletes — the chat-op surface.
send_reaction(&bed.relay, &b_view, &general, &m1, &a_hex, super::super::kind::MESSAGE, "🔥", None).await.unwrap();
bed.swap_to(&a);
let m_edit = send_message(&bed.relay, &community, &general, "A: this will be edited").await.unwrap();
send_edit(&bed.relay, &community, &general, &m_edit, "A: edited!", &[]).await.unwrap();
let m_del = send_message(&bed.relay, &community, &general, "A: this will be deleted").await.unwrap();
send_delete(&bed.relay, &community, &general, &m_del, super::super::kind::MESSAGE, None).await.unwrap();
println!("[ops] reaction + edit + delete round-tripped");
// ── B creates a channel as admin, A folds it in ──
bed.swap_to(&b);
let bugs = create_public_channel(&bed.relay, &b_view, "bug-reports").await.unwrap();
println!("[channel] B(admin) +public #bug-reports {}", crate::simd::hex::bytes_to_hex_32(&bugs.0));
bed.swap_to(&a);
if let Some(updated) = follow_control(&bed.relay, &community).await.unwrap().updated {
community = updated;
}
assert!(community.channels.iter().any(|c| c.id.0 == bugs.0), "A folds in B's authorized new channel");
println!("[follow] A folded in B's #bug-reports (now {} channels)", community.channels.len());
// ── A creates a SECOND private channel while B is already a member. B is
// NOT on its access list, so B learns the channel exists (control-follow,
// keyless) and gets no key: CORD-03's private channel is readable only by
// granted role-holders, never by every member. B keys up if and when A
// grants them the channel's access role and vends the key ──
let vault = create_private_channel(&bed.relay, &community, "vault").await.unwrap();
community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
send_message(&bed.relay, &community, &vault, "A: vault is open").await.unwrap();
println!("[channel] +private #vault {} (B is unentitled — no delivery)", crate::simd::hex::bytes_to_hex_32(&vault.0));
bed.swap_to(&b);
let session_b2 = crate::db::current_session();
if let Some(fresh) = follow_control(&bed.relay, &b_view).await.unwrap().updated {
b_view = fresh;
}
let ch = b_view.channel(&vault).expect("B recorded the announced private channel");
assert!(ch.private && ch.key.is_none() && ch.epoch == Epoch(0), "B's record is keyless at cursor 0");
let rf = follow_rekeys(&bed.relay, &b_view, &session_b2).await.unwrap();
if let Some(fresh) = rf.updated {
b_view = fresh;
}
let ch = b_view.channel(&vault).expect("still recorded");
assert!(ch.key.is_none(), "an unentitled member is never delivered the key");
assert!(
texts_in(&bed.relay, &b_view, &vault).await.is_empty(),
"and reads nothing from it"
);
assert!(
send_message(&bed.relay, &b_view, &vault, "B: in the vault").await.is_err(),
"an unentitled member cannot post into the channel either"
);
bed.swap_to(&a);
community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
println!("[private] #vault stayed sealed to the unentitled B (no key, no read, no send)");
// ── Members ──
let members = memberlist(&bed.relay, &community).await.unwrap();
let member_hexes: std::collections::BTreeSet<String> = members.iter().map(|m| m.to_hex()).collect();
assert!(member_hexes.contains(&a_hex) && member_hexes.contains(&b_hex), "A + B both in the memberlist");
println!("[members] {} members: A + B present", members.len());
// ── Moderate: ban B (banlist + strip + refound), verify severance + survival ──
set_banlist(&bed.relay, &community, &[b_hex.clone()]).await.unwrap();
grant_roles(&bed.relay, &community, &b.keys.public_key(), vec![]).await.unwrap();
let refounded = refound_community(&bed.relay, &community, &[b.keys.public_key()]).await.unwrap();
assert_eq!(refounded.root_epoch, Epoch(1), "the ban rolled the root");
let post = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &load_floors(&refounded));
assert!(post.banned.contains(&b_hex), "the ban survives the refounding");
assert!(all_texts_in(&bed.relay, &refounded, &general).await.iter().any(|t| t == "A: welcome to the deep e2e"), "pre-ban history pages back across the new epoch");
assert!(
all_texts_in(&bed.relay, &refounded, &priv_id).await.iter().any(|t| t == "A: mods-only channel"),
"PRIVATE history pages back across the channel's own rotation (per-channel multi-epoch archive)"
);
println!("[ban] B banned; root rolled to epoch 1; ban survives; pre-ban history intact (public + private)");
// B concludes it's severed.
bed.swap_to(&b);
let session_b3 = crate::db::current_session();
assert!(follow_rekeys(&bed.relay, &b_view, &session_b3).await.unwrap().self_removed, "B is cryptographically cut by the ban-refound");
println!("[ban] B's rekey-follow: self_removed = true (severed)");
// ── Unban: A lifts the ban ──
bed.swap_to(&a);
set_banlist(&bed.relay, &refounded, &[]).await.unwrap();
let after_unban = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &load_floors(&refounded));
assert!(!after_unban.banned.contains(&b_hex), "the unban clears B from the banlist");
println!("[unban] B removed from the banlist (re-invitable)");
// ── Dissolve ──
dissolve_community(&bed.relay, &refounded).await.unwrap();
assert!(crate::db::community::load_community_v2(community.id()).unwrap().unwrap().dissolved, "the community is sealed");
println!("[dissolve] community sealed (read-only)\n===== e2e PASS =====\n");
}
/// The same scenario on a REAL relay with TWO throwaway accounts, off by default. It
/// LOGS both nsecs (+ every id) so you can inspect the run and RE-RUN against the same
/// accounts by exporting `VECTOR_E2E_NSEC_A` / `_B`. Set `VECTOR_E2E_LOG=<path>` to also
/// append the transcript to a file, `VECTOR_E2E_RELAY=<url>` to pick the relay.
/// cargo test -p vector-core -- --ignored --nocapture live_e2e_two_accounts
#[tokio::test]
#[ignore]
async fn live_e2e_two_accounts() {
use nostr_sdk::prelude::ToBech32;
let relay = std::env::var("VECTOR_E2E_RELAY").unwrap_or_else(|_| "wss://jskitty.com/nostr".to_string());
let relays = vec![relay.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();
crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
// Throwaway (or bring-your-own via env for a re-run against the same accounts).
let a = std::env::var("VECTOR_E2E_NSEC_A").ok().and_then(|n| Keys::parse(&n).ok()).unwrap_or_else(Keys::generate);
let b = std::env::var("VECTOR_E2E_NSEC_B").ok().and_then(|n| Keys::parse(&n).ok()).unwrap_or_else(Keys::generate);
let log = |line: String| {
println!("{line}");
if let Ok(p) = std::env::var("VECTOR_E2E_LOG") {
use std::io::Write;
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&p) {
let _ = writeln!(f, "{line}");
}
}
};
log(format!("===== LIVE Concord v2 e2e on {relay} ====="));
log(format!("VECTOR_E2E_NSEC_A={} ({})", a.secret_key().to_bech32().unwrap(), a.public_key().to_bech32().unwrap()));
log(format!("VECTOR_E2E_NSEC_B={} ({})", b.secret_key().to_bech32().unwrap(), b.public_key().to_bech32().unwrap()));
for k in [&a, &b] {
let npub = k.public_key().to_bech32().unwrap();
std::fs::create_dir_all(tmp.path().join(&npub)).unwrap();
crate::db::set_current_account(npub.clone()).unwrap();
crate::db::init_database(&npub).unwrap();
}
// One relay connection: a v2 wrap is pre-signed (ephemeral p-key) and its seal is
// signed by MY_SECRET_KEY, so publishing needs no per-account client signer.
let client = crate::nostr_client_builder().build();
client.add_managed_relay(relay.as_str()).await.ok();
client.connect().await;
crate::state::set_nostr_client(client);
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
let become_acct = |k: &Keys| {
let npub = k.public_key().to_bech32().unwrap();
crate::db::set_current_account(npub.clone()).unwrap();
crate::db::init_database(&npub).unwrap();
crate::db::clear_id_caches();
crate::state::MY_SECRET_KEY.store_from_keys(k, &[]);
crate::state::set_my_public_key(k.public_key());
};
let settle = || crate::rt::time::sleep(std::time::Duration::from_secs(2));
// A: create + a channel + grant B admin + mint link.
become_acct(&a);
let mut community = create_community(&transport, "Live E2E", relays.clone(), None).await.expect("create");
let general = community.channels[0].id;
log(format!("[create] community {} · #general {}", crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0)));
send_message(&transport, &community, &general, "A: live hello").await.expect("send");
let ann = create_public_channel(&transport, &community, "announcements").await.expect("channel");
community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
log(format!("[channel] +public #announcements {}", crate::simd::hex::bytes_to_hex_32(&ann.0)));
grant_admin(&transport, &community, &b.public_key()).await.expect("grant admin");
let link = mint_public_link(&transport, &community, "https://vectorapp.io", None, None).await.expect("mint");
log(format!("[invite] B granted @admin · link {}", link.url));
let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(a.public_key()), None, None)).unwrap();
settle().await;
// B: join + read A's history + reply.
become_acct(&b);
let b_view = accept_parked_invite(&transport, &bundle_json, None).await.expect("join");
log(format!("[join] B joined; {} channels", b_view.channels.len()));
settle().await;
let page = fetch_channel(&transport, &b_view, &general, 50).await.expect("fetch");
let seen: Vec<String> = page.iter().map(|f| f.event.opened().rumor.content.clone()).collect();
log(format!("[read] B sees #general: {seen:?}"));
assert!(seen.iter().any(|t| t == "A: live hello"), "B reads A's message over the real relay");
send_message(&transport, &b_view, &general, "B: live reply").await.expect("reply");
// B posts a NIP-22 kind-1111 THREADED REPLY to A's message (the shape Armada
// sends) directly onto the chat plane — proving the cross-client thread
// RECEIVE path works live, not just in the offline fixture.
let hello = page.iter().find(|f| f.event.opened().rumor.content == "A: live hello").expect("A's message");
let hello_id = hello.event.opened().rumor_id.to_hex();
let bkeys = crate::state::MY_SECRET_KEY.to_keys().unwrap();
let cgroup = channel_group_key(&b_view.community_root, &general, b_view.root_epoch);
let reply_rumor = chat::build_comment_rumor(bkeys.public_key(), &general, b_view.root_epoch, "B: threaded reply to hello", &hello_id, super::super::kind::MESSAGE, &a.public_key().to_hex(), None, &[], now_ms());
let (reply_wrap, _) = chat::seal_chat_rumor(&reply_rumor, &cgroup, &bkeys, Timestamp::from_secs(now_ms() / 1000), false).expect("seal 1111");
transport.publish(&reply_wrap, &b_view.relays).await.expect("publish 1111");
log("[thread] B published a kind-1111 threaded reply to A's message".to_string());
settle().await;
// A reads the thread reply back, rendered inline with A's message as parent.
become_acct(&a);
community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let a_page = fetch_channel(&transport, &community, &general, 50).await.expect("A fetch");
let thread = a_page.iter().find(|f| f.event.opened().rumor.content == "B: threaded reply to hello").expect("A sees the 1111");
if let chat::ChatEvent::Message { reply_to, opened, .. } = &thread.event {
assert_eq!(opened.rumor.kind.as_u16(), super::super::kind::COMMENT, "wire kind preserved as 1111");
assert_eq!(reply_to.as_ref().map(|r| crate::simd::hex::bytes_to_hex_32(&r.id)), Some(hello_id.clone()), "the 1111 renders inline with A's message as parent");
} else {
panic!("the 1111 parsed as a Message");
}
log("[thread] A read B's threaded reply, parent resolved — cross-client 1111 interop OK".to_string());
become_acct(&b);
settle().await;
// A: create a PRIVATE channel while B is already a member — B is a recipient
// of the creation delivery, so B keys up from the rekey plane over the real
// relay (no bundle involved), then the two converse on it.
become_acct(&a);
community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let vault = create_private_channel(&transport, &community, "vault").await.expect("private channel");
community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
send_message(&transport, &community, &vault, "A: vault live").await.expect("vault send");
log(format!("[channel] +private #vault {} (key delivered over the rekey plane)", crate::simd::hex::bytes_to_hex_32(&vault.0)));
settle().await;
become_acct(&b);
let session_b = crate::db::current_session();
let mut b_view = crate::db::community::load_community_v2(b_view.id()).unwrap().unwrap();
if let Some(fresh) = follow_control(&transport, &b_view).await.expect("B control follow").updated {
b_view = fresh;
}
if let Some(fresh) = follow_rekeys(&transport, &b_view, &session_b).await.expect("B rekey follow").updated {
b_view = fresh;
}
let vch = b_view.channel(&vault).expect("B folded the vault");
assert!(vch.key.is_some() && vch.epoch == Epoch(1), "B adopted the vault key from the live rekey plane");
let vseen = texts_in(&transport, &b_view, &vault).await;
log(format!("[read] B sees #vault: {vseen:?}"));
assert!(vseen.iter().any(|t| t == "A: vault live"), "B reads the private channel with the ADOPTED key");
send_message(&transport, &b_view, &vault, "B: in the live vault").await.expect("vault reply");
settle().await;
become_acct(&a);
community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert!(
texts_in(&transport, &community, &vault).await.iter().any(|t| t == "B: in the live vault"),
"A reads B's private reply"
);
log("[private] two-way #vault conversation over the live relay".to_string());
// A: ban B (three-removal) + dissolve.
set_banlist(&transport, &community, &[b.public_key().to_hex()]).await.expect("banlist");
grant_roles(&transport, &community, &b.public_key(), vec![]).await.expect("strip");
let refounded = refound_community(&transport, &community, &[b.public_key()]).await.expect("refound");
log(format!("[ban] B banned; root → epoch {}", refounded.root_epoch.0));
settle().await;
dissolve_community(&transport, &refounded).await.expect("dissolve");
log("[dissolve] community sealed".to_string());
log("===== LIVE e2e PASS =====".to_string());
}
#[tokio::test]
async fn an_offline_member_learns_of_a_dissolution_on_catch_up() {
// The tombstone rides its own public plane, watched live — an OFFLINE
// member's catch-up must fetch it too, or they follow (and post into) a
// grave forever.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Doomed", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
bed.swap_to(&member);
let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
// The owner dissolves while the member sleeps.
bed.swap_to(&owner);
dissolve_community(&bed.relay, &community).await.unwrap();
// The member's catch-up learns of the death, seals, and refuses to post.
bed.swap_to(&member);
let session = crate::db::current_session();
let follow = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
assert!(follow.dissolved, "the catch-up surfaces the tombstone");
assert!(!follow.self_removed && follow.updated.is_none());
let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
assert!(crate::db::community::get_community_dissolved(&cid_hex).unwrap(), "sealed read-only locally");
let err = send_message(&bed.relay, &joined, &general, "into the void").await.unwrap_err();
assert!(err.contains("dissolved"), "sends refuse a grave: {err}");
// Subsequent follows take the local fast path — still dissolved, no churn.
let again = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
assert!(again.dissolved && again.updated.is_none());
}
#[tokio::test]
async fn a_wide_community_survives_refoundings_and_an_offline_member_converges() {
// Scale stress: MANY private channels, each rotated on every Refounding.
// A member offline across two refoundings must converge on all of them
// (the per-channel rotation fan in refound + the follow's channel×root×step
// loops stay bounded) with every channel's history readable.
const PRIV_CHANNELS: usize = 6;
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let mut community = create_community(&bed.relay, "Wide", bed.relays.clone(), None).await.unwrap();
let mut priv_ids = Vec::new();
for i in 0..PRIV_CHANNELS {
let id = create_private_channel(&bed.relay, &community, &format!("priv{i}")).await.unwrap();
community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
send_message(&bed.relay, &community, &id, &format!("priv{i} epoch0")).await.unwrap();
priv_ids.push(id);
}
// Private channels are readable only by granted role-holders (CORD-03).
for id in &priv_ids {
grant_channel_access(&bed.relay, &community, id, &member.keys.public_key()).await.unwrap();
}
let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Member(member.keys.public_key()), Some(owner.keys.public_key()), None, None)).unwrap();
// Member joins at epoch 0 with all channel keys, then goes offline.
bed.swap_to(&member);
let member_view = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
assert_eq!(member_view.channels.iter().filter(|c| c.private && c.key.is_some()).count(), PRIV_CHANNELS, "joined with all private keys");
// Two refoundings (each rotates the base + every private channel).
bed.swap_to(&owner);
for epoch in 1..=2u64 {
community = refound_community(&bed.relay, &community, &[]).await.unwrap();
assert_eq!(community.root_epoch, Epoch(epoch));
for id in &priv_ids {
send_message(&bed.relay, &community, id, &format!("{} epoch{epoch}", crate::simd::hex::bytes_to_hex_32(&id.0))).await.unwrap();
}
}
// Member returns: bounded follow to quiescence.
bed.swap_to(&member);
let session = crate::db::current_session();
let mut passes = 0;
loop {
passes += 1;
assert!(passes <= 8, "a wide catch-up must converge, not churn (pass {passes})");
let cur = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
let rk = follow_rekeys(&bed.relay, &cur, &session).await.unwrap();
assert!(!rk.self_removed);
let cur = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
let ctl = follow_control(&bed.relay, &cur).await.unwrap().updated;
if rk.updated.is_none() && ctl.is_none() {
break;
}
}
let caught_up = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
assert_eq!(caught_up.root_epoch, Epoch(2), "walked both refoundings");
// Every private channel converged to the owner's current key + reads all epochs.
for id in &priv_ids {
let mine = caught_up.channel(id).expect("channel survived");
let theirs = community.channel(id).unwrap();
assert_eq!(mine.key, theirs.key, "channel {} converged on the owner key", crate::simd::hex::bytes_to_hex_32(&id.0));
assert_eq!(mine.epoch, theirs.epoch, "…at the same epoch");
let id_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
// Opening reads the live planes; the rotated-past ones are the
// back-paging cursor's job. Both halves asserted — the point is that
// every epoch stays REACHABLE, not that opening drags it all in.
let open = texts_in(&bed.relay, &caught_up, id).await;
assert!(open.iter().any(|t| t.contains("epoch2")), "channel {id_hex} opens onto its live epoch");
let paged = all_texts_in(&bed.relay, &caught_up, id).await;
assert!(paged.iter().any(|t| t.contains("epoch0")), "channel {id_hex} pages back to epoch-0 history");
for epoch in 1..=2u64 {
assert!(paged.iter().any(|t| t.contains(&format!("epoch{epoch}"))), "channel {id_hex} pages back to epoch-{epoch} history");
}
}
}
#[tokio::test]
async fn a_backlog_deeper_than_max_steps_still_converges() {
// MAX_STEPS bounds ONE walk, not the catch-up. A member who slept through more
// rotations than the bound must still land on the head — silently stopping at
// the bound leaves them on a dead epoch reading nothing, which is
// indistinguishable from a quiet community.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let mut community = create_community(&bed.relay, "DeepSleeper", bed.relays.clone(), None).await.unwrap();
let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Member(member.keys.public_key()), Some(owner.keys.public_key()), None, None)).unwrap();
bed.swap_to(&member);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
assert_eq!(joined.root_epoch, Epoch(0));
// Past the bound, deliberately.
bed.swap_to(&owner);
let depth = MAX_WALK_STEPS + 3;
for _ in 0..depth {
community = refound_community(&bed.relay, &community, &[]).await.unwrap();
}
assert_eq!(community.root_epoch, Epoch(depth as u64));
// The member follows repeatedly, exactly as a client does on each sync. Every
// pass must make forward progress and none may lose ground.
bed.swap_to(&member);
let mut last = 0u64;
for pass in 1..=8 {
// Reload from the DB each pass, exactly as a client does: this is what
// proves every hop was CHECKPOINTED, not merely held in the walk's memory.
let view = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let session = crate::db::current_session();
let _ = follow_rekeys(&bed.relay, &view, &session).await.unwrap();
let view = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert!(
view.root_epoch.0 >= last,
"pass {pass} lost ground: {} -> {}",
last, view.root_epoch.0
);
last = view.root_epoch.0;
if last == depth as u64 {
break;
}
}
let view = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(
view.root_epoch, Epoch(depth as u64),
"a backlog deeper than one walk's step bound must still converge across passes",
);
}
#[tokio::test]
async fn an_offline_member_catches_up_across_three_refoundings() {
// The deep offline-online scenario: a member sleeps through THREE
// Refoundings, per-refound private-channel rotations, a mid-life private
// channel CREATED while they slept, a public channel, a rename, and a
// ban — then returns and converges by follow alone (no rejoin).
use nostr_sdk::prelude::ToBech32;
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let mut community = create_community(&bed.relay, "Sleeper", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
let mods = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
send_message(&bed.relay, &community, &general, "epoch0: hello").await.unwrap();
send_message(&bed.relay, &community, &mods, "epoch0: mods secret").await.unwrap();
// Private channels are readable only by granted role-holders (CORD-03).
grant_channel_access(&bed.relay, &community, &mods, &member.keys.public_key()).await.unwrap();
let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Member(member.keys.public_key()), Some(owner.keys.public_key()), None, None)).unwrap();
// Member joins at epoch 0, then goes OFFLINE.
bed.swap_to(&member);
let member_view = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
assert_eq!(member_view.root_epoch, Epoch(0));
// While they sleep, the owner reshapes everything across three epochs.
bed.swap_to(&owner);
let stranger = Keys::generate();
for epoch in 1..=3u64 {
community = refound_community(&bed.relay, &community, &[]).await.unwrap();
assert_eq!(community.root_epoch, Epoch(epoch));
send_message(&bed.relay, &community, &general, &format!("epoch{epoch}: general news")).await.unwrap();
send_message(&bed.relay, &community, &mods, &format!("epoch{epoch}: mods word")).await.unwrap();
}
let news = create_public_channel(&bed.relay, &community, "news").await.unwrap();
community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let vault = create_private_channel(&bed.relay, &community, "vault").await.unwrap();
community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
// The sleeper is on this channel's access list, so the refoundings that
// follow deliver its key to them (CORD-03).
grant_channel_access(&bed.relay, &community, &vault, &member.keys.public_key()).await.unwrap();
community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
send_message(&bed.relay, &community, &vault, "epoch3: vault opened").await.unwrap();
set_banlist(&bed.relay, &community, &[stranger.public_key().to_hex()]).await.unwrap();
let meta = control::CommunityMetadata { name: "Sleeper Reborn".into(), relays: community.relays.clone(), ..Default::default() };
edit_community_metadata(&bed.relay, &community, &meta).await.unwrap();
// The member RETURNS: rekey+control follow to quiescence (the worker's
// loop, driven explicitly). Bounded — convergence must be fast.
bed.swap_to(&member);
let session = crate::db::current_session();
let mut passes = 0;
loop {
passes += 1;
assert!(passes <= 6, "catch-up must converge, not churn");
let cur = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
let rekeyed = follow_rekeys(&bed.relay, &cur, &session).await.unwrap();
assert!(!rekeyed.self_removed, "the member was never removed");
let cur = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
let controlled = follow_control(&bed.relay, &cur).await.unwrap().updated;
if rekeyed.updated.is_none() && controlled.is_none() {
break;
}
}
let caught_up = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
// Base + name converged.
assert_eq!(caught_up.root_epoch, Epoch(3), "walked all three refoundings");
assert_eq!(caught_up.community_root, community.community_root, "landed on the owner's root");
assert_eq!(caught_up.name, "Sleeper Reborn");
// Channels: renamed set incl. the mid-sleep public + private ones.
assert!(caught_up.channels.iter().any(|c| c.id.0 == news.0), "folded the new public channel");
let m = caught_up.channel(&mods).expect("mods survived");
let owner_mods = community.channel(&mods).unwrap();
assert_eq!(m.epoch, owner_mods.epoch, "mods walked every per-refound rotation");
assert_eq!(m.key, owner_mods.key, "…to the owner's exact key");
let v = caught_up.channel(&vault).expect("vault folded in");
// The sleeper is on vault's access list, but it was created AFTER the last
// refounding — no rotation followed the grant, so no blob was ever
// addressed to them. They hold the channel keyless until the grant's own
// key vend lands (CORD-05 §6), which is what a rekey-only walk cannot do.
assert!(v.private && v.key.is_none(), "vault folds in keyless: entitled, but never delivered");
// Banlist survived the compactions.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&caught_up.id().0);
let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap();
assert!(banned.contains(&stranger.public_key().to_hex()), "the ban folded through");
// Opening reads the live planes only; paging back reaches EVERY epoch
// (public via the base-root archive, private via the per-channel archive
// built during the walk). A sleeper's deep history stays reachable — it
// just arrives when they scroll for it rather than on open.
let gen_open = texts_in(&bed.relay, &caught_up, &general).await;
assert!(gen_open.contains(&"epoch3: general news".to_string()), "general opens onto its live epoch: {gen_open:?}");
let gen_texts = all_texts_in(&bed.relay, &caught_up, &general).await;
for epoch in 0..=3u64 {
let needle = if epoch == 0 { "epoch0: hello".to_string() } else { format!("epoch{epoch}: general news") };
assert!(gen_texts.contains(&needle), "general pages back to epoch {epoch}: {gen_texts:?}");
}
let mods_open = texts_in(&bed.relay, &caught_up, &mods).await;
assert!(mods_open.contains(&"epoch3: mods word".to_string()), "mods opens onto its live epoch: {mods_open:?}");
let mods_texts = all_texts_in(&bed.relay, &caught_up, &mods).await;
for epoch in 0..=3u64 {
let needle = if epoch == 0 { "epoch0: mods secret".to_string() } else { format!("epoch{epoch}: mods word") };
assert!(mods_texts.contains(&needle), "private pages back to epoch {epoch}: {mods_texts:?}");
}
// Keyless (above) means unreadable — a rekey walk cannot substitute for the
// key vend that a grant carries.
assert!(texts_in(&bed.relay, &caught_up, &vault).await.is_empty());
// And the member can still speak.
send_message(&bed.relay, &caught_up, &general, "member: good morning").await.unwrap();
bed.swap_to(&owner);
assert!(
texts_in(&bed.relay, &community, &general).await.contains(&"member: good morning".to_string()),
"the caught-up member converses at the new epoch ({})",
member.keys.public_key().to_bech32().unwrap()
);
}
/// Seal `n` messages onto a community's #general, one per second starting at
/// `base_secs` (distinct wrap seconds so relay-side `until` paging engages).
async fn flood_general(relay: &MemoryRelay, community: &CommunityV2, author: &Keys, n: usize, base_secs: u64) {
let general = community.channels[0].id;
let group = channel_group_key(&community.community_root, &general, community.root_epoch);
for i in 0..n {
let at = base_secs + i as u64;
let rumor = chat::build_message_rumor(author.public_key(), &general, community.root_epoch, &format!("msg {i}"), None, &[], vec![], at * 1000);
let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, author, Timestamp::from_secs(at), false).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
}
#[tokio::test]
async fn the_history_walk_pages_past_a_multi_page_burst() {
// A bot offline through 120 messages must catch ALL of them, not the
// newest page; until-paging closes the gap.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Burst", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
flood_general(&relay, &community, &owner, 120, 10_000).await;
let all = fetch_channel_history(&relay, &community, &general, 50, 8, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
assert_eq!(all.len(), 120, "the walk pages the whole burst");
// Oldest→newest, no duplicates.
let contents: Vec<String> = all.iter().map(|f| f.event.opened().rumor.content.clone()).collect();
assert_eq!(contents.first().map(String::as_str), Some("msg 0"));
assert_eq!(contents.last().map(String::as_str), Some("msg 119"));
let unique: std::collections::HashSet<&String> = contents.iter().collect();
assert_eq!(unique.len(), 120, "wrap-id + rumor-id dedup holds across page boundaries");
// The single-page fetch stays a single page.
let one = fetch_channel(&relay, &community, &general, 50).await.unwrap();
assert_eq!(one.len(), 50, "fetch_channel is one newest page");
assert_eq!(one.last().map(|f| f.event.opened().rumor.content.clone()).as_deref(), Some("msg 119"));
}
#[tokio::test]
async fn a_start_until_cursor_pages_history_from_that_point_backwards() {
// The back-paging cursor: a walk that starts at an explicit `until`
// returns only what lies at-or-before it, oldest→newest — the relay-side
// half of the SDK's walk-until-dry loop.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Paged", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
flood_general(&relay, &community, &owner, 120, 10_000).await;
let older = fetch_channel_history(
&relay, &community, &general, 50, 8, None, Some(10_059),
crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default(),
)
.await
.unwrap();
let contents: Vec<String> = older.iter().map(|f| f.event.opened().rumor.content.clone()).collect();
assert_eq!(contents.len(), 60, "everything at-or-before the cursor, nothing after");
assert_eq!(contents.first().map(String::as_str), Some("msg 0"));
assert_eq!(contents.last().map(String::as_str), Some("msg 59"));
}
#[tokio::test]
async fn the_history_walk_stops_when_the_caller_is_caught_up() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Caught", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
flood_general(&relay, &community, &owner, 120, 10_000).await;
// The caller says "I hold everything" after the first page — no deeper fetch.
let mut pages = 0usize;
let got = fetch_channel_history(&relay, &community, &general, 50, 8, None, None, crate::community::transport::Evidence::Quorum, |_, _| {
pages += 1;
false
}, |_| Default::default())
.await
.unwrap();
assert_eq!(pages, 1, "the early stop is consulted once");
assert_eq!(got.len(), 50, "only the newest page is fetched");
assert_eq!(got.last().map(|f| f.event.opened().rumor.content.clone()).as_deref(), Some("msg 119"));
}
#[tokio::test]
async fn a_page_of_settled_wraps_ends_the_walk_unopened() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Settled", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
flood_general(&relay, &community, &owner, 120, 10_000).await;
let asked = std::sync::atomic::AtomicUsize::new(0);
let mut seen = Vec::new();
let got = fetch_channel_history(&relay, &community, &general, 50, 8, None, None, crate::community::transport::Evidence::Quorum, |page, held| {
seen.push((page.len(), held));
held == 0
}, |ids| {
asked.fetch_add(ids.len(), std::sync::atomic::Ordering::Relaxed);
ids.iter().copied().collect()
})
.await
.unwrap();
assert!(got.is_empty(), "nothing settled is opened");
assert_eq!(seen, [(0, 50)], "a page of only settled wraps still reaches the caller's stop");
assert_eq!(asked.into_inner(), 50, "the newest page alone: all of it held, so the walk ends there");
// Half settled: the rest open, and the walk goes on past a page with something new.
let newest = fetch_channel(&relay, &community, &general, 50).await.unwrap();
let held: std::collections::HashSet<_> = newest.iter().take(25).map(|f| f.event.opened().wrapper_id).collect();
let got = fetch_channel_history(&relay, &community, &general, 50, 8, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |ids| ids.iter().filter(|id| held.contains(*id)).copied().collect())
.await
.unwrap();
assert_eq!(got.len(), 95, "everything but the 25 held");
assert!(got.iter().all(|f| !held.contains(&f.event.opened().wrapper_id)));
}
#[tokio::test]
async fn a_same_second_history_wall_terminates_instead_of_looping() {
// 60 messages in ONE second with a 25-wrap page: a second-granular
// `until` can never page past the wall — the walk must step over it
// (bounded loss, logged) rather than spin.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Wall", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let group = channel_group_key(&community.community_root, &general, community.root_epoch);
for i in 0..60usize {
let rumor = chat::build_message_rumor(owner.public_key(), &general, community.root_epoch, &format!("burst {i}"), None, &[], vec![], 5_000_000 + i as u64);
let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &owner, Timestamp::from_secs(5_000), false).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
let got = fetch_channel_history(&relay, &community, &general, 25, 8, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
assert!(got.len() >= 25, "at least the relay page is read");
assert!(got.len() <= 60, "sane bound");
// Termination is the assertion: reaching here means the wall didn't loop.
}
#[tokio::test]
async fn a_grant_revoke_survives_a_withholding_relay() {
// Floor persistence on the delegation plane: after the owner revokes an admin,
// a relay serving only the OLD (still owner-signed) grant can't resurrect it.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Revoke", vec!["wss://good".into()], None).await.unwrap();
let admin = Keys::generate();
let rid = "d4".repeat(32);
publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::MANAGE_METADATA), 1).await;
publish_grant(&relay, &community, &owner, &admin.public_key(), vec![rid.clone()], 1).await;
follow_control(&relay, &community).await.unwrap().updated; // seed floors incl. the grant at v1
publish_grant(&relay, &community, &owner, &admin.public_key(), vec![], 2).await; // revoke → grant floor v2
follow_control(&relay, &community).await.unwrap().updated;
// A stale relay serves only the grant prefix (v1, the live grant).
inject_stale_prefix(&relay, &community, 1, "wss://stale").await;
let mut stale = community.clone();
stale.relays = vec!["wss://stale".into()];
let floors = load_floors(&community);
let editions = fetch_control(&relay, &stale).await;
let authority = fold_authority(&stale, &editions, &floors);
assert!(
!authority.roles.is_authorized(&admin.public_key().to_hex(), Some(&owner.public_key().to_hex()), Permissions::MANAGE_METADATA),
"the persisted grant floor refuses the rolled-back (re-granted) view"
);
}
/// Load the current-epoch floors for a community (test mirror of follow_control).
fn load_floors(community: &CommunityV2) -> Floors {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::get_all_edition_heads_full(&cid_hex)
.unwrap_or_default()
.into_iter()
.filter(|(_, f)| f.0 == community.root_epoch.0)
.map(|(e, f)| (e, (f.1, f.2, f.3, f.4, f.5)))
.collect()
}
/// Fetch + open every control edition at a community's control plane (test helper).
async fn fetch_control(relay: &MemoryRelay, community: &CommunityV2) -> Vec<ParsedEdition> {
let group = control::ControlPlane::of(&community).write_group().unwrap();
let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
relay
.fetch(&q, &community.relays)
.await
.unwrap_or_default()
.iter()
.filter_map(|w| control::open_control_edition(w, &group).ok().map(|(ed, _)| ed))
.collect()
}
#[tokio::test]
async fn follow_control_is_a_noop_on_a_freshly_created_community() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Fresh", vec!["wss://r".into()], None).await.unwrap();
// Only the genesis editions exist; folding them reproduces the held view.
assert!(follow_control(&relay, &community).await.unwrap().updated.is_none());
}
#[tokio::test]
async fn follow_control_adds_a_new_public_channel_and_re_subscribes_it() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Grow", vec!["wss://r".into()], None).await.unwrap();
let new_id = ChannelId([0x5a; 32]);
publish_channel_edition(&relay, &community, &owner, &new_id, "announcements", false, 1, false).await;
let updated = follow_control(&relay, &community).await.unwrap().updated.expect("a new channel changed the view");
assert_eq!(updated.channels.len(), 2);
let added = updated.channel(&new_id).expect("the new channel folded in");
assert_eq!(added.name, "announcements");
assert!(!added.private);
assert_eq!(added.key, None, "a public channel derives from the root (no stored key)");
// The new channel is now in the realtime author-set (it would be subscribed).
let authors = super::super::realtime::plane_authors(std::slice::from_ref(&updated));
let addr = channel_group_key(&updated.community_root, &new_id, updated.root_epoch).pk();
assert!(authors.contains(&addr), "the added channel joins the live subscription");
// Persisted: a reload sees it too.
let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert!(reloaded.channel(&new_id).is_some());
}
#[tokio::test]
async fn follow_control_renames_the_community_and_an_existing_channel() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Old Name", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
// A v2 metadata edition renames the community; a v2 channel edition renames #general.
publish_community_meta(&relay, &community, &owner, "New Name", 2).await;
publish_channel_edition(&relay, &community, &owner, &general, "lobby", false, 2, false).await;
let updated = follow_control(&relay, &community).await.unwrap().updated.unwrap();
assert_eq!(updated.name, "New Name");
assert_eq!(updated.channel(&general).unwrap().name, "lobby");
assert_eq!(updated.channels.len(), 1, "a rename doesn't add a channel");
}
#[tokio::test]
async fn follow_control_deletes_a_channel() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Prune", vec!["wss://r".into()], None).await.unwrap();
let extra = ChannelId([0x77; 32]);
// The channel is first added and folded into the held view.
publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 1, false).await;
let with_extra = follow_control(&relay, &community).await.unwrap().updated.expect("added");
assert!(with_extra.channel(&extra).is_some());
// Then it's tombstoned — the delete (higher version) folds the held one back out.
publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 2, true).await;
let updated = follow_control(&relay, &with_extra).await.unwrap().updated.expect("removed");
assert!(updated.channel(&extra).is_none(), "a deleted channel folds out");
assert_eq!(updated.channels.len(), 1, "only #general remains");
}
#[tokio::test]
async fn a_flood_dated_ahead_never_buries_the_history_beneath_it() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Flood", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let group = channel_group_key(&community.community_root, &general, community.root_epoch);
let (member, spammer) = (Keys::generate(), Keys::generate());
let now = crate::clock::now_ms();
let post = |keys: &Keys, text: &str, at: u64| {
let rumor = chat::build_message_rumor(keys.public_key(), &general, community.root_epoch, text, None, &[], vec![], at);
chat::seal_chat_rumor(&rumor, &group, keys, Timestamp::from_secs(at / 1000), false).unwrap().0
};
relay.publish(&post(&member, "real", now - 60_000), &community.relays).await.unwrap();
for i in 0..30u64 {
relay.publish(&post(&spammer, "ahead", now + 60_000 + i * 1_000), &community.relays).await.unwrap();
}
let page = fetch_channel_history(&relay, &community, &general, 10, 1, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
let texts: Vec<_> = page.iter().map(|f| f.event.opened().rumor.content.clone()).collect();
assert_eq!(texts, vec!["real".to_string()], "pages of messages dated ahead are stepped past, not shown");
}
#[tokio::test]
async fn a_history_read_holds_a_message_dated_ahead() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Ahead", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let group = channel_group_key(&community.community_root, &general, community.root_epoch);
let member = Keys::generate();
let now = crate::clock::now_ms();
let mut ids = Vec::new();
for (text, at) in [("on time", now), ("minutes fast", now + 3 * 60 * 1000)] {
let rumor = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, text, None, &[], vec![], at);
ids.push(rumor.id.unwrap());
let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(at / 1000), false).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
let page: Vec<_> = fetch_channel(&relay, &community, &general, 50).await.unwrap().iter().map(|f| f.event.opened().rumor_id).collect();
assert!(page.contains(&ids[0]));
assert!(!page.contains(&ids[1]), "it waits for its time instead of joining the page");
}
#[tokio::test]
async fn a_deleted_channel_leaves_every_device_with_its_files_and_in_time_my_wraps() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
relay.follow_cord01(&["wss://r".to_string()]);
let community = create_community(&relay, "Purge", vec!["wss://r".into()], None).await.unwrap();
let doomed = ChannelId([0x7a; 32]);
publish_channel_edition(&relay, &community, &owner, &doomed, "doomed", false, 1, false).await;
let held = follow_control(&relay, &community).await.unwrap().updated.expect("added");
let doomed_hex = crate::simd::hex::bytes_to_hex_32(&doomed.0);
// Mine, sent for real; someone else's; and two of my uploads, one also forwarded into a DM.
let sent = send_message(&relay, &held, &doomed, "bye").await.unwrap();
let file = |hash: &str, url: &str| crate::types::Attachment { id: hash.into(), url: url.into(), ..Default::default() };
let (kept_url, gone_url) = ("https://cdn.example/shared", "https://cdn.example/only-here");
let with_files = crate::types::Message {
id: "f1".repeat(32), content: "files".into(), at: 1_700_000_000_000, mine: true,
attachments: vec![file(&"a1".repeat(32), kept_url), file(&"b2".repeat(32), gone_url)], ..Default::default()
};
let theirs = crate::types::Message { id: "f2".repeat(32), content: "theirs".into(), at: 1_700_000_001_000, ..Default::default() };
for msg in [&with_files, &theirs] {
crate::db::events::save_message(&doomed_hex, msg).await.unwrap();
}
let elsewhere = crate::types::Message {
id: "f3".repeat(32), content: "forwarded".into(), at: 1_700_000_002_000, mine: true,
attachments: vec![file(&"a1".repeat(32), kept_url)], ..Default::default()
};
crate::db::events::save_message(&nostr_sdk::prelude::ToBech32::to_bech32(&Keys::generate().public_key()).unwrap(), &elsewhere).await.unwrap();
let purged = purge::purge_deleted_channel(&held, &doomed, None).await.expect("it held the channel");
assert_eq!(purged, purge::Purged { uploads: vec![gone_url.to_string()], scrubs: 1 }, "only my upload nothing else uses");
assert!(crate::db::community::channel_events(&doomed_hex).unwrap().is_empty(), "its history is gone");
assert!(!crate::state::STATE.lock().await.chats.iter().any(|c| c.id == doomed_hex));
assert!(crate::db::events::event_exists(&elsewhere.id).unwrap(), "the forwarded copy stays");
assert_eq!(purge::purge_deleted_channel(&held, &doomed, None).await, None, "a second run finds nothing");
// My wrap leaves the relays from the queue, one at a time.
assert_eq!(crate::db::community::next_wrap_scrub().unwrap().map(|(id, _)| id), Some(sent.clone()));
let wrap_id = crate::db::community::wrap_owners(&sent).unwrap()[0].1.clone();
assert_eq!(crate::community::message_delete::drain_scrubs(&relay, std::time::Duration::ZERO).await, 1);
assert!(relay.fetch(&Query { ids: vec![wrap_id], ..Default::default() }, &["wss://r".to_string()]).await.unwrap().is_empty());
assert_eq!(crate::db::community::next_wrap_scrub().unwrap(), None);
}
#[tokio::test]
async fn a_folded_deletion_purges_the_channel_on_a_device_that_did_not_delete_it() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Seen", vec!["wss://r".into()], None).await.unwrap();
let doomed = ChannelId([0x7b; 32]);
publish_channel_edition(&relay, &community, &owner, &doomed, "doomed", false, 1, false).await;
let held = follow_control(&relay, &community).await.unwrap().updated.expect("added");
let sent = send_message(&relay, &held, &doomed, "seen elsewhere").await.unwrap();
publish_channel_edition(&relay, &community, &owner, &doomed, "doomed", false, 2, true).await;
follow_control(&relay, &held).await.unwrap();
assert!(crate::db::community::channel_events(&crate::simd::hex::bytes_to_hex_32(&doomed.0)).unwrap().is_empty());
assert_eq!(crate::db::community::next_wrap_scrub().unwrap().map(|(id, _)| id), Some(sent), "queued to leave the relays");
}
#[tokio::test]
async fn a_later_edition_never_revives_a_deleted_channel() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Grave", vec!["wss://r".into()], None).await.unwrap();
let extra = ChannelId([0x78; 32]);
publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 1, false).await;
let with_extra = follow_control(&relay, &community).await.unwrap().updated.expect("added");
publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 2, true).await;
publish_channel_edition(&relay, &community, &owner, &extra, "back", false, 3, false).await;
let tracked = follow_control(&relay, &with_extra).await.unwrap().updated.expect("removed");
assert!(tracked.channel(&extra).is_none(), "deletion is terminal over the chain, not the head");
crate::db::community::save_community_v2(&community).unwrap();
let fresh = follow_control(&relay, &community).await.unwrap().updated.unwrap_or(community.clone());
assert!(fresh.channel(&extra).is_none(), "a fresh reader agrees");
}
#[tokio::test]
async fn an_edition_without_its_kinds_bit_cannot_hide_a_channel() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Squat", vec!["wss://r".into()], None).await.unwrap();
let extra = ChannelId([0x79; 32]);
publish_channel_edition(&relay, &community, &owner, &extra, "kept", false, 1, false).await;
let group = control::ControlPlane::of(&community).write_group().unwrap();
let stranger = Keys::generate();
for (signer, kind) in [(&owner, "99"), (&stranger, vsk::ROLE_V2)] {
let rumor = control::build_edition_rumor(signer.public_key(), kind, &extra.0, 1, None, r#"{"role_id":"x"}"#, 1_000, None);
let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
let updated = follow_control(&relay, &community).await.unwrap().updated.expect("added");
assert!(updated.channel(&extra).is_some(), "an unknown kind, or one its signer can't write, claims no coordinate");
// One its signer can write does claim it, and a reader that held the Channel lets it go too.
let rumor = control::build_edition_rumor_bound(owner.public_key(), vsk::CATEGORY, &extra.0, 1, None, r#"{"name":"Staff"}"#, 1_000, None, Some(crate::community::v2::derive::edition_binding(community.id())));
let (wrap, _) = control::seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(1_000)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
let tracked = follow_control(&relay, &updated).await.unwrap().updated.expect("let go");
assert!(tracked.channel(&extra).is_none(), "an edition aimed at another entity folds as no Channel");
}
/// Re-inject only the OLD prefix (every edition at/below `max_version`) of a
/// community's control plane onto a second relay URL — the withholding-relay
/// simulation: everything it serves is genuinely owner-signed, just stale.
async fn inject_stale_prefix(relay: &MemoryRelay, community: &CommunityV2, max_version: u64, stale_relay: &str) {
let group = control::ControlPlane::of(&community).write_group().unwrap();
let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
let wraps = relay.fetch(&query, &community.relays).await.unwrap();
for w in &wraps {
if let Ok((ed, _)) = control::open_control_edition(w, &group) {
if ed.version <= max_version {
relay.inject(w, &[stale_relay.to_string()]);
}
}
}
}
#[tokio::test]
async fn a_withholding_relay_cannot_roll_back_a_rename() {
// W2 persisted floor: after adopting the owner's v2 rename, a relay serving
// only the (owner-signed) v1 genesis must not revert the held name.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Original", vec!["wss://good".into()], None).await.unwrap();
publish_community_meta(&relay, &community, &owner, "Renamed", 2).await;
let updated = follow_control(&relay, &community).await.unwrap().updated.expect("rename adopted");
assert_eq!(updated.name, "Renamed");
// The stale relay holds only the genesis prefix; point the follow at it.
inject_stale_prefix(&relay, &community, 1, "wss://stale").await;
let mut stale_view = updated.clone();
stale_view.relays = vec!["wss://stale".into()];
assert!(
follow_control(&relay, &stale_view).await.unwrap().updated.is_none(),
"a stale-only relay must not change the held view"
);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(held.name, "Renamed", "the persisted floor refuses the rollback");
}
#[tokio::test]
async fn a_withholding_relay_cannot_resurrect_a_deleted_channel() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Prune2", vec!["wss://good".into()], None).await.unwrap();
let extra = ChannelId([0x44; 32]);
// A same-content metadata edit: no visible change (None), but the floor must
// still advance to v2 (so the genesis metadata can't re-present below).
publish_community_meta(&relay, &community, &owner, "Prune2", 2).await;
assert!(follow_control(&relay, &community).await.unwrap().updated.is_none());
publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 1, false).await;
let with_extra = follow_control(&relay, &community).await.unwrap().updated.expect("added");
publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 2, true).await;
let pruned = follow_control(&relay, &with_extra).await.unwrap().updated.expect("removed");
assert!(pruned.channel(&extra).is_none());
// The stale relay serves the add (v1) but withholds the delete (v2).
inject_stale_prefix(&relay, &community, 1, "wss://stale").await;
let mut stale_view = pruned.clone();
stale_view.relays = vec!["wss://stale".into()];
assert!(
follow_control(&relay, &stale_view).await.unwrap().updated.is_none(),
"the withheld delete must not resurrect the channel"
);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert!(held.channel(&extra).is_none(), "the deleted channel stays deleted");
}
#[tokio::test]
async fn a_new_epoch_bootstraps_past_an_old_epoch_floor() {
// The Armada-convergence carve-out: a Refounding compacts the chain and
// re-wraps a detached head at the NEW epoch's control plane. The old epoch's
// floor must not block it — epoch-filtering makes the entity bootstrap.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Before", vec!["wss://good".into()], None).await.unwrap();
publish_community_meta(&relay, &community, &owner, "Edited", 2).await;
let updated = follow_control(&relay, &community).await.unwrap().updated.expect("edit adopted");
assert_eq!(updated.name, "Edited");
// Refounding lands (epoch bump saved by the rekey path); the compacted head
// arrives DETACHED (high version, no prev) on the new epoch's plane.
let refounded = rotate_view(&updated, updated.community_root, 1);
crate::db::community::save_community_v2(&refounded).unwrap();
publish_community_meta(&relay, &refounded, &owner, "Compacted", 5).await;
let adopted = follow_control(&relay, &refounded).await.unwrap().updated.expect("compacted head adopted");
assert_eq!(adopted.name, "Compacted", "a fresh epoch bootstraps despite the dangling prev");
// The persisted floor is stamped with the epoch the FOLD ran under.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let heads = crate::db::community::get_all_edition_heads_epoched(&cid_hex).unwrap();
assert!(
heads.get(&cid_hex).is_some_and(|(e, v, _)| *e == 1 && *v == 5),
"the adopted head carries the fold's epoch + version"
);
}
#[tokio::test]
async fn a_same_version_owner_fork_at_the_floor_converges_to_the_deterministic_winner() {
// Two owner-signed editions at the SAME version (publish retry / two owner
// devices): every client must land on the lower-inner-id winner. A hash-strict
// floor would wedge here forever while Armada converges — the floor must
// CONVERGE instead.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Fork", vec!["wss://r".into()], None).await.unwrap();
let group = control::ControlPlane::of(&community).write_group().unwrap();
let genesis_hash = head_hash_on_relay(&relay, &community, &community.id().0).await.unwrap();
publish_community_meta(&relay, &community, &owner, "Ours", 2).await;
let ours = follow_control(&relay, &community).await.unwrap().updated.expect("ours adopted");
assert_eq!(ours.name, "Ours");
// Our committed v2 edition's tiebreak id.
let our_inner = {
let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
let wraps = relay.fetch(&q, &community.relays).await.unwrap();
wraps
.iter()
.find_map(|w| {
control::open_control_edition(w, &group)
.ok()
.filter(|(ed, _)| ed.version == 2 && ed.vsk == vsk::COMMUNITY_METADATA)
.map(|(ed, _)| ed.inner_id)
})
.unwrap()
};
// Craft the concurrent fork so it WINS the deterministic tiebreak (vary the
// authored timestamp until its inner id is lower).
let meta = control::CommunityMetadata { name: "Theirs".into(), ..Default::default() };
let content = serde_json::to_string(&meta).unwrap();
let mut ts = 2_000u64;
let fork_wrap = loop {
let rumor = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 2, Some(&genesis_hash), &content, ts, None);
let inner = rumor.id.unwrap().to_bytes();
if inner < our_inner {
break control::seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(ts)).unwrap().0;
}
ts += 1;
};
relay.publish(&fork_wrap, &community.relays).await.unwrap();
let converged = follow_control(&relay, &ours).await.unwrap().updated.expect("fork winner adopted");
assert_eq!(converged.name, "Theirs", "the floor converges to the lower-inner-id winner");
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let held = crate::db::community::get_edition_head_inner_id(&cid_hex, &cid_hex).unwrap();
assert!(held.is_some_and(|h| h < our_inner), "the persisted floor's tiebreak key moved to the winner");
}
#[tokio::test]
async fn an_anchored_prefix_applies_while_a_gap_above_awaits_the_missing_link() {
// v2 chains to the floor; v4 arrives but its v3 link is withheld. The
// chain-verified prefix (v2) applies NOW — refuse-downgrade holds for it —
// while the detached v4 waits. When v3 lands, the chain heals to v4.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Prefix", vec!["wss://r".into()], None).await.unwrap();
let group = control::ControlPlane::of(&community).write_group().unwrap();
publish_community_meta(&relay, &community, &owner, "Two", 2).await;
let v2_hash = head_hash_on_relay(&relay, &community, &community.id().0).await.unwrap();
// Craft v3 (held back) and v4 (published, chained to the withheld v3).
let c3 = serde_json::to_string(&control::CommunityMetadata { name: "Three".into(), ..Default::default() }).unwrap();
let r3 = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 3, Some(&v2_hash), &c3, 3_000, None);
let (w3, _) = control::seal_control_edition(&r3, &group, &owner, Timestamp::from_secs(3_000)).unwrap();
let (ed3, _) = control::open_control_edition(&w3, &group).unwrap();
let c4 = serde_json::to_string(&control::CommunityMetadata { name: "Four".into(), ..Default::default() }).unwrap();
let r4 = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 4, Some(&ed3.self_hash), &c4, 4_000, None);
let (w4, _) = control::seal_control_edition(&r4, &group, &owner, Timestamp::from_secs(4_000)).unwrap();
relay.publish(&w4, &community.relays).await.unwrap();
let updated = follow_control(&relay, &community).await.unwrap().updated.expect("the verified prefix applies");
assert_eq!(updated.name, "Two", "the anchored prefix lands; the detached v4 does not");
relay.publish(&w3, &community.relays).await.unwrap();
let healed = follow_control(&relay, &updated).await.unwrap().updated.expect("the chain heals");
assert_eq!(healed.name, "Four", "once the link arrives, the head advances past the prefix");
}
#[tokio::test]
async fn paging_rescues_a_floor_link_evicted_from_the_newest_window() {
// The held floor is v2; the owner publishes v3, then a flood of foreign junk
// wraps fills the newest window, then v4. Page 1 sees only v4 (detached →
// gapped); paging older must recover v3 (and the floor link) and heal to v4.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Paged", vec!["wss://r".into()], None).await.unwrap();
let group = control::ControlPlane::of(&community).write_group().unwrap();
publish_community_meta(&relay, &community, &owner, "Two", 2).await;
let base = follow_control(&relay, &community).await.unwrap().updated.expect("floor at v2");
publish_community_meta(&relay, &base, &owner, "Three", 3).await; // ts 1_000 (old)
let v3_hash = head_hash_on_relay(&relay, &community, &community.id().0).await.unwrap();
// Rogue flood occupying the newest window (sealed to the control plane, but
// non-owner — the authority gate drops them; they only crowd the page).
let rogue = Keys::generate();
for i in 0..(FOLLOW_PAGE as u64 - 1) {
let rumor = control::build_edition_rumor(rogue.public_key(), vsk::CHANNEL_METADATA, &[0xCC; 32], 1, None, "{\"name\":\"junk\",\"private\":false}", 4_000 + i, None);
let (w, _) = control::seal_control_edition(&rumor, &group, &rogue, Timestamp::from_secs(4_000 + i)).unwrap();
relay.publish(&w, &community.relays).await.unwrap();
}
// v4 chained to the real v3 (crafted directly: the flood also blinds the
// helper's own newest-window head lookup), timestamped newest of all.
let c4 = serde_json::to_string(&control::CommunityMetadata { name: "Four".into(), ..Default::default() }).unwrap();
let r4 = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 4, Some(&v3_hash), &c4, 10_000, None);
let (w4, _) = control::seal_control_edition(&r4, &group, &owner, Timestamp::from_secs(10_000)).unwrap();
relay.publish(&w4, &community.relays).await.unwrap();
let healed = follow_control(&relay, &base).await.unwrap().updated.expect("paging recovered the chain");
assert_eq!(healed.name, "Four", "the gap paged past the flood to the floor link");
}
#[tokio::test]
async fn a_follow_after_delete_does_not_resurrect_the_community() {
// A leave/delete racing an in-flight follow: the follow must not re-insert
// the community row or floor rows past delete_community's wipe.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Gone", vec!["wss://r".into()], None).await.unwrap();
publish_community_meta(&relay, &community, &owner, "Edited", 2).await;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::delete_community(&cid_hex).unwrap();
assert!(
follow_control(&relay, &community).await.unwrap().updated.is_none(),
"a follow racing a delete is a no-op"
);
assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_none(), "the community stays deleted");
assert!(crate::db::community::edition_head_entity_ids(&cid_hex).unwrap().is_empty(), "no orphan floor rows");
}
#[tokio::test]
async fn a_rekey_follow_after_delete_does_not_resurrect_the_community() {
// The rekey sibling of the follow_control guard: an owner rotation adopted
// mid-race must not upsert the community row back after a leave/delete.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "GoneKeys", vec!["wss://r".into()], None).await.unwrap();
let new_root = [0xB2; 32];
publish_base_rotation(&relay, &community, &owner, &[owner.public_key()], &new_root, &community.community_root).await;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::delete_community(&cid_hex).unwrap();
let session = crate::db::current_session();
let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
assert!(follow.updated.is_none() && !follow.self_removed, "a rekey follow racing a delete adopts nothing");
assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_none(), "the community stays deleted");
}
#[tokio::test]
async fn a_joiner_bootstraps_the_highest_head_across_a_lost_middle_edition() {
// {v1, v3} on the relays with v2 lost at publish time (a rate-limiting relay
// that still ACKed): the genesis anchors, so an anchored-prefix-first fold
// would take v1 and SEED the joiner's floor there — pinning them below the
// head Armada shows, forever. A joiner (floor 0) must bootstrap v3.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Skip", bed.relays.clone(), None).await.unwrap();
let group = control::ControlPlane::of(&community).write_group().unwrap();
let genesis_hash = head_hash_on_relay(&bed.relay, &community, &community.id().0).await.unwrap();
// v2 is crafted but NEVER published; v3 chains to it and is published.
let c2 = serde_json::to_string(&control::CommunityMetadata { name: "Two".into(), ..Default::default() }).unwrap();
let r2 = control::build_edition_rumor(owner.keys.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 2, Some(&genesis_hash), &c2, 2_000, None);
let (w2, _) = control::seal_control_edition(&r2, &group, &owner.keys, Timestamp::from_secs(2_000)).unwrap();
let (ed2, _) = control::open_control_edition(&w2, &group).unwrap();
let c3 = serde_json::to_string(&control::CommunityMetadata { name: "Three".into(), ..Default::default() }).unwrap();
let r3 = control::build_edition_rumor(owner.keys.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 3, Some(&ed2.self_hash), &c3, 3_000, None);
let (w3, _) = control::seal_control_edition(&r3, &group, &owner.keys, Timestamp::from_secs(3_000)).unwrap();
bed.relay.publish(&w3, &community.relays).await.unwrap();
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&member);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
assert_eq!(joined.name, "Three", "the joiner bootstraps the highest signed head, not the anchored stale prefix");
let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
let head = crate::db::community::get_edition_head(&cid_hex, &cid_hex).unwrap();
assert!(head.is_some_and(|(v, _)| v == 3), "the seeded floor is the bootstrap head");
}
#[tokio::test]
async fn a_losing_same_version_fork_cannot_replace_the_held_floor() {
// The refusal half of fork convergence: a relay withholding OUR committed
// floor edition while serving only a same-version fork with a HIGHER inner
// id must be treated as withholding — held state and floor unchanged.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Fork2", vec!["wss://good".into()], None).await.unwrap();
let group = control::ControlPlane::of(&community).write_group().unwrap();
let genesis_hash = head_hash_on_relay(&relay, &community, &community.id().0).await.unwrap();
publish_community_meta(&relay, &community, &owner, "Ours", 2).await;
let ours = follow_control(&relay, &community).await.unwrap().updated.expect("ours adopted");
assert_eq!(ours.name, "Ours");
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let held_before = crate::db::community::get_edition_head(&cid_hex, &cid_hex).unwrap().unwrap();
let our_inner = crate::db::community::get_edition_head_inner_id(&cid_hex, &cid_hex).unwrap().unwrap();
// Grind the fork to LOSE the tiebreak (higher inner id), then serve it —
// with the genesis but WITHOUT our v2 — from a withholding relay.
let meta = control::CommunityMetadata { name: "Theirs".into(), ..Default::default() };
let content = serde_json::to_string(&meta).unwrap();
let mut ts = 5_000u64;
let fork_wrap = loop {
let rumor = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 2, Some(&genesis_hash), &content, ts, None);
if rumor.id.unwrap().to_bytes() > our_inner {
break control::seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(ts)).unwrap().0;
}
ts += 1;
};
inject_stale_prefix(&relay, &community, 1, "wss://stale").await; // genesis only
relay.inject(&fork_wrap, &["wss://stale".to_string()]);
let mut stale_view = ours.clone();
stale_view.relays = vec!["wss://stale".into()];
assert!(
follow_control(&relay, &stale_view).await.unwrap().updated.is_none(),
"a losing fork served without our floor edition changes nothing"
);
let held_after = crate::db::community::get_edition_head(&cid_hex, &cid_hex).unwrap().unwrap();
assert_eq!(held_after, held_before, "the floor row is untouched");
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(held.name, "Ours", "the held state is untouched");
}
#[tokio::test]
async fn follow_control_ignores_a_non_owner_edition() {
// A member holds the community_root, so they CAN seal a control edition —
// but they aren't the owner, so the authority gate drops it (first cut:
// owner-only). The rogue channel must never appear.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Guarded", vec!["wss://r".into()], None).await.unwrap();
let rogue = Keys::generate();
let rogue_id = ChannelId([0x99; 32]);
publish_channel_edition(&relay, &community, &rogue, &rogue_id, "backdoor", false, 1, false).await;
assert!(
follow_control(&relay, &community).await.unwrap().updated.is_none(),
"a non-owner control edition is not folded"
);
}
#[tokio::test]
async fn follow_control_records_a_new_private_channel_keyless_and_unreadable() {
// A Private channel's key rides the rekey plane, not the control edition —
// control-follow records it KEYLESS (epoch 0, the rekey-scan cursor), and
// every read/send path refuses it until the key lands (never the root plane).
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Priv", vec!["wss://r".into()], None).await.unwrap();
let priv_id = ChannelId([0x33; 32]);
publish_channel_edition(&relay, &community, &owner, &priv_id, "mods", true, 1, false).await;
let updated = follow_control(&relay, &community)
.await
.unwrap()
.updated
.expect("the keyless record is a change");
let ch = updated.channel(&priv_id).expect("the private channel is recorded");
assert!(ch.private && ch.key.is_none(), "recorded keyless");
assert_eq!(ch.epoch, Epoch(0), "epoch 0 = the root generation (scan cursor)");
assert!(updated.channel_read_coords(ch).is_empty(), "unreadable until keyed");
assert!(
fetch_channel(&relay, &updated, &priv_id, 50).await.unwrap().is_empty(),
"a keyless fetch returns empty (and never queries the root plane)"
);
assert!(
send_message(&relay, &updated, &priv_id, "nope").await.is_err(),
"a keyless send refuses"
);
// The keyless record round-trips (the stored placeholder never surfaces
// as a real key).
let reloaded = crate::db::community::load_community_v2(updated.id()).unwrap().unwrap();
let rch = reloaded.channel(&priv_id).unwrap();
assert!(rch.private && rch.key.is_none() && rch.epoch == Epoch(0), "keyless survives reload");
// And a bundle minted while keyless never carries the placeholder — a
// MEMBER audience, so it's the keyless filter proving it (the link
// filter would drop the channel for the weaker reason).
let bundle = bundle_of(&reloaded, BundleAudience::Member(Keys::generate().public_key()), None, None, None);
assert!(
!bundle.channels.iter().any(|c| c.id == crate::simd::hex::bytes_to_hex_32(&priv_id.0)),
"an ungrantable keyless channel stays out of invite bundles"
);
}
#[tokio::test]
async fn a_link_bundle_never_carries_a_private_channel_key() {
// A link's audience holds no Role by construction (CORD-05), so a HELD
// private key must never ride a link bundle — anyone with the URL would
// get the channel. A member bundle carries it; a link bundle only the
// public channels.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Leak", vec!["wss://r".into()], None).await.unwrap();
create_private_channel(&relay, &community, "mods").await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let priv_hex = held
.channels
.iter()
.find(|c| c.private)
.map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0))
.expect("the private channel is held WITH its key");
let link = bundle_of(&held, BundleAudience::Link, None, None, None);
assert!(
!link.channels.iter().any(|c| c.id == priv_hex),
"a held private key must never ride a link bundle"
);
assert!(
link.channels.iter().any(|c| c.id != priv_hex),
"the public channels still ride it"
);
// A member bundle grants it only to the ENTITLED. An unrelated npub holds
// no scoped role, so it gets nothing; the creator (granted the companion
// access role at create) gets the key.
let stranger = bundle_of(&held, BundleAudience::Member(Keys::generate().public_key()), None, None, None);
assert!(
!stranger.channels.iter().any(|c| c.id == priv_hex),
"an unentitled member gets no private key"
);
let mine = bundle_of(&held, BundleAudience::Member(me_pk().unwrap()), None, None, None);
assert!(
mine.channels.iter().any(|c| c.id == priv_hex),
"the creator is entitled via the companion access role"
);
}
/// Mint a server-scope role at `position` carrying `permissions`, grant it to
/// `member`, and return its id. Used to build a RANKED roster (the owner-only
/// tests can't exercise outranking, since the owner outranks everyone).
async fn seat_ranked_role(
relay: &MemoryRelay,
community: &CommunityV2,
member: &PublicKey,
name: &str,
position: u32,
permissions: crate::community::roles::Permissions,
) -> String {
let role_id = crate::crypto::sha256_hex(format!("test/role/{name}/{position}").as_bytes());
let role = crate::community::roles::Role {
role_id: role_id.clone(),
name: name.to_string(),
position,
permissions,
scope: crate::community::roles::RoleScope::Server,
color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
};
set_role(relay, community, &role).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let mut ids: Vec<String> = {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
roster.roles_of(&member.to_hex()).map(|r| r.role_id.clone()).collect()
};
if !ids.contains(&role_id) {
ids.push(role_id.clone());
}
grant_roles(relay, &held, member, ids).await.unwrap();
role_id
}
/// Become `who` without touching the account DB — the acting identity only.
/// Enough to exercise an offer-side authority gate from a non-owner's seat.
fn act_as(who: &Keys) {
crate::state::MY_SECRET_KEY.store_from_keys(who, &[]);
crate::state::set_my_public_key(who.public_key());
}
#[tokio::test]
async fn a_moderator_cannot_revoke_channel_access_from_a_superior_and_the_channel_never_rotates() {
// CORD-04 §2: the fold drops a Grant aimed at a peer or superior, but the
// channel rotation is gated on the citation alone — so without an
// offer-side rank check the Grant dies and the target is severed anyway.
// The epoch assertion is the point: refusing the publish is worthless if
// the rekey still runs.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Ranked", vec!["wss://r".into()], None).await.unwrap();
let vault = create_private_channel(&relay, &community, "vault").await.unwrap();
let superior = Keys::generate();
let moderator = Keys::generate();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
grant_admin(&relay, &held, &superior.public_key()).await.unwrap();
seat_ranked_role(
&relay,
&community,
&moderator.public_key(),
"Moderator",
5,
crate::community::roles::Permissions(crate::community::roles::Permissions::MANAGE_ROLES),
)
.await;
// The superior legitimately holds the channel (granted by the owner).
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
grant_channel_access(&relay, &held, &vault, &superior.public_key()).await.unwrap();
let before = crate::db::community::load_community_v2(community.id())
.unwrap()
.unwrap()
.channel(&vault)
.unwrap()
.epoch;
act_as(&moderator);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let err = revoke_channel_access(&relay, &held, &vault, &superior.public_key())
.await
.expect_err("a moderator must not act on an admin");
assert!(err.contains("outrank"), "refused for RANK, not some incidental reason: {err}");
let after = crate::db::community::load_community_v2(community.id())
.unwrap()
.unwrap()
.channel(&vault)
.unwrap()
.epoch;
assert_eq!(after, before, "the refusal must also stop the rotation — the rekey IS the severance");
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
let chan_hex = crate::simd::hex::bytes_to_hex_32(&vault.0);
let owner_hex = owner.public_key().to_hex();
assert!(
roster.is_entitled(Some(&owner_hex), &superior.public_key().to_hex(), &chan_hex, &[], &[]),
"and the superior keeps their access role"
);
}
#[tokio::test]
async fn a_moderator_cannot_grant_channel_access_to_a_superior_but_the_owner_stays_grantable() {
// The grant direction of the same gate. The owner is never a valid rank
// target, yet IS a legitimate recipient of a key an admin minted — the
// rank check must not swallow that case.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Ranked", vec!["wss://r".into()], None).await.unwrap();
let vault = create_private_channel(&relay, &community, "vault").await.unwrap();
let superior = Keys::generate();
let moderator = Keys::generate();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
grant_admin(&relay, &held, &superior.public_key()).await.unwrap();
let chan_hex = crate::simd::hex::bytes_to_hex_32(&vault.0);
// Scoped access so the moderator holds the channel key itself, else the
// refusal could come from "we hold no key" and prove nothing about rank.
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
grant_channel_access(&relay, &held, &vault, &moderator.public_key()).await.unwrap();
seat_ranked_role(
&relay,
&community,
&moderator.public_key(),
"Moderator",
5,
crate::community::roles::Permissions(crate::community::roles::Permissions::MANAGE_ROLES),
)
.await;
act_as(&moderator);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let err = grant_channel_access(&relay, &held, &vault, &superior.public_key())
.await
.expect_err("a moderator must not grant against an admin");
assert!(err.contains("outrank"), "refused for RANK: {err}");
// Same seat, same channel, owner as the target: allowed.
grant_channel_access(&relay, &held, &vault, &owner.public_key())
.await
.expect("the owner is not a rank target, and may still be handed a key");
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
let owner_hex = owner.public_key().to_hex();
assert!(
roster.is_entitled(Some(&owner_hex), &owner_hex, &chan_hex, &[], &[]),
"the owner's access role landed"
);
}
#[tokio::test]
async fn roles_v2_carries_private_access_as_overwrites_and_keys_follow_them() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "AclCarry", vec!["wss://r".into()], None).await.unwrap();
let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
let (chan, cid_hex) = (crate::simd::hex::bytes_to_hex_32(&priv_id.0), crate::simd::hex::bytes_to_hex_32(&community.id().0));
let owner_hex = community.owner().unwrap().to_hex();
let (s, t) = (Keys::generate().public_key(), Keys::generate().public_key());
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
grant_channel_access(&relay, &held(), &priv_id, &s).await.unwrap();
follow_control(&relay, &held()).await.unwrap();
activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&relay, &held()).await.unwrap();
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert!(roster.everyone.is_some() && roster.channel_roles(&chan).is_empty(), "on Roles v2, no scoped roles");
assert!(roster.is_entitled(Some(&owner_hex), &s.to_hex(), &chan, &[], &[]), "the access holder still reads it");
assert!(!roster.is_entitled(Some(&owner_hex), &t.to_hex(), &chan, &[], &[]), "nobody else does");
assert_eq!(held().channel(&priv_id).unwrap().epoch, Epoch(1), "nobody lost access, so nothing rotated");
// A member overwrite lets T in: their bundle carries the key, and S's deny rotates.
grant_channel_access(&relay, &held(), &priv_id, &t).await.unwrap();
assert!(bundle_of(&held(), BundleAudience::Member(t), None, None, None).channels.iter().any(|c| c.id == chan));
revoke_channel_access(&relay, &held(), &priv_id, &s).await.unwrap();
assert_eq!(held().channel(&priv_id).unwrap().epoch, Epoch(2), "the revoke rotated the channel");
// The new key reaches who the Channel lets through, and not who it doesn't.
let group = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
let blobs: Vec<String> = fetch_rekey_chunks(&relay, &community, &group).await.unwrap().into_iter().flat_map(|c| c.blobs).map(|b| b.locator).collect();
let me = me_pk().unwrap().to_bytes();
let at = |pk: &PublicKey| rekey::blob_locator(&me, &pk.to_bytes(), RekeyScope::Channel(priv_id), Epoch(2));
assert!(blobs.contains(&at(&t)) && !blobs.contains(&at(&s)), "T is keyed, S is not");
// A peer folding the plane cold agrees.
let eds = fetch_control(&relay, &held()).await;
let f = fold_authority(&held(), &eds, &Floors::default());
assert!(f.roles.is_entitled(Some(&owner_hex), &t.to_hex(), &chan, &[], &[]));
assert!(!f.roles.is_entitled(Some(&owner_hex), &s.to_hex(), &chan, &[], &[]));
}
#[tokio::test]
async fn a_channel_made_in_a_category_takes_its_rules_until_unsynced() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Sync", vec!["wss://r".into()], None).await.unwrap();
activate_roles_v2(&relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let staff = create_category(&relay, &held(), "Announcements").await.unwrap();
set_overwrite(&relay, &held(), staff, crate::community::roles::OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
let news = create_channel_in(&relay, &held(), "news", false, Some(staff)).await.unwrap();
let m = Keys::generate().public_key().to_hex();
let may_send = |eds: &[ParsedEdition], ch: &ChannelId| {
let r = fold_authority(&held(), eds, &Floors::default()).roles;
r.channel_permissions(Some(&owner.public_key().to_hex()), &m, &crate::simd::hex::bytes_to_hex_32(&ch.0), false).contains(Permissions::SEND_MESSAGES)
};
let eds = fetch_control(&relay, &held()).await;
assert!(!may_send(&eds, &news), "the new channel follows its Category's deny");
assert!(may_send(&eds, &community.channels[0].id), "an unsynced channel doesn't");
assert_eq!(crate::db::community::get_community_roles(&cid_hex).unwrap().syncs.get(&crate::simd::hex::bytes_to_hex_32(&news.0)), Some(&crate::simd::hex::bytes_to_hex_32(&staff)));
set_channel_sync(&relay, &held(), &news, None).await.unwrap();
assert!(may_send(&fetch_control(&relay, &held()).await, &news), "unsynced, it keeps no rules of its own");
// A manager beneath a Role the Category names can't swap that rule in or out.
let (x, top) = (Keys::generate(), "f5".repeat(32));
publish_role_v2(&relay, &held(), &owner, &role_v2(&top, "Top", "B", 0), 1).await;
let low = create_role_v2(&relay, &held(), "Mods", 0, Permissions::MANAGE_ROLES | Permissions::SEND_MESSAGES | Permissions::VIEW_CHANNEL).await.unwrap();
set_member_roles(&relay, &held(), &x.public_key(), vec![low]).await.unwrap();
follow_control(&relay, &held()).await.unwrap();
set_overwrite(&relay, &held(), staff, crate::community::roles::OverwriteTarget::Role(top.clone()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let eid = crate::community::v2::derive::sync_locator(community.id(), &news);
let prev = head_hash_on_relay(&relay, &held(), &eid).await;
let version = fetch_control(&relay, &held()).await.iter().filter(|e| e.entity_id == eid).map(|e| e.version).max().unwrap();
let content = crate::community::v2::roles::sync_content_json(&crate::simd::hex::bytes_to_hex_32(&news.0), Some(&crate::simd::hex::bytes_to_hex_32(&staff)));
publish_marked(&relay, &held(), &x, vsk::CHANNEL_SYNC, &eid, version + 1, prev, &content).await;
assert!(may_send(&fetch_control(&relay, &held()).await, &news), "the low manager's re-sync is refused");
}
/// A Roles v2 community with an admin `x` (Manage Roles, Manage Channels, the channel basics).
async fn v2_bed_with_admin(name: &str) -> (TestBed, Actor, Keys, CommunityV2) {
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, name, bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let x = Keys::generate();
let bits = Permissions::MANAGE_ROLES | Permissions::MANAGE_CHANNELS | crate::community::v2::roles::EVERYONE_DEFAULT;
let admin = create_role_v2(&bed.relay, &held, "Admin", 0, bits).await.unwrap();
set_member_roles(&bed.relay, &held, &x.public_key(), vec![admin]).await.unwrap();
follow_control(&bed.relay, &held).await.unwrap();
(bed, owner, x, crate::db::community::load_community_v2(community.id()).unwrap().unwrap())
}
#[tokio::test]
async fn a_new_community_starts_on_roles_v2_and_a_joiner_reads_it_so() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community_on_roles_v2(&bed.relay, "Born", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let general = crate::simd::hex::bytes_to_hex_32(&community.channels[0].id.0);
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert_eq!(roster.everyone, Some(Permissions(crate::community::v2::roles::EVERYONE_DEFAULT)), "@everyone holds the defaults");
assert!(roster.legacy_channels.as_ref().is_some_and(|l| l.contains(&general)), "the genesis Channel is what the switch lists");
assert!(roles_v2_held(&community));
send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
bed.swap_to(&member);
let joined = accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await).await.unwrap();
follow_control(&bed.relay, &joined).await.unwrap();
let theirs = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert!(theirs.everyone.is_some() && theirs.channel_permissions(Some(&owner.keys.public_key().to_hex()), &member.keys.public_key().to_hex(), &general, false).contains(Permissions::SEND_MESSAGES), "a joiner folds it as Roles v2 and may post in general");
}
#[cfg(feature = "calls")]
#[tokio::test]
async fn who_may_join_a_voice_channel_and_who_is_heard_follow_the_roster() {
use crate::calls::voice::{allowed_relay, may_connect, may_speak};
use crate::community::roles::OverwriteTarget;
let (bed, _owner, x, community) = v2_bed_with_admin("Voice").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = held().channels[0].id;
let (m, n) = (Keys::generate().public_key(), Keys::generate().public_key());
assert!(may_connect(&held(), &ch, &m) && may_speak(&held(), &ch, &m), "@everyone connects and speaks by default");
set_overwrite(&bed.relay, &held(), ch.0, OverwriteTarget::Member(m.to_hex()), 0, Permissions::SPEAK).await.unwrap();
assert!(may_connect(&held(), &ch, &m) && !may_speak(&held(), &ch, &m), "denied Speak: in the call, not heard");
set_overwrite(&bed.relay, &held(), ch.0, OverwriteTarget::Member(n.to_hex()), 0, Permissions::CONNECT).await.unwrap();
assert!(!may_connect(&held(), &ch, &n), "denied Connect: never dialled or accepted");
timeout_member(&bed.relay, &held(), &x.public_key(), 600).await.unwrap();
assert!(may_connect(&held(), &ch, &x.public_key()) && !may_speak(&held(), &ch, &x.public_key()), "timed out: silent while it runs");
set_members_banned(&bed.relay, community.id(), &[m], true).await.unwrap();
assert!(!may_connect(&held(), &ch, &m), "banned: in no call");
let n0: iroh::RelayUrl = iroh::defaults::prod::default_relay_map().urls::<Vec<iroh::RelayUrl>>()[0].clone();
let own: iroh::RelayUrl = "https://voice.example.org/".parse().unwrap();
assert!(allowed_relay(&n0, &held()) && !allowed_relay(&own, &held()), "iroh's defaults only, until the Community lists its own");
let mut listed = held();
listed.meta_extra.insert("voice_relays".into(), serde_json::json!(["https://voice.example.org/", "http://plain.example.org/"]));
assert!(allowed_relay(&own, &listed) && !allowed_relay(&"http://plain.example.org/".parse().unwrap(), &listed), "and only over https");
}
#[tokio::test]
async fn a_voice_directive_stands_only_from_who_holds_the_bit_and_outranks_the_target() {
use super::super::voice::{self, Directive, Heard};
let (bed, owner, x, community) = v2_bed_with_admin("Directives").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = held().channels[0].id;
let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
let m = Keys::generate();
let now = now_ms();
for k in [m.public_key(), x.public_key(), owner.keys.public_key()] {
voice::note(&chan, k, now, Heard { joined: true, transport: Some("iroh".into()), endpoint: Some(k.to_bytes()), ..Default::default() }, now);
}
let (secret, epoch) = held().channel_secret(held().channel(&ch).unwrap());
let read = channel_group_key(&secret, &ch, epoch);
let wrap = |actor: &Keys, target: &PublicKey, d: Directive| {
let rumor = chat::build_voice_directive_rumor(actor.public_key(), &ch, epoch, target, d, None, None, now_ms());
chat::seal_chat_rumor(&rumor, &read, actor, Timestamp::now(), true).unwrap().0
};
let me = m.public_key();
let dispatch = |w: &nostr_sdk::prelude::Event| super::super::inbound::dispatch_wrap(w, &held(), &me, &crate::event_handler::NoOpEventHandler);
dispatch(&wrap(&x, &m.public_key(), Directive::Mute));
assert_eq!(voice::server_state(&chan, &m.public_key()), (false, false), "an admin without Mute Members mutes nobody");
dispatch(&wrap(&owner.keys, &m.public_key(), Directive::Mute));
assert_eq!(voice::server_state(&chan, &m.public_key()), (true, false), "the owner does");
dispatch(&wrap(&x, &owner.keys.public_key(), Directive::Deafen));
assert_eq!(voice::server_state(&chan, &owner.keys.public_key()), (false, false), "and nobody deafens the owner");
dispatch(&wrap(&owner.keys, &x.public_key(), Directive::Deafen));
assert_eq!(voice::server_state(&chan, &x.public_key()), (false, true));
assert!(voice::present(&chan, now_ms()).iter().any(|p| p.author == m.public_key() && p.server_muted));
act_as(&x);
assert!(send_voice_directive(&bed.relay, &held(), &ch, &m.public_key(), Directive::Mute, None).await.is_err(), "nor can they send one");
act_as(&owner.keys);
assert!(send_voice_directive(&bed.relay, &held(), &ch, &m.public_key(), Directive::Move, Some([9; 32])).await.is_err(), "a move needs a voice channel to go to");
// A same-ms tie keeps them muted: the lift is sent a moment after the mute.
tokio::time::sleep(std::time::Duration::from_millis(2)).await;
send_voice_directive(&bed.relay, &held(), &ch, &m.public_key(), Directive::Unmute, None).await.unwrap();
assert_eq!(voice::server_state(&chan, &m.public_key()), (false, false));
}
#[tokio::test]
async fn a_refounding_seals_each_private_channel_again_under_its_new_epoch() {
let (bed, _owner, _x, community) = v2_bed_with_admin("Refound").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
let before = held().channel(&ch).unwrap().epoch;
refound_community(&bed.relay, &held(), &[Keys::generate().public_key()]).await.unwrap();
let after = held().channel(&ch).cloned().unwrap();
assert!(after.epoch > before, "the Refounding mints the channel a fresh epoch");
assert_eq!(after.sealed.as_ref().map(|s| (s.epoch, s.open)), Some((after.epoch.0, true)), "and seals its metadata under it, for whoever joins at it");
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().resealed, 0, "leaving the duty nothing");
}
#[tokio::test]
async fn a_channel_manager_makes_a_private_channel_and_is_let_in_as_its_creator() {
let (bed, owner, x, community) = v2_bed_with_admin("Made").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let (owner_hex, x_hex) = (owner.keys.public_key().to_hex(), x.public_key().to_hex());
act_as(&x);
let ch = create_private_channel(&bed.relay, &held(), "mods").await.unwrap();
let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
assert!(crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap().is_entitled(Some(&owner_hex), &x_hex, &chan, &[], &[]), "in from the start");
send_chat_message(&bed.relay, &held(), &ch, "made by a mod", None, &[], vec![]).await.unwrap();
// The owner's device reads the creator from the sealed metadata, and its duty keeps them.
act_as(&owner.keys);
follow_control(&bed.relay, &held()).await.unwrap();
let fold = || async { fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default()).roles };
let roster = fold().await;
assert!(roster.is_entitled(Some(&owner_hex), &x_hex, &chan, &[], &[]), "the creator, on a fold of the plane");
assert!(!roster.is_entitled(Some(&owner_hex), &Keys::generate().public_key().to_hex(), &chan, &[], &[]), "and no one else");
let epoch = held().channel(&ch).unwrap().epoch;
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().cut, 0);
assert_eq!(held().channel(&ch).unwrap().epoch, epoch, "no rotation cuts them");
// An outranking member's deny still shuts them out, and so does losing Manage Channels.
set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Member(x_hex.clone()), 0, Permissions::VIEW_CHANNEL).await.unwrap();
assert!(!fold().await.is_entitled(Some(&owner_hex), &x_hex, &chan, &[], &[]), "an explicit deny wins");
assert!(held().channel(&ch).unwrap().epoch > epoch, "and rotates them out");
set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Member(x_hex.clone()), 0, 0).await.unwrap();
assert!(fold().await.is_entitled(Some(&owner_hex), &x_hex, &chan, &[], &[]), "the creator rule stands once the deny goes");
set_member_roles(&bed.relay, &held(), &x.public_key(), vec![]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert!(!fold().await.is_entitled(Some(&owner_hex), &x_hex, &chan, &[], &[]), "only while they manage channels");
}
#[tokio::test]
async fn a_reader_takes_the_key_its_creator_delivers_though_it_cant_see_the_creator_rule() {
let (bed, _owner, x, community) = v2_bed_with_admin("Keyless").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
act_as(&x);
let ch = create_private_channel(&bed.relay, &held(), "mods").await.unwrap();
let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
let m = Keys::generate();
set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Member(m.public_key().to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().delivered, 0, "the creator delivered with the change itself");
// M's device: keyless, and its fold can't open the seal that names the creator.
let mut c = held();
let e = c.channels.iter_mut().find(|e| e.id.0 == ch.0).unwrap();
(e.key, e.sealed) = (None, None);
e.meta_extra.clear();
crate::db::community::save_community_v2(&c).unwrap();
let mut roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
roster.creators.clear();
crate::db::community::set_community_roles(&cid_hex, &roster, crate::db::community::get_community_roles_at(&cid_hex).unwrap_or(0)).unwrap();
assert!(!roster.is_entitled(None, &x.public_key().to_hex(), &chan, &[], &[]), "to M, the creator isn't entitled");
act_as(&m);
assert_eq!(collect_access(&bed.relay, &held()).await.unwrap(), 1, "but manages channels, so its delivery counts");
absorb_parked_channel_keys(&held(), &crate::db::current_session());
assert!(held().channel(&ch).unwrap().key.is_some(), "and the key is taken");
act_as(&x);
}
#[tokio::test]
async fn a_creator_named_outside_the_seal_lets_nobody_in() {
let (bed, owner, x, community) = v2_bed_with_admin("Plain").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
let mut c = held();
let x_hex = x.public_key().to_hex();
let entry = c.channels.iter_mut().find(|e| e.id.0 == ch.0).unwrap();
entry.meta_extra.insert("creator".into(), x_hex.clone().into());
assert_eq!(entry.creator(), Some(x_hex.as_str()), "read from the opened seal");
entry.sealed = None;
assert_eq!(entry.creator(), None, "a plain edition names no creator: anyone with Manage Channels could write one");
let roster = fold_authority(&c, &fetch_control(&bed.relay, &c).await, &Floors::default()).roles;
assert!(!roster.is_entitled(Some(&owner.keys.public_key().to_hex()), &x_hex, &chan, &[], &[]));
}
#[tokio::test]
async fn a_private_channel_stays_closed_whatever_everyone_is_allowed() {
// Privacy doesn't hang on an @everyone deny a manager could clear: a private
// Channel opens only to a Role's or a member's allow.
let (bed, owner, x, community) = v2_bed_with_admin("Closed").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "admins").await.unwrap();
let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
let owner_hex = owner.keys.public_key().to_hex();
let m = Keys::generate().public_key().to_hex();
let fold = || async { fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default()).roles };
assert!(!fold().await.is_entitled(Some(&owner_hex), &m, &chan, &[], &[]));
assert!(!fold().await.is_entitled(Some(&owner_hex), &x.public_key().to_hex(), &chan, &[], &[]), "not even an admin, until let in");
// The admin allows @everyone View there: still closed.
act_as(&x);
set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Everyone, Permissions::VIEW_CHANNEL, 0).await.unwrap();
assert!(!fold().await.is_entitled(Some(&owner_hex), &m, &chan, &[], &[]), "@everyone never opens a private channel");
assert!(fold().await.channel_permissions(Some(&owner_hex), &m, &chan, false).contains(Permissions::VIEW_CHANNEL), "a public one it would");
act_as(&owner.keys);
}
#[tokio::test]
async fn a_member_overwrite_cant_be_replaced_through_a_role_of_the_same_bytes() {
let (bed, owner, x, community) = v2_bed_with_admin("Alias").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
let (chan, owner_hex) = (crate::simd::hex::bytes_to_hex_32(&ch.0), owner.keys.public_key().to_hex());
grant_channel_access(&bed.relay, &held(), &ch, &x.public_key()).await.unwrap();
revoke_channel_access(&bed.relay, &held(), &ch, &x.public_key()).await.unwrap();
// X mints a Role whose id is X's own key, beneath X, then writes an overwrite for
// that Role at the coordinate of X's Member overwrite.
follow_control(&bed.relay, &held()).await.unwrap();
publish_role_v2(&bed.relay, &held(), &x, &role_v2(&x.public_key().to_hex(), "Alias", "z", 0), 1).await;
let member_eid = {
let t = crate::community::v2::roles::overwrite_target_bytes(community.id(), &crate::community::roles::OverwriteTarget::Member(x.public_key().to_hex())).unwrap();
crate::community::v2::derive::acl_locator(community.id(), &ch.0, &t)
};
let prev = head_hash_on_relay(&bed.relay, &held(), &member_eid).await;
let version = fetch_control(&bed.relay, &held()).await.iter().filter(|e| e.entity_id == member_eid).map(|e| e.version).max().unwrap();
let o = crate::community::roles::Overwrite { scope: chan.clone(), target: crate::community::roles::OverwriteTarget::Role(x.public_key().to_hex()), allow: Permissions(0), deny: Permissions(0) };
publish_marked(&bed.relay, &held(), &x, vsk::CHANNEL_ACL, &member_eid, version + 1, prev, &crate::community::v2::roles::overwrite_content_json(&o)).await;
let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
assert!(f.roles.overwrites.iter().any(|o| o.target == crate::community::roles::OverwriteTarget::Member(x.public_key().to_hex()) && o.deny.contains(Permissions::VIEW_CHANNEL)), "the owner's deny stands");
assert!(!f.roles.is_entitled(Some(&owner_hex), &x.public_key().to_hex(), &chan, &[], &[]));
}
#[tokio::test]
async fn a_banned_member_loses_every_overwrite_and_every_rekey() {
let (bed, owner, _x, community) = v2_bed_with_admin("BanAcl").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
let (chan, owner_hex) = (crate::simd::hex::bytes_to_hex_32(&ch.0), owner.keys.public_key().to_hex());
let (b, keep) = (Keys::generate().public_key(), Keys::generate().public_key());
grant_channel_access(&bed.relay, &held(), &ch, &b).await.unwrap();
grant_channel_access(&bed.relay, &held(), &ch, &keep).await.unwrap();
set_members_banned(&bed.relay, held().id(), &[b], true).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
assert!(!f.roles.is_entitled(Some(&owner_hex), &b.to_hex(), &chan, &[], &[]), "a ban drops their overwrite");
assert!(f.roles.is_entitled(Some(&owner_hex), &keep.to_hex(), &chan, &[], &[]), "and only theirs");
// The next rotation of the channel keys the one who kept access, not the banned.
let other = Keys::generate().public_key();
grant_channel_access(&bed.relay, &held(), &ch, &other).await.unwrap();
revoke_channel_access(&bed.relay, &held(), &ch, &other).await.unwrap();
let now = held();
let epoch = now.channel(&ch).unwrap().epoch;
let group = channel_rekey_group_key(&now.community_root, &ch, epoch);
let blobs: Vec<String> = fetch_rekey_chunks(&bed.relay, &now, &group).await.unwrap().into_iter().flat_map(|c| c.blobs).map(|b| b.locator).collect();
let me = me_pk().unwrap().to_bytes();
let at = |pk: &PublicKey| rekey::blob_locator(&me, &pk.to_bytes(), RekeyScope::Channel(ch), epoch);
assert!(blobs.contains(&at(&keep)) && !blobs.contains(&at(&b)));
}
#[tokio::test]
async fn a_roster_read_without_everyone_changes_nothing() {
let (bed, owner, x, community) = v2_bed_with_admin("Degraded").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let everyone = crate::community::v2::derive::everyone_locator(community.id());
let blind = Hiding { inner: &bed.relay, group: control::ControlPlane::of(&held()).write_group().unwrap(), hide: Box::new(move |e| e.entity_id == everyone) };
let before = fetch_control(&bed.relay, &held()).await.len();
act_as(&x);
forget_held(&held());
let err = set_everyone(&blind, &held(), 0).await.unwrap_err();
assert!(err.contains("couldn't be read"), "{err}");
assert_eq!(fetch_control(&bed.relay, &held()).await.len(), before, "nothing was published");
// The owner may still restate it: that is how a refused head is repaired.
act_as(&owner.keys);
assert!(set_everyone(&blind, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.is_ok());
}
#[tokio::test]
async fn a_withheld_overwrite_stays_as_this_device_held_it() {
let (bed, owner, _x, community) = v2_bed_with_admin("WithheldAcl").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
let m = Keys::generate().public_key();
grant_channel_access(&bed.relay, &held(), &ch, &m).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex).unwrap().into_iter().filter(|(_, f)| f.0 == held().root_epoch.0).map(|(e, f)| (e, (f.1, f.2, f.3, f.4, f.5))).collect();
let served: Vec<ParsedEdition> = fetch_control(&bed.relay, &held()).await.into_iter().filter(|e| e.vsk != vsk::CHANNEL_ACL).collect();
let f = fold_authority(&held(), &served, &floors);
assert!(f.roles.is_entitled(Some(&owner.keys.public_key().to_hex()), &m.to_hex(), &crate::simd::hex::bytes_to_hex_32(&ch.0), &[], &[]), "withholding doesn't revoke");
}
#[tokio::test]
async fn overwrites_and_syncs_cross_a_refounding_and_readers_agree() {
let (bed, owner, _x, community) = v2_bed_with_admin("AclCarry2").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let owner_hex = owner.keys.public_key().to_hex();
let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
let staff = create_role_v2(&bed.relay, &held(), "Staff", 0, 0).await.unwrap();
set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Role(staff.clone()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
let m = Keys::generate().public_key();
set_member_roles(&bed.relay, &held(), &m, vec![staff]).await.unwrap();
let cat = create_category(&bed.relay, &held(), "Lobby").await.unwrap();
set_overwrite(&bed.relay, &held(), cat, crate::community::roles::OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
let news = create_channel_in(&bed.relay, &held(), "news", false, Some(cat)).await.unwrap();
// A sync past its first edition is judged against its predecessor, which must cross too.
set_channel_sync(&bed.relay, &held(), &news, None).await.unwrap();
set_channel_sync(&bed.relay, &held(), &news, Some(cat)).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let (chan, news_hex) = (crate::simd::hex::bytes_to_hex_32(&ch.0), crate::simd::hex::bytes_to_hex_32(&news.0));
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let mut epoch = community.root_epoch;
for round in 0..2 {
set_members_banned(&bed.relay, held().id(), &[Keys::generate().public_key()], true).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let now = held();
assert_ne!(now.root_epoch, epoch, "the ban re-founded");
epoch = now.root_epoch;
let eds = fetch_control(&bed.relay, &now).await;
let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex).unwrap().into_iter().filter(|(_, f)| f.0 == now.root_epoch.0).map(|(e, f)| (e, (f.1, f.2, f.3, f.4, f.5))).collect();
let probe = Keys::generate().public_key().to_hex();
for (who, f) in [("cold", fold_authority(&now, &eds, &Floors::default())), ("floored", fold_authority(&now, &eds, &floors))] {
assert!(f.roles.is_entitled(Some(&owner_hex), &m.to_hex(), &chan, &[], &[]), "{round} {who}: the role's allow crossed");
assert!(!f.roles.is_entitled(Some(&owner_hex), &probe, &chan, &[], &[]), "{round} {who}: and nobody else got in");
assert_eq!(f.roles.syncs.get(&news_hex), Some(&crate::simd::hex::bytes_to_hex_32(&cat)), "{round} {who}: the sync crossed");
assert!(!f.roles.channel_permissions(Some(&owner_hex), &probe, &news_hex, false).contains(Permissions::SEND_MESSAGES), "{round} {who}: and it binds");
}
}
}
#[tokio::test]
async fn a_member_without_add_reactions_cant_react() {
use crate::community::roles::Permissions;
async fn react(relay: &MemoryRelay, community: &CommunityV2, ch: &ChannelId, owner: &str) -> Result<String, String> {
send_reaction(relay, community, ch, &"ab".repeat(32), owner, super::super::kind::MESSAGE, "+", None).await
}
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Reacts", vec!["wss://r".into()], None).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let (ch, owner_hex, m) = (community.channels[0].id, owner.public_key().to_hex(), Keys::generate());
act_as(&m);
assert!(react(&relay, &held(), &ch, &owner_hex).await.is_ok(), "the legacy roster refuses no reaction");
act_as(&owner);
activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
act_as(&m);
assert!(react(&relay, &held(), &ch, &owner_hex).await.is_ok(), "@everyone reacts by default");
act_as(&owner);
set_everyone(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT & !Permissions::ADD_REACTIONS).await.unwrap();
act_as(&m);
let err = react(&relay, &held(), &ch, &owner_hex).await.unwrap_err();
assert!(err.contains("can't react"), "{err}");
act_as(&owner);
assert!(react(&relay, &held(), &ch, &owner_hex).await.is_ok(), "the owner holds everything");
}
#[tokio::test]
async fn a_timeout_silences_until_it_ends_or_is_lifted() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Timeout", vec!["wss://r".into()], None).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let (m, peer) = (Keys::generate(), Keys::generate());
let ch = community.channels[0].id;
timeout_member(&relay, &held(), &m.public_key(), 600).await.unwrap();
let t = community_timeouts(&held()).unwrap();
let (from, until) = t[&m.public_key()];
assert!(until >= from + 600 && until <= from + 601);
act_as(&m);
let err = send_chat_message(&relay, &held(), &ch, "hi", None, &[], vec![]).await.unwrap_err();
assert!(err.contains("timed out"), "{err}");
let target = "ab".repeat(32);
let err = send_reaction(&relay, &held(), &ch, &target, &owner.public_key().to_hex(), super::super::kind::MESSAGE, "+", None).await.unwrap_err();
assert!(err.contains("timed out"), "nor react: {err}");
let err = send_edit(&relay, &held(), &ch, &target, "rewritten", &[]).await.unwrap_err();
assert!(err.contains("timed out"), "nor edit: {err}");
// A peer with no standing can't lift it, nor time anyone out.
act_as(&peer);
assert!(timeout_member(&relay, &held(), &m.public_key(), 0).await.is_err());
act_as(&owner);
// A co-moderator's clock runs ahead: the lift still outranks their Timeout.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let (mut events, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
let ahead = now_ms() + 600_000;
events.push(guestbook::GuestbookEvent {
rumor_id: [8; 32],
entry: guestbook::GuestbookEntry::Timeout { actor: owner.public_key(), target: m.public_key(), until_secs: ahead / 1000 + 600, citation: None, at_ms: ahead },
epoch: Some(held().root_epoch.0),
observed_at: None,
});
crate::db::community::set_guestbook(&cid_hex, &events, cursor).unwrap();
timeout_member(&relay, &held(), &m.public_key(), 0).await.unwrap();
assert!(community_timeouts(&held()).unwrap().is_empty(), "a Timeout in the past lifts it");
act_as(&m);
assert!(send_chat_message(&relay, &held(), &ch, "back", None, &[], vec![]).await.is_ok());
act_as(&owner);
}
#[tokio::test]
async fn a_running_timeout_crosses_a_refounding() {
let (bed, owner, _x, community) = v2_bed_with_admin("TimeoutCarry").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let (m, ended, unseen) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
// Issued well before the Refounding, so a window it moved would show.
let (mut events, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
let issued = now_ms() - 100_000;
events.push(guestbook::GuestbookEvent {
rumor_id: [7; 32],
entry: guestbook::GuestbookEntry::Timeout { actor: owner.keys.public_key(), target: m, until_secs: issued / 1000 + 600, citation: None, at_ms: issued },
epoch: Some(held().root_epoch.0),
observed_at: None,
});
crate::db::community::set_guestbook(&cid_hex, &events, cursor).unwrap();
timeout_member(&bed.relay, &held(), &ended, 600).await.unwrap();
timeout_member(&bed.relay, &held(), &ended, 0).await.unwrap();
timeout_member(&bed.relay, &held(), &unseen, 600).await.unwrap();
let before_lift = crate::db::community::get_guestbook(&cid_hex).unwrap();
timeout_member(&bed.relay, &held(), &unseen, 0).await.unwrap();
// A lift another device published, which this one hasn't read.
crate::db::community::set_guestbook(&cid_hex, &before_lift.0, before_lift.1).unwrap();
let from = issued / 1000;
refound_community(&bed.relay, &held(), &[]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert_ne!(held().root_epoch, community.root_epoch, "the ban re-founded");
// A device that never read the old Guestbook.
crate::db::community::set_guestbook(&cid_hex, &[], 0).unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
let t = community_timeouts(&held()).unwrap();
assert_eq!(t.get(&m).map(|w| w.0), Some(from), "the running Timeout crossed, its window unmoved");
assert!(!t.contains_key(&ended), "a lifted one stayed lifted");
assert!(!t.contains_key(&unseen), "even one lifted where the refounder hadn't read yet");
let _ = owner;
}
#[tokio::test]
async fn a_builder_cant_open_a_channel_in_a_restricted_category() {
let (bed, _owner, _x, community) = v2_bed_with_admin("Builder").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let builders = create_role_v2(&bed.relay, &held(), "Builders", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
let y = Keys::generate();
set_member_roles(&bed.relay, &held(), &y.public_key(), vec![builders]).await.unwrap();
let (open, staff) = (create_category(&bed.relay, &held(), "Open").await.unwrap(), create_category(&bed.relay, &held(), "Staff").await.unwrap());
set_overwrite(&bed.relay, &held(), staff, crate::community::roles::OverwriteTarget::Everyone, 0, Permissions::VIEW_CHANNEL).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
act_as(&y);
let err = create_channel_in(&bed.relay, &held(), "leak", false, Some(staff)).await.unwrap_err();
assert!(err.contains("Manage Roles"), "{err}");
assert!(create_channel_in(&bed.relay, &held(), "fine", false, Some(open)).await.is_ok(), "a Category with no rules of its own takes anyone who may make channels");
}
#[tokio::test]
async fn rules_reaching_a_private_channel_this_device_cant_read_are_refused() {
let (bed, _owner, _x, community) = v2_bed_with_admin("Keyless").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "dark").await.unwrap();
let cat = create_category(&bed.relay, &held(), "Vault").await.unwrap();
set_channel_sync(&bed.relay, &held(), &ch, Some(cat)).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let mut keyless = held();
keyless.channels.iter_mut().find(|c| c.id.0 == ch.0).unwrap().key = None;
crate::db::community::save_community_v2(&keyless).unwrap();
let err = set_overwrite(&bed.relay, &held(), cat, crate::community::roles::OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap_err();
assert!(err.contains("don't have access to it yourself"), "through its Category: {err}");
let err = set_channel_sync(&bed.relay, &held(), &ch, None).await.unwrap_err();
assert!(err.contains("don't have access to it yourself"), "or its sync: {err}");
}
#[tokio::test]
async fn a_channel_squatting_a_grant_coordinate_cant_block_the_grant() {
// A channel edition at a member's grant coordinate, before their first Grant, leaves a
// control floor there; it must not hold the Grant to a version it never had.
let (bed, owner, x, community) = v2_bed_with_admin("Squat").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let builders = create_role_v2(&bed.relay, &held(), "Builders", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
let readers = create_role_v2(&bed.relay, &held(), "Readers", 0, 0).await.unwrap();
let s = Keys::generate();
set_member_roles(&bed.relay, &held(), &s.public_key(), vec![builders]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let m = Keys::generate().public_key();
let spot = super::super::derive::grant_locator(community.id(), &m.to_bytes());
let squat = serde_json::to_string(&control::ChannelMetadata { name: "squat".into(), ..Default::default() }).unwrap();
publish_marked(&bed.relay, &held(), &s, vsk::CHANNEL_METADATA, &spot, 50, None, &squat).await;
follow_control(&bed.relay, &held()).await.unwrap();
let (cid_hex, spot_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&spot));
let squatted = crate::db::community::get_all_edition_heads_full(&cid_hex).unwrap()[&spot_hex];
let before = crate::db::community::get_community_roles(&cid_hex).unwrap();
act_as(&x);
set_member_roles(&bed.relay, &held(), &m, vec![readers.clone()]).await.unwrap();
act_as(&owner.keys);
// Another device saw the squat but not this publish.
crate::db::community::set_community_roles(&cid_hex, &before, 0).unwrap();
crate::db::community::delete_edition_head(&cid_hex, &spot_hex).unwrap();
let (epoch, v, hash, inner, author, _) = squatted;
crate::db::community::set_family_head_at_epoch(&cid_hex, &spot_hex, v, &hash, &inner.unwrap(), &author.unwrap(), epoch, crate::db::community::FLOOR_CONTROL).unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let roster = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
assert!(roster.roles_of(&m.to_hex()).any(|r| r.role_id == readers), "the admin's Grant stands");
}
/// Post `text` straight to a plane, as a client ignoring the ledger would.
#[allow(clippy::too_many_arguments)]
async fn post_raw(relay: &MemoryRelay, community: &CommunityV2, author: &Keys, channel: &ChannelId, group: &GroupKey, epoch: Epoch, wepoch: Option<Epoch>, text: &str, at_ms: u64) {
post_certified(relay, community, author, channel, group, epoch, wepoch.map(|w| (w, None)), text, at_ms).await
}
/// [`post_raw`], at a writer epoch with the author's certificate for it, as a client posts.
#[allow(clippy::too_many_arguments)]
async fn post_certified(relay: &MemoryRelay, community: &CommunityV2, author: &Keys, channel: &ChannelId, group: &GroupKey, epoch: Epoch, writer: Option<(Epoch, Option<[u8; 64]>)>, text: &str, at_ms: u64) {
let rumor = chat::build_message_rumor(author.public_key(), channel, epoch, text, None, &[], vec![], at_ms);
let rumor = match writer {
Some((w, cert)) => chat::with_writer(rumor, w, cert.as_ref()),
None => rumor,
};
let (wrap, _) = chat::seal_chat_rumor(&rumor, group, author, Timestamp::from_secs(at_ms / 1000), false).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
async fn channel_texts(relay: &MemoryRelay, community: &CommunityV2, channel: &ChannelId) -> Vec<String> {
fetch_channel(relay, community, channel, 50)
.await
.unwrap()
.into_iter()
.filter_map(|f| match f.event {
ChatEvent::Message { opened, .. } => Some(opened.rumor.content.clone()),
_ => None,
})
.collect()
}
/// What a handler was shown: a message's text and whether it rang, an update's text after
/// `~` with its mark, a removal's id after `-`.
#[derive(Default)]
struct Shown(std::sync::Mutex<Vec<(String, bool)>>);
impl crate::event_handler::InboundEventHandler for Shown {
fn on_community_message(&self, _chat: &str, m: &crate::types::Message, is_new: bool) {
self.0.lock().unwrap().push((m.content.clone(), is_new));
}
fn on_community_update(&self, _chat: &str, _target: &str, m: &crate::types::Message) {
self.0.lock().unwrap().push((format!("~{}", m.content), m.unauthorized));
}
fn on_community_removed(&self, _chat: &str, target: &str) {
self.0.lock().unwrap().push((format!("-{target}"), false));
}
}
impl Shown {
fn take(&self) -> Vec<(String, bool)> {
std::mem::take(&mut *self.0.lock().unwrap())
}
}
/// An owner and a member (a manager when `manages`) in a community whose #general the owner
/// has restricted, both having read it so.
async fn restricted_bed(manages: bool) -> (TestBed, Actor, Actor, CommunityV2, ChannelId) {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member) = TestBed::new();
let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Held", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let general = community.channels[0].id;
let bits = if manages { Permissions::MANAGE_CHANNELS } else { 0 };
let role = create_role_v2(&bed.relay, &held(&community), "Member", 0, bits).await.unwrap();
set_member_roles(&bed.relay, &held(&community), &member.keys.public_key(), vec![role]).await.unwrap();
send_direct_invite(&bed.relay, &held(&community), &member.keys.public_key(), None, None).await.unwrap();
bed.swap_to(&member);
accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await).await.unwrap();
follow_control(&bed.relay, &held(&community)).await.unwrap();
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
collect_writers(&bed.relay, &held(&community)).await.unwrap();
assert!(held(&community).channel(&general).unwrap().restricted());
let community = held(&community);
(bed, owner, member, community, general)
}
/// The reactions `community`'s `channel` shows a reader: (author, emoji).
async fn channel_reactions(relay: &MemoryRelay, community: &CommunityV2, channel: &ChannelId) -> Vec<(PublicKey, String)> {
fetch_channel(relay, community, channel, 50)
.await
.unwrap()
.into_iter()
.filter_map(|f| match f.event {
ChatEvent::Reaction { opened, emoji, .. } => Some((opened.author, emoji)),
_ => None,
})
.collect()
}
#[tokio::test]
async fn a_locked_channel_takes_every_write_only_from_whom_it_lets_write() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member) = TestBed::new();
let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Locked", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let general = community.channels[0].id;
let reactor = create_role_v2(&bed.relay, &held(&community), "Reactor", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(&community), &member.keys.public_key(), vec![reactor.clone()]).await.unwrap();
send_direct_invite(&bed.relay, &held(&community), &member.keys.public_key(), None, None).await.unwrap();
bed.swap_to(&member);
accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await).await.unwrap();
follow_control(&bed.relay, &held(&community)).await.unwrap();
// The Reactor Role may react; @everyone may write nothing at all.
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Role(reactor), Permissions::ADD_REACTIONS, 0).await.unwrap();
let nothing = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT;
set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
let ch = held(&community).channel(&general).cloned().unwrap();
assert!(ch.restricted() && ch.locked(), "locking mints a Locked writer epoch");
let rules = send_chat_message(&bed.relay, &held(&community), &general, "the rules", None, &[], vec![]).await.unwrap();
let owner_hex = owner.keys.public_key().to_hex();
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
collect_writers(&bed.relay, &held(&community)).await.unwrap();
let ch = held(&community).channel(&general).cloned().unwrap();
let (live, ..) = writing::live_writer(&held(&community), &ch).expect("a reactor holds the key");
assert!(writing::my_cert(&held(&community), &ch, live).is_none(), "but no whole certificate");
assert_eq!(writing::my_scoped_cert(&held(&community), &ch, live).map(|(_, r)| r), Some(Permissions::ADD_REACTIONS), "a scoped one, for reactions");
send_reaction(&bed.relay, &held(&community), &general, &rules, &owner_hex, super::super::kind::MESSAGE, "👍", None).await.unwrap();
assert!(send_chat_message(&bed.relay, &held(&community), &general, "may I post?", None, &[], vec![]).await.is_err(), "a reactor can't post");
assert!(!can_post(&held(&community), &general));
// Nor does a post they force out at the writer address stand on a scoped certificate.
let (_, _, writer) = writing::live_writer(&held(&community), &ch).unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let at_writer = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
let (cert, rights) = writing::my_scoped_cert(&held(&community), &ch, live).unwrap();
let forced = chat::with_writer_cert(chat::build_message_rumor(member.keys.public_key(), &general, community.root_epoch, "forced", None, &[], vec![], now_ms()), live, Some(chat::WriterCert::Scoped(cert, rights)));
let (wrap, _) = chat::seal_chat_rumor(&forced, &at_writer, &member.keys, Timestamp::from_secs(now_ms() / 1000), false).unwrap();
bed.relay.publish(&wrap, &community.relays).await.unwrap();
// Dated back to when the Channel was open, before the key it rides was given.
let before = ch.writers.as_ref().unwrap().writer_start(live).unwrap() - 60_000;
let backdated = chat::with_writer_cert(chat::build_message_rumor(member.keys.public_key(), &general, community.root_epoch, "backdated", None, &[], vec![], before), live, Some(chat::WriterCert::Scoped(cert, rights)));
let (wrap, _) = chat::seal_chat_rumor(&backdated, &at_writer, &member.keys, Timestamp::from_secs(before / 1000), false).unwrap();
bed.relay.publish(&wrap, &community.relays).await.unwrap();
// A certificate for reactions doesn't put them in a call.
let judge = writing::Judge::of(&held(&community), &ch).unwrap();
let presence = chat::with_writer_cert(chat::build_voice_presence_rumor(member.keys.public_key(), &general, community.root_epoch, None, Default::default(), now_ms()), live, Some(chat::WriterCert::Scoped(cert, rights)));
let (wrap, _) = chat::seal_chat_rumor(&presence, &at_writer, &member.keys, Timestamp::from_secs(now_ms() / 1000), true).unwrap();
let heard = chat::open_writer_chat_event(&wrap, &wrap.pubkey, live, read.conv_key(), &general, community.root_epoch).unwrap();
assert!(!judge.admits(&heard, Some(live)), "a reactor joins no call");
let me = member.keys.public_key();
assert!(matches!(crate::community::v2::inbound::dispatch_wrap(&wrap, &held(&community), &me, &crate::NoOpEventHandler), crate::community::v2::inbound::DispatchedV2::Ignored), "and is shown in none");
let at_read = chat::seal_chat_rumor(&chat::build_voice_presence_rumor(member.keys.public_key(), &general, community.root_epoch, None, Default::default(), now_ms()), &read, &member.keys, Timestamp::from_secs(now_ms() / 1000), true).unwrap().0;
assert!(!judge.admits(&chat::open_chat_event(&at_read, &read, &general, community.root_epoch).unwrap(), None), "nor through the read address");
// A key alone with no rights: someone who can't react is refused before anything goes out.
let stranger = Keys::generate();
act_as(&stranger);
assert!(send_reaction(&bed.relay, &held(&community), &general, &rules, &owner_hex, super::super::kind::MESSAGE, "💩", None).await.is_err());
// And a reaction forged at the read address, or by a reactor posting there, stands nowhere.
let forged = chat::build_reaction_rumor(stranger.public_key(), &general, community.root_epoch, &rules, &owner_hex, super::super::kind::MESSAGE, "💩", None, now_ms());
let (wrap, _) = chat::seal_chat_rumor(&forged, &read, &stranger, Timestamp::from_secs(now_ms() / 1000), false).unwrap();
bed.relay.publish(&wrap, &community.relays).await.unwrap();
// A reactor's client gets the ten minutes past the lock any writer does to read the move.
let past_grace = ch.writers.as_ref().unwrap().writer_start(live).unwrap() + crate::community::v2::writers::ENTRY_SKEW_MS + 1_000;
let sneaky = chat::build_reaction_rumor(member.keys.public_key(), &general, community.root_epoch, &rules, &owner_hex, super::super::kind::MESSAGE, "🙃", None, past_grace);
let (wrap, _) = chat::seal_chat_rumor(&sneaky, &read, &member.keys, Timestamp::from_secs(past_grace / 1000), false).unwrap();
bed.relay.publish(&wrap, &community.relays).await.unwrap();
// Junk posted at the read address after the lock reaches nobody, a manager included.
let junk = chat::build_message_rumor(stranger.public_key(), &general, community.root_epoch, "junk", None, &[], vec![], past_grace);
let (wrap, _) = chat::seal_chat_rumor(&junk, &read, &stranger, Timestamp::from_secs(past_grace / 1000), false).unwrap();
bed.relay.publish(&wrap, &community.relays).await.unwrap();
assert!(!crate::community::v2::realtime::plane_authors(&[held(&community)]).contains(&read.pk()), "nobody listens at a Locked read address");
bed.swap_to(&owner);
assert!(!channel_texts(&bed.relay, &held(&community), &general).await.contains(&"junk".to_string()), "not even marked for a manager");
let seen = channel_reactions(&bed.relay, &held(&community), &general).await;
assert_eq!(seen, vec![(member.keys.public_key(), "👍".to_string())], "only the reactor's, at the writer address: {seen:?}");
let sent = fetch_channel(&bed.relay, &held(&community), &general, 50).await.unwrap();
let carried = sent.iter().find_map(|f| match &f.event {
ChatEvent::Reaction { opened, .. } => Some(opened.rumor.clone()),
_ => None,
});
let carried = carried.unwrap();
assert!(chat::writer_cert_of(&carried).is_none() && chat::scoped_cert_of(&carried).is_some(), "it carries its scoped certificate");
let forced: Vec<bool> = sent.iter().filter(|f| matches!(&f.event, ChatEvent::Message { opened, .. } if opened.rumor.content == "forced")).map(|f| f.event.opened().held).collect();
assert_eq!(forced, vec![true], "a scoped certificate never carries a post: a manager sees it only marked");
let backdated: Vec<bool> = sent.iter().filter(|f| matches!(&f.event, ChatEvent::Message { opened, .. } if opened.rumor.content == "backdated")).map(|f| f.event.opened().held).collect();
assert_eq!(backdated, vec![true], "nor one dated into the open past");
// Letting @everyone react again leaves posting gated: a fresh epoch that isn't Locked.
set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
let ch = held(&community).channel(&general).cloned().unwrap();
assert!(ch.restricted() && !ch.locked());
assert!(ch.writers.as_ref().unwrap().current_writer().unwrap().0 > live, "the flag is the window's: a new epoch");
}
/// Serves what `inner` does, noting every query it was asked.
struct Watching<'a> {
inner: &'a MemoryRelay,
asked: std::sync::Mutex<Vec<Query>>,
}
#[async_trait::async_trait]
impl Transport for Watching<'_> {
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
self.asked.lock().unwrap().push(query.clone());
self.inner.fetch_plane(plane, query, relays).await
}
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.inner.publish(e, r).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.inner.publish_durable(e, r).await
}
async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
self.asked.lock().unwrap().push(q.clone());
self.inner.fetch(q, r).await
}
}
#[tokio::test]
async fn a_locked_read_address_is_read_only_up_to_the_lock() {
use crate::community::roles::OverwriteTarget;
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Quiet", vec!["wss://r".into()], None).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
let general = community.channels[0].id;
send_chat_message(&relay, &held(), &general, "before", None, &[], vec![]).await.unwrap();
let nothing = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT;
set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
assert!(ledger.locked());
let lock = ledger.writer_start(ledger.current_writer().unwrap().0).unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch).pk().to_hex();
let watching = Watching { inner: &relay, asked: Default::default() };
// Read as from an hour on, past the minutes a client that hadn't read the lock gets.
let later = Some(now_ms() / 1000 + 3600);
let got = fetch_channel_history(&watching, &held(), &general, 50, 4, None, later, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
assert!(got.iter().any(|f| matches!(&f.event, ChatEvent::Message { opened, .. } if opened.rumor.content == "before")), "history before the lock still reads");
let asked: Vec<Query> = watching.asked.lock().unwrap().iter().filter(|q| q.authors.contains(&read)).cloned().collect();
assert!(!asked.is_empty());
let bound = (lock + crate::community::v2::writers::ENTRY_SKEW_MS) / 1000 + 1;
assert!(asked.iter().all(|q| q.until.is_some_and(|u| u <= bound)), "never past the lock's first minutes: {:?}", asked.iter().map(|q| q.until).collect::<Vec<_>>());
// The minter seals up to the lock at once, and the lock's first minutes once they pass.
let skew = crate::community::v2::writers::ENTRY_SKEW_MS;
assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().seal_target(lock), Some(lock));
access_duty(&relay, &held()).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
assert_eq!(ledger.seal.as_ref().map(|s| (s.until, s.run, s.count)), Some((lock, lock, 1)), "sealed to the lock");
assert_eq!(ledger.seal_target(lock + skew - 1), None, "not before its time");
assert_eq!(ledger.seal_target(lock + skew), Some(lock + skew));
let _ = owner;
}
#[tokio::test]
async fn a_sealed_lock_reads_its_history_by_id_so_nothing_backdated_gets_in() {
use crate::community::roles::OverwriteTarget;
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Sealed", vec!["wss://r".into()], None).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
let general = community.channels[0].id;
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
// More than two pages of history, a second apart, before the lock.
let total = crate::community::v2::seal::MAX_SEAL_IDS * 2 + 50;
let start = now_ms() - (total as u64 + 100) * 1000;
for i in 0..total {
post_raw(&relay, &held(), &owner, &general, &read, community.root_epoch, None, &format!("m{i}"), start + i as u64 * 1000).await;
}
let nothing = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT;
set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
let ch = held().channel(&general).cloned().unwrap();
let lock = ch.writers.as_ref().unwrap().run_start().unwrap();
let after_grace = lock + crate::community::v2::writers::ENTRY_SKEW_MS;
assert_eq!(sealing::seal_history_at(&relay, &held(), &ch, lock).await.unwrap(), Some(total), "to the lock at once");
assert_eq!(sealing::seal_history_at(&relay, &held(), held().channel(&general).unwrap(), after_grace - 1).await.unwrap(), None);
assert_eq!(sealing::seal_history_at(&relay, &held(), held().channel(&general).unwrap(), after_grace).await.unwrap(), Some(0));
let sealed = held().channel(&general).unwrap().writers.clone().unwrap().seal.expect("the ledger names the seal");
assert_eq!((sealed.until, sealed.count), (after_grace, total as u64), "the seal covers the lock's first minutes");
assert_eq!(sealing::seal_history_at(&relay, &held(), held().channel(&general).unwrap(), after_grace).await.unwrap(), None, "once per run");
// A fresh epoch while still Locked keeps the run, and its seal.
let roster = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
writing::mint_for_test(&relay, &held(), &general, &roster).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
assert!(ledger.current_writer().unwrap().0 > ch.writers.as_ref().unwrap().current_writer().unwrap().0 && ledger.seal_target(after_grace).is_none() && ledger.locked());
// Anyone with the read key dates junk into the sealed past, after the seal was made.
let stranger = Keys::generate();
for (i, at) in [start - 5_000, start + 1_500, start + (total as u64 / 2) * 1000 + 500].into_iter().enumerate() {
post_raw(&relay, &held(), &stranger, &general, &read, community.root_epoch, None, &format!("junk{i}"), at).await;
}
let watching = Watching { inner: &relay, asked: Default::default() };
let later = Some(now_ms() / 1000 + 3600);
let got = fetch_channel_history(&watching, &held(), &general, 200, 40, None, later, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
let texts: Vec<String> = got.iter().filter_map(|f| match &f.event { ChatEvent::Message { opened, .. } => Some(opened.rumor.content.clone()), _ => None }).collect();
assert!(!texts.iter().any(|t| t.starts_with("junk")), "nothing dated into the seal is read");
assert_eq!(texts.iter().filter(|t| t.starts_with('m')).count(), total, "and all of what it holds is");
let read_hex = read.pk().to_hex();
let floor = sealed.until / 1000;
assert!(watching.asked.lock().unwrap().iter().filter(|q| q.authors.contains(&read_hex)).all(|q| q.since.is_some_and(|s| s >= floor)), "the read address is never asked for anything the seal covers");
}
#[tokio::test]
async fn an_unlocked_channel_still_reads_back_into_the_seal() {
use crate::community::roles::OverwriteTarget;
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Reopened", vec!["wss://r".into()], None).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
let general = community.channels[0].id;
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let start = now_ms() - 600_000;
for i in 0..20 {
post_raw(&relay, &held(), &owner, &general, &read, community.root_epoch, None, &format!("old{i}"), start + i * 1000).await;
}
let nothing = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT;
set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
sealing::seal_history(&relay, &held(), held().channel(&general).unwrap()).await.unwrap();
set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
let ch = held().channel(&general).cloned().unwrap();
assert!(!ch.restricted() && ch.writers.as_ref().unwrap().seal.is_some(), "open again, the seal kept");
let stranger = Keys::generate();
post_raw(&relay, &held(), &stranger, &general, &read, community.root_epoch, None, "junk", start + 5_500).await;
// The Channel is open again: nothing new until someone posts, and whatever comes back is above the seal.
let texts = |got: Vec<FetchedEvent>| -> Vec<String> { got.into_iter().filter_map(|f| match f.event { ChatEvent::Message { opened, .. } => Some(opened.rumor.content), _ => None }).collect() };
let got = texts(fetch_channel_history(&relay, &held(), &general, 50, 6, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap());
assert_eq!(got.iter().filter(|t| t.starts_with("old")).count(), 20, "an empty read address hands on to the seal: {got:?}");
assert!(!got.contains(&"junk".to_string()));
send_chat_message(&relay, &held(), &general, "new", None, &[], vec![]).await.unwrap();
let got = texts(fetch_channel_history(&relay, &held(), &general, 50, 6, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap());
assert!(got.contains(&"new".to_string()) && got.iter().filter(|t| t.starts_with("old")).count() == 20 && !got.contains(&"junk".to_string()), "{got:?}");
}
#[tokio::test]
async fn a_lock_seals_at_once_and_takes_in_its_first_minutes_after() {
use crate::community::roles::OverwriteTarget;
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Two steps", vec!["wss://r".into()], None).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
let general = community.channels[0].id;
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
post_raw(&relay, &held(), &owner, &general, &read, community.root_epoch, None, "before", now_ms() - 60_000).await;
let nothing = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT;
set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
let lock = held().channel(&general).unwrap().writers.as_ref().unwrap().run_start().unwrap();
// Only a device holding every plane's key seals: what it can't open would be left out for all.
let ch = held().channel(&general).cloned().unwrap();
assert!(sealing::reads_whole_history(&held(), &ch, &read_planes(&held(), &ch)));
assert!(!sealing::reads_whole_history(&held(), &ch, &[]));
let views: Vec<(ReadPlane, Epoch)> = read_planes(&held(), &ch).into_iter().map(|(p, e)| (ReadPlane::View(p.address(), *p.conv()), e)).collect();
assert!(!sealing::reads_whole_history(&held(), &ch, &views), "a view holds no key a page could ride");
assert_eq!(sealing::seal_history_at(&relay, &held(), held().channel(&general).unwrap(), lock).await.unwrap(), Some(1));
assert!(sealing::seal_history_at(&relay, &held(), &ch, lock).await.is_err(), "a sealer that read the ledger before another's seal adds none");
assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().seal.as_ref().unwrap().count, 1);
// Dated into the open past after the seal, in the seal's own second, which is read by date.
let edge = chat::build_message_rumor(owner.public_key(), &general, community.root_epoch, "edge", None, &[], vec![], lock - 1);
let (edge, _) = chat::seal_chat_rumor(&edge, &read, &owner, Timestamp::from_secs((lock - 1) / 1000), false).unwrap();
relay.publish(&edge, &community.relays).await.unwrap();
assert!(matches!(crate::community::v2::inbound::dispatch_wrap(&edge, &held(), &owner.public_key(), &crate::NoOpEventHandler), crate::community::v2::inbound::DispatchedV2::Ignored), "nor live");
let texts = || async { fetch_channel_history(&relay, &held(), &general, 50, 6, None, Some(now_ms() / 1000 + 3600), crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap().into_iter().filter_map(|f| match f.event { ChatEvent::Message { opened, .. } => Some(opened.rumor.content), _ => None }).collect::<Vec<_>>() };
assert_eq!(texts().await, vec!["before"], "below the seal only what it names stands");
// In the lock's first minutes a manager's client that hadn't read it still posts at the read
// address; a stranger's post there stands nowhere.
post_raw(&relay, &held(), &owner, &general, &read, community.root_epoch, None, "late", lock + 1).await;
post_raw(&relay, &held(), &Keys::generate(), &general, &read, community.root_epoch, None, "junk", lock + 2).await;
let after_grace = lock + crate::community::v2::writers::ENTRY_SKEW_MS;
assert_eq!(sealing::seal_history_at(&relay, &held(), held().channel(&general).unwrap(), after_grace).await.unwrap(), Some(1), "the late post, not the junk");
let sealed = held().channel(&general).unwrap().writers.clone().unwrap().seal.unwrap();
assert_eq!((sealed.until, sealed.run, sealed.count), (after_grace, lock, 2));
let mut texts = texts().await;
texts.sort();
assert_eq!(texts, vec!["before", "late"]);
}
#[tokio::test]
async fn a_seal_takes_in_a_second_holding_more_than_a_page() {
use crate::community::roles::OverwriteTarget;
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Busy second", vec!["wss://r".into()], None).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
let general = community.channels[0].id;
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let second = (now_ms() - 120_000) / 1000 * 1000;
for i in 0..250 {
post_raw(&relay, &held(), &owner, &general, &read, community.root_epoch, None, &format!("m{i}"), second + i).await;
}
let nothing = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT;
set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
assert_eq!(sealing::seal_history(&relay, &held(), held().channel(&general).unwrap()).await.unwrap(), Some(250));
}
/// Serves what `inner` does, less the read-address wraps dated in `gone` (unix seconds).
struct Forgetting<'a> {
inner: &'a MemoryRelay,
address: PublicKey,
gone: std::ops::Range<u64>,
}
impl Forgetting<'_> {
fn keep(&self, evs: Vec<Event>) -> Vec<Event> {
evs.into_iter().filter(|e| e.pubkey != self.address || !self.gone.contains(&e.created_at.as_secs())).collect()
}
}
#[async_trait::async_trait]
impl Transport for Forgetting<'_> {
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
let mut f = self.inner.fetch_plane(plane, query, relays).await?;
f.events = self.keep(f.events);
Ok(f)
}
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.inner.publish(e, r).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.inner.publish_durable(e, r).await
}
async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
Ok(self.keep(self.inner.fetch(q, r).await?))
}
}
#[tokio::test]
async fn sealed_ids_no_relay_serves_any_more_page_on_to_what_lies_past_them() {
use crate::community::roles::OverwriteTarget;
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Forgotten", vec!["wss://r".into()], None).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
let general = community.channels[0].id;
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let total = crate::community::v2::seal::MAX_SEAL_IDS + 20;
let start = (now_ms() - (total as u64 + 100) * 1000) / 1000 * 1000;
for i in 0..total {
post_raw(&relay, &held(), &owner, &general, &read, community.root_epoch, None, &format!("m{i}"), start + i as u64 * 1000).await;
}
let nothing = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT;
set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
assert_eq!(sealing::seal_history(&relay, &held(), held().channel(&general).unwrap()).await.unwrap(), Some(total));
// A page no relay serves leaves what lies past it unread, not absent.
let lock = held().channel(&general).unwrap().writers.as_ref().unwrap().seal.as_ref().unwrap().until;
let pageless = Forgetting { inner: &relay, address: read.pk(), gone: (lock - 1) / 1000..(lock - 1) / 1000 + 1 };
let (_, _, complete) = fetch_channel_history_paged(&pageless, &held(), &general, 50, 40, None, Some(now_ms() / 1000 + 3600), crate::community::transport::Evidence::Quorum, |_, _, _| true, |_| Default::default()).await.unwrap();
assert!(!complete);
// Every post the newest page names has expired from the relay.
let first_gone = start / 1000 + 20;
let forgetting = Forgetting { inner: &relay, address: read.pk(), gone: first_gone..first_gone + crate::community::v2::seal::MAX_SEAL_IDS as u64 };
let got = fetch_channel_history(&forgetting, &held(), &general, 50, 40, None, Some(now_ms() / 1000 + 3600), crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
let texts: std::collections::BTreeSet<String> = got.into_iter().filter_map(|f| match f.event { ChatEvent::Message { opened, .. } => Some(opened.rumor.content), _ => None }).collect();
assert_eq!(texts, (0..20).map(|i| format!("m{i}")).collect(), "the older page still reads");
}
#[tokio::test]
async fn a_second_lock_chains_its_seal_onto_the_first() {
use crate::community::roles::OverwriteTarget;
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Twice", vec!["wss://r".into()], None).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
let general = community.channels[0].id;
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let nothing = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT;
let start = now_ms() - 900_000;
for i in 0..5 {
post_raw(&relay, &held(), &owner, &general, &read, community.root_epoch, None, &format!("first{i}"), start + i * 1000).await;
}
set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
assert_eq!(sealing::seal_history(&relay, &held(), held().channel(&general).unwrap()).await.unwrap(), Some(5));
let first = held().channel(&general).unwrap().writers.clone().unwrap().seal.unwrap();
set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
for i in 0..3 {
send_chat_message(&relay, &held(), &general, &format!("second{i}"), None, &[], vec![]).await.unwrap();
}
set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
assert!(held().channel(&general).unwrap().writers.as_ref().unwrap().seal_target(now_ms()).is_some(), "a new run");
assert_eq!(sealing::seal_history(&relay, &held(), held().channel(&general).unwrap()).await.unwrap(), Some(3), "only what came since the first");
let second = held().channel(&general).unwrap().writers.clone().unwrap().seal.unwrap();
assert_eq!(second.count, 8);
assert!(second.until > first.until && second.page != first.page);
// Junk dated anywhere before the second seal stays out of reach.
let stranger = Keys::generate();
for at in [start - 1_000, start + 2_500, first.until + 1] {
post_raw(&relay, &held(), &stranger, &general, &read, community.root_epoch, None, "junk", at).await;
}
let got = fetch_channel_history(&relay, &held(), &general, 3, 20, None, Some(now_ms() / 1000 + 3600), crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
let mut texts: Vec<String> = got.into_iter().filter_map(|f| match f.event { ChatEvent::Message { opened, .. } => Some(opened.rumor.content), _ => None }).collect();
texts.sort();
assert_eq!(texts, vec!["first0", "first1", "first2", "first3", "first4", "second0", "second1", "second2"], "one chain, both seals, read in small pages");
}
#[tokio::test]
async fn a_post_held_on_rules_this_device_hadnt_read_stands_once_it_reads_them() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
bed.swap_to(&owner);
let (live, secret, _) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
assert!(!held().channel(&general).unwrap().restricted(), "the owner reopened it");
let p = Keys::generate();
post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "after the reopen", now_ms()).await;
// Once it is open anyone may post at the read address, so a post at a writer's takes nothing new.
let writer = GroupKey::from_parts(crate::community::v2::derive::channel_writer_group_key(&secret, &general, live).keys().clone(), read.conv_key().clone());
post_raw(&bed.relay, &held(), &p, &general, &writer, community.root_epoch, Some(live), "at the old writer address", now_ms() + 1).await;
bed.swap_to(&member);
let texts = channel_texts(&bed.relay, &held(), &general).await;
assert!(!texts.iter().any(|t| t == "after the reopen" || t == "at the old writer address"), "judged on the ledger this device holds: {texts:?}");
let waiting = crate::db::community::held_wraps(&cid_hex).unwrap();
assert_eq!(waiting.len(), 2, "held, not dropped");
let ids: Vec<String> = waiting.iter().map(|w| w.0.clone()).collect();
assert_eq!(crate::db::events::community_wraps_settled(&ids).len(), 2, "a catch-up takes held wraps as settled");
let shown = Shown::default();
assert_eq!(writing::rejudge_held(&held(), &shown).await, 0, "nothing stands on the old rules");
assert!(shown.take().is_empty());
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(writing::rejudge_held(&held(), &shown).await, 2);
assert_eq!(sorted(shown.take().into_iter().map(|(t, rang)| { assert!(!rang, "a late arrival never rings"); t }).collect()), vec!["after the reopen".to_string(), "at the old writer address".to_string()]);
assert!(crate::db::community::held_wraps(&cid_hex).unwrap().is_empty(), "let go once they stand");
assert_eq!(writing::rejudge_held(&held(), &shown).await, 0);
}
#[tokio::test]
async fn a_post_at_a_writer_address_can_be_pinned() {
let (bed, owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
bed.swap_to(&owner);
let rumor = send_chat_message(&bed.relay, &held(), &general, "pin me", None, &[], vec![]).await.unwrap();
let far = now_ms() / 1000 + 100;
let got = fetch_channel_history(&bed.relay, &held(), &general, 50, 4, None, Some(far), crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
let wrap = got.iter().find(|e| e.event.opened().rumor_id.to_hex() == rumor).and_then(|e| e.wrap.clone()).expect("the post reads back");
let read = channel_group_key(&held().community_root, &general, held().root_epoch);
assert_ne!(wrap.pubkey, read.pk(), "posted at its writer's address, not the read one");
let chan = crate::simd::hex::bytes_to_hex_32(&general.0);
let wrap_of = crate::db::events::get_event_wrap_context(&rumor).unwrap().and_then(|(w, _)| w);
assert_eq!(wrap_of, Some(wrap.id.to_hex()), "the send recorded the wrap it went out in");
pin_message(&bed.relay, &held(), &general, &rumor).await.unwrap();
let pinned = writable_pin_entries(&held(), &general).unwrap();
assert!(pinned.iter().filter_map(|e| super::super::pins::verify_pin_entry(e, &chan)).any(|v| v.rumor_id == rumor), "and its pin verifies");
}
#[tokio::test]
async fn a_writer_in_flight_across_the_restrict_stands_only_while_a_member() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
bed.swap_to(&owner);
let (w, z) = (Keys::generate(), Keys::generate());
let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
for k in [&w, &z] {
set_member_roles(&bed.relay, &held(), &k.public_key(), vec![plain.clone()]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(k.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
}
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
let start = ledger.writer_start(ledger.current_writer().unwrap().0).unwrap();
// Sent before its client read the restrict, at the read address.
post_raw(&bed.relay, &held(), &w, &general, &read, community.root_epoch, None, "in flight", start + 1_000).await;
post_raw(&bed.relay, &held(), &w, &general, &read, community.root_epoch, None, "long after", start + crate::community::v2::writers::ENTRY_SKEW_MS + 1_000).await;
post_raw(&bed.relay, &held(), &z, &general, &read, community.root_epoch, None, "banned in flight", start + 1_500).await;
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
let texts = channel_texts(&bed.relay, &held(), &general).await;
assert!(texts.contains(&"in flight".to_string()) && texts.contains(&"banned in flight".to_string()), "a writer whose client lagged the move keeps its post: {texts:?}");
assert!(!texts.contains(&"long after".to_string()), "past the skew, a writer posts at its own address");
bed.swap_to(&owner);
kick_member(&bed.relay, &held(), &w.public_key()).await.unwrap();
set_members_banned(&bed.relay, community.id(), &[z.public_key()], true).await.unwrap();
post_raw(&bed.relay, &held(), &w, &general, &read, community.root_epoch, None, "kicked in flight", start + 2_000).await;
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
let texts = channel_texts(&bed.relay, &held(), &general).await;
assert!(!texts.contains(&"kicked in flight".to_string()), "a writer no longer a member vouches for nothing: {texts:?}");
assert!(!texts.contains(&"banned in flight".to_string()), "nor one banned");
}
#[tokio::test]
async fn a_member_let_into_a_private_channel_finds_its_key_on_its_own_next_sweep() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member) = TestBed::new();
let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Prompt", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let m = member.keys.public_key();
let ch = create_private_channel(&bed.relay, &held(&community), "staff").await.unwrap();
send_direct_invite(&bed.relay, &held(&community), &m, None, None).await.unwrap();
bed.swap_to(&member);
accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &m).await).await.unwrap();
follow_control(&bed.relay, &held(&community)).await.unwrap();
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(&community), ch.0, OverwriteTarget::Member(m.to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
// No holder's duty runs: the change itself put the key where the member's client looks.
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert_eq!(collect_access(&bed.relay, &held(&community)).await.unwrap(), 1);
}
#[tokio::test]
async fn an_action_reads_an_access_plane_once_and_afresh_after_writing_to_it() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Once", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held, "staff").await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let (m, other) = (member.keys.public_key(), Keys::generate().public_key());
let room = held.channel(&ch).unwrap();
let (key, epoch) = (room.key.unwrap(), room.epoch);
// Someone else's delivery, sealed ahead of the action and published while it runs.
let theirs = build_deliveries(&held, &ch, rekey::RekeyScope::Channel(ch), epoch, None, &key, &[other], &Default::default(), false).await.unwrap();
let count = || async { fetch_access_deliveries(&bed.relay, &held, &ch).await.unwrap().len() };
let before = count().await;
reading_planes_once(async {
assert_eq!(count().await, before);
for wrap in &theirs {
bed.relay.publish(wrap, &held.relays).await.unwrap();
}
assert_eq!(count().await, before, "the plane was read once: a second look asks no relay");
deliver_access(&bed.relay, &held, &ch, &[m]).await.unwrap();
assert_eq!(count().await, before + 2, "after its own delivery the action reads the plane afresh");
})
.await;
assert_eq!(count().await, before + 2);
// Outside an action every read is the relays' own.
deliver_access(&bed.relay, &held, &ch, &[other]).await.unwrap();
assert_eq!(count().await, before + 3);
}
#[tokio::test]
async fn a_holder_never_cuts_someone_a_fresh_read_lets_in() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member) = TestBed::new();
let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Race", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let ch = create_private_channel(&bed.relay, &held(&community), "staff").await.unwrap();
let (m, chan) = (member.keys.public_key(), crate::simd::hex::bytes_to_hex_32(&ch.0));
let owner_hex = owner.keys.public_key().to_hex();
assert_eq!(still_left_out(&bed.relay, &held(&community), &chan, &owner_hex, vec![m]).await, vec![m], "not let in: cut");
set_overwrite(&bed.relay, &held(&community), ch.0, OverwriteTarget::Member(m.to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
assert!(still_left_out(&bed.relay, &held(&community), &chan, &owner_hex, vec![m]).await.is_empty(), "let in since the duty's read: kept");
}
#[tokio::test]
async fn a_member_back_after_leaving_opens_its_key_delivery_again() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member) = TestBed::new();
let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Return", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let m = member.keys.public_key();
let ch = create_private_channel(&bed.relay, &held(&community), "staff").await.unwrap();
send_direct_invite(&bed.relay, &held(&community), &m, None, None).await.unwrap();
bed.swap_to(&member);
let invite = fetch_direct_invite(&bed.relay, &bed.relays, &m).await;
accept_direct_invite(&bed.relay, &invite).await.unwrap();
follow_control(&bed.relay, &held(&community)).await.unwrap();
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(&community), ch.0, OverwriteTarget::Member(m.to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert_eq!(collect_access(&bed.relay, &held(&community)).await.unwrap(), 1);
assert_eq!(absorb_parked_channel_keys(&held(&community), &crate::db::current_session()), vec![ch]);
// Gone and back without the session ending: the seat is new, the delivery is the same one.
leave_community(&bed.relay, &held(&community)).await.unwrap();
accept_direct_invite(&bed.relay, &invite).await.unwrap();
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert!(held(&community).channel(&ch).is_some_and(|c| c.key.is_none()), "back without the key");
assert_eq!(collect_access(&bed.relay, &held(&community)).await.unwrap(), 1, "the delivery it opened before is opened again");
assert_eq!(absorb_parked_channel_keys(&held(&community), &crate::db::current_session()), vec![ch]);
}
#[tokio::test]
async fn a_member_given_the_right_to_post_moments_after_joining_gets_the_key() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member) = TestBed::new();
let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Gate", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let general = community.channels[0].id;
set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
let m = member.keys.public_key();
send_direct_invite(&bed.relay, &held(&community), &m, None, None).await.unwrap();
bed.swap_to(&member);
accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &m).await).await.unwrap();
follow_control(&bed.relay, &held(&community)).await.unwrap();
// The owner lets them post before its Guestbook has read their Join.
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Member(m.to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert_eq!(collect_writers(&bed.relay, &held(&community)).await.unwrap(), 1);
assert!(can_post(&held(&community), &general));
}
#[tokio::test]
async fn a_writers_certificate_the_ledger_disowns_is_collected_again() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(member.keys.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(collect_writers(&bed.relay, &held()).await.unwrap(), 1);
assert!(can_post(&held(), &general));
let ch = held().channel(&general).unwrap().clone();
let live = ch.writers.as_ref().unwrap().current_writer().unwrap().0;
let real = writing::my_cert(&held(), &ch, live).unwrap();
// A mint that lost its race left a certificate its certifier never stood behind.
let key = format!("writer_cert:{}:{}:{}", crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0), live.0);
crate::db::settings::set_sql_setting(key.clone(), "77".repeat(64)).unwrap();
assert!(!can_post(&held(), &general), "a post it would carry could never stand");
assert!(crate::db::settings::get_sql_setting(key).unwrap().is_none(), "dropped for a fresh one");
collect_writers(&bed.relay, &held()).await.unwrap();
assert_eq!(writing::my_cert(&held(), &ch, live), Some(real), "the real one, collected again");
assert!(can_post(&held(), &general));
}
#[tokio::test]
async fn a_certified_delivery_past_one_event_keeps_each_writers_key_beside_their_certificate() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Many", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
let scope = crate::community::v2::writers::writer_rekey_scope(&general);
let writers: Vec<PublicKey> = (0..rekey::MAX_CERTIFIED_BLOBS_PER_EVENT + 2).map(|_| Keys::generate().public_key()).collect();
let certs: std::collections::HashMap<PublicKey, chat::WriterCert> = writers.iter().enumerate().map(|(i, w)| (*w, chat::WriterCert::Full([i as u8; 64]))).collect();
deliver_certified(&bed.relay, &community, &general, scope, Epoch(1), Some([0x42; 32]), &[0x5e; 32], &writers, &certs).await.unwrap();
let deliveries = fetch_plane_deliveries(&bed.relay, &community, &general, scope).await.unwrap();
assert_eq!(deliveries.len(), 2, "split at the certified cap");
assert!(deliveries.iter().all(|d| d.blobs.len() <= rekey::MAX_CERTIFIED_BLOBS_PER_EVENT));
for w in &writers {
let with_blob: Vec<&rekey::AccessDelivery> = deliveries.iter().filter(|d| rekey::find_my_blob(&d.blobs, &d.deliverer.to_bytes(), &w.to_bytes(), scope, Epoch(1)).is_some()).collect();
assert_eq!(with_blob.len(), 1);
assert!(matches!(certs[w], chat::WriterCert::Full(c) if with_blob[0].certs.contains(&(w.to_bytes(), c))), "a writer's certificate rides with its key");
}
}
#[tokio::test]
async fn leaving_keeps_the_keys_a_self_scrub_needs_and_drops_the_writers() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Leave", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
for scope in [crate::community::v2::writers::secret_scope(&general), crate::community::v2::writers::minted_scope(&general), crate::community::v2::writers::certifier_scope(&general), chan_hex.clone()] {
crate::db::community::store_epoch_key(&cid_hex, &scope, 1, &[0x5e; 32]).unwrap();
}
crate::db::community::hold_wrap(&cid_hex, &chan_hex, &"ab".repeat(32), "{}", "", 1).unwrap();
crate::db::community::delete_community_retain_keys(&cid_hex).unwrap();
assert!(crate::db::community::held_epoch_key(&cid_hex, &chan_hex, 1).unwrap().is_some(), "a self-scrub signs with the read keys");
for scope in [crate::community::v2::writers::secret_scope(&general), crate::community::v2::writers::minted_scope(&general), crate::community::v2::writers::certifier_scope(&general)] {
assert!(crate::db::community::held_epoch_key(&cid_hex, &scope, 1).unwrap().is_none(), "nothing that posts or vouches outlives membership: {scope}");
}
assert!(crate::db::community::held_wraps(&cid_hex).unwrap().is_empty());
}
#[tokio::test]
async fn a_writer_who_left_vouches_for_nothing_whatever_role_lingers() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
bed.swap_to(&owner);
let w = Keys::generate();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
let start = ledger.writer_start(ledger.current_writer().unwrap().0).unwrap();
let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
let leave = guestbook::build_leave_rumor(w.public_key(), now_ms());
let (wrap, _) = guestbook::seal_guestbook_rumor(&leave, &gb, &w, Timestamp::from_secs(now_ms() / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
post_raw(&bed.relay, &held(), &w, &general, &read, community.root_epoch, None, "after leaving", start + 1_000).await;
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
crate::rt::time::sleep(std::time::Duration::from_millis(1_100)).await;
assert!(!channel_texts(&bed.relay, &held(), &general).await.contains(&"after leaving".to_string()), "a Role they still hold is no membership once they left");
}
#[tokio::test]
async fn a_writer_who_leaves_posts_nothing_that_stands_and_costs_no_ledger_line() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
bed.swap_to(&owner);
let w = Keys::generate();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let (live, _, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
let cert = cert_for(&held(), &general, live, &w.public_key());
let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "before leaving", now_ms()).await;
crate::rt::time::sleep(std::time::Duration::from_millis(1_100)).await;
let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
let leave = guestbook::build_leave_rumor(w.public_key(), now_ms());
let (wrap, _) = guestbook::seal_guestbook_rumor(&leave, &gb, &w, Timestamp::from_secs(now_ms() / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
crate::rt::time::sleep(std::time::Duration::from_millis(1_100)).await;
// Their key and certificate still sign, and a Role still says they may post.
post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "after leaving", now_ms()).await;
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.cut, 0, "the Guestbook is the stop: no ledger line");
assert_eq!(held().channel(&general).unwrap().writers, Some(ledger));
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
let texts = channel_texts(&bed.relay, &held(), &general).await;
assert!(texts.contains(&"before leaving".to_string()), "what they posted while here stays theirs");
assert!(!texts.contains(&"after leaving".to_string()), "a member who left posts nothing that stands");
// Nor does a fresh epoch for others reach them.
bed.swap_to(&owner);
let wr = create_role_v2(&bed.relay, &held(), "W", 0, 0).await.unwrap();
let (y1, y2) = (Keys::generate(), Keys::generate());
for y in [&y1, &y2] {
set_member_roles(&bed.relay, &held(), &y.public_key(), vec![wr.clone()]).await.unwrap();
}
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(wr.clone()), Permissions::SEND_MESSAGES, 0).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(wr), 0, 0).await.unwrap();
let fresh = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
assert!(fresh > live, "two lost Send at once");
let scope = crate::community::v2::writers::writer_rekey_scope(&general);
let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
assert!(!served_at(&plane, &w.public_key(), scope, fresh, &|_| true), "one who left is no writer");
}
#[tokio::test]
async fn a_leave_read_later_takes_back_what_was_shown_since() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let (cid_hex, chan_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
bed.swap_to(&owner);
let w = Keys::generate();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let (live, _, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
let cert = cert_for(&held(), &general, live, &w.public_key());
let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
let leave = guestbook::build_leave_rumor(w.public_key(), now_ms());
let (wrap, _) = guestbook::seal_guestbook_rumor(&leave, &gb, &w, Timestamp::from_secs(now_ms() / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "after leaving", now_ms() + 2_000).await;
// The member shows it before its Guestbook holds the Leave.
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
let shown = page.iter().find(|f| f.event.opened().rumor.content == "after leaving").expect("stood before the Leave was read");
crate::community::v2::inbound::persist_routed_chat_event(&shown.event, &chan_hex, &community.id().0, &member.keys.public_key()).await.expect("stored");
let id = shown.event.opened().rumor_id.to_hex();
clear_owed(&cid_hex);
sync_guestbook(&bed.relay, &held()).await.unwrap();
let owed = crate::db::community::owed_author_retractions(&cid_hex).unwrap();
assert_eq!(owed.iter().map(|(c, a, ..)| (c.clone(), a.clone())).collect::<Vec<_>>(), vec![(chan_hex.clone(), w.public_key().to_hex())], "the Leave owes their posts a take-back, nobody else's");
writing::retract_by(&bed.relay, &held(), held().channel(&general).unwrap(), &w.public_key(), owed[0].2, owed[0].3, &Shown::default()).await.unwrap();
assert!(crate::db::events::get_message_by_id(&id).await.unwrap().is_none());
}
#[tokio::test]
async fn a_guestbook_longer_than_one_pass_is_still_read_whole() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Big", bed.relays.clone(), None).await.unwrap();
let gb = crate::community::v2::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let base = now_ms() / 1000 - 100_000;
let joiners: Vec<Keys> = (0..6_100).map(|_| Keys::generate()).collect();
for (i, k) in joiners.iter().enumerate() {
let at = base + i as u64;
let join = guestbook::build_join_rumor(k.public_key(), None, at * 1000);
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, k, Timestamp::from_secs(at)).unwrap();
bed.relay.publish(&wrap, &community.relays).await.unwrap();
}
super::control_sync::set_budget_for_test(Some(6_000));
sync_guestbook(&bed.relay, &community).await.unwrap();
assert!(!guestbook_walked_this_session(&community), "one pass's worth falls short");
sync_guestbook(&bed.relay, &community).await.unwrap();
super::control_sync::set_budget_for_test(None);
assert!(guestbook_walked_this_session(&community), "the next goes on from where it stopped");
let (_, cursor) = crate::db::community::get_guestbook(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
assert!(cursor + 600 >= now_ms() / 1000, "the cursor reaches the newest the whole walk saw, not only its last pass");
let members = stored_memberlist_strict(&crate::db::community::load_community_v2(community.id()).unwrap().unwrap()).unwrap();
assert!(members.contains(&joiners[0].public_key()) && members.contains(&joiners[6_099].public_key()), "oldest and newest both");
}
#[tokio::test]
async fn a_writer_nobody_saw_leave_is_never_stopped_for_an_absence() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
bed.swap_to(&owner);
let w = Keys::generate();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
// The role that made them a member goes; no Leave, no Kick, no ban says they left.
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![]).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.cut, 0, "an absence is no departure");
}
#[tokio::test]
async fn a_stopped_writer_who_now_manages_costs_no_fresh_epoch() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
bed.swap_to(&owner);
let w = Keys::generate();
let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain.clone()]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, 0).await.unwrap();
assert!(held().channel(&general).unwrap().writers.as_ref().unwrap().stopped(Epoch(1), &w.public_key().to_bytes(), u64::MAX));
// Let back as a manager without a settle: their posts stand by the Roster whatever the key.
let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain, mods]).await.unwrap();
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await;
follow_control(&bed.relay, &held()).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 0);
assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(1));
}
#[tokio::test]
async fn a_manager_without_the_certifier_lets_a_fresh_epoch_land_before_minting_over_it() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
bed.swap_to(&owner);
let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(), &member.keys.public_key(), vec![plain.clone(), mods]).await.unwrap();
let w = Keys::generate();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain]).await.unwrap();
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await;
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
assert!(writing::certifier_held(&held(), held().channel(&general).unwrap(), Epoch(1)).is_none());
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 0, "a fresh epoch's own deliveries get their while");
}
#[tokio::test]
async fn taking_back_never_reads_a_reopened_channel_stricter_than_judging() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
bed.swap_to(&owner);
let z = Keys::generate();
set_member_roles(&bed.relay, &held(), &z.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(z.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
// Restricted again and reopened while this member wasn't looking; z posted at the read
// address in between, in flight across the restrict.
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
let start = held().channel(&general).unwrap().writers.as_ref().unwrap().entries.last().unwrap().at;
post_raw(&bed.relay, &held(), &z, &general, &read, community.root_epoch, None, "in flight", start + 300).await;
crate::rt::time::sleep(std::time::Duration::from_millis(1_200)).await;
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
bed.swap_to(&member);
let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
for f in page.iter().filter(|f| f.event.opened().rumor.content == "in flight") {
crate::community::v2::inbound::persist_routed_chat_event(&f.event, &chan_hex, &community.id().0, &member.keys.public_key()).await.expect("it stood on the open ledger");
}
follow_control(&bed.relay, &held()).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
let added: Vec<_> = ledger.entries[ledger.entries.len() - 2..].to_vec();
let shown = Shown::default();
assert_eq!(writing::retract_after(&bed.relay, &held(), held().channel(&general).unwrap(), &added, &shown).await, 0, "a writer in flight keeps the post");
}
#[tokio::test]
async fn a_held_post_whose_author_is_banned_since_is_let_go() {
let (bed, owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
bed.swap_to(&owner);
let p = Keys::generate();
post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "spam", now_ms()).await;
assert!(marked_texts(&bed.relay, &held(), &general).await.contains(&"spam".to_string()));
assert_eq!(crate::db::community::held_wraps(&cid_hex).unwrap().len(), 1);
crate::db::community::set_community_banlist(&cid_hex, &[p.public_key().to_hex()], 1).unwrap();
let shown = Shown::default();
writing::rejudge_held(&held(), &shown).await;
assert!(crate::db::community::held_wraps(&cid_hex).unwrap().is_empty(), "nothing to wait for");
}
#[tokio::test]
async fn a_writer_served_without_a_certificate_is_served_again_with_one() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let m = member.keys.public_key();
bed.swap_to(&owner);
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(m.to_hex()), Permissions::SEND_MESSAGES, 0).await;
follow_control(&bed.relay, &held()).await.unwrap();
// An older client hands over the key alone.
let (live, secret, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
deliver_on_plane(&bed.relay, &held(), &general, crate::community::v2::writers::writer_rekey_scope(&general), live, Some(writer.pk().to_bytes()), &secret, &[m]).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(collect_writers(&bed.relay, &held()).await.unwrap(), 1, "the key");
assert!(!can_post(&held(), &general), "but no proof to post with");
bed.swap_to(&owner);
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.delivered, 1, "a key without its certificate serves nobody");
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.delivered, 0, "once");
bed.swap_to(&member);
collect_writers(&bed.relay, &held()).await.unwrap();
assert!(can_post(&held(), &general));
}
#[tokio::test]
async fn what_waits_shows_marked_to_a_new_manager_and_leaves_a_former_one() {
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
bed.swap_to(&owner);
let p = Keys::generate();
post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "spam", now_ms()).await;
bed.swap_to(&member);
assert!(!channel_texts(&bed.relay, &held(), &general).await.contains(&"spam".to_string()));
let shown = Shown::default();
assert_eq!(writing::rejudge_held(&held(), &shown).await, 0);
assert!(shown.take().is_empty(), "a member is shown nothing");
bed.swap_to(&owner);
let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
set_member_roles(&bed.relay, &held(), &member.keys.public_key(), vec![mods]).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(writing::rejudge_held(&held(), &shown).await, 0, "still held");
assert_eq!(shown.take(), vec![("spam".to_string(), false)], "a new manager sees it, unrung");
let id = crate::db::community::held_wraps(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
assert_eq!(id.len(), 1, "it still waits");
bed.swap_to(&owner);
set_member_roles(&bed.relay, &held(), &member.keys.public_key(), vec![]).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
writing::rejudge_held(&held(), &shown).await;
let gone = shown.take();
assert_eq!(gone.len(), 1);
assert!(gone[0].0.starts_with('-'), "a former manager stops seeing it: {gone:?}");
assert!(channel_texts(&bed.relay, &held(), &general).await.iter().all(|t| t != "spam"));
}
#[tokio::test]
async fn a_held_post_dated_ahead_never_dates_a_managers_entry() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
bed.swap_to(&owner);
let p = Keys::generate();
post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "from the future", now_ms() + 5 * 60_000).await;
let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
assert!(!page.iter().any(|f| f.event.opened().rumor.content == "from the future"), "it waits for its time, before the writers' rules judge it");
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
let at = held().channel(&general).unwrap().writers.as_ref().unwrap().entries.last().unwrap().at;
assert!(at < now_ms() + 60_000, "the reopen is dated now, not by a post the rules held");
}
#[tokio::test]
async fn writers_lost_together_take_one_fresh_epoch_and_one_alone_a_stop() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
bed.swap_to(&owner);
let (a, b, c) = (Keys::generate(), Keys::generate(), Keys::generate());
let writers = create_role_v2(&bed.relay, &held(), "Writers", 0, 0).await.unwrap();
let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
for k in [&a, &b, &c] {
set_member_roles(&bed.relay, &held(), &k.public_key(), vec![plain.clone(), writers.clone()]).await.unwrap();
}
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(writers.clone()), Permissions::SEND_MESSAGES, 0).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(1), "gained, not minted");
set_member_roles(&bed.relay, &held(), &a.public_key(), vec![plain.clone()]).await.unwrap();
let l = held().channel(&general).unwrap().writers.clone().unwrap();
assert_eq!(l.current_writer().unwrap().0, Epoch(1));
assert!(l.stopped(Epoch(1), &a.public_key().to_bytes(), u64::MAX), "one writer lost is a stop");
set_member_roles(&bed.relay, &held(), &a.public_key(), vec![plain.clone(), writers.clone()]).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(2), "let back in after a stop, a writer takes a fresh epoch");
// Everyone the role let post loses it in one change.
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(writers), 0, 0).await.unwrap();
let l = held().channel(&general).unwrap().writers.clone().unwrap();
assert_eq!(l.current_writer().unwrap().0, Epoch(3), "several lost at once take a fresh epoch");
let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, crate::community::v2::writers::writer_rekey_scope(&general)).await.unwrap();
assert!(plane.iter().filter(|d| d.epoch == Epoch(3)).all(|d| d.certs.iter().all(|(w, _)| *w != b.public_key().to_bytes() && *w != c.public_key().to_bytes())), "without them");
}
#[tokio::test]
async fn a_demoted_manager_who_writes_takes_a_fresh_epoch_not_a_stop() {
use crate::community::roles::OverwriteTarget;
let (bed, _owner, x, community) = v2_bed_with_admin("Demoted writer").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
// x manages and writes through one role, and loses both in one change.
let lead = create_role_v2(&bed.relay, &held(), "Lead", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(lead.clone()), Permissions::SEND_MESSAGES, 0).await.unwrap();
set_member_roles(&bed.relay, &held(), &x.public_key(), vec![plain.clone(), lead]).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(1));
set_member_roles(&bed.relay, &held(), &x.public_key(), vec![plain]).await.unwrap();
let l = held().channel(&general).unwrap().writers.clone().unwrap();
assert_eq!(l.current_writer().unwrap().0, Epoch(2), "the certifier x held goes with a fresh epoch");
assert!(!l.stopped(Epoch(1), &x.public_key().to_bytes(), u64::MAX));
}
#[tokio::test]
async fn a_stop_fits_only_while_the_live_entry_stays_and_the_writer_isnt_stopped() {
use crate::community::v2::writers::{writer_address, Ledger, Spell};
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Full", bed.relays.clone(), None).await.unwrap();
let mut ch = community.channels[0].clone();
let mut l = Ledger::new(&ch.id).appended(1_000, Spell::Writer { epoch: Epoch(1), pk: writer_address(&[1; 32], &ch.id, Epoch(1)), root: Epoch(0), by: [0x0b; 32], certifier: None }).unwrap();
let w = Keys::generate().public_key();
for _ in 1..crate::community::v2::writers::MAX_LEDGER - 1 {
l = l.appended(2_000, Spell::Stop { writer: Keys::generate().public_key().to_bytes() }).unwrap();
}
ch.writers = Some(l.clone());
assert!(writing::stop_fits(&ch, &w), "one slot left");
ch.writers = Some(l.appended(2_000, Spell::Stop { writer: w.to_bytes() }).unwrap());
assert!(!writing::stop_fits(&ch, &w), "stopped already");
assert!(!writing::stop_fits(&ch, &Keys::generate().public_key()), "full: a stop would retire the live entry");
}
#[tokio::test]
async fn an_epoch_from_before_certificates_is_replaced_by_one_with_a_certifier() {
use crate::community::roles::OverwriteTarget;
use crate::community::v2::writers::{writer_address, Ledger, Spell};
let (bed, owner, _x, community) = v2_bed_with_admin("Legacy").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
let old = Ledger::new(&general).appended(2_001_000, Spell::Writer { epoch: Epoch(1), pk: writer_address(&[0x77; 32], &general, Epoch(1)), root: Epoch(0), by: owner.keys.public_key().to_bytes(), certifier: None }).unwrap();
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await;
publish_marked(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 1, None, &old.to_json()).await;
follow_control(&bed.relay, &held()).await.unwrap();
assert!(held().channel(&general).unwrap().writers.as_ref().is_some_and(|l| l.certifier(Epoch(1)).is_none()), "folded the old ledger");
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 1);
let l = held().channel(&general).unwrap().writers.clone().unwrap();
assert_eq!(l.current_writer().unwrap().0, Epoch(2));
assert!(l.certifier(Epoch(2)).is_some(), "anyone handed the old key could post");
}
#[tokio::test]
async fn a_manager_promoted_since_the_mint_is_handed_the_certifier() {
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
bed.swap_to(&owner);
let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
set_member_roles(&bed.relay, &held(), &member.keys.public_key(), vec![mods]).await.unwrap();
access_duty(&bed.relay, &held()).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
collect_writers(&bed.relay, &held()).await.unwrap();
let ch = held().channel(&general).unwrap().clone();
let live = ch.writers.as_ref().unwrap().current_writer().unwrap().0;
assert!(writing::certifier_held(&held(), &ch, live).is_some(), "a manager can let a writer in without a new epoch");
assert!(writing::live_writer(&held(), &ch).is_some(), "and holds the key to hand on");
assert_eq!(live, Epoch(1));
}
#[tokio::test]
async fn a_manager_who_leaves_takes_the_certifier_with_them_so_a_fresh_epoch_replaces_it() {
let (bed, owner, member, community, general) = restricted_bed(true).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
bed.swap_to(&member);
collect_writers(&bed.relay, &held()).await.unwrap();
let ch = held().channel(&general).unwrap().clone();
assert!(writing::certifier_held(&held(), &ch, Epoch(1)).is_some());
let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
// A role they still hold never reads as newer than leaving.
let left_at = now_ms();
let leave = guestbook::build_leave_rumor(member.keys.public_key(), left_at);
let (wrap, _) = guestbook::seal_guestbook_rumor(&leave, &gb, &member.keys, Timestamp::from_secs(left_at / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
bed.swap_to(&owner);
sync_guestbook(&bed.relay, &held()).await.unwrap();
crate::rt::time::sleep(std::time::Duration::from_millis(1_100)).await;
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 1);
assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(2));
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers, WriterDuty::default(), "once");
}
#[tokio::test]
async fn a_post_shown_before_its_writers_stop_was_read_is_taken_back() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
bed.swap_to(&owner);
let w = Keys::generate();
let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let (live, _, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
let cert = cert_for(&held(), &general, live, &w.public_key());
post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "before", now_ms() - 5_000).await;
post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "after", now_ms() + 3_000).await;
// A member reads both while w may still post.
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
let ids: std::collections::HashMap<String, String> = page.iter().map(|f| (f.event.opened().rumor.content.clone(), f.event.opened().rumor_id.to_hex())).collect();
for f in page.iter().filter(|f| ids.contains_key(&f.event.opened().rumor.content)) {
crate::community::v2::inbound::persist_routed_chat_event(&f.event, &chan_hex, &community.id().0, &member.keys.public_key()).await;
}
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, 0).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
let added = vec![ledger.entries.last().unwrap().clone()];
let shown = Shown::default();
assert_eq!(writing::retract_after(&bed.relay, &held(), held().channel(&general).unwrap(), &added, &shown).await, 1);
assert_eq!(shown.take(), vec![(format!("-{}", ids["after"]), false)], "only what the stop undoes");
assert!(crate::db::events::get_message_by_id(&ids["after"]).await.unwrap().is_none());
assert!(crate::db::events::get_message_by_id(&ids["before"]).await.unwrap().is_some(), "a writer's past posts stay theirs");
// The read after the move holds it again, for a later judgment.
assert!(!channel_texts(&bed.relay, &held(), &general).await.contains(&"after".to_string()));
assert_eq!(crate::db::community::held_wraps(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap().len(), 1);
}
#[tokio::test]
async fn an_edit_a_stopped_writer_made_after_the_stop_is_undone() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
bed.swap_to(&owner);
let w = Keys::generate();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let (live, _, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
let cert = cert_for(&held(), &general, live, &w.public_key());
post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "original", now_ms() - 5_000).await;
let original = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap()
.into_iter().find(|f| f.event.opened().rumor.content == "original").unwrap().event.opened().rumor_id.to_hex();
let edit = chat::with_writer(chat::build_edit_rumor(w.public_key(), &general, community.root_epoch, &original, "rewritten", &[], None, now_ms() + 3_000), live, Some(&cert));
let (wrap, _) = chat::seal_chat_rumor(&edit, &signed, &w, Timestamp::from_secs(now_ms() / 1000 + 3), false).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
for f in &page {
crate::community::v2::inbound::persist_routed_chat_event(&f.event, &chan_hex, &community.id().0, &member.keys.public_key()).await;
}
assert_eq!(crate::db::events::get_message_by_id(&original).await.unwrap().unwrap().1.content, "rewritten");
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, 0).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
let added = vec![ledger.entries.last().unwrap().clone()];
let shown = Shown::default();
assert_eq!(writing::retract_after(&bed.relay, &held(), held().channel(&general).unwrap(), &added, &shown).await, 1);
assert_eq!(crate::db::events::get_message_by_id(&original).await.unwrap().unwrap().1.content, "original", "the edit is undone");
assert_eq!(shown.take(), vec![("~original".to_string(), false)]);
assert_eq!(crate::db::community::held_wraps(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap().len(), 1, "and its wrap waits");
}
#[tokio::test]
async fn a_read_address_post_shown_before_the_restrict_was_read_is_taken_back() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
let p = Keys::generate();
post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "while open", now_ms() - 5_000).await;
post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "after the restrict", now_ms() + 3_000).await;
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
let ids: std::collections::HashMap<String, String> = page.iter().map(|f| (f.event.opened().rumor.content.clone(), f.event.opened().rumor_id.to_hex())).collect();
for f in &page {
crate::community::v2::inbound::persist_routed_chat_event(&f.event, &chan_hex, &community.id().0, &member.keys.public_key()).await;
}
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
let added = vec![ledger.entries.last().unwrap().clone()];
assert!(matches!(added[0].spell, crate::community::v2::writers::Spell::Writer { .. }));
let shown = Shown::default();
assert_eq!(writing::retract_after(&bed.relay, &held(), held().channel(&general).unwrap(), &added, &shown).await, 1);
assert_eq!(shown.take(), vec![(format!("-{}", ids["after the restrict"]), false)]);
assert!(crate::db::events::get_message_by_id(&ids["while open"]).await.unwrap().is_some(), "what was said while open stays");
}
#[tokio::test]
async fn a_post_dated_past_the_horizon_or_by_a_banned_author_is_never_held() {
let (bed, owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
bed.swap_to(&owner);
let (far, banned) = (Keys::generate(), Keys::generate());
crate::db::community::set_community_banlist(&cid_hex, &[banned.public_key().to_hex()], 1).unwrap();
post_raw(&bed.relay, &held(), &far, &general, &read, community.root_epoch, None, "from next week", now_ms() + 7 * 86_400_000).await;
post_raw(&bed.relay, &held(), &banned, &general, &read, community.root_epoch, None, "banned", now_ms()).await;
let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
assert!(page.iter().all(|f| !f.event.opened().held), "a manager keeps no copy of either");
assert!(crate::db::community::held_wraps(&cid_hex).unwrap().is_empty(), "and nothing waits");
}
#[tokio::test]
async fn a_backstop_acting_on_one_writer_checks_them_on_the_roster_it_reads_again() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let m = member.keys.public_key();
bed.swap_to(&owner);
let before = crate::db::community::get_community_roles(&cid_hex).unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(m.to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone();
// A pass whose roster predates the grant would stop a writer who may post.
assert_eq!(writing::backstop_act_on(&bed.relay, &held(), &general, &before, writing::Act::Stop(m, writing::Rights::Full)).await.unwrap(), writing::Backstop::StoodDown);
assert_eq!(held().channel(&general).unwrap().writers, ledger);
// And one whose roster still lets a stopped writer post can't let them back once it doesn't.
let after = crate::db::community::get_community_roles(&cid_hex).unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(m.to_hex()), 0, 0).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone();
assert!(ledger.as_ref().unwrap().stopped(Epoch(1), &m.to_bytes(), u64::MAX));
assert_eq!(writing::backstop_act_on(&bed.relay, &held(), &general, &after, writing::Act::Restart(m)).await.unwrap(), writing::Backstop::StoodDown);
assert_eq!(held().channel(&general).unwrap().writers, ledger);
}
#[tokio::test]
async fn demoting_a_manager_who_never_held_the_certifier_spends_nothing() {
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
bed.swap_to(&owner);
let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(), &member.keys.public_key(), vec![plain.clone(), mods]).await.unwrap();
set_member_roles(&bed.relay, &held(), &member.keys.public_key(), vec![plain]).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(1), "promoted and demoted before anyone handed them the certifier");
}
#[tokio::test]
async fn losing_send_again_after_a_stop_spends_nothing() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let m = member.keys.public_key();
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(m.to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(m.to_hex()), 0, 0).await;
follow_control(&bed.relay, &held()).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.cut, 1);
// Let back without a settle, then taken away by one: the stop already stands.
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(m.to_hex()), Permissions::SEND_MESSAGES, 0).await;
follow_control(&bed.relay, &held()).await.unwrap();
let entries = held().channel(&general).unwrap().writers.as_ref().unwrap().entries.len();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(m.to_hex()), 0, 0).await.unwrap();
let l = held().channel(&general).unwrap().writers.clone().unwrap();
assert_eq!((l.current_writer().unwrap().0, l.entries.len()), (Epoch(1), entries), "no fresh epoch, no second stop");
}
#[tokio::test]
async fn a_member_who_left_and_came_back_is_judged_on_a_memberlist_read_whole() {
let (bed, owner, member, community, general) = restricted_bed(true).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
bed.swap_to(&member);
collect_writers(&bed.relay, &held()).await.unwrap();
let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
let left_at = now_ms();
let leave = guestbook::build_leave_rumor(member.keys.public_key(), left_at);
let (wrap, _) = guestbook::seal_guestbook_rumor(&leave, &gb, &member.keys, Timestamp::from_secs(left_at / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
bed.swap_to(&owner);
sync_guestbook(&bed.relay, &held()).await.unwrap();
// They come back; this device starts again and hasn't read the plane whole yet.
crate::rt::time::sleep(std::time::Duration::from_millis(1_100)).await;
let join = guestbook::build_join_rumor(member.keys.public_key(), None, now_ms());
bed.swap_to(&member);
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &member.keys, Timestamp::from_secs(now_ms() / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
bed.swap_to(&owner);
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 0, "the stored memberlist says they left, but it isn't the whole story");
sync_guestbook(&bed.relay, &held()).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 0, "read whole, they're back");
assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(1));
}
/// Loses the `nth` distinct event sent to one plane, every time it is sent.
struct LosesOne<'a> {
inner: &'a MemoryRelay,
plane: String,
nth: usize,
seen: std::sync::Mutex<Vec<nostr_sdk::prelude::EventId>>,
}
#[async_trait::async_trait]
impl Transport for LosesOne<'_> {
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
self.inner.fetch_plane(plane, query, relays).await
}
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
if e.pubkey.to_hex() == self.plane {
let mut seen = self.seen.lock().unwrap();
if !seen.contains(&e.id) {
seen.push(e.id);
}
if seen.iter().position(|id| *id == e.id) == Some(self.nth - 1) {
return Err("dropped".into());
}
}
self.inner.publish(e, r).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.publish(e, r).await
}
async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
self.inner.fetch(q, r).await
}
}
#[tokio::test]
async fn a_mint_whose_delivery_lost_a_part_leaves_nobody_out() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
bed.swap_to(&owner);
let role = create_role_v2(&bed.relay, &held(), "Writers", 0, 0).await.unwrap();
// Three parts, so the one dropped holds writers whatever order its recipients sort in.
let writers: Vec<Keys> = (0..2 * rekey::MAX_CERTIFIED_BLOBS_PER_EVENT + 2).map(|_| Keys::generate()).collect();
for w in &writers {
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![role.clone()]).await.unwrap();
}
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(role.clone()), Permissions::SEND_MESSAGES, 0).await.unwrap();
// Two lose Send at once: a fresh epoch, whose second part a relay drops.
let lossy = LosesOne { inner: &bed.relay, plane: access_group(&held(), &general).pk_hex(), nth: 2, seen: Default::default() };
for w in &writers[..2] {
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, Permissions::SEND_MESSAGES).await;
}
let before = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let after = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
let _ = writing::settle_for_test(&lossy, &held(), &before, &after).await;
let live = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
assert_eq!(live, Epoch(2));
let scope = crate::community::v2::writers::writer_rekey_scope(&general);
let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
let stranded: Vec<&Keys> = writers[2..].iter().filter(|w| !served_at(&plane, &w.public_key(), scope, live, &|_| true)).collect();
assert!(!stranded.is_empty(), "the part a relay dropped served nobody");
sync_guestbook(&bed.relay, &held()).await.unwrap();
access_duty(&bed.relay, &held()).await.unwrap();
let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
assert!(writers[2..].iter().all(|w| served_at(&plane, &w.public_key(), scope, live, &|_| true)), "the next pass serves those the lost part left out");
assert!(writers[..2].iter().all(|w| !served_at(&plane, &w.public_key(), scope, live, &|_| true)), "and never those the change took out");
}
#[tokio::test]
async fn a_mint_with_no_part_in_view_cuts_nobody_whatever_the_minter_tops_up() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
bed.swap_to(&owner);
let role = create_role_v2(&bed.relay, &held(), "Writers", 0, 0).await.unwrap();
let writers: Vec<Keys> = (0..4).map(|_| Keys::generate()).collect();
for w in &writers {
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![role.clone()]).await.unwrap();
}
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(role.clone()), Permissions::SEND_MESSAGES, 0).await.unwrap();
// Two lose Send at once: a fresh epoch, whose only part a relay drops for good.
let lossy = LosesOne { inner: &bed.relay, plane: access_group(&held(), &general).pk_hex(), nth: 1, seen: Default::default() };
for w in &writers[..2] {
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, Permissions::SEND_MESSAGES).await;
}
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let before = crate::db::community::get_community_roles(&cid_hex).unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let after = crate::db::community::get_community_roles(&cid_hex).unwrap();
let _ = writing::settle_for_test(&lossy, &held(), &before, &after).await;
let live = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
assert_eq!(live, Epoch(2));
// The minter tops up a writer the Channel gains: untagged, never the mint.
let fresh = Keys::generate();
set_member_roles(&bed.relay, &held(), &fresh.public_key(), vec![role]).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
access_duty(&bed.relay, &held()).await.unwrap();
let scope = crate::community::v2::writers::writer_rekey_scope(&general);
let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
assert!(writers[2..].iter().all(|w| served_at(&plane, &w.public_key(), scope, live, &|_| true)), "those the lost mint carried are served, not cut");
}
#[tokio::test]
async fn taking_back_judges_the_wrap_as_it_came_whatever_its_date_says() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
bed.swap_to(&owner);
let w = Keys::generate();
let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let (e1, _, writer1) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
let cert1 = cert_for(&held(), &general, e1, &w.public_key());
let at1 = GroupKey::from_parts(writer1.keys().clone(), read.conv_key().clone());
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
// w is stopped, then two lose Send at once and a fresh epoch begins; w keeps posting at e1.
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, 0).await.unwrap();
let (y1, y2) = (Keys::generate(), Keys::generate());
let wr = create_role_v2(&bed.relay, &held(), "W", 0, 0).await.unwrap();
for y in [&y1, &y2] {
set_member_roles(&bed.relay, &held(), &y.public_key(), vec![wr.clone()]).await.unwrap();
}
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(wr.clone()), Permissions::SEND_MESSAGES, 0).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(wr), 0, 0).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
assert!(ledger.current_writer().unwrap().0 > e1, "a fresh epoch began");
post_certified(&bed.relay, &held(), &w, &general, &at1, community.root_epoch, Some((e1, Some(cert1))), "at the old address", now_ms() + 2_000).await;
// The member stores it on the ledger it holds, then folds what moved.
bed.swap_to(&member);
let stale = held();
let page = fetch_channel_history(&bed.relay, &stale, &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
for f in page.iter().filter(|f| f.event.opened().rumor.content == "at the old address") {
crate::community::v2::inbound::persist_routed_chat_event(&f.event, &chan_hex, &community.id().0, &member.keys.public_key()).await.expect("stood on the stale ledger");
}
follow_control(&bed.relay, &held()).await.unwrap();
let now_ledger = held().channel(&general).unwrap().writers.clone().unwrap();
let added: Vec<_> = now_ledger.entries.iter().filter(|e| !stale.channel(&general).unwrap().writers.as_ref().unwrap().entries.contains(e)).cloned().collect();
let shown = Shown::default();
writing::retract_after(&bed.relay, &held(), held().channel(&general).unwrap(), &added, &shown).await;
assert!(!channel_texts(&bed.relay, &held(), &general).await.contains(&"at the old address".to_string()));
let ids: Vec<String> = page.iter().filter(|f| f.event.opened().rumor.content == "at the old address").map(|f| f.event.opened().rumor_id.to_hex()).collect();
assert!(crate::db::events::get_message_by_id(&ids[0]).await.unwrap().is_none(), "a stopped writer's post at the old address goes, however late it is dated");
}
#[tokio::test]
async fn a_read_address_rewrite_made_after_the_restrict_is_undone_once_it_is_read() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
let z = Keys::generate();
set_member_roles(&bed.relay, &held(), &z.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
let stale = held();
assert!(!stale.channel(&general).unwrap().restricted());
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
let target_post = chat::build_message_rumor(z.public_key(), &general, community.root_epoch, "z original", None, &[], vec![], now_ms() - 60_000);
let target = target_post.id.unwrap().to_hex();
let (tw, _) = chat::seal_chat_rumor(&target_post, &read, &z, Timestamp::from_secs(now_ms() / 1000 - 60), false).unwrap();
bed.relay.publish(&tw, &held().relays).await.unwrap();
let edit = chat::build_edit_rumor(z.public_key(), &general, community.root_epoch, &target, "z rewritten", &[], None, now_ms() + 2_000);
let (ew, _) = chat::seal_chat_rumor(&edit, &read, &z, Timestamp::from_secs(now_ms() / 1000 + 2), false).unwrap();
bed.relay.publish(&ew, &held().relays).await.unwrap();
bed.swap_to(&member);
let ch = stale.channel(&general).unwrap().clone();
let judge = writing::Judge::of(&stale, &ch);
for wrap in [&tw, &ew] {
let ev = chat::open_chat_event(wrap, &read, &general, community.root_epoch).unwrap();
if let Some(ev) = writing::judge_arrival(judge.as_ref(), &community.id().0, &general, wrap, ev, None) {
crate::community::v2::inbound::persist_routed_chat_event(&ev, &chan_hex, &community.id().0, &member.keys.public_key()).await;
}
}
assert_eq!(crate::db::events::get_message_by_id(&target).await.unwrap().unwrap().1.content, "z rewritten", "stood on the open ledger");
follow_control(&bed.relay, &held()).await.unwrap();
let now_ledger = held().channel(&general).unwrap().writers.clone().unwrap();
let added: Vec<_> = now_ledger.entries.iter().filter(|e| !stale.channel(&general).unwrap().writers.as_ref().map_or(false, |l| l.entries.contains(e))).cloned().collect();
let shown = Shown::default();
writing::retract_after(&bed.relay, &held(), held().channel(&general).unwrap(), &added, &shown).await;
assert_eq!(crate::db::events::get_message_by_id(&target).await.unwrap().unwrap().1.content, "z original", "a non-writer's rewrite after the restrict is undone");
assert_eq!(crate::state::STATE.lock().await.find_message(&target).map(|(_, m)| m.content), Some("z original".to_string()), "on screen too");
}
#[tokio::test]
async fn taking_back_keeps_what_it_has_no_room_to_hold_and_lets_go_what_is_dated_past_the_hour() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
let p = Keys::generate();
post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "soon", now_ms() + 30 * 60_000).await;
post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "far", now_ms() + 2 * 60 * 60_000).await;
// Shown once their time came, read here as a device whose clock has reached them.
crate::clock::shift_for_test(3 * 60 * 60_000);
let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
let mut ids = std::collections::HashMap::new();
for f in page.iter().filter(|f| ["soon", "far"].contains(&f.event.opened().rumor.content.as_str())) {
crate::community::v2::inbound::persist_routed_chat_event(&f.event, &chan_hex, &community.id().0, &member.keys.public_key()).await.expect("stood while open");
ids.insert(f.event.opened().rumor.content.clone(), f.event.opened().rumor_id.to_hex());
}
crate::clock::shift_for_test(0);
assert_eq!(ids.len(), 2);
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
// The Channel's held store is full of posts dated nearer now.
for a in 0..crate::db::community::MAX_HELD_WRAPS / crate::db::community::MAX_HELD_PER_AUTHOR {
let author = Keys::generate().public_key().to_hex();
for i in 0..crate::db::community::MAX_HELD_PER_AUTHOR {
crate::db::community::hold_wrap(&cid_hex, &chan_hex, &format!("{a:02}{i:062}"), "{}", &author, now_ms()).unwrap();
}
}
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
let added = vec![ledger.entries.last().unwrap().clone()];
writing::retract_after(&bed.relay, &held(), held().channel(&general).unwrap(), &added, &Shown::default()).await;
assert!(crate::db::events::get_message_by_id(&ids["soon"]).await.unwrap().is_some(), "with no room to hold it, it stays");
assert!(crate::db::events::get_message_by_id(&ids["far"]).await.unwrap().is_none(), "past the hour the relays keep it until its date nears");
}
/// Fails each event's first send to one plane.
struct FailsFirst<'a> {
inner: &'a MemoryRelay,
plane: String,
tried: std::sync::Mutex<std::collections::HashSet<nostr_sdk::prelude::EventId>>,
}
#[async_trait::async_trait]
impl Transport for FailsFirst<'_> {
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
self.inner.fetch_plane(plane, query, relays).await
}
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
if e.pubkey.to_hex() == self.plane && self.tried.lock().unwrap().insert(e.id) {
return Err("flaked".into());
}
self.inner.publish(e, r).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.publish(e, r).await
}
async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
self.inner.fetch(q, r).await
}
}
#[tokio::test]
async fn a_mint_sends_each_part_again_when_a_send_fails() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
bed.swap_to(&owner);
let role = create_role_v2(&bed.relay, &held(), "Writers", 0, 0).await.unwrap();
let writers: Vec<Keys> = (0..4).map(|_| Keys::generate()).collect();
for w in &writers {
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![role.clone()]).await.unwrap();
}
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(role), Permissions::SEND_MESSAGES, 0).await.unwrap();
let flaky = FailsFirst { inner: &bed.relay, plane: access_group(&held(), &general).pk_hex(), tried: Default::default() };
for w in &writers[..2] {
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, Permissions::SEND_MESSAGES).await;
}
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let before = crate::db::community::get_community_roles(&cid_hex).unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let after = crate::db::community::get_community_roles(&cid_hex).unwrap();
writing::settle_for_test(&flaky, &held(), &before, &after).await.unwrap();
let live = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
let scope = crate::community::v2::writers::writer_rekey_scope(&general);
let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
assert!(writers[2..].iter().all(|w| served_at(&plane, &w.public_key(), scope, live, &|_| true)), "a send that failed once is sent again");
}
#[tokio::test]
async fn a_mint_the_backstop_finds_owed_to_one_writer_only_stops_that_one() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
bed.swap_to(&owner);
let role = create_role_v2(&bed.relay, &held(), "Writers", 0, 0).await.unwrap();
let writers: Vec<Keys> = (0..3).map(|_| Keys::generate()).collect();
for w in &writers {
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![role.clone()]).await.unwrap();
}
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(role), Permissions::SEND_MESSAGES, 0).await.unwrap();
let live = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
// The pass judged two gone; by the backstop only one still is.
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(writers[0].public_key().to_hex()), 0, Permissions::SEND_MESSAGES).await;
follow_control(&bed.relay, &held()).await.unwrap();
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
let cut = [(writers[0].public_key(), writing::Rights::Full), (writers[1].public_key(), writing::Rights::Full)];
writing::backstop_act_on(&bed.relay, &held(), &general, &roster, writing::Act::Mint(&cut)).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
assert_eq!(ledger.current_writer().unwrap().0, live, "one left: a stop, not a fresh epoch");
assert!(ledger.stopped(live, &writers[0].public_key().to_bytes(), u64::MAX));
assert!(!ledger.stopped(live, &writers[1].public_key().to_bytes(), u64::MAX));
}
#[tokio::test]
async fn the_backstop_reads_the_guestbook_again_before_it_stops_anyone() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
bed.swap_to(&owner);
let w = Keys::generate();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let live = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
let leave = guestbook::build_leave_rumor(w.public_key(), now_ms());
let (wrap, _) = guestbook::seal_guestbook_rumor(&leave, &gb, &w, Timestamp::from_secs(now_ms() / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
crate::rt::time::sleep(std::time::Duration::from_millis(1_100)).await;
// They come back after the pass read the Leave.
let join = guestbook::build_join_rumor(w.public_key(), None, now_ms());
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &w, Timestamp::from_secs(now_ms() / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
writing::backstop_act_on(&bed.relay, &held(), &general, &roster, writing::Act::Stop(w.public_key(), writing::Rights::Full)).await.unwrap();
assert!(!held().channel(&general).unwrap().writers.as_ref().unwrap().stopped(live, &w.public_key().to_bytes(), u64::MAX), "a Join since stands it down");
}
#[tokio::test]
async fn a_writer_a_whole_mint_left_out_who_may_post_again_gets_a_fresh_epoch() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
bed.swap_to(&owner);
let role = create_role_v2(&bed.relay, &held(), "Writers", 0, 0).await.unwrap();
let writers: Vec<Keys> = (0..4).map(|_| Keys::generate()).collect();
for w in &writers {
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![role.clone()]).await.unwrap();
}
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(role), Permissions::SEND_MESSAGES, 0).await.unwrap();
for w in &writers[..2] {
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, Permissions::SEND_MESSAGES).await;
}
let before = crate::db::community::get_community_roles(&cid_hex).unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let after = crate::db::community::get_community_roles(&cid_hex).unwrap();
writing::settle_for_test(&bed.relay, &held(), &before, &after).await.unwrap();
let minted = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
// Let back by an edit settled elsewhere: the epoch's whole mint left them out, so nobody may serve them this epoch.
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(writers[0].public_key().to_hex()), 0, 0).await;
follow_control(&bed.relay, &held()).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
access_duty(&bed.relay, &held()).await.unwrap();
let now = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
assert!(now > minted, "a fresh epoch takes them back");
let scope = crate::community::v2::writers::writer_rekey_scope(&general);
let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
assert!(served_at(&plane, &writers[0].public_key(), scope, now, &|_| true));
assert!(!served_at(&plane, &writers[1].public_key(), scope, now, &|_| true));
}
#[tokio::test]
async fn edits_made_within_one_second_fold_in_the_order_they_were_made() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Edits", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
let z = Keys::generate();
let second = (now_ms() / 1000 - 30) * 1000;
let post = chat::build_message_rumor(z.public_key(), &general, community.root_epoch, "first", None, &[], vec![], second - 5_000);
let target = post.id.unwrap().to_hex();
let edits = [("third", 900), ("second", 100)].map(|(text, ms)| chat::build_edit_rumor(z.public_key(), &general, community.root_epoch, &target, text, &[], None, second + ms));
for rumor in std::iter::once(&post).chain(edits.iter()) {
let (wrap, _) = chat::seal_chat_rumor(rumor, &read, &z, Timestamp::from_secs(second / 1000), false).unwrap();
let opened = chat::open_chat_event(&wrap, &read, &general, community.root_epoch).unwrap();
crate::community::v2::inbound::persist_routed_chat_event(&opened, &chan_hex, &community.id().0, &owner.keys.public_key()).await.expect("stored");
}
let (_, message) = crate::db::events::get_message_by_id(&target).await.unwrap().unwrap();
assert_eq!(message.content, "third", "the later edit wins whichever arrived last");
}
#[tokio::test]
async fn a_stop_any_read_folds_is_owed_its_retraction() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let (cid_hex, chan_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
bed.swap_to(&owner);
let w = Keys::generate();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
clear_owed(&cid_hex);
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, 0).await.unwrap();
let stop_at = held().channel(&general).unwrap().writers.as_ref().unwrap().entries.last().unwrap().at;
// A backstop's read of the Control Plane, not the live follow, is what folds it here.
bed.swap_to(&member);
follow_fresh(&bed.relay, community.id()).await.unwrap();
let owed = crate::db::community::owed_author_retractions(&cid_hex).unwrap();
assert_eq!(owed.iter().map(|(c, a, s, ..)| (c.clone(), a.clone(), *s)).collect::<Vec<_>>(), vec![(chan_hex.clone(), w.public_key().to_hex(), stop_at)], "a stop owes its writer's posts alone");
assert!(crate::db::community::owed_retractions(&cid_hex).unwrap().is_empty());
// What is owed while a drain runs survives its clear.
let author = w.public_key().to_hex();
crate::db::community::owe_author_retraction(&cid_hex, &chan_hex, &author, stop_at + 1, None).unwrap();
crate::db::community::settle_author_retraction(&cid_hex, &chan_hex, &author, owed[0].2, owed[0].3, owed[0].4).unwrap();
assert_eq!(crate::db::community::owed_author_retractions(&cid_hex).unwrap().len(), 1);
}
#[tokio::test]
async fn a_page_stored_after_its_ledger_moved_owes_a_retraction() {
let (_bed, _owner, _member, community, general) = restricted_bed(false).await;
let (cid_hex, chan_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
clear_owed(&cid_hex);
let judged_on = writing::writers_head(&chan_hex).unwrap();
writing::owe_if_moved(&chan_hex, Some(judged_on.clone()), 5_000);
assert!(crate::db::community::owed_retractions(&cid_hex).unwrap().is_empty(), "judged on the ledger it landed under");
// A move that only reopens takes nothing back.
let ledger = crate::community::v2::writers::Ledger::parse(&judged_on).unwrap();
let reopened = ledger.appended(now_ms(), crate::community::v2::writers::Spell::Open).unwrap();
crate::db::community::set_community_writers(&cid_hex, &chan_hex, &reopened.to_json(), 99, true).unwrap();
writing::owe_if_moved(&chan_hex, Some(judged_on.clone()), 5_000);
assert!(crate::db::community::owed_retractions(&cid_hex).unwrap().is_empty(), "an open owes nothing");
// A stop owes from its own entry, never from a post's earlier date.
let stop_at = now_ms() + 1;
let stopped_writer = Keys::generate().public_key();
let stopped = ledger.appended(stop_at, crate::community::v2::writers::Spell::Stop { writer: stopped_writer.to_bytes() }).unwrap();
crate::db::community::set_community_writers(&cid_hex, &chan_hex, &stopped.to_json(), 100, true).unwrap();
clear_owed(&cid_hex);
writing::owe_if_moved(&chan_hex, Some(judged_on), 5_000);
assert_eq!(crate::db::community::owed_author_retractions(&cid_hex).unwrap().iter().map(|(c, a, s, ..)| (c.clone(), a.clone(), *s)).collect::<Vec<_>>(), vec![(chan_hex, stopped_writer.to_hex(), stop_at)]);
}
#[tokio::test]
async fn an_edition_no_reader_folds_never_holds_a_mint_back() {
use crate::community::roles::OverwriteTarget;
use crate::community::v2::writers::Spell;
let (bed, owner, x, community) = v2_bed_with_admin("Orphaned").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
let theirs = held().channel(&general).unwrap().writers.clone().unwrap().appended(now_ms(), Spell::Open).unwrap();
// Built on a sibling every reader refuses: nothing folds it.
let cite = cite_on_relay(&bed.relay, &held(), &x).await;
let rumor = control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, 3, Some(&[7u8; 32]), &theirs.to_json(), now_ms() / 1000, cite.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())));
let group = control::ControlPlane::of(&held()).write_group().unwrap();
let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(now_ms() / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
act_as(&owner.keys);
let roster = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
let before = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
writing::mint_for_test(&bed.relay, &held(), &general, &roster).await.unwrap();
assert!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0 > before);
}
#[tokio::test]
async fn a_sibling_that_wins_the_tie_over_the_held_head_holds_a_mint_back() {
use crate::community::roles::OverwriteTarget;
use crate::community::v2::writers::{Ledger, Spell};
let (bed, owner, x, community) = v2_bed_with_admin("Sibling").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
let mine = crate::db::community::get_edition_head_inner_id(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&eid)).unwrap().unwrap();
let cite = cite_on_relay(&bed.relay, &held(), &x).await;
// x restricted it at the same moment: a first edition of its own, ground until it sorts ahead.
let secs = now_ms() / 1000;
let rumor = (0..1000u64)
.map(|i| {
let (secret, certifying) = (crate::community::random_32(), crate::community::random_32());
let spell = Spell::Writer { epoch: Epoch(1), pk: crate::community::v2::writers::writer_address(&secret, &general, Epoch(1)), root: community.root_epoch, by: x.public_key().to_bytes(), certifier: crate::community::v2::writers::certifier_of(&certifying) };
let theirs = Ledger::new(&general).appended(secs * 1000 + i, spell).unwrap();
control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, 1, None, &theirs.to_json(), secs, cite.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())))
})
.find(|r| r.id.unwrap().to_bytes() < mine)
.unwrap();
let group = control::ControlPlane::of(&held()).write_group().unwrap();
let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(secs)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
act_as(&owner.keys);
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert_eq!(writing::mint_for_test(&bed.relay, &held(), &general, &roster).await, Err(writing::LEDGER_MOVED_FOR_TEST.to_string()));
}
#[tokio::test]
async fn a_manager_who_left_posts_nothing_that_stands_whatever_role_lingers() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
bed.swap_to(&owner);
let w = Keys::generate();
let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain.clone()]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let live = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
// Promoted, then gone before anyone handed them the certifier.
let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain, mods]).await.unwrap();
let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
let leave = guestbook::build_leave_rumor(w.public_key(), now_ms());
let (wrap, _) = guestbook::seal_guestbook_rumor(&leave, &gb, &w, Timestamp::from_secs(now_ms() / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
let (_, _, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let cert = cert_for(&held(), &general, live, &w.public_key());
let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "after leaving", now_ms() + 2_000).await;
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
assert!(!channel_texts(&bed.relay, &held(), &general).await.contains(&"after leaving".to_string()), "one who left is no manager, whatever a Role still says");
}
#[tokio::test]
async fn a_mint_reads_the_memberlist_whole_before_it_leaves_anyone_out() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Unread", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
// A writer by their own overwrite, whose Join only the relays hold so far.
let w = Keys::generate();
let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
let join = guestbook::build_join_rumor(w.public_key(), None, now_ms());
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &w, Timestamp::from_secs(now_ms() / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
let live = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
let scope = crate::community::v2::writers::writer_rekey_scope(&general);
let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
assert!(served_at(&plane, &w.public_key(), scope, live, &|_| true), "the mint read the Guestbook whole first");
}
#[tokio::test]
async fn letting_back_a_writer_the_whole_mint_left_out_takes_a_fresh_epoch() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
bed.swap_to(&owner);
let role = create_role_v2(&bed.relay, &held(), "Writers", 0, 0).await.unwrap();
let writers: Vec<Keys> = (0..4).map(|_| Keys::generate()).collect();
for w in &writers {
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![role.clone()]).await.unwrap();
}
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(role), Permissions::SEND_MESSAGES, 0).await.unwrap();
for w in &writers[..2] {
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, Permissions::SEND_MESSAGES).await;
}
let before = crate::db::community::get_community_roles(&cid_hex).unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let after = crate::db::community::get_community_roles(&cid_hex).unwrap();
writing::settle_for_test(&bed.relay, &held(), &before, &after).await.unwrap();
let minted = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(writers[0].public_key().to_hex()), 0, 0).await.unwrap();
let now = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
assert!(now > minted, "the change itself mints them back in");
let scope = crate::community::v2::writers::writer_rekey_scope(&general);
let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
assert!(!served_at(&plane, &writers[0].public_key(), scope, minted, &|_| true), "never handed the epoch that left them out");
assert!(served_at(&plane, &writers[0].public_key(), scope, now, &|_| true));
}
#[tokio::test]
async fn a_refounding_starts_the_memberlist_read_again() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Read again", bed.relays.clone(), None).await.unwrap();
while !guestbook_walked_this_session(&community) {
sync_guestbook(&bed.relay, &community).await.unwrap();
}
let gb = crate::community::v2::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let mut moved = community.clone();
moved.root_epoch = Epoch(community.root_epoch.0 + 1);
assert_ne!(crate::community::v2::derive::guestbook_group_key(&moved.community_root, moved.id(), moved.root_epoch).pk(), gb.pk());
assert!(!guestbook_walked_this_session(&moved), "a new plane is read whole again");
}
#[tokio::test]
async fn an_edit_at_a_writer_address_is_no_sign_of_presence() {
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
bed.swap_to(&owner);
let (e1, _, writer1) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
let at1 = GroupKey::from_parts(writer1.keys().clone(), read.conv_key().clone());
// A key handed to someone who never joined.
let w = Keys::generate();
let post = chat::with_writer_epoch(chat::build_message_rumor(w.public_key(), &general, community.root_epoch, "at the writer address", None, &[], vec![], now_ms()), e1);
let target = post.id.unwrap().to_hex();
let edit = chat::with_writer_epoch(chat::build_edit_rumor(w.public_key(), &general, community.root_epoch, &target, "edited there", &[], None, now_ms() + 1_000), e1);
bed.swap_to(&member);
for rumor in [&post, &edit] {
let (wrap, _) = chat::seal_chat_rumor(rumor, &at1, &w, Timestamp::from_secs(now_ms() / 1000), false).unwrap();
let opened = chat::open_writer_chat_event(&wrap, &wrap.pubkey, e1, read.conv_key(), &general, community.root_epoch).unwrap();
crate::community::v2::inbound::persist_routed_chat_event(&opened, &chan_hex, &community.id().0, &member.keys.public_key()).await.expect("stored");
}
assert_eq!(crate::db::events::get_message_by_id(&target).await.unwrap().unwrap().1.content, "edited there");
assert!(!stored_memberlist_strict(&held()).unwrap().contains(&w.public_key()), "neither the post nor its edit there is a sign of presence");
}
#[tokio::test]
async fn a_managers_copy_of_a_post_dated_past_the_hour_goes_rather_than_waits_flagged() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(true).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
let p = Keys::generate();
post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "far", now_ms() + 2 * 60 * 60_000).await;
// Shown once its time came, read here as a device whose clock has reached it.
crate::clock::shift_for_test(3 * 60 * 60_000);
let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
let far = page.iter().find(|f| f.event.opened().rumor.content == "far").unwrap();
crate::community::v2::inbound::persist_routed_chat_event(&far.event, &chan_hex, &community.id().0, &member.keys.public_key()).await.expect("stood while open");
crate::clock::shift_for_test(0);
let id = far.event.opened().rumor_id.to_hex();
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
writing::retract_since(&bed.relay, &held(), held().channel(&general).unwrap(), ledger.entries.last().unwrap().at, &Shown::default()).await.unwrap();
assert!(crate::db::events::get_message_by_id(&id).await.unwrap().is_none(), "no flag without a held wrap: the relays keep it until its date nears");
}
#[tokio::test]
async fn a_post_at_an_address_the_ledger_names_nowhere_is_taken_back() {
let (bed, _owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
bed.swap_to(&member);
let elsewhere = channel_group_key(&[9u8; 32], &general, community.root_epoch);
let at = now_ms();
let mut ids = Vec::new();
// One that came to a writer address the ledger no longer names, one this device has no key for.
for (i, writer) in [(0u8, true), (1, false)] {
let author = Keys::generate();
let rumor = chat::build_message_rumor(author.public_key(), &general, community.root_epoch, "sealed elsewhere", None, &[], vec![], at + i as u64);
let (wrap, _) = chat::seal_chat_rumor(&rumor, &elsewhere, &author, Timestamp::from_secs(at / 1000), false).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
let msg = crate::types::Message {
id: format!("{i:x}").repeat(64),
content: "unreadable here".into(),
at: at + i as u64,
npub: Some(nostr_sdk::prelude::ToBech32::to_bech32(&author.public_key()).unwrap()),
wrapper_event_id: Some(wrap.id.to_hex()),
writer,
..Default::default()
};
crate::db::events::save_message(&chan_hex, &msg).await.unwrap();
ids.push(msg.id);
}
writing::retract_since(&bed.relay, &held(), held().channel(&general).unwrap(), at - 1_000, &Shown::default()).await.unwrap();
assert!(crate::db::events::get_message_by_id(&ids[0]).await.unwrap().is_none(), "a writer-address post the ledger names nowhere stands nowhere");
assert!(crate::db::events::get_message_by_id(&ids[1]).await.unwrap().is_some(), "one without its key stays");
}
#[tokio::test]
async fn a_retraction_whose_reads_fail_leaves_the_rest_owed() {
let (bed, _owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
bed.swap_to(&member);
let msg = crate::types::Message { id: "e".repeat(64), content: "owed".into(), at: now_ms(), npub: Some(nostr_sdk::prelude::ToBech32::to_bech32(&Keys::generate().public_key()).unwrap()), wrapper_event_id: Some("d".repeat(64)), ..Default::default() };
crate::db::events::save_message(&chan_hex, &msg).await.unwrap();
let down = FetchErrors(MemoryRelay::new());
assert!(writing::retract_since(&down, &held(), held().channel(&general).unwrap(), msg.at - 1, &Shown::default()).await.is_err(), "a read that failed is no answer");
assert_eq!(writing::retract_since(&NoIds(&bed.relay), &held(), held().channel(&general).unwrap(), msg.at - 1, &Shown::default()).await, Ok(0), "answered without it: done");
}
#[tokio::test]
async fn a_banned_managers_edition_never_holds_a_mint_back() {
use crate::community::roles::OverwriteTarget;
use crate::community::v2::writers::Spell;
let (bed, owner, x, community) = v2_bed_with_admin("Banned").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
// Banned, with the Grant still standing.
set_banlist(&bed.relay, &held(), &[x.public_key().to_hex()]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
let (v, head) = crate::db::community::get_edition_head(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&eid)).unwrap().unwrap();
let theirs = held().channel(&general).unwrap().writers.clone().unwrap().appended(now_ms(), Spell::Open).unwrap();
let cite = cite_on_relay(&bed.relay, &held(), &x).await;
let rumor = control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, v + 1, Some(&head), &theirs.to_json(), now_ms() / 1000, cite.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())));
let group = control::ControlPlane::of(&held()).write_group().unwrap();
let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(now_ms() / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
act_as(&owner.keys);
let before = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
writing::mint_for_test(&bed.relay, &held(), &general, &roster).await.unwrap();
assert!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0 > before, "an edition every reader refuses moves nothing");
}
/// Answers each read after a pause, as a slow relay does.
struct Paused<'a>(&'a MemoryRelay);
#[async_trait::async_trait]
impl Transport for Paused<'_> {
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
crate::rt::time::sleep(std::time::Duration::from_millis(50)).await;
self.0.fetch_plane(plane, query, relays).await
}
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.0.publish(e, r).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.0.publish_durable(e, r).await
}
async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
crate::rt::time::sleep(std::time::Duration::from_millis(50)).await;
self.0.fetch(q, r).await
}
}
#[tokio::test]
async fn two_guestbook_reads_at_once_both_keep_what_they_found() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Two reads", bed.relays.clone(), None).await.unwrap();
let gb = crate::community::v2::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
// Each relay holds a Join the other doesn't.
let other = MemoryRelay::new();
let (a, b) = (Keys::generate(), Keys::generate());
for (relay, k) in [(&bed.relay, &a), (&other, &b)] {
let join = guestbook::build_join_rumor(k.public_key(), None, now_ms());
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, k, Timestamp::from_secs(now_ms() / 1000)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
let (first, second) = (Paused(&bed.relay), Paused(&other));
let (one, two) = tokio::join!(sync_guestbook(&first, &community), sync_guestbook(&second, &community));
one.unwrap();
two.unwrap();
let (events, _) = crate::db::community::get_guestbook(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
let joined = |k: &Keys| events.iter().any(|e| matches!(e.entry, guestbook::GuestbookEntry::Join { member, .. } if member == k.public_key()));
assert!(joined(&a) && joined(&b), "neither write drops what the other stored");
}
#[tokio::test]
async fn a_manager_whose_grant_sits_past_a_page_still_moves_the_ledger() {
use crate::community::roles::OverwriteTarget;
use crate::community::v2::writers::Spell;
let (bed, owner, x, community) = v2_bed_with_admin("Buried").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
let cite = cite_on_relay(&bed.relay, &held(), &x).await;
// A page's worth of editions nobody folds, newer than the admin's Grant, a second apart (a
// flood inside one second is a wall no read steps past, and reads as short).
let group = control::ControlPlane::of(&held()).write_group().unwrap();
let binding = Some(crate::community::v2::derive::edition_binding(community.id()));
let base = now_ms() / 1000;
for i in 0..600u32 {
let mut eid = [0u8; 32];
eid[..4].copy_from_slice(&i.to_be_bytes());
let at = base + 1 + i as u64;
let rumor = control::build_edition_rumor_bound(owner.keys.public_key(), "99", &eid, 1, None, "{}", at, None, binding);
let (wrap, _) = control::seal_control_edition(&rumor, &group, &owner.keys, Timestamp::from_secs(at)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
}
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
let (v, head) = crate::db::community::get_edition_head(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&eid)).unwrap().unwrap();
let theirs = held().channel(&general).unwrap().writers.clone().unwrap().appended(now_ms(), Spell::Open).unwrap();
let rumor = control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, v + 1, Some(&head), &theirs.to_json(), now_ms() / 1000, cite.as_ref(), binding);
let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(now_ms() / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
act_as(&owner.keys);
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert_eq!(writing::mint_for_test(&bed.relay, &held(), &general, &roster).await, Err(writing::LEDGER_MOVED_FOR_TEST.to_string()), "read as deep as a follow, the admin's edition is seen");
}
#[test]
fn a_fork_switch_owes_from_what_it_dropped() {
use crate::community::v2::writers::{Ledger, Spell};
let ch = ChannelId([4; 32]);
let w = Keys::generate().public_key().to_bytes();
let writer = Spell::Writer { epoch: Epoch(1), pk: crate::community::v2::writers::writer_address(&[1; 32], &ch, Epoch(1)), root: Epoch(0), by: w, certifier: None };
let base = Ledger::new(&ch).appended(1_000, writer).unwrap();
let losing = base.appended(2_000, Spell::Open).unwrap();
let winning = base.appended(2_500, Spell::Stop { writer: w }).unwrap();
assert_eq!(crate::db::community::retraction_since(Some(&losing.to_json()), &winning.to_json()), Some(2_000), "the open the switch dropped admitted posts from 2_000");
assert_eq!(crate::db::community::retraction_since(Some(&base.to_json()), &winning.to_json()), None, "a stop is its writer's alone");
assert_eq!(crate::db::community::stop_owes(Some(&base.to_json()), &winning.to_json()), vec![(w, 2_500)]);
assert_eq!(crate::db::community::retraction_since(Some(&base.to_json()), &losing.to_json()), None, "an open added takes nothing back");
let dated = base.appended_from(3_000, Spell::Stop { writer: w }, Some(1_500)).unwrap();
assert_eq!(crate::db::community::stop_owes(Some(&base.to_json()), &dated.to_json()), vec![(w, 1_500)], "a stop that records a departure owes from it");
}
#[tokio::test]
async fn a_leave_arriving_live_owes_only_that_members_posts() {
let (_bed, _owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let (cid_hex, chan_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
let (w, stranger) = (Keys::generate(), Keys::generate());
let at = now_ms();
let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Join { member: w.public_key(), invited_by: None, at_ms: at - 5_000 }), at / 1000 - 5).unwrap();
let shown = crate::types::Message { id: "a".repeat(64), content: "since".into(), at: at + 1_000, npub: Some(nostr_sdk::prelude::ToBech32::to_bech32(&w.public_key()).unwrap()), wrapper_event_id: Some("b".repeat(64)), writer: true, ..Default::default() };
crate::db::events::save_message(&chan_hex, &shown).await.unwrap();
clear_owed(&cid_hex);
// A Leave from a key that never posted, dated as early as it likes, owes nothing.
ingest_guestbook_event(&held(), event(2, guestbook::GuestbookEntry::Leave { member: stranger.public_key(), at_ms: 1 }), at / 1000).unwrap();
assert!(crate::db::community::owed_author_retractions(&cid_hex).unwrap().is_empty());
ingest_guestbook_event(&held(), event(3, guestbook::GuestbookEntry::Leave { member: w.public_key(), at_ms: at }), at / 1000).unwrap();
assert_eq!(crate::db::community::owed_author_retractions(&cid_hex).unwrap().iter().map(|(c, a, s, ..)| (c.clone(), a.clone(), *s)).collect::<Vec<_>>(), vec![(chan_hex, w.public_key().to_hex(), at)]);
assert!(crate::db::community::owed_retractions(&cid_hex).unwrap().is_empty(), "nobody else's posts are read again");
clear_owed(&cid_hex);
owe_new_departures(&held());
assert!(crate::db::community::owed_author_retractions(&cid_hex).unwrap().is_empty(), "a departure is owed once");
}
#[tokio::test]
async fn a_kick_holds_its_date_whatever_leave_follows_and_a_join_ends_it() {
let (_bed, _owner, _member, community, _general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let owner_pk = community.owner().unwrap();
let w = Keys::generate();
let at = now_ms();
let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Join { member: w.public_key(), invited_by: None, at_ms: at - 60_000 }), at / 1000 - 60).unwrap();
ingest_guestbook_event(&held(), event(2, guestbook::GuestbookEntry::Kick { actor: owner_pk, target: w.public_key(), citation: None, at_ms: at - 50_000 }), at / 1000 - 50).unwrap();
// Their own Leave dated later never moves the Kick.
ingest_guestbook_event(&held(), event(3, guestbook::GuestbookEntry::Leave { member: w.public_key(), at_ms: at + 50 * 60_000 }), at / 1000).unwrap();
let away = stored_departure_windows(&held());
assert_eq!(away.get(&w.public_key()).map(|s| s.to_vec()), Some(vec![(at - 50_000, None, true)]));
ingest_guestbook_event(&held(), event(4, guestbook::GuestbookEntry::Join { member: w.public_key(), invited_by: None, at_ms: at - 10_000 }), at / 1000 - 10).unwrap();
let away = stored_departure_windows(&held());
assert_eq!(away.get(&w.public_key()).map(|w| w[0]), Some((at - 50_000, Some(at - 10_000), true)), "a Join ends the span, it doesn't erase it");
}
#[tokio::test]
async fn a_kick_that_stands_only_once_its_kicker_is_read_is_owed_then() {
let (bed, owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let (cid_hex, chan_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
bed.swap_to(&owner);
let (m, w) = (Keys::generate(), Keys::generate());
let at = now_ms();
let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Join { member: w.public_key(), invited_by: None, at_ms: at - 60_000 }), at / 1000 - 60).unwrap();
let shown = crate::types::Message { id: "a".repeat(64), content: "since".into(), at: at + 1_000, npub: Some(nostr_sdk::prelude::ToBech32::to_bech32(&w.public_key()).unwrap()), wrapper_event_id: Some("b".repeat(64)), writer: true, ..Default::default() };
crate::db::events::save_message(&chan_hex, &shown).await.unwrap();
// A Kick from one who may kick only once a Role edit this device hasn't read lands.
let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(), &m.public_key(), vec![mods.clone()]).await.unwrap();
let citation = required_authority_citation(&held(), &m.public_key()).unwrap();
ingest_guestbook_event(&held(), event(2, guestbook::GuestbookEntry::Kick { actor: m.public_key(), target: w.public_key(), citation, at_ms: at }), at / 1000).unwrap();
clear_owed(&cid_hex);
assert!(crate::db::community::owed_author_retractions(&cid_hex).unwrap().is_empty());
edit_role_v2(&bed.relay, &held(), &mods, "Mods", 0, Permissions::KICK, false, false).await.unwrap();
owe_new_departures(&held());
assert_eq!(crate::db::community::owed_author_retractions(&cid_hex).unwrap().iter().map(|(c, a, s, ..)| (c.clone(), a.clone(), *s)).collect::<Vec<_>>(), vec![(chan_hex, w.public_key().to_hex(), at)], "the follow that reads the kicker owes it");
}
#[tokio::test]
async fn a_refounding_stops_its_kicked_writers_from_when_they_were_kicked() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
bed.swap_to(&owner);
let w = Keys::generate();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let live = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
let left_at = now_ms();
let kick = guestbook::build_kick_rumor(owner.keys.public_key(), w.public_key(), None, left_at);
let (wrap, _) = guestbook::seal_guestbook_rumor(&kick, &gb, &owner.keys, Timestamp::from_secs(left_at / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
// They post on after leaving; this device holds what it can't stand behind.
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let (_, _, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
let cert = cert_for(&held(), &general, live, &w.public_key());
let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "after leaving", left_at + 500).await;
channel_texts(&bed.relay, &held(), &general).await;
assert!(crate::db::community::holds_wraps_at(&crate::simd::hex::bytes_to_hex_32(&community.id().0), &crate::simd::hex::bytes_to_hex_32(&general.0), &w.public_key().to_hex(), &writer.pk().to_bytes()));
crate::rt::time::sleep(std::time::Duration::from_millis(1_100)).await;
refound_community(&bed.relay, &held(), &[]).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
assert!(ledger.current_writer().unwrap().0 > live, "the Refounding re-minted");
assert!(ledger.stopped(live, &w.public_key().to_bytes(), left_at), "a reader who never reads the old Guestbook still sees them stopped from when they left");
assert!(!ledger.stopped(live, &w.public_key().to_bytes(), left_at - 1));
}
#[tokio::test]
async fn a_page_stored_after_a_departure_owes_that_members_posts() {
let (_bed, _owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let (cid_hex, chan_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
let (w, stayer) = (Keys::generate(), Keys::generate());
let at = now_ms();
let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Join { member: w.public_key(), invited_by: None, at_ms: at - 5_000 }), at / 1000 - 5).unwrap();
ingest_guestbook_event(&held(), event(2, guestbook::GuestbookEntry::Leave { member: w.public_key(), at_ms: at }), at / 1000).unwrap();
clear_owed(&cid_hex);
writing::owe_if_departed(&chan_hex, &[(w.public_key(), at - 1_000), (stayer.public_key(), at + 1_000)]);
assert!(crate::db::community::owed_author_retractions(&cid_hex).unwrap().is_empty(), "posted while here, or by one who stayed");
writing::owe_if_departed(&chan_hex, &[(w.public_key(), at + 1_000)]);
assert_eq!(crate::db::community::owed_author_retractions(&cid_hex).unwrap().iter().map(|(c, a, s, ..)| (c.clone(), a.clone(), *s)).collect::<Vec<_>>(), vec![(chan_hex, w.public_key().to_hex(), at + 1_000)]);
}
#[tokio::test]
async fn departure_spans_are_folded_once_per_change() {
let (_bed, _owner, _member, community, _general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let first = stored_departure_windows(&held());
assert!(std::sync::Arc::ptr_eq(&first, &stored_departure_windows(&held())), "judging a post folds nothing again");
let w = Keys::generate();
let leave = guestbook::GuestbookEvent { rumor_id: [7; 32], entry: guestbook::GuestbookEntry::Leave { member: w.public_key(), at_ms: now_ms() }, epoch: Some(held().root_epoch.0), observed_at: None };
ingest_guestbook_event(&held(), leave, now_ms() / 1000).unwrap();
assert!(stored_departure_windows(&held()).contains_key(&w.public_key()), "a Guestbook write refolds");
}
#[tokio::test]
async fn a_guestbook_entry_that_moves_no_departure_keeps_the_folded_spans() {
let (_bed, _owner, _member, community, _general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let at = now_ms();
let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
let (gone, stayer, fresh) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Join { member: gone, invited_by: None, at_ms: at - 10_000 }), at / 1000).unwrap();
ingest_guestbook_event(&held(), event(2, guestbook::GuestbookEntry::Leave { member: gone, at_ms: at - 5_000 }), at / 1000).unwrap();
ingest_guestbook_event(&held(), event(3, guestbook::GuestbookEntry::Join { member: stayer, invited_by: None, at_ms: at - 4_000 }), at / 1000).unwrap();
let folded = stored_departure_windows(&held());
ingest_guestbook_event(&held(), event(4, guestbook::GuestbookEntry::Join { member: fresh, invited_by: None, at_ms: at - 3_000 }), at / 1000).unwrap();
let carried = stored_departure_windows(&held());
assert!(std::sync::Arc::ptr_eq(&folded, &carried), "a newcomer's Join opens or closes nothing");
departure_cache().lock().unwrap().clear();
assert_eq!(*carried, *stored_departure_windows(&held()), "what was carried is what a fold from scratch finds");
ingest_guestbook_event(&held(), event(5, guestbook::GuestbookEntry::Join { member: gone, invited_by: None, at_ms: at - 1_000 }), at / 1000).unwrap();
let back = stored_departure_windows(&held());
assert_eq!(back.get(&gone).map(|s| s.to_vec()), Some(vec![(at - 5_000, Some(at - 1_000), false)]), "a departed member's Join closes their span");
departure_cache().lock().unwrap().clear();
assert_eq!(*back, *stored_departure_windows(&held()));
}
#[tokio::test]
async fn folded_spans_are_not_carried_over_a_write_they_did_not_judge() {
let (_bed, _owner, _member, community, _general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let at = now_ms();
let join = guestbook::GuestbookEvent { rumor_id: [9; 32], entry: guestbook::GuestbookEntry::Join { member: Keys::generate().public_key(), invited_by: None, at_ms: at }, epoch: Some(held().root_epoch.0), observed_at: None };
let folded = stored_departure_windows(&held());
let after = departures_after(&cid_hex, [&join.entry]);
assert!(matches!(&after, DeparturesAfter::Members(_, moved) if moved.is_empty()), "a newcomer's Join moves nothing");
crate::db::community::bump_membership_generation();
crate::db::community::store_guestbook_events(&cid_hex, std::slice::from_ref(&join), at / 1000).unwrap();
departures_stored(&held(), &cid_hex, after, [at]);
assert!(!std::sync::Arc::ptr_eq(&folded, &stored_departure_windows(&held())), "a write landing in between is folded");
// Nor windows some slower fold put back, read before the generation the Join was judged at.
let join = guestbook::GuestbookEvent { rumor_id: [10; 32], ..join };
let DeparturesAfter::Members(judged, _) = departures_after(&cid_hex, [&join.entry]) else { panic!("a newcomer's Join moves nothing") };
let stale = std::sync::Arc::new(DepartureSpans::from([(Keys::generate().public_key(), vec![(1, None, false)].into())]));
departure_cache().lock().unwrap().insert(cid_hex.clone(), HeldDepartures { generation: judged - 1, spans: stale.clone(), due: None });
crate::db::community::store_guestbook_events(&cid_hex, std::slice::from_ref(&join), at / 1000).unwrap();
departures_stored(&held(), &cid_hex, DeparturesAfter::Members(judged, Vec::new()), [at]);
assert!(!std::sync::Arc::ptr_eq(&stale, &stored_departure_windows(&held())));
}
#[tokio::test]
async fn departure_windows_kept_across_writes_match_a_fold_from_scratch() {
let (_bed, owner, _member, community, _general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let pool: Vec<PublicKey> = (0..5).map(|_| Keys::generate().public_key()).collect();
let stranger = Keys::generate().public_key();
let base = now_ms() - 100_000;
let mut seed = 0x2545_f491_4f6c_dd1du64;
let mut next = move |n: u64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed % n
};
let mut event = |i: u32| {
let member = pool[next(5) as usize];
// Few distinct times, so ties are common; some too far ahead to count yet.
let at_ms = if next(12) == 0 { now_ms() + guestbook::MAX_FUTURE_MS + 60_000 + next(1_000) } else { base + next(40) * 1_000 };
let entry = match next(6) {
0 | 1 => guestbook::GuestbookEntry::Join { member, invited_by: None, at_ms },
2 => guestbook::GuestbookEntry::Leave { member, at_ms },
3 => guestbook::GuestbookEntry::Kick { actor: owner.keys.public_key(), target: member, citation: None, at_ms },
4 => guestbook::GuestbookEntry::Kick { actor: stranger, target: member, citation: None, at_ms },
_ => guestbook::GuestbookEntry::Nickname { actor: member, target: member, nick: "n".into(), citation: None, at_ms },
};
let mut rumor_id = [next(256) as u8; 32];
rumor_id[..4].copy_from_slice(&i.to_le_bytes());
(guestbook::GuestbookEvent { rumor_id, entry, epoch: Some(held().root_epoch.0), observed_at: None }, next(12) as u32 + 1)
};
for i in 0..300u32 {
ingest_guestbook_event(&held(), event(i).0, now_ms() / 1000).unwrap();
let c = held();
assert_eq!(*stored_departure_windows(&c), fold_departure_windows(&c, &cid_hex).0, "after write {i}");
}
// A walk stores a batch at once.
let mut i = 300u32;
for round in 0..60 {
let size = event(0).1;
let batch: Vec<_> = (0..size).map(|_| { i += 1; event(i).0 }).collect();
store_guestbook_and_departures(&held(), &cid_hex, &batch, now_ms() / 1000).unwrap();
let c = held();
assert_eq!(*stored_departure_windows(&c), fold_departure_windows(&c, &cid_hex).0, "after batch {round}");
}
assert!(stored_departure_windows(&held()).values().any(|w| w.iter().any(|s| s.2)), "an honoured Kick was folded");
}
#[tokio::test]
async fn an_entry_too_far_ahead_brought_over_is_due_later() {
let (_bed, _owner, _member, community, _general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
let folded = stored_departure_windows(&held());
assert_eq!(departure_cache().lock().unwrap()[&cid_hex].due, None);
let ahead = now_ms() + guestbook::MAX_FUTURE_MS + 60_000;
ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Join { member: Keys::generate().public_key(), invited_by: None, at_ms: ahead }), now_ms() / 1000).unwrap();
assert!(std::sync::Arc::ptr_eq(&folded, &stored_departure_windows(&held())));
assert_eq!(departure_cache().lock().unwrap()[&cid_hex].due, Some(ahead), "folded again once it is due");
let sooner = ahead - 1_000;
let batch = [event(2, guestbook::GuestbookEntry::Join { member: Keys::generate().public_key(), invited_by: None, at_ms: now_ms() }), event(3, guestbook::GuestbookEntry::Join { member: Keys::generate().public_key(), invited_by: None, at_ms: sooner })];
store_guestbook_and_departures(&held(), &cid_hex, &batch, now_ms() / 1000).unwrap();
assert_eq!(departure_cache().lock().unwrap()[&cid_hex].due, Some(sooner), "whichever entry of a batch comes due first");
}
#[tokio::test]
async fn the_owed_record_lets_go_of_members_the_windows_no_longer_hold() {
let (_bed, _owner, _member, community, _general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let at = now_ms();
let w = Keys::generate().public_key();
let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Join { member: w, invited_by: None, at_ms: at - 5_000 }), at / 1000).unwrap();
ingest_guestbook_event(&held(), event(2, guestbook::GuestbookEntry::Leave { member: w, at_ms: at - 1_000 }), at / 1000).unwrap();
// Ahead of every member in key order, then behind them all.
for extra in [[0u8; 32], [0xff; 32]] {
let mut seen = (*stored_departure_windows(&held())).clone();
seen.insert(PublicKey::from_byte_array(extra), vec![(1, None, false)].into());
crate::db::community::set_departures_seen(&cid_hex, std::sync::Arc::new(seen)).unwrap();
owe_new_departures(&held());
assert_eq!(*crate::db::community::departures_seen(&cid_hex).unwrap().spans, *stored_departure_windows(&held()));
}
}
#[tokio::test]
async fn a_nickname_or_timeout_write_folds_no_departure_again() {
let (bed, owner, member, community, _general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
bed.swap_to(&owner);
let at = now_ms();
let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
let gone = Keys::generate().public_key();
ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Leave { member: gone, at_ms: at - 1_000 }), at / 1000).unwrap();
let folded = stored_departure_windows(&held());
set_nickname(&bed.relay, &held(), &owner.keys.public_key(), "Boss").await.unwrap();
assert!(std::sync::Arc::ptr_eq(&folded, &stored_departure_windows(&held())), "a Nickname moves nobody's departure");
timeout_member(&bed.relay, &held(), &member.keys.public_key(), 60).await.unwrap();
assert!(std::sync::Arc::ptr_eq(&folded, &stored_departure_windows(&held())), "nor does a Timeout");
}
#[tokio::test]
async fn folded_spans_are_never_carried_past_an_entry_coming_due() {
let (_bed, _owner, _member, community, _general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let at = now_ms();
let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
let ahead = Keys::generate().public_key();
ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Leave { member: ahead, at_ms: at + guestbook::MAX_FUTURE_MS + 60_000 }), at / 1000).unwrap();
let folded = stored_departure_windows(&held());
assert!(!folded.contains_key(&ahead), "too far ahead to count yet");
ingest_guestbook_event(&held(), event(2, guestbook::GuestbookEntry::Join { member: Keys::generate().public_key(), invited_by: None, at_ms: at }), at / 1000).unwrap();
assert!(std::sync::Arc::ptr_eq(&folded, &stored_departure_windows(&held())));
departure_cache().lock().unwrap().get_mut(&cid_hex).unwrap().due = Some(at);
ingest_guestbook_event(&held(), event(3, guestbook::GuestbookEntry::Join { member: Keys::generate().public_key(), invited_by: None, at_ms: at }), at / 1000).unwrap();
assert!(!std::sync::Arc::ptr_eq(&folded, &stored_departure_windows(&held())), "folded again once what it left out comes due");
}
#[tokio::test]
async fn a_ban_stops_a_writer_and_an_unban_takes_them_back_on_a_fresh_epoch() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
bed.swap_to(&owner);
let w = Keys::generate();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let (live, _, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
let cert = cert_for(&held(), &general, live, &w.public_key());
let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
set_banlist(&bed.relay, &held(), &[w.public_key().to_hex()]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.cut, 1, "a ban is a stop on the ledger");
assert!(held().channel(&general).unwrap().writers.as_ref().unwrap().stopped(live, &w.public_key().to_bytes(), u64::MAX));
post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "while banned", now_ms() + 1_000).await;
set_banlist(&bed.relay, &held(), &[]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
assert!(!channel_texts(&bed.relay, &held(), &general).await.contains(&"while banned".to_string()), "an un-ban brings nothing back");
// Un-banned, they rejoin.
bed.swap_to(&owner);
crate::rt::time::sleep(std::time::Duration::from_millis(1_100)).await;
let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
let join = guestbook::build_join_rumor(w.public_key(), None, now_ms());
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &w, Timestamp::from_secs(now_ms() / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
access_duty(&bed.relay, &held()).await.unwrap();
let fresh = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
let scope = crate::community::v2::writers::writer_rekey_scope(&general);
let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
assert!(fresh > live && served_at(&plane, &w.public_key(), scope, fresh, &|_| true), "the un-banned writer posts again on a fresh epoch");
}
#[tokio::test]
async fn one_back_from_a_kick_posts_nothing_more_at_that_epoch_whatever_their_join_says() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
bed.swap_to(&owner);
let w = Keys::generate();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let (live, _, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
let cert = cert_for(&held(), &general, live, &w.public_key());
let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
let kicked_at = now_ms();
let kick = guestbook::build_kick_rumor(owner.keys.public_key(), w.public_key(), None, kicked_at);
let (wrap, _) = guestbook::seal_guestbook_rumor(&kick, &gb, &owner.keys, Timestamp::from_secs(kicked_at / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "while kicked", kicked_at + 500).await;
// They come back with a Join dated a moment after the Kick.
let join = guestbook::build_join_rumor(w.public_key(), None, kicked_at + 1);
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &w, Timestamp::from_secs(kicked_at / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "after the join", kicked_at + 2_000).await;
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
let texts = channel_texts(&bed.relay, &held(), &general).await;
assert!(!texts.contains(&"while kicked".to_string()) && !texts.contains(&"after the join".to_string()), "back, they post on a fresh epoch, never this one");
bed.swap_to(&owner);
sync_guestbook(&bed.relay, &held()).await.unwrap();
access_duty(&bed.relay, &held()).await.unwrap();
let fresh = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
assert!(fresh > live, "the duty restarts them");
}
#[tokio::test]
async fn a_writer_who_left_of_their_own_accord_posts_again_on_rejoining() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
bed.swap_to(&owner);
let w = Keys::generate();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let (live, _, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
let cert = cert_for(&held(), &general, live, &w.public_key());
let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
let left = now_ms();
for (rumor, at) in [(guestbook::build_leave_rumor(w.public_key(), left), left), (guestbook::build_join_rumor(w.public_key(), None, left + 1_000), left + 1_000)] {
let (wrap, _) = guestbook::seal_guestbook_rumor(&rumor, &gb, &w, Timestamp::from_secs(at / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
}
post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "back again", left + 2_000).await;
sync_guestbook(&bed.relay, &held()).await.unwrap();
access_duty(&bed.relay, &held()).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, live, "a Leave of their own costs no fresh epoch");
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
assert!(channel_texts(&bed.relay, &held(), &general).await.contains(&"back again".to_string()));
}
#[tokio::test]
async fn a_kicked_writer_back_again_cannot_post_until_a_fresh_epoch() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(member.keys.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
collect_writers(&bed.relay, &held()).await.unwrap();
assert!(writing::can_post(&held(), &general), "a writer posts");
let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
let at = now_ms();
let kick = guestbook::build_kick_rumor(owner.keys.public_key(), member.keys.public_key(), None, at);
let (wrap, _) = guestbook::seal_guestbook_rumor(&kick, &gb, &owner.keys, Timestamp::from_secs(at / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
let join = guestbook::build_join_rumor(member.keys.public_key(), None, at + 1_000);
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &member.keys, Timestamp::from_secs(at / 1000 + 1)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
assert!(!writing::can_post(&held(), &general), "what they'd post at the epoch they were kicked in stands nowhere: the composer waits");
// Made a manager, their posts stand on the Roster: nothing to wait for.
bed.swap_to(&owner);
let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
set_member_roles(&bed.relay, &held(), &member.keys.public_key(), vec![mods]).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
assert!(writing::can_post(&held(), &general), "a manager back from a Kick posts at once");
}
#[tokio::test]
async fn a_departure_owes_only_the_posts_made_while_away() {
let (_bed, _owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let (cid_hex, chan_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
let w = Keys::generate();
let at = now_ms();
let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Join { member: w.public_key(), invited_by: None, at_ms: at - 5_000 }), at / 1000 - 5).unwrap();
let shown = crate::types::Message { id: "a".repeat(64), content: "while away".into(), at: at + 1_000, npub: Some(nostr_sdk::prelude::ToBech32::to_bech32(&w.public_key()).unwrap()), wrapper_event_id: Some("b".repeat(64)), writer: true, ..Default::default() };
crate::db::events::save_message(&chan_hex, &shown).await.unwrap();
clear_owed(&cid_hex);
ingest_guestbook_event(&held(), event(2, guestbook::GuestbookEntry::Leave { member: w.public_key(), at_ms: at }), at / 1000).unwrap();
ingest_guestbook_event(&held(), event(3, guestbook::GuestbookEntry::Join { member: w.public_key(), invited_by: None, at_ms: at + 2_000 }), at / 1000 + 2).unwrap();
let owed = crate::db::community::owed_author_retractions(&cid_hex).unwrap();
assert!(owed.iter().any(|o| o.3 == Some(at + 2_000)), "a Leave's take-back ends at the Join that ended it: {owed:?}");
assert!(owed.iter().all(|o| o.3.is_some()), "nothing owed past the span");
// Away again: only the new span is owed, never the one already taken back.
clear_owed(&cid_hex);
ingest_guestbook_event(&held(), event(4, guestbook::GuestbookEntry::Leave { member: w.public_key(), at_ms: at + 3_000 }), at / 1000 + 3).unwrap();
let again = crate::types::Message { id: "c".repeat(64), at: at + 4_000, wrapper_event_id: Some("d".repeat(64)), ..shown };
crate::db::events::save_message(&chan_hex, &again).await.unwrap();
ingest_guestbook_event(&held(), event(5, guestbook::GuestbookEntry::Join { member: w.public_key(), invited_by: None, at_ms: at + 5_000 }), at / 1000 + 5).unwrap();
let owed = crate::db::community::owed_author_retractions(&cid_hex).unwrap();
assert!(!owed.is_empty() && owed.iter().all(|o| o.2 >= at + 3_000), "{owed:?}");
}
#[tokio::test]
async fn a_closing_mint_stops_nobody_for_read_address_spam() {
let (bed, owner, _member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
bed.swap_to(&owner);
let spammer = Keys::generate();
let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
let at = now_ms();
let kick = guestbook::build_kick_rumor(owner.keys.public_key(), spammer.public_key(), None, at);
let (wrap, _) = guestbook::seal_guestbook_rumor(&kick, &gb, &owner.keys, Timestamp::from_secs(at / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
post_raw(&bed.relay, &held(), &spammer, &general, &read, community.root_epoch, None, "spam", at + 500).await;
channel_texts(&bed.relay, &held(), &general).await;
let roster = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
writing::mint_for_test(&bed.relay, &held(), &general, &roster).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
assert!(!ledger.entries.iter().any(|e| matches!(e.spell, crate::community::v2::writers::Spell::Stop { writer } if writer == spammer.public_key().to_bytes())), "only posts sent with the closing key earn a stop");
}
fn clear_owed(cid_hex: &str) {
for (chan, since, generation) in crate::db::community::owed_retractions(cid_hex).unwrap() {
crate::db::community::settle_retraction(cid_hex, &chan, since, generation).unwrap();
}
for (chan, author, since, until, generation) in crate::db::community::owed_author_retractions(cid_hex).unwrap() {
crate::db::community::settle_author_retraction(cid_hex, &chan, &author, since, until, generation).unwrap();
}
}
/// Answers no fetch by id, as a relay that serves a plane only to its own key.
struct NoIds<'a>(&'a MemoryRelay);
#[async_trait::async_trait]
impl Transport for NoIds<'_> {
async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
if !query.ids.is_empty() {
return Ok(crate::community::transport::PlaneFetch { events: Vec::new(), answered: relays.len(), attempted: relays.len() });
}
self.0.fetch_plane(_plane, query, relays).await
}
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.0.publish(e, r).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.0.publish_durable(e, r).await
}
async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
if !q.ids.is_empty() {
return Ok(Vec::new());
}
self.0.fetch(q, r).await
}
}
#[tokio::test]
async fn nothing_is_taken_back_that_could_not_be_held() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
let p = Keys::generate();
post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "after the restrict", now_ms() + 3_000).await;
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
for f in page.iter().filter(|f| f.event.opened().rumor.content == "after the restrict") {
crate::community::v2::inbound::persist_routed_chat_event(&f.event, &chan_hex, &community.id().0, &member.keys.public_key()).await.expect("stood while open");
}
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
let added = vec![ledger.entries.last().unwrap().clone()];
let shown = Shown::default();
assert_eq!(writing::retract_after(&NoIds(&bed.relay), &held(), held().channel(&general).unwrap(), &added, &shown).await, 0);
assert!(shown.take().is_empty(), "the post stays until its wrap can be held");
}
#[tokio::test]
async fn a_mint_whose_ledger_moved_while_it_built_sends_nothing() {
use crate::community::roles::OverwriteTarget;
use crate::community::v2::writers::Spell;
let (bed, owner, x, community) = v2_bed_with_admin("Moved mid-build").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
let mine = held().channel(&general).unwrap().writers.clone().unwrap();
// x reopens on the relays; this device hasn't folded it.
let theirs = mine.appended(now_ms(), Spell::Open).unwrap();
let cite = cite_on_relay(&bed.relay, &held(), &x).await;
let prev = crate::db::community::get_edition_head(&crate::simd::hex::bytes_to_hex_32(&community.id().0), &crate::simd::hex::bytes_to_hex_32(&eid)).unwrap().map(|(_, h)| h);
let rumor = control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, 2, prev.as_ref(), &theirs.to_json(), now_ms() / 1000, cite.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())));
let group = control::ControlPlane::of(&held()).write_group().unwrap();
let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(now_ms() / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
act_as(&owner.keys);
let scope = crate::community::v2::writers::writer_rekey_scope(&general);
let before = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap().len();
let roster = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
assert_eq!(writing::mint_for_test(&bed.relay, &held(), &general, &roster).await, Err(writing::LEDGER_MOVED_FOR_TEST.to_string()));
assert_eq!(fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap().len(), before, "nothing sent over a ledger that moved");
}
#[tokio::test]
async fn a_guestbook_wall_of_one_second_is_stepped_past() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Wall", bed.relays.clone(), None).await.unwrap();
let gb = crate::community::v2::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let old = Keys::generate();
let at = now_ms() / 1000 - 10_000;
let join = guestbook::build_join_rumor(old.public_key(), None, (at - 5) * 1000);
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &old, Timestamp::from_secs(at - 5)).unwrap();
bed.relay.publish(&wrap, &community.relays).await.unwrap();
for _ in 0..600 {
let k = Keys::generate();
let join = guestbook::build_join_rumor(k.public_key(), None, at * 1000);
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &k, Timestamp::from_secs(at)).unwrap();
bed.relay.publish(&wrap, &community.relays).await.unwrap();
}
while !guestbook_walked_this_session(&community) {
sync_guestbook(&bed.relay, &community).await.unwrap();
}
let members = stored_memberlist_strict(&crate::db::community::load_community_v2(community.id()).unwrap().unwrap()).unwrap();
assert!(members.contains(&old.public_key()), "what sits below a one-second wall is read too");
}
#[tokio::test]
async fn a_reaction_paged_before_its_target_lands_once_the_target_does() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Windows", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = channel_group_key(&community.community_root, &general, community.root_epoch);
let peer = Keys::generate();
let at = now_ms() - 60_000;
let open = |rumor: nostr_sdk::prelude::UnsignedEvent, at: u64| {
let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &peer, Timestamp::from_secs(at / 1000), false).unwrap();
FetchedEvent { event: chat::open_chat_event(&wrap, &group, &general, community.root_epoch).unwrap(), epoch: community.root_epoch, wrap: Some(wrap) }
};
let message = open(chat::build_message_rumor(peer.public_key(), &general, community.root_epoch, "first", None, &[], vec![], at), at);
let target = message.event.opened().rumor_id.to_hex();
let reaction = open(chat::build_reaction_rumor(peer.public_key(), &general, community.root_epoch, &target, &peer.public_key().to_hex(), super::super::kind::MESSAGE, "+", None, at + 1_000), at + 1_000);
let me = owner.keys.public_key();
let session = crate::db::current_session;
// The newer window first: its reaction has nothing to land on yet.
let (_, waiting) = crate::VectorCore::v2_ingest_chat_page_keeping(&chan_hex, me, session(), vec![reaction]).await;
assert_eq!(waiting.len(), 1, "kept back for its target");
crate::VectorCore::v2_ingest_chat_page(&chan_hex, me, session(), vec![message]).await;
crate::VectorCore::v2_ingest_chat_page_waiting(&chan_hex, me, session(), waiting).await;
let (_, landed) = crate::state::STATE.lock().await.find_message(&target).unwrap();
assert_eq!(landed.reactions.len(), 1, "the reaction lands on its target");
let (_, none_left) = crate::VectorCore::v2_ingest_chat_page_keeping(&chan_hex, me, session(), Vec::new()).await;
assert!(none_left.is_empty());
}
#[tokio::test]
async fn a_page_judged_before_a_stop_landed_is_judged_again_as_it_lands() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(false).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
bed.swap_to(&owner);
let w = Keys::generate();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let (e1, _, writer1) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
let cert = cert_for(&held(), &general, e1, &w.public_key());
let at1 = GroupKey::from_parts(writer1.keys().clone(), read.conv_key().clone());
post_certified(&bed.relay, &held(), &w, &general, &at1, community.root_epoch, Some((e1, Some(cert))), "late", now_ms() + 3_000).await;
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
assert!(page.iter().any(|f| f.event.opened().rumor.content == "late"));
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, 0).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held()).await.unwrap();
crate::VectorCore::v2_ingest_chat_page(&chan_hex, member.keys.public_key(), crate::db::current_session(), page).await;
assert!(crate::db::events::posts_since(&chan_hex, 0).unwrap().iter().all(|p| p.npub.as_deref() != Some(nostr_sdk::prelude::ToBech32::to_bech32(&w.public_key()).unwrap().as_str())), "a page read before the stop keeps nothing the stop undoes");
assert!(!crate::db::community::held_wraps(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap().is_empty(), "held, to be judged again");
}
#[tokio::test]
async fn a_re_mint_that_fails_waits_before_trying_again() {
use crate::community::roles::OverwriteTarget;
use crate::community::v2::writers::{writer_address, Ledger, Spell};
let (bed, owner, _x, community) = v2_bed_with_admin("Legacy retry").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
let old = Ledger::new(&general).appended(2_001_000, Spell::Writer { epoch: Epoch(1), pk: writer_address(&[0x77; 32], &general, Epoch(1)), root: Epoch(0), by: owner.keys.public_key().to_bytes(), certifier: None }).unwrap();
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await;
publish_marked(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 1, None, &old.to_json()).await;
follow_control(&bed.relay, &held()).await.unwrap();
let refusing = RefusesControl { inner: &bed.relay, control: control::ControlPlane::of(&held()).write_group().unwrap().pk_hex(), allow: 0.into(), tried: 0.into() };
let _ = access_duty(&refusing, &held()).await;
let _ = access_duty(&refusing, &held()).await;
assert_eq!(refusing.tried.load(std::sync::atomic::Ordering::SeqCst), 1, "a refused re-mint waits out its lane");
}
#[tokio::test]
async fn a_managers_marked_copy_loses_its_mark_once_the_post_stands() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member, community, general) = restricted_bed(true).await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
let p = Keys::generate();
post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "early", now_ms()).await;
bed.swap_to(&member);
let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
let copy = page.into_iter().find(|f| f.event.opened().rumor.content == "early").expect("a manager keeps a copy");
assert!(copy.event.opened().held, "marked");
let id = copy.event.opened().rumor_id.to_hex();
crate::community::v2::inbound::persist_routed_chat_event(©.event, &chan_hex, &community.id().0, &member.keys.public_key()).await.expect("stored");
assert!(crate::db::events::get_message_by_id(&id).await.unwrap().unwrap().1.unauthorized);
assert!(crate::db::community::community_member_activity(&cid_hex).unwrap().iter().all(|(n, _)| PublicKey::parse(n).unwrap() != p.public_key()), "a held post is no sign of membership");
follow_control(&bed.relay, &held()).await.unwrap();
let shown = Shown::default();
assert_eq!(writing::rejudge_held(&held(), &shown).await, 1);
assert_eq!(shown.take(), vec![("~early".to_string(), false)], "the copy shown loses its mark");
assert!(!crate::db::events::get_message_by_id(&id).await.unwrap().unwrap().1.unauthorized, "and so does the stored one");
}
#[tokio::test]
async fn a_restricted_channel_takes_posts_only_from_its_writers() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member) = TestBed::new();
let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Announce", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let general = community.channels[0].id;
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let m = member.keys.clone();
let plain = create_role_v2(&bed.relay, &held(&community), "Member", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(&community), &m.public_key(), vec![plain]).await.unwrap();
send_direct_invite(&bed.relay, &held(&community), &m.public_key(), None, None).await.unwrap();
bed.swap_to(&member);
accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &m.public_key()).await).await.unwrap();
follow_control(&bed.relay, &held(&community)).await.unwrap();
send_chat_message_at(&bed.relay, &held(&community), &general, "before", None, &[], vec![], now_ms() - 20_000).await.unwrap();
bed.swap_to(&owner);
// A mint whose publish failed left this secret behind; the retry reuses it.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::store_epoch_key(&cid_hex, &crate::community::v2::writers::minted_scope(&general), 1, &[0x5e; 32]).unwrap();
set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
let ch = held(&community).channel(&general).unwrap().clone();
assert_eq!(ch.writers.as_ref().unwrap().current_writer().unwrap().1, crate::community::v2::writers::writer_address(&[0x5e; 32], &general, Epoch(1)));
assert!(ch.restricted() && ch.writers.as_ref().unwrap().current_writer().unwrap().0 == Epoch(1), "restricting mints the ledger");
assert!(can_post(&held(&community), &general), "the owner writes");
send_message(&bed.relay, &held(&community), &general, "announcement").await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert!(held(&community).channel(&general).unwrap().restricted(), "every member folds the ledger");
assert!(!can_post(&held(&community), &general));
assert_eq!(collect_writers(&bed.relay, &held(&community)).await.unwrap(), 0, "nothing for a member the channel doesn't let post");
assert!(send_message(&bed.relay, &held(&community), &general, "denied").await.is_err());
post_raw(&bed.relay, &held(&community), &m, &general, &read, community.root_epoch, None, "sneaky", now_ms()).await;
let texts = channel_texts(&bed.relay, &held(&community), &general).await;
assert!(texts.contains(&"before".to_string()) && texts.contains(&"announcement".to_string()), "a reader without the key reads the writers: {texts:?}");
assert!(!texts.contains(&"sneaky".to_string()), "a member never sees what the windows don't stand behind");
// Let the member post: the change's author hands them the live key.
bed.swap_to(&owner);
assert_eq!(marked_texts(&bed.relay, &held(&community), &general).await, vec!["sneaky".to_string()], "a manager sees it, marked");
// A stranger leaves m certificates the certifier never signed, either side of the real one.
let (live, pk) = held(&community).channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap();
let forged = std::collections::HashMap::from([(m.public_key(), chat::WriterCert::Full([0x77; 64]))]);
let stranger = Keys::generate();
let forge = || async {
act_as(&stranger);
deliver_certified(&bed.relay, &held(&community), &general, crate::community::v2::writers::writer_rekey_scope(&general), live, Some(pk), &[0x99; 32], &[m.public_key()], &forged).await.unwrap();
act_as(&owner.keys);
};
forge().await;
set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Member(m.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
forge().await;
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert_eq!(collect_writers(&bed.relay, &held(&community)).await.unwrap(), 1);
assert_eq!(collect_writers(&bed.relay, &held(&community)).await.unwrap(), 0, "held now");
assert!(can_post(&held(&community), &general));
send_message(&bed.relay, &held(&community), &general, "from m").await.unwrap();
let (_, old_secret, old_writer) = writing::live_writer(&held(&community), held(&community).channel(&general).unwrap()).unwrap();
bed.swap_to(&owner);
assert!(channel_texts(&bed.relay, &held(&community), &general).await.contains(&"from m".to_string()));
// Take it back: a stop voids their certificate from then on, with no new key to hand out.
set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Member(m.public_key().to_hex()), 0, 0).await.unwrap();
let ledger = held(&community).channel(&general).unwrap().writers.clone().unwrap();
assert_eq!(ledger.current_writer().unwrap().0, Epoch(1), "no fresh epoch");
let last = ledger.entries.last().unwrap();
assert!(matches!(last.spell, crate::community::v2::writers::Spell::Stop { writer } if writer == m.public_key().to_bytes()));
let closed_at = last.at;
let stale = GroupKey::from_parts(old_writer.keys().clone(), read.conv_key().clone());
assert_eq!(crate::community::v2::derive::channel_writer_group_key(&old_secret, &general, Epoch(1)).pk(), stale.pk());
let m_cert = cert_for(&held(&community), &general, Epoch(1), &m.public_key());
post_certified(&bed.relay, &held(&community), &m, &general, &stale, community.root_epoch, Some((Epoch(1), Some(m_cert))), "late", closed_at + 5_000).await;
post_certified(&bed.relay, &held(&community), &m, &general, &stale, community.root_epoch, Some((Epoch(1), Some(m_cert))), "in time", closed_at - 1).await;
post_raw(&bed.relay, &held(&community), &m, &general, &stale, community.root_epoch, Some(Epoch(2)), "wrong epoch", closed_at - 2).await;
send_message(&bed.relay, &held(&community), &general, "second").await.unwrap();
let texts = channel_texts(&bed.relay, &held(&community), &general).await;
assert!(texts.contains(&"in time".to_string()) && texts.contains(&"from m".to_string()), "a writer's past posts stay theirs: {texts:?}");
assert_eq!(marked_texts(&bed.relay, &held(&community), &general).await, vec!["sneaky".to_string(), "late".to_string()], "nothing new through a key they kept stands");
assert!(!texts.contains(&"wrong epoch".to_string()), "a post commits the epoch whose address served it");
assert!(texts.contains(&"second".to_string()));
let (live, live_secret, _) = writing::live_writer(&held(&community), held(&community).channel(&general).unwrap()).unwrap();
// Even handed the live key, a member the channel doesn't let post never takes it.
deliver_on_plane(&bed.relay, &held(&community), &general, crate::community::v2::writers::writer_rekey_scope(&general), live, Some(crate::community::v2::writers::writer_address(&live_secret, &general, live)), &live_secret, &[m.public_key()]).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert_eq!(collect_writers(&bed.relay, &held(&community)).await.unwrap(), 0, "the channel no longer lets them post");
crate::db::community::store_epoch_key(&cid_hex, &crate::community::v2::writers::secret_scope(&general), live.0, &[0x42; 32]).unwrap();
assert!(!can_post(&held(&community), &general), "a held secret that doesn't derive to the ledger's address writes nothing");
crate::db::community::store_epoch_key(&cid_hex, &crate::community::v2::writers::secret_scope(&general), live.0, &live_secret).unwrap();
assert!(!can_post(&held(&community), &general), "and the right key is no licence once the channel stops letting them post");
assert!(send_message(&bed.relay, &held(&community), &general, "kept the key").await.is_err());
assert!(!can_post(&held(&community), &general) && send_message(&bed.relay, &held(&community), &general, "denied").await.is_err());
assert!(channel_texts(&bed.relay, &held(&community), &general).await.contains(&"second".to_string()), "still a reader");
// Reopen: posts move back to the read address.
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
assert!(!held(&community).channel(&general).unwrap().restricted());
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert!(can_post(&held(&community), &general));
send_message(&bed.relay, &held(&community), &general, "open again").await.unwrap();
bed.swap_to(&owner);
let texts = channel_texts(&bed.relay, &held(&community), &general).await;
assert!(texts.contains(&"open again".to_string()), "{texts:?}");
assert!(marked_texts(&bed.relay, &held(&community), &general).await.contains(&"sneaky".to_string()), "what a closed window got stays marked");
}
/// Publish an overwrite the way another client would: no settle follows it here.
async fn publish_overwrite_raw<T: Transport + ?Sized>(relay: &T, community: &CommunityV2, scope: [u8; 32], target: crate::community::roles::OverwriteTarget, allow: u64, deny: u64) {
let bytes = crate::community::v2::roles::overwrite_target_bytes(community.id(), &target).unwrap();
let o = crate::community::roles::Overwrite { scope: crate::simd::hex::bytes_to_hex_32(&scope), target, allow: Permissions(allow), deny: Permissions(deny) };
publish_control_edition(relay, community, vsk::CHANNEL_ACL, &crate::community::v2::derive::acl_locator(community.id(), &scope, &bytes), &crate::community::v2::roles::overwrite_content_json(&o)).await.unwrap();
}
#[tokio::test]
async fn the_writer_duty_backs_up_a_change_made_elsewhere() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member) = TestBed::new();
let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Backstop", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let general = community.channels[0].id;
let m = member.keys.public_key();
let plain = create_role_v2(&bed.relay, &held(&community), "Member", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(&community), &m, vec![plain]).await.unwrap();
send_direct_invite(&bed.relay, &held(&community), &m, None, None).await.unwrap();
bed.swap_to(&member);
accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &m).await).await.unwrap();
bed.swap_to(&owner);
publish_overwrite_raw(&bed.relay, &held(&community), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await;
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert!(!held(&community).channel(&general).unwrap().restricted(), "nobody moved the ledger yet");
let blind = BreaksAfterPublish { inner: &bed.relay, broken: true.into() };
assert!(access_duty(&blind, &held(&community)).await.is_err(), "nothing moves on a partial read");
assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers, WriterDuty { moved: 1, ..Default::default() });
assert!(held(&community).channel(&general).unwrap().restricted());
assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers, WriterDuty::default(), "in line now");
publish_overwrite_raw(&bed.relay, &held(&community), general.0, OverwriteTarget::Member(m.to_hex()), Permissions::SEND_MESSAGES, 0).await;
follow_control(&bed.relay, &held(&community)).await.unwrap();
// A stranger hands the new writer a key the ledger never named.
let stranger = Keys::generate();
act_as(&stranger);
let scope = crate::community::v2::writers::writer_rekey_scope(&general);
let named = held(&community).channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().1;
deliver_on_plane(&bed.relay, &held(&community), &general, scope, Epoch(1), Some(named), &[0x99; 32], &[m]).await.unwrap();
act_as(&owner.keys);
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert_eq!(collect_writers(&bed.relay, &held(&community)).await.unwrap(), 0, "a key that derives elsewhere is never taken");
assert!(!can_post(&held(&community), &general));
bed.swap_to(&owner);
// Even a manager's blob serves nobody when it names another address: a losing fork's.
deliver_on_plane(&bed.relay, &held(&community), &general, scope, Epoch(1), Some([0x11; 32]), &[0x99; 32], &[m]).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers.delivered, 1, "the new writer is owed the live key");
assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers.delivered, 0, "once");
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert_eq!(collect_writers(&bed.relay, &held(&community)).await.unwrap(), 1);
assert!(can_post(&held(&community), &general));
assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers, WriterDuty::default(), "a member served already owes nobody");
bed.swap_to(&owner);
publish_overwrite_raw(&bed.relay, &held(&community), general.0, OverwriteTarget::Member(m.to_hex()), 0, 0).await;
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers.cut, 0, "who may post is an absence verdict: not before the memberlist is read whole");
sync_guestbook(&bed.relay, &held(&community)).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers.cut, 1, "a served writer the channel no longer lets post");
let ledger = held(&community).channel(&general).unwrap().writers.clone().unwrap();
assert_eq!(ledger.current_writer().unwrap().0, Epoch(1), "stopped, with no new key");
assert!(ledger.stopped(Epoch(1), &m.to_bytes(), u64::MAX));
assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers, WriterDuty::default(), "stopped once");
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert!(!can_post(&held(&community), &general));
bed.swap_to(&owner);
// Let back in, a writer this epoch stopped is owed a fresh one.
publish_overwrite_raw(&bed.relay, &held(&community), general.0, OverwriteTarget::Member(m.to_hex()), Permissions::SEND_MESSAGES, 0).await;
follow_control(&bed.relay, &held(&community)).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert!(!can_post(&held(&community), &general), "a writer this epoch stopped posts nothing here, key or not");
bed.swap_to(&owner);
assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers.moved, 0, "letting someone back is judged on a memberlist read whole");
sync_guestbook(&bed.relay, &held(&community)).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers.moved, 1);
assert_eq!(held(&community).channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(2));
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
collect_writers(&bed.relay, &held(&community)).await.unwrap();
assert!(can_post(&held(&community), &general));
bed.swap_to(&owner);
publish_overwrite_raw(&bed.relay, &held(&community), general.0, OverwriteTarget::Member(m.to_hex()), 0, 0).await;
follow_control(&bed.relay, &held(&community)).await.unwrap();
sync_guestbook(&bed.relay, &held(&community)).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers.cut, 1, "stopped at the fresh epoch too");
assert!(held(&community).channel(&general).unwrap().writers.as_ref().unwrap().stopped(Epoch(2), &m.to_bytes(), u64::MAX));
assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers.cut, 0, "once");
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert!(!can_post(&held(&community), &general));
bed.swap_to(&owner);
publish_overwrite_raw(&bed.relay, &held(&community), general.0, OverwriteTarget::Everyone, 0, 0).await;
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers.moved, 1);
assert!(!held(&community).channel(&general).unwrap().restricted());
}
#[tokio::test]
async fn a_refounding_retires_the_writer_key() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member) = TestBed::new();
let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Retire", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let general = community.channels[0].id;
let m = member.keys.public_key();
let plain = create_role_v2(&bed.relay, &held(&community), "Member", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(&community), &m, vec![plain]).await.unwrap();
send_direct_invite(&bed.relay, &held(&community), &m, None, None).await.unwrap();
bed.swap_to(&member);
accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &m).await).await.unwrap();
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Member(m.to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert_eq!(collect_writers(&bed.relay, &held(&community)).await.unwrap(), 1, "a writer before the ban");
bed.swap_to(&owner);
assert_eq!(held(&community).channel(&general).unwrap().writers.as_ref().unwrap().live().map(|l| l.0), Some(Epoch(0)));
set_members_banned(&bed.relay, community.id(), &[m], true).await.unwrap();
let after = held(&community);
assert!(after.root_epoch > community.root_epoch, "a ban refounds");
// The Refounder re-mints at once; the duty finds nothing left.
let ledger = held(&community).channel(&general).unwrap().writers.clone().unwrap();
assert_eq!((ledger.current_writer().unwrap().0, ledger.live().map(|l| l.0)), (Epoch(2), Some(after.root_epoch)));
let scope = crate::community::v2::writers::writer_rekey_scope(&general);
let on_plane = fetch_plane_deliveries(&bed.relay, &held(&community), &general, scope).await.unwrap();
assert!(!served_at(&on_plane, &m, scope, Epoch(2), &|_| true), "the banned writer is left out");
assert!(served_at(&on_plane, &owner.keys.public_key(), scope, Epoch(2), &|_| true));
follow_control(&bed.relay, &after).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers, WriterDuty::default(), "retired once");
}
#[tokio::test]
async fn a_manager_cuts_only_writers_it_outranks() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Ranks", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
// Senior ranks above Admin without managing anything: a manager may hold the key anyway.
let senior = create_role_v2(&bed.relay, &held(), "Senior", 0, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
let admin = create_role_v2(&bed.relay, &held(), "Admin", 0, Permissions::MANAGE_CHANNELS | crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
let (y, x) = (Keys::generate(), Keys::generate());
set_member_roles(&bed.relay, &held(), &y.public_key(), vec![senior.clone()]).await.unwrap();
set_member_roles(&bed.relay, &held(), &x.public_key(), vec![admin]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(senior.clone()), Permissions::SEND_MESSAGES, 0).await.unwrap();
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Role(senior), 0, 0).await;
follow_control(&bed.relay, &held()).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
act_as(&x);
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.cut, 0, "a writer who outranks this manager is someone else's to cut");
act_as(&owner.keys);
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.cut, 1);
}
#[tokio::test]
async fn a_private_channels_metadata_is_sealed_from_members_without_its_key() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member) = TestBed::new();
let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Sealed", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let m = member.keys.public_key();
let managers = create_role_v2(&bed.relay, &held(&community), "Managers", 0, Permissions::MANAGE_CHANNELS | crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
set_member_roles(&bed.relay, &held(&community), &m, vec![managers]).await.unwrap();
let ch = create_private_channel(&bed.relay, &held(&community), "war room").await.unwrap();
let mut meta = held(&community).channel(&ch).unwrap().metadata();
meta.extra.insert("topic".into(), "the plan".into());
edit_channel_metadata(&bed.relay, &held(&community), &ch, &meta).await.unwrap();
let editions = fetch_control(&bed.relay, &held(&community)).await;
let heads: Vec<&ParsedEdition> = editions.iter().filter(|e| e.vsk == vsk::CHANNEL_METADATA && e.entity_id == ch.0).collect();
assert!(heads.len() >= 2 && heads.iter().all(|e| !e.content.contains("war room") && !e.content.contains("the plan")), "nothing a keyless member reads names it");
assert!(heads.iter().all(|e| control::parse_sealed_channel_meta(&e.content).is_some()));
send_direct_invite(&bed.relay, &held(&community), &m, None, None).await.unwrap();
bed.swap_to(&member);
accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &m).await).await.unwrap();
follow_control(&bed.relay, &held(&community)).await.unwrap();
let dark = held(&community).channel(&ch).cloned().expect("a keyless member still sees it exists");
assert!(dark.private && dark.key.is_none() && dark.name.is_empty() && dark.sealed.as_ref().is_some_and(|s| !s.open), "{dark:?}");
assert!(edit_channel_metadata(&bed.relay, &held(&community), &ch, &meta).await.is_err(), "a writer can't build a sealed edition from metadata it couldn't read");
// Let them in: the key arrives and opens the seal.
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(&community), ch.0, OverwriteTarget::Member(m.to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
follow_control(&bed.relay, &held(&community)).await.unwrap();
access_duty(&bed.relay, &held(&community)).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert_eq!(collect_access(&bed.relay, &held(&community)).await.unwrap(), 1);
assert_eq!(absorb_parked_channel_keys(&held(&community), &crate::db::current_session()).len(), 1);
let open = held(&community).channel(&ch).cloned().unwrap();
assert_eq!((open.name.as_str(), open.topic()), ("war room", Some("the plan")), "the key opens the seal");
// Unopened details are never republished, even by a key holder.
let whole = held(&community);
let mut stale = whole.clone();
stale.channels.iter_mut().find(|c| c.id == ch).unwrap().sealed.as_mut().unwrap().open = false;
crate::db::community::save_community_v2(&stale).unwrap();
assert!(edit_channel_metadata(&bed.relay, &held(&community), &ch, &meta).await.unwrap_err().contains("sealed"));
crate::db::community::save_community_v2(&whole).unwrap();
// A rename by someone else opens on arrival.
bed.swap_to(&owner);
let mut renamed = held(&community).channel(&ch).unwrap().metadata();
renamed.name = "situation room".into();
edit_channel_metadata(&bed.relay, &held(&community), &ch, &renamed).await.unwrap();
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert_eq!(held(&community).channel(&ch).unwrap().name, "situation room");
// A rotation the member survives: the rotator re-seals under the new key, and the
// member opens it once their rekey walk takes that key.
bed.swap_to(&owner);
let y = Keys::generate();
let guests = create_role_v2(&bed.relay, &held(&community), "Guests", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(&community), &y.public_key(), vec![guests]).await.unwrap();
set_overwrite(&bed.relay, &held(&community), ch.0, OverwriteTarget::Member(y.public_key().to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
set_overwrite(&bed.relay, &held(&community), ch.0, OverwriteTarget::Member(y.public_key().to_hex()), 0, 0).await.unwrap();
let rotated = held(&community).channel(&ch).cloned().unwrap();
assert!(rotated.epoch.0 >= 2);
assert_eq!(rotated.sealed.as_ref().map(|s| (s.epoch, s.open)), Some((rotated.epoch.0, true)), "the rotator re-seals");
assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().resealed, 0, "nothing left to re-seal");
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
follow_rekeys(&bed.relay, &held(&community), &crate::db::current_session()).await.unwrap();
let kept = held(&community).channel(&ch).cloned().unwrap();
assert_eq!((kept.epoch, kept.sealed.as_ref().map(|s| (s.epoch, s.open))), (rotated.epoch, Some((rotated.epoch.0, true))), "the new key opens the new seal");
// Cut them: the next rotation re-seals beyond their reach.
bed.swap_to(&owner);
set_overwrite(&bed.relay, &held(&community), ch.0, OverwriteTarget::Member(m.to_hex()), 0, 0).await.unwrap();
let rotated = held(&community).channel(&ch).cloned().unwrap();
// A manager without the key still deletes it: the seal travels verbatim.
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
delete_channel(&bed.relay, &held(&community), &ch, "").await.unwrap();
bed.swap_to(&owner);
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert!(held(&community).channel(&ch).is_none(), "every member folds the deletion");
let editions = fetch_control(&bed.relay, &held(&community)).await;
let tomb = editions.iter().filter(|e| e.vsk == vsk::CHANNEL_METADATA && e.entity_id == ch.0).max_by_key(|e| e.version).unwrap();
let tomb = control::parse_sealed_channel_meta(&tomb.content).unwrap();
assert!(tomb.deleted && tomb.epoch == rotated.epoch.0);
}
#[tokio::test]
async fn clearing_the_only_overwrite_that_named_someone_still_cuts_them() {
use crate::community::roles::OverwriteTarget;
let (bed, _owner, _x, community) = v2_bed_with_admin("OnlyNamed").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "side").await.unwrap();
let y = Keys::generate();
set_overwrite(&bed.relay, &held(), ch.0, OverwriteTarget::Member(y.public_key().to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
let before = held().channel(&ch).unwrap().epoch;
set_overwrite(&bed.relay, &held(), ch.0, OverwriteTarget::Member(y.public_key().to_hex()), 0, 0).await.unwrap();
assert!(held().channel(&ch).unwrap().epoch > before, "the key they were handed rotates away");
}
#[tokio::test]
async fn a_manager_seals_a_private_channel_left_plain() {
let (bed, _owner, _x, community) = v2_bed_with_admin("Plain").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "staff").await.unwrap();
let plain = control::ChannelMetadata { name: "staff".into(), private: true, voice: None, deleted: None, custom: None, extra: Default::default() };
publish_control_edition(&bed.relay, &held(), vsk::CHANNEL_METADATA, &ch.0, &serde_json::to_string(&plain).unwrap()).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert!(held().channel(&ch).unwrap().sealed.is_none(), "a plain head unseals the record");
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().resealed, 1);
follow_control(&bed.relay, &held()).await.unwrap();
let after = held().channel(&ch).cloned().unwrap();
assert!(after.sealed.as_ref().is_some_and(|s| s.open) && after.name == "staff");
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().resealed, 0, "sealed once");
}
#[tokio::test]
async fn a_demoted_minters_blobs_still_show_who_holds_the_key() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Minter", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_CHANNELS | Permissions::MANAGE_ROLES | crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
let members = create_role_v2(&bed.relay, &held(), "Members", 0, 0).await.unwrap();
let (x, y) = (Keys::generate(), Keys::generate());
set_member_roles(&bed.relay, &held(), &x.public_key(), vec![mods]).await.unwrap();
set_member_roles(&bed.relay, &held(), &y.public_key(), vec![members]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
act_as(&x);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(y.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
act_as(&owner.keys);
assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().live().map(|l| l.1), Some(x.public_key().to_bytes()));
// The minter loses its standing, then y loses Send where nobody settles it.
set_member_roles(&bed.relay, &held(), &x.public_key(), vec![]).await.unwrap();
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(y.public_key().to_hex()), 0, 0).await;
follow_control(&bed.relay, &held()).await.unwrap();
// The demotion took the certifier back with a fresh epoch at once; y, whom it still
// vouches for, is stopped there.
assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(2));
sync_guestbook(&bed.relay, &held()).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.cut, 1);
assert!(held().channel(&general).unwrap().writers.as_ref().unwrap().stopped(Epoch(2), &y.public_key().to_bytes(), u64::MAX));
}
#[tokio::test]
async fn a_manager_nobody_served_mints_a_key_it_can_use() {
use crate::community::roles::OverwriteTarget;
use crate::community::v2::writers::{writer_address, Ledger, Spell};
let (bed, owner, _x, community) = v2_bed_with_admin("Starved").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
let lost = Ledger::new(&general).appended(2_001_000, Spell::Writer { epoch: Epoch(1), pk: writer_address(&[0x77; 32], &general, Epoch(1)), root: Epoch(0), by: owner.keys.public_key().to_bytes(), certifier: crate::community::v2::writers::certifier_of(&[0x66; 32]) }).unwrap();
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await;
publish_marked(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 1, None, &lost.to_json()).await;
follow_control(&bed.relay, &held()).await.unwrap();
assert!(!can_post(&held(), &general), "a key nobody holds");
let stranger = Keys::generate();
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(stranger.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await;
follow_control(&bed.relay, &held()).await.unwrap();
// Another manager left a blob at the owner's locator that opens to nothing usable.
let scope = crate::community::v2::writers::writer_rekey_scope(&general);
act_as(&_x);
deliver_on_plane(&bed.relay, &held(), &general, scope, Epoch(1), Some(lost.current_writer().unwrap().1), &[0x55; 32], &[owner.keys.public_key()]).await.unwrap();
act_as(&owner.keys);
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 0, "a manager just able to post waits for its key");
writing::backdate_postable(&held(), &general, 1);
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 1, "a blob that opens to nothing is no key");
assert!(can_post(&held(), &general));
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
assert_eq!(ledger.current_writer().unwrap().0, Epoch(2));
let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
assert!(!served_at(&plane, &stranger.public_key(), scope, Epoch(2), &|_| true), "someone only an overwrite names is no member, so no writer");
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers, WriterDuty::default(), "minted once");
}
#[tokio::test]
async fn history_pages_each_address_on_its_own() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Pages", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
let now = now_ms();
for i in 0..25u64 {
send_chat_message_at(&bed.relay, &held(), &general, &format!("post {i}"), None, &[], vec![], now - (25 - i) * 60_000).await.unwrap();
}
// One old reaction at the read address, far below the writer posts.
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let old = now - 2 * 86_400_000;
let reaction = chat::build_reaction_rumor(owner.keys.public_key(), &general, community.root_epoch, &"ab".repeat(32), &owner.keys.public_key().to_hex(), 9, "+", None, old);
let (wrap, _) = chat::seal_chat_rumor(&reaction, &read, &owner.keys, Timestamp::from_secs(old / 1000), false).unwrap();
bed.relay.publish(&wrap, &community.relays).await.unwrap();
let got = fetch_channel_history(&bed.relay, &held(), &general, 10, 10, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
let posts = got.iter().filter(|f| matches!(f.event, ChatEvent::Message { .. })).count();
assert_eq!(posts, 25, "a quiet address's old bottom never skips the busy one's middle");
assert!(got.iter().any(|f| matches!(f.event, ChatEvent::Reaction { .. })));
}
#[tokio::test]
async fn history_hands_back_where_to_page_on_from() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Spam", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
let now = now_ms();
send_chat_message_at(&bed.relay, &held(), &general, "a writer's post", None, &[], vec![], now + 1_000).await.unwrap();
// Anyone with the read key fills the read address, inside the window.
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let spammer = Keys::generate();
for i in 0..25u64 {
let at = now + 60_000 + i * 2_000;
let rumor = chat::build_message_rumor(spammer.public_key(), &general, community.root_epoch, "spam", None, &[], vec![], at);
let (wrap, _) = chat::seal_chat_rumor(&rumor, &read, &spammer, Timestamp::from_secs(at / 1000), false).unwrap();
bed.relay.publish(&wrap, &community.relays).await.unwrap();
}
// Read once the flood is due, so it is paged rather than held.
crate::clock::shift_for_test(3 * 60_000);
let (got, cursor, _) = fetch_channel_history_paged(&bed.relay, &held(), &general, 10, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _, _| true, |_| Default::default()).await.unwrap();
assert!(!got.iter().any(|f| f.event.opened().rumor.content == "a writer's post") && cursor.is_some_and(|c| c > (now + 1_000) / 1000), "nothing below where the relay walk stopped");
let (got, ..) = fetch_channel_history_paged(&bed.relay, &held(), &general, 10, 4, None, cursor, crate::community::transport::Evidence::Quorum, |_, _, _| true, |_| Default::default()).await.unwrap();
crate::clock::shift_for_test(0);
assert!(got.iter().any(|f| f.event.opened().rumor.content == "a writer's post"), "paging on from the cursor reaches it");
}
#[tokio::test]
async fn a_catch_up_reads_through_held_rows_down_to_its_floor() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Hole", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let now = now_ms();
let at = |i: u64| now - (30 - i) * 60_000;
for i in 0..30u64 {
send_chat_message_at(&relay, &community, &general, &format!("m{i}"), None, &[], vec![], at(i)).await.unwrap();
}
let all = fetch_channel(&relay, &community, &general, 100).await.unwrap();
let id_of = |text: &str| all.iter().find(|f| f.event.opened().rumor.content == text).map(|f| f.event.opened().rumor_id.to_hex()).unwrap();
// The oldest ten were read before going away and the newest ten arrived live after; nothing read the middle.
let held: std::collections::HashSet<String> = (0..10).chain(20..30).map(|i| id_of(&format!("m{i}"))).collect();
let walk = |floor: Option<u64>| {
let held = held.clone();
let relay = &relay;
let community = &community;
async move {
let (got, ..) = fetch_channel_history_paged(relay, community, &general, 10, 10, None, None, crate::community::transport::Evidence::Quorum, |p, s, n| catch_up_pages_on(p, s, n, floor, |id| held.contains(id)), |_| Default::default()).await.unwrap();
got.iter().map(|f| f.event.opened().rumor.content.clone()).collect::<std::collections::HashSet<_>>()
}
};
assert!(!walk(None).await.contains("m15"), "without a floor the first held page ends the walk");
let got = walk(Some(at(5) / 1000)).await;
assert!((10..20).all(|i| got.contains(&format!("m{i}"))), "the unread middle is read");
}
#[tokio::test]
async fn a_member_who_never_held_a_past_root_reads_it_once_the_channel_publishes_it() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Kept", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let now = now_ms();
send_chat_message_at(&relay, &community, &general, "before", None, &[], vec![], now - 60_000).await.unwrap();
let rotated = refound_community(&relay, &community, &[]).await.unwrap();
send_chat_message_at(&relay, &rotated, &general, "after", None, &[], vec![], now + 1_000).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let (root, past) = (crate::community::SERVER_ROOT_SCOPE_HEX, community.root_epoch);
crate::db::community::delete_epoch_key(&cid_hex, root, past.0).unwrap();
assert_eq!(all_texts_in(&relay, &held(), &general).await, vec!["after"], "without the past root, only what came after");
// A device that held it publishes the Channel's plane there.
crate::db::community::store_epoch_key(&cid_hex, root, past.0, &community.community_root).unwrap();
let ch = held().channel(&general).unwrap().clone();
let (owed, scanned) = owed_history(&relay, &held(), &ch).await;
assert_eq!((owed.iter().map(|(e, _)| *e).collect::<Vec<_>>(), scanned), (vec![past], Some(past.0)));
assert!(publish_history(&relay, &held(), &general, owed).await.unwrap());
follow_control(&relay, &held()).await.unwrap();
let ch = held().channel(&general).unwrap().clone();
assert!(owed_history(&relay, &held(), &ch).await.0.is_empty(), "published once, nothing more is owed");
crate::db::community::delete_epoch_key(&cid_hex, root, past.0).unwrap();
assert_eq!(all_texts_in(&relay, &held(), &general).await, vec!["before", "after"], "the published plane reads for a member who never held its root");
// A catch-up reads it too, whole, while this device hasn't: a Channel whose every post
// predates the rotation isn't left empty until someone scrolls.
let unread: Vec<PublicKey> = held().channel(&general).unwrap().published_history().iter().map(|(_, g)| g.pk()).collect();
let live = Some((held().root_epoch, None));
let (got, ..) = fetch_channel_history_since_epoch(&relay, &held(), &general, 50, 8, None, None, crate::community::transport::Evidence::Quorum, |_, _, _| true, |_| Default::default(), live, &[]).await.unwrap();
assert!(!got.iter().any(|f| f.event.opened().rumor.content == "before"), "a catch-up reads the live epoch");
let (got, ..) = fetch_channel_history_since_epoch(&relay, &held(), &general, 50, 8, None, None, crate::community::transport::Evidence::Quorum, |_, _, _| true, |_| Default::default(), live, &unread).await.unwrap();
assert!(got.iter().any(|f| f.event.opened().rumor.content == "before"), "and a published plane it never read");
}
#[tokio::test]
async fn after_a_rotation_a_manager_publishes_the_closed_epoch_once() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Rotated", vec!["wss://r".into()], None).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&relay, &held()).await.unwrap();
let general = community.channels[0].id;
send_chat_message_at(&relay, &held(), &general, "before", None, &[], vec![], now_ms() - 60_000).await.unwrap();
let past = held().root_epoch;
refound_community(&relay, &held(), &[]).await.unwrap();
follow_control(&relay, &held()).await.unwrap();
assert_eq!(access_duty(&relay, &held()).await.unwrap().history, 1);
follow_control(&relay, &held()).await.unwrap();
assert_eq!(held().channel(&general).unwrap().published_history().iter().map(|(e, _)| *e).collect::<Vec<_>>(), vec![past]);
assert_eq!(access_duty(&relay, &held()).await.unwrap().history, 0, "nothing more to publish");
}
#[tokio::test]
async fn a_past_root_the_channel_never_wrote_under_is_not_published() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Quiet", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
refound_community(&relay, &community, &[]).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let (owed, scanned) = owed_history(&relay, &held, held.channel(&general).unwrap()).await;
assert!(owed.is_empty());
assert_eq!(scanned, Some(community.root_epoch.0), "looked at, so not again");
}
#[tokio::test]
async fn a_private_channel_made_public_hands_what_it_said_while_private_to_every_member() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Opened", vec!["wss://r".into()], None).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&relay, &held()).await.unwrap();
let directory = create_private_channel(&relay, &held(), "directory").await.unwrap();
send_chat_message_at(&relay, &held(), &directory, "the list", None, &[], vec![], now_ms() - 60_000).await.unwrap();
let epoch = held().channel(&directory).unwrap().epoch;
publicize_channel(&relay, &held(), &directory).await.unwrap();
follow_control(&relay, &held()).await.unwrap();
assert!(!held().channel(&directory).unwrap().private);
let (cid_hex, ch_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&directory.0));
crate::db::community::delete_epoch_key(&cid_hex, &ch_hex, epoch.0).unwrap();
assert_eq!(all_texts_in(&relay, &held(), &directory).await, vec!["the list"], "a member who never held its key reads it");
}
#[tokio::test]
async fn a_channel_whose_everyone_reads_no_history_publishes_none() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Closed", vec!["wss://r".into()], None).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&relay, &held()).await.unwrap();
let directory = create_private_channel(&relay, &held(), "directory").await.unwrap();
send_chat_message_at(&relay, &held(), &directory, "the list", None, &[], vec![], now_ms() - 60_000).await.unwrap();
set_overwrite(&relay, &held(), directory.0, crate::community::roles::OverwriteTarget::Everyone, 0, crate::community::roles::Permissions::READ_MESSAGE_HISTORY).await.unwrap();
follow_control(&relay, &held()).await.unwrap();
publicize_channel(&relay, &held(), &directory).await.unwrap();
follow_control(&relay, &held()).await.unwrap();
assert!(held().channel(&directory).unwrap().published_history().is_empty());
let (cid_hex, ch_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&directory.0));
let epoch = crate::db::community::held_epoch_keys(&cid_hex, &ch_hex).unwrap()[0].0;
crate::db::community::delete_epoch_key(&cid_hex, &ch_hex, epoch.0).unwrap();
assert!(all_texts_in(&relay, &held(), &directory).await.is_empty(), "history starts where reading did");
}
#[test]
fn a_malformed_history_entry_names_nothing() {
let good = channel_group_key(&[7u8; 32], &ChannelId([1u8; 32]), Epoch(2));
let mut ch = crate::community::v2::community::ChannelV2 { id: ChannelId([1u8; 32]), name: "c".into(), private: false, key: None, epoch: Epoch(0), voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed: None };
ch.meta_extra.insert(
"history".into(),
serde_json::json!([[2, crate::simd::hex::bytes_to_hex_32(&good.secret())], [3, "zz"], ["4", crate::simd::hex::bytes_to_hex_32(&good.secret())], [9007199254740992u64, crate::simd::hex::bytes_to_hex_32(&good.secret())], [5]]),
);
let got = ch.published_history();
assert_eq!(got.len(), 1);
assert_eq!((got[0].0, got[0].1.pk()), (Epoch(2), good.pk()));
}
#[tokio::test]
async fn a_catch_up_after_a_rotation_reads_the_epochs_its_proof_never_read() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Moved", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let now = now_ms();
for i in 0..5u64 {
send_chat_message_at(&relay, &community, &general, &format!("old{i}"), None, &[], vec![], now - (60 - i) * 60_000).await.unwrap();
}
let between = refound_community(&relay, &community, &[]).await.unwrap();
for i in 0..5u64 {
send_chat_message_at(&relay, &between, &general, &format!("mid{i}"), None, &[], vec![], now - (20 - i) * 60_000).await.unwrap();
}
let rotated = refound_community(&relay, &between, &[]).await.unwrap();
for i in 0..5u64 {
send_chat_message_at(&relay, &rotated, &general, &format!("new{i}"), None, &[], vec![], now + (i + 1) * 60_000).await.unwrap();
}
crate::clock::shift_for_test(10 * 60_000);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(held.root_epoch, rotated.root_epoch);
// Proven on the old epoch after all of it was said: a floor above every new message.
let floor = Some((now + 8 * 60_000) / 1000);
let walk = |past: Option<(Epoch, Option<u64>)>| {
let (relay, held) = (&relay, &held);
async move {
let (got, ..) = fetch_channel_history_since_epoch(relay, held, &general, 10, 8, floor, None, crate::community::transport::Evidence::Quorum, |p, s, n| catch_up_pages_on(p, s, n, floor, |_| false), |_| Default::default(), past, &[]).await.unwrap();
got.iter().map(|f| f.event.opened().rumor.content.clone()).collect::<std::collections::HashSet<_>>()
}
};
assert!(walk(None).await.is_empty(), "the live epoch from the floor holds nothing");
let got = walk(Some((community.root_epoch, None))).await;
crate::clock::shift_for_test(0);
assert!((0..5).all(|i| got.contains(&format!("new{i}")) && got.contains(&format!("mid{i}"))), "every epoch adopted since the proof is read whole");
assert!(!got.iter().any(|t| t.starts_with("old")), "the proof's own epoch is read from its floor");
}
#[tokio::test]
async fn a_proof_holds_only_for_the_epoch_it_was_read_under() {
let (_tmp, _guard, _owner) = init_test_db();
let chat = "ab".repeat(32);
let now = 40 * 24 * 3600;
crate::db::set_sql_setting(format!("history_proven:{chat}"), (now - 3600).to_string()).unwrap();
assert_eq!(crate::history_gaps::proven_epoch(&chat), None, "a proof that names no epoch vouches for nothing");
assert!(crate::history_gaps::floor(&chat, None, now).is_some_and(|f| f < now - 3600), "so the catch-up looks back as if unproven");
crate::history_gaps::prove(&chat, now, 3);
assert_eq!(crate::history_gaps::proven_epoch(&chat), Some(3));
assert!(crate::history_gaps::proven(&chat, 3).is_some_and(|p| p < now));
assert_eq!(crate::history_gaps::proven(&chat, 4), None, "a later epoch was read by nothing");
assert!(crate::history_gaps::history_read(&chat).is_empty());
crate::history_gaps::mark_history_read(&chat, ["aa".repeat(32)]);
assert!(crate::history_gaps::history_read(&chat).contains(&"aa".repeat(32)));
}
#[tokio::test]
async fn after_the_switch_an_unmarked_channel_edition_names_only_a_channel_that_stood() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Allow", vec!["wss://r".into()], None).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let old = create_public_channel(&relay, &held(), "old").await.unwrap();
activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&relay, &held()).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let listed = crate::db::community::get_community_roles(&cid_hex).unwrap().legacy_channels.expect("the switch lists what stood");
assert!(listed.contains(&crate::simd::hex::bytes_to_hex_32(&old.0)) && listed.contains(&crate::simd::hex::bytes_to_hex_32(&community.channels[0].id.0)));
let meta = |name: &str| serde_json::to_string(&control::ChannelMetadata { name: name.into(), private: false, voice: None, deleted: None, custom: None, extra: Default::default() }).unwrap();
// One replayed from another Community never adds a Channel here.
let foreign = ChannelId([0x6f; 32]);
publish_fork(&[&relay], &held(), &owner, vsk::CHANNEL_METADATA, &foreign.0, 1, None, &meta("replayed"), None).await;
follow_control(&relay, &held()).await.unwrap();
assert!(held().channel(&foreign).is_none());
// An unmarked edit of a Channel that stood still folds.
let head = crate::db::community::get_edition_head(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&old.0)).unwrap().unwrap();
publish_fork(&[&relay], &held(), &owner, vsk::CHANNEL_METADATA, &old.0, head.0 + 1, Some(head.1), &meta("renamed"), None).await;
follow_control(&relay, &held()).await.unwrap();
assert_eq!(held().channel(&old).unwrap().name, "renamed");
// A Channel made after the switch is marked, and stands.
let new = create_public_channel(&relay, &held(), "new").await.unwrap();
follow_control(&relay, &held()).await.unwrap();
let joiner = verify_owner_root_and_reconcile(&relay, held()).await.unwrap().community;
assert!(joiner.channel(&new).is_some() && joiner.channel(&old).is_some() && joiner.channel(&foreign).is_none(), "a fresh fold agrees");
// Editing @everyone carries the list.
set_everyone(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT & !Permissions::ADD_REACTIONS).await.unwrap();
follow_control(&relay, &held()).await.unwrap();
assert_eq!(crate::db::community::get_community_roles(&cid_hex).unwrap().legacy_channels, Some(listed.clone()));
// A read that misses @everyone keeps the list, and a replay still finds no room.
let everyone = crate::community::v2::derive::everyone_locator(community.id());
let blind = Hiding { inner: &relay, group: control::ControlPlane::of(&held()).write_group().unwrap(), hide: Box::new(move |e| e.entity_id == everyone) };
let other = ChannelId([0x70; 32]);
publish_fork(&[&relay], &held(), &owner, vsk::CHANNEL_METADATA, &other.0, 1, None, &meta("replayed too"), None).await;
follow_control(&blind, &held()).await.unwrap();
assert!(held().channel(&other).is_none());
assert_eq!(crate::db::community::get_community_roles(&cid_hex).unwrap().legacy_channels, Some(listed.clone()));
// An @everyone edit with a shorter list changes nothing, for this reader or a fresh one.
let head = crate::db::community::get_edition_head(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&everyone)).unwrap().unwrap();
let shorter: std::collections::BTreeSet<String> = listed.iter().filter(|c| **c != crate::simd::hex::bytes_to_hex_32(&old.0)).cloned().collect();
let content = crate::community::v2::roles::everyone_content_json_with(crate::community::v2::roles::EVERYONE_DEFAULT, Some(&shorter));
publish_marked(&relay, &held(), &owner, vsk::ROLE_V2, &everyone, head.0 + 1, Some(head.1), &content).await;
follow_control(&relay, &held()).await.unwrap();
assert_eq!(crate::db::community::get_community_roles(&cid_hex).unwrap().legacy_channels, Some(listed.clone()));
// A list held from elsewhere gives way to the switch's own.
let mut other = crate::db::community::get_community_roles(&cid_hex).unwrap();
other.legacy_channels = Some(shorter.clone());
crate::db::community::set_community_roles(&cid_hex, &other, 0).unwrap();
follow_control(&relay, &held()).await.unwrap();
assert_eq!(crate::db::community::get_community_roles(&cid_hex).unwrap().legacy_channels, Some(listed.clone()));
// After a Refounding the switch itself isn't served: the list held stays, whatever a later
// owner edition says.
let newest = head.0 + 1;
let carried = Hiding { inner: &relay, group: control::ControlPlane::of(&held()).write_group().unwrap(), hide: Box::new(move |e| e.entity_id == everyone && e.version < newest) };
follow_control(&carried, &held()).await.unwrap();
assert_eq!(crate::db::community::get_community_roles(&cid_hex).unwrap().legacy_channels, Some(listed.clone()));
let mut forgot = crate::db::community::get_community_roles(&cid_hex).unwrap();
forgot.legacy_channels = None;
crate::db::community::set_community_roles(&cid_hex, &forgot, 0).unwrap();
let floors: Floors = Default::default();
let fresh = fold_authority(&held(), &fetch_control(&relay, &held()).await, &floors);
assert_eq!(fresh.roles.legacy_channels, Some(listed), "the switch's own list");
}
#[tokio::test]
async fn a_device_that_folded_legacy_edits_made_after_the_switch_lands_where_a_fresh_reader_does() {
// An older client takes a legacy admin's unmarked edits made after the switch, and floors
// them without an author. Once upgraded it must read what every other reader reads.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Upgrade", vec!["wss://r".into()], None).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
// What an older client publishes: unmarked, citing the Grant it holds.
let legacy_edit = |signer: Keys, channel: ChannelId, name: &'static str, version: u64, prev: Option<[u8; 32]>| {
let relay = &relay;
async move {
let community = held();
let cite = cite_on_relay(relay, &community, &signer).await;
let content = serde_json::to_string(&control::ChannelMetadata { name: name.into(), ..Default::default() }).unwrap();
let rumor = control::build_edition_rumor(signer.public_key(), vsk::CHANNEL_METADATA, &channel.0, version, prev.as_ref(), &content, 1_000, cite.as_ref());
let (wrap, _) = control::seal_control_edition(&rumor, &control::ControlPlane::of(&community).write_group().unwrap(), &signer, Timestamp::from_secs(1_000)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
};
let admin = Keys::generate();
let ra = "a7".repeat(32);
publish_role(&relay, &community, &owner, &role_at(&ra, "Admin", 1, Permissions::MANAGE_CHANNELS), 1).await;
publish_grant(&relay, &community, &owner, &admin.public_key(), vec![ra.clone()], 1).await;
// A Channel that stood before the switch, by an admin demoted since, stays where it's held.
let demoted = Keys::generate();
publish_grant(&relay, &community, &owner, &demoted.public_key(), vec![ra.clone()], 1).await;
follow_control(&relay, &held()).await.unwrap();
let early = ChannelId([0x5b; 32]);
legacy_edit(demoted.clone(), early, "early", 1, None).await;
follow_control(&relay, &held()).await.unwrap();
assert!(held().channel(&early).is_some());
publish_grant(&relay, &community, &owner, &demoted.public_key(), vec![], 2).await;
follow_control(&relay, &held()).await.unwrap();
assert!(held().channel(&early).is_some());
activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&relay, &held()).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let hex = |c: &ChannelId| crate::simd::hex::bytes_to_hex_32(&c.0);
// So does one made after the switch, marked, by an admin whose standing went since.
let later = Keys::generate();
let gl = crate::community::v2::derive::grant_locator(community.id(), &later.public_key().to_bytes());
let grant = |role_ids: Vec<String>| crate::community::v2::roles::grant_content_json(&MemberGrant { member: later.public_key().to_hex(), role_ids }).unwrap();
publish_marked(&relay, &held(), &owner, vsk::GRANT, &gl, 1, None, &grant(vec![ra.clone()])).await;
follow_control(&relay, &held()).await.unwrap();
let stood = ChannelId([0x5c; 32]);
let meta = serde_json::to_string(&control::ChannelMetadata { name: "stood".into(), ..Default::default() }).unwrap();
publish_marked(&relay, &held(), &later, vsk::CHANNEL_METADATA, &stood.0, 1, None, &meta).await;
follow_control(&relay, &held()).await.unwrap();
assert!(held().channel(&stood).is_some());
let (gv, gh) = crate::db::community::get_edition_head(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&gl)).unwrap().unwrap();
publish_marked(&relay, &held(), &owner, vsk::GRANT, &gl, gv + 1, Some(gh), &grant(vec![])).await;
follow_control(&relay, &held()).await.unwrap();
let lounge = create_public_channel(&relay, &held(), "lounge").await.unwrap();
follow_control(&relay, &held()).await.unwrap();
let (v, _) = crate::db::community::get_edition_head(&cid_hex, &hex(&lounge)).unwrap().unwrap();
// That build chains to the owner's marked edition by its unsigned hash.
let marked = fetch_control(&relay, &held()).await.into_iter().find(|e| e.entity_id == lounge.0 && e.version == v).unwrap();
assert!(marked.binding.is_some());
let unsigned = crate::community::version::edition_hash(&marked.entity_id, marked.version, marked.prev_hash.as_ref(), marked.content.as_bytes());
let made = ChannelId([0x5a; 32]);
legacy_edit(admin.clone(), lounge, "renamed", v + 1, Some(unsigned)).await;
legacy_edit(admin.clone(), made, "made", 1, None).await;
let editions = fetch_control(&relay, &held()).await;
let edition = |c: &ChannelId, version: u64| editions.iter().find(|e| e.entity_id == c.0 && e.version == version).unwrap().clone();
let (renamed, own) = (edition(&lounge, v + 1), edition(&made, 1));
crate::db::community::set_edition_head_with_id(&cid_hex, &hex(&lounge), renamed.version, &renamed.self_hash, &renamed.inner_id).unwrap();
crate::db::community::set_edition_head_with_id(&cid_hex, &hex(&made), own.version, &own.self_hash, &own.inner_id).unwrap();
let mut old = held();
old.channels.iter_mut().find(|c| c.id == lounge).unwrap().name = "renamed".into();
let mut extra = old.channels[0].clone();
extra.id = made;
extra.name = "made".into();
old.channels.push(extra);
crate::db::community::save_community_v2(&old).unwrap();
let joiner = verify_owner_root_and_reconcile(&relay, community.clone()).await.unwrap().community;
assert_eq!(joiner.channel(&lounge).map(|c| c.name.as_str()), Some("lounge"), "a fresh reader refuses the rename");
assert!(joiner.channel(&made).is_none(), "and the Channel");
follow_control(&relay, &held()).await.unwrap();
assert_eq!(held().channel(&lounge).map(|c| c.name.as_str()), Some("lounge"));
assert!(held().channel(&made).is_none());
assert!(held().channel(&early).is_some() && held().channel(&stood).is_some());
}
#[tokio::test]
async fn a_manager_behind_on_the_ledger_never_forks_it() {
use crate::community::roles::OverwriteTarget;
use crate::community::v2::writers::{writer_address, Spell};
let (bed, owner, x, community) = v2_bed_with_admin("Behind").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let m = Keys::generate();
let plain = create_role_v2(&bed.relay, &held(), "Member", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(), &m.public_key(), vec![plain]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(m.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
// Another manager moves the ledger on; this device hasn't folded it.
let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let (_, head) = crate::db::community::get_edition_head(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&eid)).unwrap().unwrap();
let theirs = held().channel(&general).unwrap().writers.clone().unwrap().appended(now_ms(), Spell::Writer { epoch: Epoch(2), pk: writer_address(&[0x2b; 32], &general, Epoch(2)), root: Epoch(0), by: x.public_key().to_bytes(), certifier: None }).unwrap();
let group = control::ControlPlane::of(&held()).write_group().unwrap();
let cite = cite_on_relay(&bed.relay, &held(), &x).await;
let secs = now_ms() / 1000;
let rumor = control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, 2, Some(&head), &theirs.to_json(), secs, cite.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())));
let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(secs)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
// Cutting m reads the plane again first, finds the ledger moved, and leaves it.
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(m.public_key().to_hex()), 0, 0).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
assert_eq!(ledger.live().map(|l| l.1), Some(x.public_key().to_bytes()), "the other manager's entry stands, not a fork over it");
let _ = owner;
}
#[tokio::test]
async fn sealed_details_open_with_the_key_of_their_own_epoch() {
let (bed, _owner, _x, community) = v2_bed_with_admin("Epochs").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "vault").await.unwrap();
let first = held().channel(&ch).unwrap().clone();
let old_key = first.key.unwrap();
// Rotate, then put a head sealed under the archived epoch over the rotator's reseal.
let y = Keys::generate();
let guests = create_role_v2(&bed.relay, &held(), "Guests", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(), &y.public_key(), vec![guests]).await.unwrap();
set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Member(y.public_key().to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Member(y.public_key().to_hex()), 0, 0).await.unwrap();
assert!(held().channel(&ch).unwrap().epoch > first.epoch);
let mut meta = first.metadata();
meta.name = "old-epoch name".into();
let prev = channel_head(&held(), &ch).unwrap();
let content = control::seal_channel_metadata(&meta, channel_group_key(&old_key, &ch, first.epoch).conv_key(), first.epoch.0, prev.as_ref()).unwrap();
publish_control_edition(&bed.relay, &held(), vsk::CHANNEL_METADATA, &ch.0, &content).await.unwrap();
let mut stale = held();
stale.channels.iter_mut().find(|c| c.id == ch).unwrap().sealed = None;
crate::db::community::save_community_v2(&stale).unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let read = held().channel(&ch).cloned().unwrap();
assert_eq!((read.name.as_str(), read.sealed.as_ref().map(|s| s.open)), ("old-epoch name", Some(true)), "the archived key of its epoch opens it");
}
#[tokio::test]
async fn a_seal_the_key_cant_open_keeps_what_was_read_and_is_sealed_again() {
let (bed, owner, _x, community) = v2_bed_with_admin("Junk").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "keep").await.unwrap();
let epoch = held().channel(&ch).unwrap().epoch;
let first_head = channel_head(&held(), &ch).unwrap().unwrap();
let first_content = held().channel(&ch).unwrap().sealed.clone().unwrap().raw;
// Garbage under the live epoch, then the first seal replayed as a newer edition.
for (why, content) in [
("garbage", serde_json::json!({ "private": true, "epoch": epoch.0.to_string(), "sealed": "AAAA" }).to_string()),
("a replay", first_content.clone()),
] {
publish_control_edition(&bed.relay, &held(), vsk::CHANNEL_METADATA, &ch.0, &content).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let read = held().channel(&ch).cloned().unwrap();
assert!(read.sealed.as_ref().is_some_and(|s| s.junk) && read.name == "keep", "{why}: the details last read stay");
follow_control(&bed.relay, &held()).await.unwrap();
assert!(held().channel(&ch).unwrap().sealed.as_ref().is_some_and(|s| s.junk), "{why}: tried again, still junk");
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().resealed, 1, "{why}: and a manager seals them again");
follow_control(&bed.relay, &held()).await.unwrap();
assert!(held().channel(&ch).unwrap().sealed.as_ref().is_some_and(|s| s.open), "{why}");
}
assert_ne!(channel_head(&held(), &ch).unwrap(), Some(first_head));
let _ = owner;
}
#[tokio::test]
async fn a_sealed_head_on_a_public_channel_takes_it_private_and_keyless() {
let (bed, _owner, _x, community) = v2_bed_with_admin("Public").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let content = serde_json::json!({ "private": true, "epoch": "1", "sealed": "AAAA" }).to_string();
publish_control_edition(&bed.relay, &held(), vsk::CHANNEL_METADATA, &general.0, &content).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let ch = held().channel(&general).cloned().unwrap();
assert!(ch.private && ch.key.is_none() && ch.sealed.is_some(), "made private, it waits for its key rotation");
assert!(held().channel_read_coords(&ch).is_empty(), "and is never read or sent at the public plane meanwhile");
}
#[tokio::test]
async fn history_pages_two_busy_addresses_without_a_gap() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Pages2", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let now = now_ms();
// Read-address posts spread over the last day, then writer posts packed in the last hour.
for i in 0..15u64 {
send_chat_message_at(&bed.relay, &held(), &general, &format!("open {i}"), None, &[], vec![], now - 86_400_000 + i * 3_600_000).await.unwrap();
}
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
for i in 0..15u64 {
send_chat_message_at(&bed.relay, &held(), &general, &format!("writer {i}"), None, &[], vec![], now - 3_600_000 + i * 60_000 + 60_000).await.unwrap();
}
let got = fetch_channel_history(&bed.relay, &held(), &general, 10, 10, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
let posts = got.iter().filter(|f| matches!(f.event, ChatEvent::Message { .. })).count();
assert_eq!(posts, 30, "both addresses page down without skipping either");
}
#[tokio::test]
async fn a_slow_clock_never_closes_a_window_on_posts_already_made() {
use crate::community::roles::OverwriteTarget;
let (bed, _owner, _x, community) = v2_bed_with_admin("Clock").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
// Someone whose clock runs ahead posted "two minutes from now".
let ahead = now_ms() + 120_000;
send_chat_message_at(&bed.relay, &held(), &general, "from a fast clock", None, &[], vec![], ahead).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
let entry = held().channel(&general).unwrap().writers.as_ref().unwrap().entries[0].at;
assert!(entry > ahead, "the window opens after the newest post held");
}
#[tokio::test]
async fn a_writers_blob_vouches_for_nobody() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _x, community) = v2_bed_with_admin("Vouch").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let (w, w2) = (Keys::generate(), Keys::generate());
let plain = create_role_v2(&bed.relay, &held(), "Member", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain.clone()]).await.unwrap();
set_member_roles(&bed.relay, &held(), &w2.public_key(), vec![plain]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(w2.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await;
follow_control(&bed.relay, &held()).await.unwrap();
let (live, pk) = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap();
act_as(&w);
deliver_on_plane(&bed.relay, &held(), &general, crate::community::v2::writers::writer_rekey_scope(&general), live, Some(pk), &[0x99; 32], &[w2.public_key()]).await.unwrap();
act_as(&owner.keys);
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.delivered, 1, "a writer's blob at w2's locator still leaves w2 owed");
}
#[tokio::test]
async fn a_ledger_head_its_signer_lost_standing_for_is_kept() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, x, community) = v2_bed_with_admin("Kept").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
act_as(&x);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
act_as(&owner.keys);
follow_control(&bed.relay, &held()).await.unwrap();
let minted = held().channel(&general).unwrap().writers.clone().unwrap();
assert!(minted.entries.len() == 2 && !minted.restricted(), "x reopened what the owner restricted");
// x's standing goes with nothing sealing what x did.
publish_grant(&bed.relay, &held(), &owner.keys, &x.public_key(), vec![], 2).await;
follow_control(&bed.relay, &held()).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers, Some(minted), "what the ledger recorded stays recorded");
}
#[tokio::test]
async fn a_caller_paging_from_its_oldest_row_misses_nothing() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Frontier", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let now = now_ms();
for i in 0..15u64 {
send_chat_message_at(&bed.relay, &held(), &general, &format!("open {i}"), None, &[], vec![], now - 86_400_000 + i * 3_600_000).await.unwrap();
}
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
let opened = held().channel(&general).unwrap().writers.as_ref().unwrap().entries[0].at;
for i in 0..15u64 {
send_chat_message_at(&bed.relay, &held(), &general, &format!("writer {i}"), None, &[], vec![], opened + i * 1_000 + 1_000).await.unwrap();
}
// The writers' posts are dated just ahead; read once they are due.
crate::clock::shift_for_test(60_000);
let mut seen = std::collections::HashSet::new();
let mut until = None;
for _ in 0..12 {
let page = fetch_channel_history(&bed.relay, &held(), &general, 10, 1, None, until, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
let fresh: Vec<&FetchedEvent> = page.iter().filter(|f| matches!(f.event, ChatEvent::Message { .. }) && seen.insert(f.event.opened().rumor_id)).collect();
let Some(oldest) = page.iter().map(|f| f.event.opened().at_ms).min() else { break };
if fresh.is_empty() && until == Some(oldest / 1000) {
break;
}
until = Some(oldest / 1000);
}
crate::clock::shift_for_test(0);
assert_eq!(seen.len(), 30, "one page at a time from its oldest row, every post comes");
}
#[tokio::test]
async fn a_writers_ledger_needs_manage_channels_and_the_mark() {
use crate::community::v2::writers::{writer_address, Ledger, Spell};
let (bed, owner, x, community) = v2_bed_with_admin("Ledger").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let head = || crate::db::community::get_edition_head(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&eid)).unwrap().map(|h| h.1);
// publish_marked dates an edition at 2_000 + version seconds.
let at = |version: u64| (2_000 + version) * 1000;
let mint = |base: &Ledger, at: u64, n: u8, by: &Keys| {
let epoch = base.next_epoch().unwrap();
base.appended(at, Spell::Writer { epoch, pk: writer_address(&[n; 32], &general, epoch), root: Epoch(0), by: by.public_key().to_bytes(), certifier: None }).unwrap()
};
let empty = Ledger::new(&general);
let plain = create_role_v2(&bed.relay, &held(), "Member", 0, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
let nobody = Keys::generate();
set_member_roles(&bed.relay, &held(), &nobody.public_key(), vec![plain]).await.unwrap();
publish_marked(&bed.relay, &held(), &nobody, vsk::WRITERS, &eid, 1, None, &mint(&empty, at(1), 1, &nobody).to_json()).await;
follow_control(&bed.relay, &held()).await.unwrap();
assert!(held().channel(&general).unwrap().writers.is_none(), "a member without Manage Channels moves nothing");
let group = control::ControlPlane::of(&held()).write_group().unwrap();
let rumor = control::build_edition_rumor(owner.keys.public_key(), vsk::WRITERS, &eid, 1, None, &mint(&empty, 2_100_000, 2, &owner.keys).to_json(), 2_100, None);
let (wrap, _) = control::seal_control_edition(&rumor, &group, &owner.keys, Timestamp::from_secs(2_100)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert!(held().channel(&general).unwrap().writers.is_none(), "a new kind is read marked only");
// A first edition holds one entry, or it could close the read address over the past.
let backdated = mint(&empty, at(1) - 1_000_000, 6, &x).appended(at(1), Spell::Open).unwrap();
publish_marked(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 1, None, &backdated.to_json()).await;
follow_control(&bed.relay, &held()).await.unwrap();
assert!(held().channel(&general).unwrap().writers.is_none(), "a first edition with history");
// And an entry dated past this reader's horizon waits.
let ahead = mint(&empty, now_ms() + 2 * 3_600_000, 7, &x);
let group = control::ControlPlane::of(&held()).write_group().unwrap();
let cite = cite_on_relay(&bed.relay, &held(), &x).await;
let secs = ahead.entries[0].at / 1000;
let rumor = control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, 1, None, &ahead.to_json(), secs, cite.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())));
let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(secs)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert!(held().channel(&general).unwrap().writers.is_none(), "a far-future ledger");
let first = mint(&empty, at(1), 3, &x);
publish_marked(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 1, None, &first.to_json()).await;
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers, Some(first.clone()), "a channel manager's ledger stands");
// Successors that break the ledger's rules never fold: the head it had stays.
let other = Ledger::new(&ChannelId([0x05; 32])).appended(at(2), Spell::Open).unwrap();
let foreign_minter = first.appended(at(2), Spell::Writer { epoch: Epoch(2), pk: writer_address(&[4; 32], &general, Epoch(2)), root: Epoch(0), by: owner.keys.public_key().to_bytes(), certifier: None }).unwrap();
for (why, content) in [
("another channel's", other.to_json()),
("malformed", r#"{"channel":"00"}"#.to_string()),
("rewriting what it carries", mint(&empty, at(2), 9, &x).to_json()),
("a writer entry another signed", foreign_minter.to_json()),
("dated an hour from its edition", first.appended(at(2) + 3_600_000, Spell::Open).unwrap().to_json()),
("two entries at once", first.appended(at(2), Spell::Open).unwrap().appended(at(2), Spell::Writer { epoch: Epoch(2), pk: writer_address(&[5; 32], &general, Epoch(2)), root: Epoch(0), by: x.public_key().to_bytes(), certifier: None }).unwrap().to_json()),
] {
publish_marked(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 2, head(), &content).await;
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers, Some(first.clone()), "{why}");
}
// Nor one whose entry is dated before the one it follows.
let mut early: serde_json::Value = serde_json::from_str(&first.appended(at(2), Spell::Open).unwrap().to_json()).unwrap();
early["ledger"][1]["at"] = serde_json::json!(at(1) - 1_000);
publish_marked(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 2, head(), &early.to_string()).await;
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers, Some(first.clone()), "dated before the entry it follows");
// A manager's root beside the chain, with the longer history: a reader that holds the
// chain keeps it, a fresh one takes the longer, and with its signer's standing gone, the first.
let y = Keys::generate();
let mods = create_role_v2(&bed.relay, &held(), "Mod", 0, Permissions::MANAGE_CHANNELS | crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
set_member_roles(&bed.relay, &held(), &y.public_key(), vec![mods]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let beside = mint(&first, at(2), 8, &y);
publish_marked(&bed.relay, &held(), &y, vsk::WRITERS, &eid, 2, Some([0x3c; 32]), &beside.to_json()).await;
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers, Some(first.clone()), "a dangling predecessor");
let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
assert!(fresh.writers.iter().any(|(_, content, ..)| *content == beside.to_json()), "a fresh fold takes the longer history");
publish_grant(&bed.relay, &held(), &owner.keys, &y.public_key(), vec![], 2).await;
follow_control(&bed.relay, &held()).await.unwrap();
let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
assert!(fresh.writers.iter().any(|(_, content, ..)| *content == first.to_json()), "with its signer's standing gone, the first stands");
let second = first.appended(at(2), Spell::Open).unwrap();
publish_marked(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 2, head(), &second.to_json()).await;
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers, Some(second.clone()), "one that carries it forward moves it on");
// A fresh joiner folds the ledger from the join walk itself.
let joiner = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
assert!(joiner.writers.iter().any(|(c, content, ..)| *c == crate::simd::hex::bytes_to_hex_32(&general.0) && *content == second.to_json()));
}
/// The texts of a channel's posts its writers' rules don't stand behind, oldest first: what a
/// device that manages the channel keeps marked.
async fn marked_texts<T: Transport + ?Sized>(relay: &T, community: &CommunityV2, channel: &ChannelId) -> Vec<String> {
fetch_channel_history(relay, community, channel, 100, 8, None, Some(now_ms() / 1000 + 3600), crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default())
.await
.unwrap()
.iter()
.filter(|f| matches!(f.event, ChatEvent::Message { .. }) && f.event.opened().held)
.map(|f| f.event.opened().rumor.content.clone())
.collect()
}
fn sorted(mut v: Vec<String>) -> Vec<String> {
v.sort();
v
}
/// A writer certificate for `writer` at `epoch` of `channel`, from the certifier this device minted.
fn cert_for(community: &CommunityV2, channel: &ChannelId, epoch: Epoch, writer: &PublicKey) -> [u8; 64] {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let secret = crate::db::community::held_epoch_key(&cid_hex, &crate::community::v2::writers::certifier_scope(channel), epoch.0).unwrap().unwrap();
crate::community::v2::writers::sign_writer_cert(&secret, &crate::community::v2::writers::cert_digest(&community.id().0, &channel.0, epoch, &writer.to_bytes())).unwrap()
}
/// [`publish_marked`], returning the edition's hash.
async fn publish_marked_hash(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, vsk_code: &str, eid: &[u8; 32], version: u64, prev: Option<[u8; 32]>, content: &str) -> [u8; 32] {
let group = control::ControlPlane::of(community).write_group().unwrap();
let cite = cite_on_relay(relay, community, signer).await;
let binding = Some(crate::community::v2::derive::edition_binding(community.id()));
let rumor = control::build_edition_rumor_bound(signer.public_key(), vsk_code, eid, version, prev.as_ref(), content, 2_000 + version, cite.as_ref(), binding);
let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(2_000 + version)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
control::open_control_edition(&wrap, &group).unwrap().0.self_hash
}
#[tokio::test]
async fn the_longest_ledger_history_takes_every_reader() {
use crate::community::v2::writers::{writer_address, Ledger, Spell};
let (bed, owner, x, community) = v2_bed_with_admin("Longest").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
let at = |version: u64| (2_000 + version) * 1000;
let mint = |base: &Ledger, at: u64, n: u8, by: &Keys| {
let epoch = base.next_epoch().unwrap();
base.appended(at, Spell::Writer { epoch, pk: writer_address(&[n; 32], &general, epoch), root: Epoch(0), by: by.public_key().to_bytes(), certifier: None }).unwrap()
};
// x's chain, three long, against the owner's lone first edition: rank settles only a tie.
let first = mint(&Ledger::new(&general), at(1), 1, &x);
let h1 = publish_marked_hash(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 1, None, &first.to_json()).await;
let second = first.appended(at(2), Spell::Open).unwrap();
let h2 = publish_marked_hash(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 2, Some(h1), &second.to_json()).await;
let third = mint(&second, at(3), 3, &x);
publish_marked(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 3, Some(h2), &third.to_json()).await;
publish_marked(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 1, None, &mint(&Ledger::new(&general), at(1), 9, &owner.keys).to_json()).await;
// A first edition is version 1: one that names no predecessor higher up roots nothing.
publish_marked(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 7, None, &mint(&Ledger::new(&general), at(7), 7, &owner.keys).to_json()).await;
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers, Some(third.clone()));
let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
assert!(fresh.writers.iter().any(|(_, content, ..)| *content == third.to_json()), "a fresh reader takes the same");
// After a Refounding, the head it carried outlasts a first edition made after it.
let carried_ch = create_public_channel(&bed.relay, &held(), "carried").await.unwrap();
let eid2 = crate::community::v2::derive::writers_locator(community.id(), &carried_ch);
let mint2 = |base: &Ledger, at: u64, n: u8, by: &Keys| {
let epoch = base.next_epoch().unwrap();
base.appended(at, Spell::Writer { epoch, pk: writer_address(&[n; 32], &carried_ch, epoch), root: Epoch(0), by: by.public_key().to_bytes(), certifier: None }).unwrap()
};
let head = mint2(&mint2(&Ledger::new(&carried_ch), at(1), 1, &owner.keys), at(9), 2, &owner.keys);
let hc = publish_marked_hash(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid2, 9, Some([0x5a; 32]), &head.to_json()).await;
let grown = head.appended(at(10), Spell::Open).unwrap();
publish_marked(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid2, 10, Some(hc), &grown.to_json()).await;
publish_marked(&bed.relay, &held(), &x, vsk::WRITERS, &eid2, 1, None, &mint2(&Ledger::new(&carried_ch), at(1), 8, &x).to_json()).await;
let fresh = verify_owner_root_and_reconcile(&bed.relay, held()).await.unwrap();
assert!(fresh.writers.iter().any(|(_, content, ..)| *content == grown.to_json()));
}
#[tokio::test]
async fn a_post_dated_far_ahead_never_dates_a_ledger_entry() {
use crate::community::roles::OverwriteTarget;
let (bed, _owner, _x, community) = v2_bed_with_admin("Ahead").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let tomorrow = now_ms() + 86_400_000;
send_chat_message_at(&bed.relay, &held(), &general, "from tomorrow", None, &[], vec![], tomorrow).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone().expect("restricted");
assert!(ledger.entries[0].at < tomorrow, "a post's date is no clock");
let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
assert!(fresh.writers.iter().any(|(_, content, ..)| *content == ledger.to_json()), "another reader folds it");
}
#[tokio::test]
async fn a_manager_after_a_fast_clock_publishes_what_readers_take() {
use crate::community::roles::OverwriteTarget;
use crate::community::v2::writers::{writer_address, Ledger, Spell};
let (bed, owner, x, community) = v2_bed_with_admin("Skew").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
// x restricts with a clock half an hour fast.
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await;
let fast = now_ms() + 1_800_000;
let ledger = Ledger::new(&general).appended(fast, Spell::Writer { epoch: Epoch(1), pk: writer_address(&[0x21; 32], &general, Epoch(1)), root: Epoch(0), by: x.public_key().to_bytes(), certifier: None }).unwrap();
let group = control::ControlPlane::of(&held()).write_group().unwrap();
let cite = cite_on_relay(&bed.relay, &held(), &x).await;
let rumor = control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, 1, None, &ledger.to_json(), fast / 1000, cite.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())));
let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(fast / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers, Some(ledger));
// The owner reopens it straight after.
act_as(&owner.keys);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, Permissions::SEND_MESSAGES, 0).await.unwrap();
let reopened = held().channel(&general).unwrap().writers.clone().unwrap();
assert!(!reopened.restricted() && reopened.entries.len() == 2);
let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
assert!(fresh.writers.iter().any(|(_, content, ..)| *content == reopened.to_json()), "another reader folds it");
let mine = fetch_control(&bed.relay, &held()).await.into_iter().find(|e| e.vsk == vsk::WRITERS && e.author == owner.keys.public_key()).unwrap();
assert!(mine.created_at >= fast / 1000, "dated with the entry it carries");
let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
let ahead = bed.relay.fetch(&query, &held().relays).await.unwrap().iter().filter(|w| w.created_at.as_secs() > now_ms() / 1000 + 1).count();
assert_eq!(ahead, 1, "x's own is the one wrap dated ahead for a relay to refuse");
}
#[tokio::test]
async fn a_ledger_this_device_cant_chain_from_is_never_published_over() {
use crate::community::roles::OverwriteTarget;
let (bed, _owner, _x, community) = v2_bed_with_admin("Unchained").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let w = Keys::generate();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Member", 0, 0).await.unwrap()]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let eid_hex = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::writers_locator(community.id(), &general));
// The head this device would chain from isn't the ledger it holds.
crate::db::community::set_edition_head(&cid_hex, &eid_hex, 7, &[0x42; 32]).unwrap();
let before = fetch_control(&bed.relay, &held()).await.iter().filter(|e| e.vsk == vsk::WRITERS).count();
let scope = crate::community::v2::writers::writer_rekey_scope(&general);
let delivered = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap().len();
// Cutting w takes a mint: none goes out, not even its deliveries; nor does a reopen.
let _ = set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, 0).await;
let _ = set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await;
assert_eq!(fetch_control(&bed.relay, &held()).await.iter().filter(|e| e.vsk == vsk::WRITERS).count(), before, "nothing readers would refuse goes out");
assert_eq!(fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap().len(), delivered, "nor a key for one");
assert_eq!(held().channel(&general).unwrap().writers, Some(ledger));
}
#[tokio::test]
async fn the_switch_refuses_more_channels_than_it_can_list() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let crowd = |name: &'static str, total: usize| {
let relay = &relay;
async move {
let community = create_community(relay, name, vec!["wss://r".into()], None).await.unwrap();
let mut crowded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = crowded.channels[0].clone();
for i in 1..total {
let mut ch = general.clone();
ch.id = ChannelId(crate::community::random_32());
ch.name = format!("c{i}");
crowded.channels.push(ch);
}
crate::db::community::save_community_v2(&crowded).unwrap();
crowded
}
};
let max = crate::community::v2::roles::MAX_LEGACY_CHANNELS;
let full = crowd("Full", max).await;
activate_roles_v2(&relay, &full, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&relay, &full).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&full.id().0);
assert_eq!(crate::db::community::get_community_roles(&cid_hex).unwrap().legacy_channels.map(|l| l.len()), Some(max), "every one listed");
let crowded = crowd("Crowded", max + 1).await;
let err = activate_roles_v2(&relay, &crowded, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap_err();
assert!(err.contains("at most"), "{err}");
assert!(!fetch_authority(&relay, &crowded).await.activated, "nothing switched");
}
#[tokio::test]
async fn a_reader_builds_on_the_ledger_it_holds_when_a_window_misses_it() {
use crate::community::v2::writers::{writer_address, Ledger, Spell};
let (bed, owner, _x, community) = v2_bed_with_admin("Anchored").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
let at = |version: u64| (2_000 + version) * 1000;
let first = Ledger::new(&general).appended(at(1), Spell::Writer { epoch: Epoch(1), pk: writer_address(&[1; 32], &general, Epoch(1)), root: Epoch(0), by: owner.keys.public_key().to_bytes(), certifier: None }).unwrap();
let h1 = publish_marked_hash(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 1, None, &first.to_json()).await;
let second = first.appended(at(2), Spell::Open).unwrap();
let h2 = publish_marked_hash(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 2, Some(h1), &second.to_json()).await;
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers, Some(second.clone()));
let third = second.appended(at(3), Spell::Writer { epoch: Epoch(2), pk: writer_address(&[2; 32], &general, Epoch(2)), root: Epoch(0), by: owner.keys.public_key().to_bytes(), certifier: None }).unwrap();
publish_marked(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 3, Some(h2), &third.to_json()).await;
// A read that serves the first edition and the newest, not the one this reader holds.
let window = Hiding { inner: &bed.relay, group: control::ControlPlane::of(&held()).write_group().unwrap(), hide: Box::new(move |e| e.self_hash == h2) };
follow_control(&window, &held()).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers, Some(third));
}
/// Refuses Control Plane publishes after the first `allow`: a relay that goes away mid-change.
struct RefusesControl<'a> {
inner: &'a MemoryRelay,
control: String,
allow: std::sync::atomic::AtomicUsize,
tried: std::sync::atomic::AtomicUsize,
}
#[async_trait::async_trait]
impl Transport for RefusesControl<'_> {
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
self.inner.fetch_plane(plane, query, relays).await
}
#[allow(deprecated)] // fetch_update, see next_send_ms
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
if e.pubkey.to_hex() == self.control {
self.tried.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
if e.pubkey.to_hex() == self.control && self.allow.fetch_update(std::sync::atomic::Ordering::SeqCst, std::sync::atomic::Ordering::SeqCst, |n| n.checked_sub(1)).is_err() {
return Err("refused".into());
}
self.inner.publish(e, r).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.publish(e, r).await
}
async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
self.inner.fetch(q, r).await
}
}
#[tokio::test]
async fn a_change_whose_ledger_failed_to_publish_is_finished_by_the_next_pass() {
use crate::community::roles::OverwriteTarget;
let (bed, _owner, _x, community) = v2_bed_with_admin("Unfinished").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
assert!(access_duty_due(community.id(), false));
assert!(!access_duty_due(community.id(), false), "not again within the period");
// The overwrite lands; the ledger edition after it doesn't.
let flaky = RefusesControl { inner: &bed.relay, control: control::ControlPlane::of(&held()).write_group().unwrap().pk_hex(), allow: 1.into(), tried: 0.into() };
assert!(set_overwrite(&flaky, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.is_err());
assert!(!held().channel(&general).unwrap().restricted());
assert!(access_duty_due(community.id(), false), "making the change again would move nothing, so the duty runs next pass");
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 1);
assert!(held().channel(&general).unwrap().restricted());
}
#[tokio::test]
async fn a_backstop_on_a_roster_read_before_the_change_stands_down() {
use crate::community::roles::OverwriteTarget;
let (bed, _owner, _x, community) = v2_bed_with_admin("Stale").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let stale = crate::db::community::get_community_roles(&cid_hex).unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
assert_eq!(writing::backstop_on(&bed.relay, &held(), &general, &stale).await.unwrap(), writing::Backstop::StoodDown, "a roster from before the restrict reopens nothing");
assert_eq!(held().channel(&general).unwrap().writers, Some(ledger));
}
#[tokio::test]
async fn a_backstop_that_fails_waits_like_one_that_acted() {
use crate::community::roles::OverwriteTarget;
let (bed, _owner, _x, community) = v2_bed_with_admin("Fails").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await;
follow_control(&bed.relay, &held()).await.unwrap();
let refusing = RefusesControl { inner: &bed.relay, control: control::ControlPlane::of(&held()).write_group().unwrap().pk_hex(), allow: 0.into(), tried: 0.into() };
let scope = crate::community::v2::writers::writer_rekey_scope(&general);
let delivered = || async { fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap().len() };
let _ = access_duty(&refusing, &held()).await;
assert_eq!(delivered().await, 0, "a ledger the relays refuse sends nothing after it");
assert!(!held().channel(&general).unwrap().restricted());
let _ = access_duty(&refusing, &held()).await;
assert_eq!(delivered().await, 0, "and the next pass waits too");
}
#[tokio::test]
async fn an_edit_from_an_old_read_keeps_a_rename_that_landed_since() {
let (bed, owner, x, community) = v2_bed_with_admin("Merge").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let stale = held();
act_as(&x);
let mut renamed = held().channel(&general).unwrap().metadata();
renamed.name = "renamed".into();
edit_channel_metadata(&bed.relay, &held(), &general, &renamed).await.unwrap();
act_as(&owner.keys);
follow_control(&bed.relay, &held()).await.unwrap();
// The owner's edit was built from what it read before the rename.
let mut topic = stale.channel(&general).unwrap().metadata();
topic.extra.insert("topic".into(), "news".into());
edit_channel_metadata(&bed.relay, &stale, &general, &topic).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let ch = held().channel(&general).cloned().unwrap();
assert_eq!((ch.name.as_str(), ch.meta_extra.get("topic").and_then(|t| t.as_str())), ("renamed", Some("news")));
// A client's own fields merge one by one too.
let stale = held();
act_as(&x);
let mut theirs = held().channel(&general).unwrap().metadata();
theirs.custom.get_or_insert_with(Default::default).insert("a".into(), 1.into());
edit_channel_metadata(&bed.relay, &held(), &general, &theirs).await.unwrap();
act_as(&owner.keys);
follow_control(&bed.relay, &held()).await.unwrap();
let mut mine = stale.channel(&general).unwrap().metadata();
mine.custom.get_or_insert_with(Default::default).insert("b".into(), 2.into());
edit_channel_metadata(&bed.relay, &stale, &general, &mine).await.unwrap();
let custom = held().channel(&general).unwrap().meta_custom.clone().unwrap_or_default();
assert_eq!((custom.get("a"), custom.get("b")), (Some(&1.into()), Some(&2.into())));
}
#[tokio::test]
async fn a_ledger_nobody_can_fold_blocks_nobody() {
use crate::community::roles::OverwriteTarget;
use crate::community::v2::writers::{writer_address, Ledger, Spell};
let (bed, owner, x, community) = v2_bed_with_admin("Refused").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
// x's ledger is dated past this reader's horizon: served, and refused whole.
let ahead = now_ms() + 2 * 3_600_000;
let ledger = Ledger::new(&general).appended(ahead, Spell::Writer { epoch: Epoch(1), pk: writer_address(&[3; 32], &general, Epoch(1)), root: Epoch(0), by: x.public_key().to_bytes(), certifier: None }).unwrap();
let group = control::ControlPlane::of(&held()).write_group().unwrap();
let cite = cite_on_relay(&bed.relay, &held(), &x).await;
let rumor = control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, 1, None, &ledger.to_json(), ahead / 1000, cite.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())));
let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(now_ms() / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert!(held().channel(&general).unwrap().writers.is_none());
// A member without Manage Channels blocks nothing with one of their own.
let two = create_public_channel(&bed.relay, &held(), "two").await.unwrap();
let m = Keys::generate();
set_member_roles(&bed.relay, &held(), &m.public_key(), vec![create_role_v2(&bed.relay, &held(), "Member", 0, 0).await.unwrap()]).await.unwrap();
let eid_two = crate::community::v2::derive::writers_locator(community.id(), &two);
let theirs = Ledger::new(&two).appended(2_001_000, Spell::Open).unwrap();
publish_marked(&bed.relay, &held(), &m, vsk::WRITERS, &eid_two, 1, None, &theirs.to_json()).await;
follow_control(&bed.relay, &held()).await.unwrap();
act_as(&x);
set_overwrite(&bed.relay, &held(), two.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
assert!(held().channel(&two).unwrap().restricted());
// Nor does a ledger nobody can fold yet: a manager restricts over it.
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
act_as(&owner.keys);
let mine = held().channel(&general).unwrap().writers.clone().expect("restricted");
let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
assert!(fresh.writers.iter().any(|(_, content, ..)| *content == mine.to_json()), "another reader takes it");
}
#[tokio::test]
async fn a_settled_race_stays_settled_when_ranks_change() {
use crate::community::v2::writers::{writer_address, Ledger, Spell};
let (bed, _owner, x, community) = v2_bed_with_admin("Settled").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
let y = Keys::generate();
let mods = create_role_v2(&bed.relay, &held(), "Mod", 0, Permissions::MANAGE_CHANNELS | crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
set_member_roles(&bed.relay, &held(), &y.public_key(), vec![mods]).await.unwrap();
let at = |version: u64| (2_000 + version) * 1000;
let mint = |at: u64, n: u8, by: &Keys| Ledger::new(&general).appended(at, Spell::Writer { epoch: Epoch(1), pk: writer_address(&[n; 32], &general, Epoch(1)), root: Epoch(0), by: by.public_key().to_bytes(), certifier: None }).unwrap();
// x and y restrict at once; x's goes on.
publish_marked(&bed.relay, &held(), &y, vsk::WRITERS, &eid, 1, None, &mint(at(1), 2, &y).to_json()).await;
let xs = mint(at(1), 1, &x);
let h1 = publish_marked_hash(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 1, None, &xs.to_json()).await;
let grown = xs.appended(at(2), Spell::Open).unwrap();
publish_marked(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 2, Some(h1), &grown.to_json()).await;
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers, Some(grown.clone()));
// x steps down, its decisions sealed: y now outranks it, and nothing flips.
set_member_roles(&bed.relay, &held(), &x.public_key(), vec![]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers, Some(grown.clone()));
let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
assert!(fresh.writers.iter().any(|(_, content, ..)| *content == grown.to_json()), "a fresh reader takes the longer history");
}
#[tokio::test]
async fn an_edition_on_a_hidden_held_head_must_extend_it() {
use crate::community::v2::writers::{writer_address, Ledger, Spell};
let (bed, owner, _x, community) = v2_bed_with_admin("Extend").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
let at = |version: u64| (2_000 + version) * 1000;
let first = Ledger::new(&general).appended(at(1), Spell::Writer { epoch: Epoch(1), pk: writer_address(&[1; 32], &general, Epoch(1)), root: Epoch(0), by: owner.keys.public_key().to_bytes(), certifier: None }).unwrap();
let h1 = publish_marked_hash(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 1, None, &first.to_json()).await;
let second = first.appended(at(2), Spell::Open).unwrap();
let h2 = publish_marked_hash(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 2, Some(h1), &second.to_json()).await;
follow_control(&bed.relay, &held()).await.unwrap();
// Names the held head, but drops what it carried.
let skipped = first.appended(at(3), Spell::Writer { epoch: Epoch(2), pk: writer_address(&[2; 32], &general, Epoch(2)), root: Epoch(0), by: owner.keys.public_key().to_bytes(), certifier: None }).unwrap();
publish_marked(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 3, Some(h2), &skipped.to_json()).await;
let window = Hiding { inner: &bed.relay, group: control::ControlPlane::of(&held()).write_group().unwrap(), hide: Box::new(move |e| e.self_hash == h2) };
let _ = follow_control(&window, &held()).await;
assert_eq!(held().channel(&general).unwrap().writers, Some(second));
}
#[tokio::test]
async fn one_channel_that_cant_settle_never_holds_back_the_rest() {
let (bed, _owner, _x, community) = v2_bed_with_admin("Isolated").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let other = create_public_channel(&bed.relay, &held(), "other").await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
// general's ledger head isn't one this device can chain from.
let eid_hex = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::writers_locator(community.id(), &general));
crate::db::community::set_edition_head(&cid_hex, &eid_hex, 7, &[0x42; 32]).unwrap();
let _ = set_everyone(&bed.relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT & !Permissions::SEND_MESSAGES).await;
let restricted = |id: &ChannelId| held().channel(id).unwrap().restricted();
assert!(!restricted(&general));
assert!(restricted(&other), "the next channel still moved");
}
#[tokio::test]
async fn a_post_signed_with_a_leaked_writer_key_is_marked() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, x, community) = v2_bed_with_admin("Leaked").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let (w, n) = (Keys::generate(), Keys::generate());
let plain = create_role_v2(&bed.relay, &held(), "Member", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain.clone()]).await.unwrap();
set_member_roles(&bed.relay, &held(), &n.public_key(), vec![plain]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let (live, secret, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
// w hands the key to n, who may not post; both post with it.
act_as(&w);
deliver_on_plane(&bed.relay, &held(), &general, crate::community::v2::writers::writer_rekey_scope(&general), live, Some(writer.pk().to_bytes()), &secret, &[n.public_key()]).await.unwrap();
act_as(&owner.keys);
let ws = cert_for(&held(), &general, live, &w.public_key());
post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(ws))), "from the writer", now_ms()).await;
// A post carries its proof: a writer's without one is no different from a stranger's.
post_raw(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some(live), "w without its certificate", now_ms()).await;
post_raw(&bed.relay, &held(), &n, &general, &signed, community.root_epoch, Some(live), "through a leaked key", now_ms()).await;
// A manager's post stands wherever it lands, certificate or not.
act_as(&x);
post_raw(&bed.relay, &held(), &x, &general, &read, community.root_epoch, None, "a manager on an old client", now_ms()).await;
act_as(&owner.keys);
// Nor does another writer's certificate vouch for n.
post_certified(&bed.relay, &held(), &n, &general, &signed, community.root_epoch, Some((live, Some(ws))), "with w's certificate", now_ms()).await;
let marked = vec!["through a leaked key".to_string(), "w without its certificate".to_string(), "with w's certificate".to_string()];
assert_eq!(sorted(marked_texts(&bed.relay, &held(), &general).await), marked);
// A post carries its proof: a certificate n is handed later vouches for nothing n posted before.
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(n.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(n.public_key().to_hex()), 0, 0).await;
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(sorted(marked_texts(&bed.relay, &held(), &general).await), marked);
}
#[tokio::test]
async fn a_manager_holding_the_certifier_lets_a_writer_in_without_a_new_key() {
use crate::community::roles::OverwriteTarget;
let (bed, _owner, x, community) = v2_bed_with_admin("Certifier").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let w = Keys::generate();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Member", 0, 0).await.unwrap()]).await.unwrap();
// x joined.
let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
let join = guestbook::build_join_rumor(x.public_key(), None, now_ms());
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &x, Timestamp::from_secs(now_ms() / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
// x's own device: it holds neither the owner's certifier nor the key until it collects them.
let scopes = [crate::community::v2::writers::certifier_scope(&general), crate::community::v2::writers::secret_scope(&general), crate::community::v2::writers::minted_scope(&general)];
for scope in &scopes {
crate::db::community::delete_epoch_key(&cid_hex, scope, 1).unwrap();
}
act_as(&x);
follow_control(&bed.relay, &held()).await.unwrap();
collect_writers(&bed.relay, &held()).await.unwrap();
let certifier = crate::db::community::held_epoch_key(&cid_hex, &scopes[0], 1).unwrap().expect("a manager is handed the certifier");
assert_eq!(crate::community::v2::writers::certifier_of(&certifier), held().channel(&general).unwrap().writers.as_ref().unwrap().certifier(Epoch(1)));
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(1), "no new key");
let scope = crate::community::v2::writers::writer_rekey_scope(&general);
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
let handed = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap().into_iter().filter(|d| d.deliverer == x.public_key()).flat_map(|d| d.certs).find(|(who, _)| *who == w.public_key().to_bytes());
assert!(handed.is_some_and(|(_, c)| ledger.certifies(&community.id().0, Epoch(1), &w.public_key().to_bytes(), &c)), "x certified w");
}
#[tokio::test]
async fn two_managers_restricting_at_once_settle_on_one_ledger() {
use crate::community::roles::OverwriteTarget;
use crate::community::v2::writers::{writer_address, Ledger, Spell};
let (bed, owner, x, community) = v2_bed_with_admin("Race").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
act_as(&x);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
act_as(&owner.keys);
let x_first = held().channel(&general).unwrap().writers.clone().unwrap();
// The owner's backstop minted too before x's edition reached it.
let at = now_ms();
let owners = Ledger::new(&general).appended(at, Spell::Writer { epoch: Epoch(1), pk: writer_address(&[0x0e; 32], &general, Epoch(1)), root: Epoch(0), by: owner.keys.public_key().to_bytes(), certifier: None }).unwrap();
let group = control::ControlPlane::of(&held()).write_group().unwrap();
let rumor = control::build_edition_rumor_bound(owner.keys.public_key(), vsk::WRITERS, &eid, 1, None, &owners.to_json(), at / 1000, None, Some(crate::community::v2::derive::edition_binding(community.id())));
let (wrap, _) = control::seal_control_edition(&rumor, &group, &owner.keys, Timestamp::from_secs(at / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
assert_ne!(x_first, owners);
// The lower inner id wins, whoever signed it: what never changes settles the tie.
let ids: Vec<([u8; 32], String)> = fetch_control(&bed.relay, &held()).await.into_iter().filter(|e| e.vsk == vsk::WRITERS).map(|e| (e.inner_id, e.content)).collect();
let winner = ids.iter().min_by_key(|(id, _)| *id).map(|(_, c)| c.clone()).unwrap();
let winner = Ledger::parse(&winner).unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(held().channel(&general).unwrap().writers, Some(winner.clone()), "the device that held one converges on the winner");
let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
assert!(fresh.writers.iter().any(|(_, content, ..)| *content == winner.to_json()), "and a fresh reader takes the same");
// Demoting x builds on the settled race, and takes back a certifier only if x minted the
// epoch that won.
let x_won = winner.live().map(|l| l.1) == Some(x.public_key().to_bytes());
set_member_roles(&bed.relay, &held(), &x.public_key(), vec![]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let after = held().channel(&general).unwrap().writers.clone().unwrap();
assert_eq!(after.entries[0], winner.entries[0]);
assert_eq!(after.current_writer().unwrap().0, if x_won { Epoch(2) } else { Epoch(1) });
let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
assert!(fresh.writers.iter().any(|(_, content, ..)| *content == after.to_json()));
// The ledger moves on from there.
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
let reopened = held().channel(&general).unwrap().writers.clone().unwrap();
assert!(!reopened.restricted() && reopened.entries.len() == after.entries.len() + 1);
let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
assert!(fresh.writers.iter().any(|(_, content, ..)| *content == reopened.to_json()));
}
#[tokio::test]
async fn a_ledger_out_of_line_moves_once_an_hour() {
use crate::community::roles::OverwriteTarget;
use crate::community::v2::writers::Spell;
let (bed, _owner, x, community) = v2_bed_with_admin("Damped").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await;
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 1);
// x's roster disagrees and reopens it.
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
let head = crate::db::community::get_edition_head(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&eid)).unwrap().unwrap();
let reopened = ledger.appended(now_ms(), Spell::Open).unwrap();
let group = control::ControlPlane::of(&held()).write_group().unwrap();
let cite = cite_on_relay(&bed.relay, &held(), &x).await;
let rumor = control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, head.0 + 1, Some(&head.1), &reopened.to_json(), now_ms() / 1000, cite.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())));
let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(now_ms() / 1000)).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert!(!held().channel(&general).unwrap().restricted());
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 0, "no ping-pong");
}
#[tokio::test]
async fn a_junk_seal_opens_once_the_key_for_its_epoch_does() {
let (bed, _owner, _x, community) = v2_bed_with_admin("Retry").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "keep").await.unwrap();
let (key, epoch) = { let c = held().channel(&ch).cloned().unwrap(); (c.key.unwrap(), c.epoch) };
let meta = control::ChannelMetadata { name: "renamed".into(), private: true, ..Default::default() };
let prev = channel_head(&held(), &ch).unwrap();
let content = control::seal_channel_metadata(&meta, channel_group_key(&key, &ch, epoch).conv_key(), epoch.0, prev.as_ref()).unwrap();
publish_control_edition(&bed.relay, &held(), vsk::CHANNEL_METADATA, &ch.0, &content).await.unwrap();
let set_key = |k: [u8; 32]| {
let mut row = held();
row.channels.iter_mut().find(|c| c.id == ch).unwrap().key = Some(k);
crate::db::community::save_community_v2(&row).unwrap();
};
set_key([0x11; 32]);
follow_control(&bed.relay, &held()).await.unwrap();
assert!(held().channel(&ch).unwrap().sealed.as_ref().is_some_and(|s| s.junk), "a key that can't open it");
set_key(key);
follow_control(&bed.relay, &held()).await.unwrap();
let read = held().channel(&ch).cloned().unwrap();
assert_eq!((read.name.as_str(), read.sealed.as_ref().map(|s| (s.open, s.junk))), ("renamed", Some((true, false))));
}
#[tokio::test]
async fn a_minter_who_cant_post_hands_on_the_key_it_minted() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, x, community) = v2_bed_with_admin("Minter").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let w = Keys::generate();
let plain = create_role_v2(&bed.relay, &held(), "Member", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(x.public_key().to_hex()), 0, Permissions::SEND_MESSAGES).await.unwrap();
act_as(&x);
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
assert!(!can_post(&held(), &general), "x minted a key it may not post with");
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
act_as(&owner.keys);
let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
assert_eq!(ledger.current_writer().unwrap().0, Epoch(1), "no second mint for a writer gained");
let scope = crate::community::v2::writers::writer_rekey_scope(&general);
let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
assert!(served_at(&plane, &w.public_key(), scope, Epoch(1), &|d| *d == x.public_key()), "the minter served them");
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.cut, 0, "a manager holding what it minted is nobody to cut");
// Demoted, what x decided stands, and the certifier x held is replaced by a fresh epoch.
set_member_roles(&bed.relay, &held(), &x.public_key(), vec![]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert!(held().channel(&general).unwrap().restricted());
assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(2));
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers, WriterDuty::default(), "nothing of x's left to take back");
}
#[tokio::test]
async fn a_key_passed_on_lets_nobody_post_and_costs_no_new_epoch() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _x, community) = v2_bed_with_admin("Passed").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let general = held().channels[0].id;
let w = Keys::generate();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Member", 0, 0).await.unwrap()]).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let (live, secret, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
// The writer hands the key to h, who may not post, and h hands it on to k.
let (h, k) = (Keys::generate(), Keys::generate());
set_member_roles(&bed.relay, &held(), &h.public_key(), vec![create_role_v2(&bed.relay, &held(), "Guest", 0, 0).await.unwrap()]).await.unwrap();
let scope = crate::community::v2::writers::writer_rekey_scope(&general);
act_as(&w);
deliver_on_plane(&bed.relay, &held(), &general, scope, live, Some(writer.pk().to_bytes()), &secret, &[h.public_key()]).await.unwrap();
act_as(&h);
deliver_on_plane(&bed.relay, &held(), &general, scope, live, Some(writer.pk().to_bytes()), &secret, &[k.public_key()]).await.unwrap();
act_as(&owner.keys);
let read = channel_group_key(&community.community_root, &general, community.root_epoch);
let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
post_raw(&bed.relay, &held(), &k, &general, &signed, community.root_epoch, Some(live), "through a passed key", now_ms()).await;
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers, WriterDuty::default(), "nobody to stop: a key without a certificate vouches for nothing");
assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, live, "and no epoch spent on it");
assert_eq!(marked_texts(&bed.relay, &held(), &general).await, vec!["through a passed key".to_string()]);
}
#[tokio::test]
async fn a_role_that_opens_a_private_channel_its_granter_cant_read_is_refused() {
let (bed, owner, x, community) = v2_bed_with_admin("Gatekeeper").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "staff").await.unwrap();
let staff = create_role_v2(&bed.relay, &held(), "Staff", 0, 0).await.unwrap();
set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Role(staff.clone()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
let key = held().channel(&ch).unwrap().key;
let with_key = |k: Option<[u8; 32]>| {
let mut c = held();
c.channels.iter_mut().find(|c| c.id.0 == ch.0).unwrap().key = k;
crate::db::community::save_community_v2(&c).unwrap();
};
let m = Keys::generate();
// A manager of roles who isn't in the channel: the member would wait at its door.
with_key(None);
act_as(&x);
let refused = set_member_roles(&bed.relay, &held(), &m.public_key(), vec![staff.clone()]).await.unwrap_err();
assert!(refused.contains("opens a private channel you don't have access to"), "{refused}");
let others = create_role_v2(&bed.relay, &held(), "Others", 0, 0).await.unwrap();
set_member_roles(&bed.relay, &held(), &m.public_key(), vec![others.clone()]).await.unwrap();
// A granter holding its key hands it over with the grant.
act_as(&owner.keys);
with_key(key);
set_member_roles(&bed.relay, &held(), &m.public_key(), vec![others, staff]).await.unwrap();
}
#[tokio::test]
async fn a_holder_delivers_on_the_access_plane_and_the_member_adopts_it() {
let (bed, owner, x, community) = v2_bed_with_admin("Access").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
let readers = create_role_v2(&bed.relay, &held(), "Readers", 0, 0).await.unwrap();
set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Role(readers.clone()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
let (m, d, f, stranger) = (Keys::generate(), Keys::generate(), Keys::generate(), Keys::generate());
let key = held().channel(&ch).unwrap().key.unwrap();
let epoch = held().channel(&ch).unwrap().epoch;
let with_channel = |k: Option<[u8; 32]>, e: Epoch| {
let mut c = held();
let slot = c.channels.iter_mut().find(|x| x.id.0 == ch.0).unwrap();
slot.key = k;
slot.epoch = e;
crate::db::community::save_community_v2(&c).unwrap();
};
// Granted by a client that delivers nothing with the grant, so only a holder's duty serves them.
let quiet = NoAccessDeliveries(&bed.relay, access_group(&held(), &ch).pk());
set_member_roles(&quiet, &held(), &m.public_key(), vec![readers.clone()]).await.unwrap();
set_member_roles(&quiet, &held(), &d.public_key(), vec![readers.clone()]).await.unwrap();
set_member_roles(&quiet, &held(), &f.public_key(), vec![readers]).await.unwrap();
let others = create_role_v2(&bed.relay, &held(), "Others", 0, 0).await.unwrap();
set_member_roles(&quiet, &held(), &stranger.public_key(), vec![others]).await.unwrap();
crate::db::current_session().scoped::<AccessLedger, std::sync::Mutex<std::collections::HashSet<([u8; 32], u64, [u8; 32])>>>().lock().unwrap().clear();
follow_control(&bed.relay, &held()).await.unwrap();
let trusted = |pk: &PublicKey| *pk == owner.keys.public_key();
let served = |pk: PublicKey| {
let relay = &bed.relay;
let c = held();
async move { served_on_plane(&fetch_access_deliveries(relay, &c, &ch).await.unwrap(), &pk, &ch, c.channel(&ch).unwrap().epoch, &trusted) }
};
// Someone the channel doesn't let in stakes blobs at every member's locator first.
with_channel(Some([0x99; 32]), epoch);
act_as(&stranger);
deliver_access(&bed.relay, &held(), &ch, &[m.public_key(), d.public_key(), f.public_key()]).await.unwrap();
// An entitled member offers a key far past the channel's epoch.
with_channel(Some([0x77; 32]), Epoch(epoch.0 + 1000));
act_as(&f);
deliver_access(&bed.relay, &held(), &ch, &[m.public_key()]).await.unwrap();
with_channel(Some(key), epoch);
act_as(&owner.keys);
let blind = BreaksAfterPublish { inner: &bed.relay, broken: true.into() };
assert!(access_duty(&blind, &held()).await.is_err(), "nothing goes out on a partial read");
act_as(&x);
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().delivered, 0, "a holder the channel doesn't let in delivers nothing readers would take");
act_as(&owner.keys);
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().delivered, 3, "a stranger's blobs serve nobody: every member is owed");
assert!(served(m.public_key()).await && served(d.public_key()).await);
assert!(!served(stranger.public_key()).await, "nobody the channel doesn't let in");
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().delivered, 0, "a served member is served once");
// D, later banned, also serves M a key of D's own at the channel's epoch.
with_channel(Some([0x66; 32]), epoch);
act_as(&d);
deliver_access(&bed.relay, &held(), &ch, &[m.public_key()]).await.unwrap();
act_as(&owner.keys);
// The member's own device, without the key; D is banned there.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::set_community_banlist(&cid_hex, &[d.public_key().to_hex()], 1).unwrap();
with_channel(None, epoch);
act_as(&m);
assert_eq!(collect_access(&bed.relay, &held()).await.unwrap(), 1, "only the honest delivery: not the banned member's, nor one far ahead");
assert_eq!(collect_access(&bed.relay, &held()).await.unwrap(), 0, "and once a session: re-parking would crowd out other candidates");
crate::db::community::set_community_banlist(&cid_hex, &[], 2).unwrap();
assert_eq!(absorb_parked_channel_keys(&held(), &crate::db::current_session()).len(), 1);
assert_eq!(held().channel(&ch).unwrap().key, Some(key), "the delivered key is the channel's");
act_as(&stranger);
with_channel(None, epoch);
assert_eq!(collect_access(&bed.relay, &held()).await.unwrap(), 0, "a member it doesn't let in finds nothing");
act_as(&owner.keys);
with_channel(Some(key), epoch);
// A rotation that carries a member serves them; one that leaves out a member who held the
// last epoch has cut them, whatever the roster still says.
let readers = crate::db::community::get_community_roles(&cid_hex).unwrap().roles.iter().find(|r| r.name == "Readers").unwrap().role_id.clone();
let (rider, fresh_member) = (Keys::generate(), Keys::generate());
set_member_roles(&bed.relay, &held(), &rider.public_key(), vec![readers.clone()]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
rekey_channel_excluding(&bed.relay, &held(), &ch, &roster, &[], &[d.public_key()]).await.unwrap();
set_member_roles(&bed.relay, &held(), &fresh_member.public_key(), vec![readers]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().delivered, 0, "the rotation carried m and the rider, cut d, and the grant itself served the member entitled since");
assert!(served(fresh_member.public_key()).await && !served(d.public_key()).await && !served(rider.public_key()).await);
}
#[tokio::test]
async fn a_manager_cuts_a_holder_the_channel_no_longer_lets_in() {
// A strip that rotated nothing (its author couldn't, or it came from another client)
// leaves the member holding the key: a manager's duty is the backstop.
let (bed, owner, x, community) = v2_bed_with_admin("Backstop").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
let readers = create_role_v2(&bed.relay, &held(), "Readers", 0, 0).await.unwrap();
set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Role(readers.clone()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
let (m, kept) = (Keys::generate().public_key(), Keys::generate().public_key());
set_member_roles(&bed.relay, &held(), &m, vec![readers.clone()]).await.unwrap();
set_member_roles(&bed.relay, &held(), &kept, vec![readers]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
rekey_channel_excluding(&bed.relay, &held(), &ch, &crate::db::community::get_community_roles(&cid_hex).unwrap(), &[], &[]).await.unwrap();
// A member who joined, then whose strip lands with no rotation behind it.
let (mut events, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
events.push(guestbook::GuestbookEvent { epoch: Some(held().root_epoch.0), observed_at: None, rumor_id: [12u8; 32], entry: guestbook::GuestbookEntry::Join { member: m, invited_by: None, at_ms: now_ms() } });
crate::db::community::set_guestbook(&cid_hex, &events, cursor).unwrap();
publish_grant(&bed.relay, &held(), &owner.keys, &m, vec![], 2).await;
follow_control(&bed.relay, &held()).await.unwrap();
let epoch = held().channel(&ch).unwrap().epoch;
act_as(&x);
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().cut, 0, "a manager who doesn't hold the channel's View delivers and cuts nothing");
act_as(&owner.keys);
act_as(&owner.keys);
let done = access_duty(&bed.relay, &held()).await.unwrap();
assert_eq!(done.cut, 1, "the holder the channel no longer lets in");
let now = held().channel(&ch).unwrap().epoch;
assert!(now > epoch, "the channel rotated");
let minted = minting_rotations(&bed.relay, &held(), &ch, now).await.unwrap();
let any = |_: &PublicKey| true;
assert!(!rotation_carries(&minted, &any, &m, &ch, now), "without them");
assert!(rotation_carries(&minted, &any, &kept, &ch, now), "and with whoever it still lets in");
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap(), AccessDuty::default(), "and then there is nothing left to do");
}
#[tokio::test]
async fn a_member_cut_then_let_back_in_walks_through_the_cut_to_the_rotation_that_names_them() {
let (bed, owner, _x, community) = v2_bed_with_admin("Back").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let m = Keys::generate();
let member = crate::community::roles::OverwriteTarget::Member(m.public_key().to_hex());
set_overwrite(&bed.relay, &held(), ch.0, member.clone(), Permissions::VIEW_CHANNEL, Permissions::READ_MESSAGE_HISTORY).await.unwrap();
let joined = held().channel(&ch).unwrap().epoch;
let key = crate::db::community::held_epoch_key(&cid_hex, &chan, joined.0).unwrap().unwrap();
set_overwrite(&bed.relay, &held(), ch.0, member.clone(), 0, Permissions::VIEW_CHANNEL).await.unwrap();
set_overwrite(&bed.relay, &held(), ch.0, member, Permissions::VIEW_CHANNEL, Permissions::READ_MESSAGE_HISTORY).await.unwrap();
let back = held().channel(&ch).unwrap().epoch;
assert!(back.0 >= joined.0 + 2, "a cut, then the rotation that lets them back in");
// Their device, holding the epoch they joined at.
let mut c = held();
let x = c.channels.iter_mut().find(|x| x.id.0 == ch.0).unwrap();
(x.key, x.epoch) = (Some(key), joined);
crate::db::community::save_community_v2(&c).unwrap();
act_as(&m);
for _ in 0..4 {
if let Some(next) = follow_rekeys(&bed.relay, &held(), &crate::db::current_session()).await.unwrap().updated {
crate::db::community::save_community_v2(&next).unwrap();
}
}
let now = held().channel(&ch).cloned().expect("a cut keeps the channel known");
assert_eq!((now.epoch, now.key.is_some()), (back, true), "and the walk reaches the epoch that names them");
act_as(&owner.keys);
}
#[tokio::test]
async fn a_view_grant_without_history_lets_them_in_at_a_fresh_epoch() {
let (bed, owner, _x, community) = v2_bed_with_admin("Fresh").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
send_chat_message(&bed.relay, &held(), &ch, "before them", None, &[], vec![]).await.unwrap();
let before = held().channel(&ch).unwrap().epoch;
let (m, n) = (Keys::generate().public_key(), Keys::generate().public_key());
let member = |pk: &PublicKey| crate::community::roles::OverwriteTarget::Member(pk.to_hex());
set_overwrite(&bed.relay, &held(), ch.0, member(&m), Permissions::VIEW_CHANNEL, 0).await.unwrap();
assert_eq!(held().channel(&ch).unwrap().epoch, before, "with history, the epoch they're handed is kept");
let stale = held();
set_overwrite(&bed.relay, &held(), ch.0, member(&n), Permissions::VIEW_CHANNEL, Permissions::READ_MESSAGE_HISTORY).await.unwrap();
let after = held().channel(&ch).unwrap().epoch;
access_duty(&bed.relay, &stale).await.unwrap();
assert_eq!(held().channel(&ch).unwrap().epoch, after, "a duty that judged the epoch before the grant's rotation mints nothing over it");
assert!(after > before, "without it, the grant mints the epoch they come in at");
let any = |_: &PublicKey| true;
assert!(rotation_carries(&minting_rotations(&bed.relay, &held(), &ch, after).await.unwrap(), &any, &n, &ch, after));
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
let owner_hex = owner.keys.public_key().to_hex();
let vends = |pk: &PublicKey| held().vendable_channels(&roster, Some(&owner_hex), Some(&pk.to_hex()), &[], &[]).iter().any(|c| c.id.0 == ch.0);
assert!(vends(&m) && !vends(&n), "no bundle hands them an epoch");
let access = crate::VectorCore.channel_access(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&ch.0)).unwrap();
let npub = |pk: &PublicKey| serde_json::json!(nostr_sdk::prelude::ToBech32::to_bech32(pk).unwrap());
assert_eq!(access["members"].as_array().unwrap().len(), 2, "both overwrites let them in");
assert!(access["members"].as_array().unwrap().contains(&npub(&n)));
let handed = |pk: PublicKey, e: Epoch| {
let (relay, c, o) = (&bed.relay, held(), owner.keys.public_key());
async move { fetch_access_deliveries(relay, &c, &ch).await.unwrap().iter().any(|d| d.epoch == e && rekey::find_my_blob(&d.blobs, &o.to_bytes(), &pk.to_bytes(), rekey::RekeyScope::Channel(ch), e).is_some()) }
};
access_duty(&bed.relay, &held()).await.unwrap();
assert!(!handed(n, before).await, "nor does the duty");
assert_eq!(held().channel(&ch).unwrap().epoch, after, "and it has nothing left to mint for them");
let key_at = |e: Epoch| crate::db::community::held_epoch_key(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&ch.0), e.0).unwrap();
let kept = key_at(after);
rekey_channel_excluding(&bed.relay, &stale, &ch, &roster, &[], &[]).await.unwrap();
assert_eq!(key_at(after), kept, "a rotation from an old copy never re-mints an epoch already held");
assert_eq!(held().channel(&ch).unwrap().epoch, Epoch(after.0 + 1));
let stale = held();
set_overwrite(&bed.relay, &held(), ch.0, member(&m), 0, Permissions::VIEW_CHANNEL).await.unwrap();
let cut = held().channel(&ch).unwrap().epoch;
assert!(cut > stale.channel(&ch).unwrap().epoch, "the revoke rotated them out");
access_duty(&bed.relay, &stale).await.unwrap();
assert_eq!(held().channel(&ch).unwrap().epoch, cut, "nor does a duty that judged the epoch before that cut");
}
#[tokio::test]
async fn read_message_history_hands_a_new_reader_the_past_read_only() {
let (bed, owner, _x, community) = v2_bed_with_admin("History").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
send_chat_message(&bed.relay, &held(), &ch, "early", None, &[], vec![]).await.unwrap();
let first = held().channel(&ch).unwrap().epoch;
rekey_channel_excluding(&bed.relay, &held(), &ch, &crate::db::community::get_community_roles(&cid_hex).unwrap(), &[], &[]).await.unwrap();
send_chat_message(&bed.relay, &held(), &ch, "later", None, &[], vec![]).await.unwrap();
let now = held().channel(&ch).unwrap().epoch;
assert!(now > first);
// Two readers join after the rotation; one is denied history in this channel.
let readers = create_role_v2(&bed.relay, &held(), "Readers", 0, 0).await.unwrap();
set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Role(readers.clone()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
let (m, n) = (Keys::generate(), Keys::generate());
set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Member(n.public_key().to_hex()), 0, Permissions::READ_MESSAGE_HISTORY).await.unwrap();
set_member_roles(&bed.relay, &held(), &m.public_key(), vec![readers.clone()]).await.unwrap();
set_member_roles(&bed.relay, &held(), &n.public_key(), vec![readers]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().delivered, 0, "the grants themselves served them");
let blob_for = |who: PublicKey| {
let (relay, c) = (&bed.relay, held());
let owner_pk = owner.keys.public_key();
async move {
fetch_history_deliveries(relay, &c, &ch).await.unwrap().iter().any(|d| d.blobs.iter().any(|b| b.locator == rekey::history_locator(&owner_pk.to_bytes(), &who.to_bytes(), &ch, d.epoch)))
}
};
assert!(blob_for(m.public_key()).await && !blob_for(n.public_key()).await, "history goes only to who may read it");
// Someone the channel doesn't let in offers M an epoch nobody else did.
let stranger = Keys::generate();
let fake = rekey::HistoryView { address: [0x55; 32], conv_key: [0x66; 32] };
let blob = rekey::build_history_blob_local(&stranger, &m.public_key(), &ch, Epoch(0), &fake).unwrap();
let rumor = rekey::build_history_rumor(stranger.public_key(), &ch, Epoch(0), &[blob], now_ms() / 1000).unwrap();
let (wrap, _) = rekey::seal_rekey_chunk(&rumor, &access_group(&held(), &ch), &stranger, Timestamp::now()).unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
// And a holder sends N history N may not read.
deliver_history(&bed.relay, &held(), &ch, &[n.public_key()]).await.unwrap();
// A reader denied history is let in by a fresh epoch, which their grant minted.
let rotated = held().channel(&ch).unwrap().epoch;
assert!(rotated > now);
// Each reader's own device: keyless where its fold left it, and no secret of the past epoch.
let as_reader = |who: &Keys| {
let mut c = held();
let x = c.channels.iter_mut().find(|x| x.id.0 == ch.0).unwrap();
(x.key, x.epoch) = (None, now);
crate::db::community::save_community_v2(&c).unwrap();
crate::db::get_write_connection_guard_static().unwrap()
.execute("DELETE FROM community_epoch_keys WHERE community_id = ?1 AND scope_id IN (?2, ?3, ?4)", rusqlite::params![cid_hex, chan, format!("hist:{chan}"), format!("hista:{chan}")])
.unwrap();
act_as(who);
};
let texts = |c: CommunityV2| {
let relay = &bed.relay;
async move {
let far = now_ms() / 1000 + 100;
let got = fetch_channel_history(relay, &c, &ch, 50, 4, None, Some(far), crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
got.iter().filter_map(|e| match &e.event { chat::ChatEvent::Message { opened, .. } => Some(opened.rumor.content.clone()), _ => None }).collect::<Vec<_>>()
}
};
as_reader(&m);
assert_eq!(collect_access(&bed.relay, &held()).await.unwrap(), 1);
absorb_parked_channel_keys(&held(), &crate::db::current_session());
assert_eq!(texts(held()).await, vec!["later".to_string()], "the key alone opens only its own epoch");
assert_eq!(collect_history(&bed.relay, &held()).await.unwrap(), 1, "the earlier epoch, read-only, and not the stranger's");
assert_eq!(crate::db::community::history_views(&cid_hex, &chan).unwrap().iter().map(|(e, _)| *e).collect::<Vec<_>>(), vec![first]);
assert!(crate::db::community::held_epoch_key(&cid_hex, &chan, first.0).unwrap().is_none(), "never its secret");
assert_eq!(texts(held()).await, vec!["early".to_string(), "later".to_string()], "history reads back");
// A catch-up that already proved the live epoch, as one run the moment the key landed has,
// reads an epoch delivered after it only when that plane counts as unread.
let proof = now_ms() / 1000;
let view = PublicKey::from_slice(&crate::db::community::history_views(&cid_hex, &chan).unwrap()[0].1.address).unwrap();
let caught = |unread: Vec<PublicKey>| {
let (relay, c) = (&bed.relay, held());
async move {
let live = c.channel(&ch).unwrap().epoch;
let (got, ..) = fetch_channel_history_since_epoch(relay, &c, &ch, 50, 2, Some(proof), None, crate::community::transport::Evidence::Quorum, |_, _, _| true, |_| Default::default(), Some((live, None)), &unread).await.unwrap();
got.iter().any(|e| matches!(&e.event, chat::ChatEvent::Message { opened, .. } if opened.rumor.content == "early"))
}
};
assert!(!caught(vec![]).await, "read from the proof, the delivered epoch is passed over");
assert!(caught(vec![view]).await, "unread, it is read whole");
assert_eq!(collect_history(&bed.relay, &held()).await.unwrap(), 0, "once");
as_reader(&n);
assert_eq!(collect_access(&bed.relay, &held()).await.unwrap(), 0, "never this epoch's key, which opens what came before them");
let adopted = follow_rekeys(&bed.relay, &held(), &crate::db::current_session()).await.unwrap().updated.expect("the rotation names them");
crate::db::community::save_community_v2(&adopted).unwrap();
assert_eq!(held().channel(&ch).unwrap().epoch, rotated);
assert_eq!(collect_history(&bed.relay, &held()).await.unwrap(), 0, "denied history, it takes none even when sent");
assert!(texts(held()).await.is_empty(), "nothing from before their access");
send_chat_message(&bed.relay, &held(), &ch, "after", None, &[], vec![]).await.unwrap();
assert_eq!(texts(held()).await, vec!["after".to_string()], "history starts where access did");
act_as(&owner.keys);
}
#[tokio::test]
async fn a_timeout_counts_only_with_the_grant_it_cites() {
let (bed, _owner, _x, community) = v2_bed_with_admin("Cited").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MODERATE_MEMBERS).await.unwrap();
let (y, m) = (Keys::generate(), Keys::generate().public_key());
set_member_roles(&bed.relay, &held(), &y.public_key(), vec![mods]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
act_as(&y);
timeout_member(&bed.relay, &held(), &m, 600).await.unwrap();
assert!(community_timeouts(&held()).unwrap().contains_key(&m), "a cited Timeout stands");
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let (mut events, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
events.push(guestbook::GuestbookEvent {
rumor_id: [9; 32],
entry: guestbook::GuestbookEntry::Timeout { actor: y.public_key(), target: m, until_secs: 0, citation: None, at_ms: now_ms() + 1_000 },
epoch: Some(held().root_epoch.0),
observed_at: None,
});
crate::db::community::set_guestbook(&cid_hex, &events, cursor).unwrap();
assert!(community_timeouts(&held()).unwrap().contains_key(&m), "an uncited lift lifts nothing");
}
fn nick_of(community: &CommunityV2, who: &PublicKey) -> Option<String> {
community_nicknames(community).unwrap().remove(who)
}
/// Forget the local Guestbook and read it back from the relays, as a device that never saw it.
async fn reread_guestbook(relay: &MemoryRelay, community: &CommunityV2) {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::set_guestbook(&cid_hex, &[], 0).unwrap();
sync_guestbook(relay, community).await.unwrap();
}
#[tokio::test]
async fn a_member_names_themselves_and_a_moderator_renames_those_beneath() {
let (bed, owner, x, community) = v2_bed_with_admin("Names").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_NICKNAMES).await.unwrap();
let (y, m) = (Keys::generate(), Keys::generate());
set_member_roles(&bed.relay, &held(), &y.public_key(), vec![mods]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
act_as(&m);
set_nickname(&bed.relay, &held(), &m.public_key(), " Moth ").await.unwrap();
assert_eq!(nick_of(&held(), &m.public_key()).as_deref(), Some("Moth"), "a member names themselves, trimmed");
assert!(set_nickname(&bed.relay, &held(), &y.public_key(), "Boss").await.is_err(), "and nobody else");
assert!(set_nickname(&bed.relay, &held(), &m.public_key(), &"x".repeat(33)).await.is_err(), "in at most 32 characters");
act_as(&y);
set_nickname(&bed.relay, &held(), &m.public_key(), "Moderated").await.unwrap();
assert_eq!(nick_of(&held(), &m.public_key()).as_deref(), Some("Moderated"), "a moderator renames a member beneath them");
assert!(set_nickname(&bed.relay, &held(), &x.public_key(), "Demoted").await.is_err(), "never one above");
assert!(set_nickname(&bed.relay, &held(), &owner.keys.public_key(), "Nobody").await.is_err(), "nor the owner");
act_as(&x);
assert!(set_nickname(&bed.relay, &held(), &m.public_key(), "Nope").await.is_err(), "outranking takes Manage Nicknames too");
act_as(&owner.keys);
let log = audit_log(&bed.relay, &held()).await.unwrap();
let renames: Vec<_> = log.entries.iter().filter(|e| e.action == "member_nick_update").collect();
assert_eq!(renames.len(), 2, "each change is one entry");
assert_eq!(renames[0].actor.as_deref(), Some(nostr_sdk::prelude::ToBech32::to_bech32(&y.public_key()).unwrap().as_str()));
assert_eq!(renames[0].changes, vec![serde_json::json!({ "field": "nick", "old": "Moth", "new": "Moderated" })]);
reread_guestbook(&bed.relay, &held()).await;
assert_eq!(nick_of(&held(), &m.public_key()).as_deref(), Some("Moderated"), "a device reading the relays agrees");
act_as(&m);
set_nickname(&bed.relay, &held(), &m.public_key(), "").await.unwrap();
assert_eq!(nick_of(&held(), &m.public_key()), None, "clearing leaves their own name");
act_as(&owner.keys);
}
#[tokio::test]
async fn on_the_legacy_roster_anyone_names_themselves() {
let (bed, owner, _m) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Legacy", bed.relays.clone(), None).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let (m, n) = (Keys::generate(), Keys::generate().public_key());
act_as(&m);
set_nickname(&bed.relay, &held(), &m.public_key(), "Moth").await.unwrap();
assert_eq!(nick_of(&held(), &m.public_key()).as_deref(), Some("Moth"));
assert!(set_nickname(&bed.relay, &held(), &n, "Them").await.is_err(), "but only themselves");
act_as(&owner.keys);
}
#[tokio::test]
async fn a_banned_members_nickname_names_nobody() {
let (bed, owner, _x, community) = v2_bed_with_admin("BannedName").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let m = Keys::generate();
act_as(&m);
set_nickname(&bed.relay, &held(), &m.public_key(), "Admin").await.unwrap();
act_as(&owner.keys);
set_members_banned(&bed.relay, community.id(), &[m.public_key()], true).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(nick_of(&held(), &m.public_key()), None);
}
#[tokio::test]
async fn turning_off_change_nickname_takes_down_the_ones_members_set() {
let (bed, owner, _x, community) = v2_bed_with_admin("NoNames").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let (m, n) = (Keys::generate(), Keys::generate().public_key());
act_as(&m);
set_nickname(&bed.relay, &held(), &m.public_key(), "Mine").await.unwrap();
act_as(&owner.keys);
set_nickname(&bed.relay, &held(), &n, "Given").await.unwrap();
set_everyone(&bed.relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT & !Permissions::CHANGE_NICKNAME).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(nick_of(&held(), &m.public_key()), None, "a member's own Nickname stands only while they may set it");
assert_eq!(nick_of(&held(), &n).as_deref(), Some("Given"), "one the owner gave stays");
act_as(&m);
assert!(set_nickname(&bed.relay, &held(), &m.public_key(), "Again").await.is_err());
act_as(&owner.keys);
}
#[tokio::test]
async fn renaming_someone_else_counts_only_with_the_grant_it_cites() {
let (bed, _owner, _x, community) = v2_bed_with_admin("NameCited").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_NICKNAMES).await.unwrap();
let (y, m) = (Keys::generate(), Keys::generate().public_key());
set_member_roles(&bed.relay, &held(), &y.public_key(), vec![mods]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
act_as(&y);
set_nickname(&bed.relay, &held(), &m, "Cited").await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let (mut events, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
events.push(guestbook::GuestbookEvent {
rumor_id: [9; 32],
entry: guestbook::GuestbookEntry::Nickname { actor: y.public_key(), target: m, nick: "Uncited".into(), citation: None, at_ms: now_ms() + 1_000 },
epoch: Some(held().root_epoch.0),
observed_at: None,
});
crate::db::community::set_guestbook(&cid_hex, &events, cursor).unwrap();
assert_eq!(nick_of(&held(), &m).as_deref(), Some("Cited"), "an uncited one names nobody");
// A co-moderator's clock runs ahead: the next rename still lands after theirs.
let (mut events, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
events.push(guestbook::GuestbookEvent {
rumor_id: [10; 32],
entry: guestbook::GuestbookEntry::Nickname { actor: _owner.keys.public_key(), target: m, nick: "Ahead".into(), citation: None, at_ms: now_ms() + 600_000 },
epoch: Some(held().root_epoch.0),
observed_at: None,
});
crate::db::community::set_guestbook(&cid_hex, &events, cursor).unwrap();
assert_eq!(nick_of(&held(), &m).as_deref(), Some("Ahead"));
set_nickname(&bed.relay, &held(), &m, "Latest").await.unwrap();
assert_eq!(nick_of(&held(), &m).as_deref(), Some("Latest"));
// A member nobody lets name m plants one an hour ahead: it moves nobody's next rename.
let (mut events, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
events.push(guestbook::GuestbookEvent {
rumor_id: [11; 32],
entry: guestbook::GuestbookEntry::Nickname { actor: Keys::generate().public_key(), target: m, nick: "Junk".into(), citation: None, at_ms: now_ms() + 3_500_000 },
epoch: Some(held().root_epoch.0),
observed_at: None,
});
crate::db::community::set_guestbook(&cid_hex, &events, cursor).unwrap();
set_nickname(&bed.relay, &held(), &m, "Prompt").await.unwrap();
let w = &standing_nicknames(&held()).unwrap()[&m];
assert_eq!(w.nick, "Prompt");
assert!(w.at_ms < now_ms() + 1_000_000, "dated after what counts, not after junk");
}
#[tokio::test]
async fn nicknames_cross_a_refounding() {
let (bed, owner, x, community) = v2_bed_with_admin("NameCarry").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let (m, gone) = (Keys::generate(), Keys::generate().public_key());
act_as(&m);
set_nickname(&bed.relay, &held(), &m.public_key(), "Moth").await.unwrap();
let first = standing_nicknames(&held()).unwrap()[&m.public_key()].at_ms;
act_as(&owner.keys);
set_nickname(&bed.relay, &held(), &x.public_key(), "Given").await.unwrap();
set_nickname(&bed.relay, &held(), &gone, "Former").await.unwrap();
refound_community(&bed.relay, &held(), &[]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert_ne!(held().root_epoch, community.root_epoch);
sync_guestbook(&bed.relay, &held()).await.unwrap();
let named = standing_nicknames(&held()).unwrap();
assert_eq!(named.get(&x.public_key()).map(|w| w.nick.as_str()), Some("Given"), "the refounder carried the one it gave");
assert!(!named.contains_key(&gone), "but only for a member it re-keyed");
assert!(!named.contains_key(&m.public_key()), "a member's own waits for their own client, even on a device that held it");
act_as(&m);
carry_my_nickname(&bed.relay, &held()).await.unwrap();
act_as(&owner.keys);
let log = audit_log(&bed.relay, &held()).await.unwrap();
let renames: Vec<_> = log.entries.iter().filter(|e| e.action == "member_nick_update").collect();
assert_eq!(renames.len(), 3, "what a Refounding carried is no new act");
reread_guestbook(&bed.relay, &held()).await;
let named = standing_nicknames(&held()).unwrap();
assert_eq!(named.get(&m.public_key()).map(|w| (w.nick.as_str(), w.at_ms)), Some(("Moth", first)), "carried, dated as first issued");
assert_eq!(named.get(&x.public_key()).map(|w| w.nick.as_str()), Some("Given"));
}
#[tokio::test]
async fn a_carried_nickname_reads_the_same_on_every_device_and_goes_out_once() {
let (bed, owner, _x, community) = v2_bed_with_admin("CarryOnce").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_NICKNAMES).await.unwrap();
let bans = create_role_v2(&bed.relay, &held(), "Bans", 0, Permissions::BAN).await.unwrap();
let (y, z, m, t) = (Keys::generate(), Keys::generate(), Keys::generate(), Keys::generate().public_key());
set_member_roles(&bed.relay, &held(), &y.public_key(), vec![mods]).await.unwrap();
set_member_roles(&bed.relay, &held(), &z.public_key(), vec![bans]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
act_as(&m);
set_nickname(&bed.relay, &held(), &m.public_key(), "Moth").await.unwrap();
act_as(&y);
set_nickname(&bed.relay, &held(), &t, "Given").await.unwrap();
act_as(&owner.keys);
set_everyone(&bed.relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT & !Permissions::CHANGE_NICKNAME).await.unwrap();
set_everyone(&bed.relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
act_as(&z);
refound_community(&bed.relay, &held(), &[]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
// Nobody could carry what y gave t: a device that held it and one that never did agree.
assert_eq!(nick_of(&held(), &t), None, "a device that held the old Guestbook");
act_as(&m);
carry_my_nickname(&bed.relay, &held()).await.unwrap();
// m's other device holds the first copy, and reads the carried one off the new plane.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let (mut events, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
for e in events.iter_mut().filter(|e| matches!(e.entry, guestbook::GuestbookEntry::Nickname { .. })) {
e.epoch = Some(community.root_epoch.0);
}
crate::db::community::set_guestbook(&cid_hex, &events, cursor).unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
let gb = super::super::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch).pk().to_hex();
let q = Query { kinds: vec![1059], authors: vec![gb], ..Default::default() };
let published = bed.relay.fetch(&q, &held().relays).await.unwrap().len();
for _ in 0..2 {
carry_my_nickname(&bed.relay, &held()).await.unwrap();
}
assert_eq!(bed.relay.fetch(&q, &held().relays).await.unwrap().len(), published, "the other device doesn't send it again");
act_as(&owner.keys);
reread_guestbook(&bed.relay, &held()).await;
assert_eq!(nick_of(&held(), &t), None, "a device that never held it");
assert_eq!(nick_of(&held(), &m.public_key()).as_deref(), Some("Moth"));
}
#[tokio::test]
async fn a_carried_nickname_still_stands_on_its_members_own_word() {
let (bed, owner, _x, community) = v2_bed_with_admin("CarryWord").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
// A Role with no bits makes m someone the Refounding re-keys, naming themselves on @everyone's bit alone.
let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
let m = Keys::generate();
set_member_roles(&bed.relay, &held(), &m.public_key(), vec![plain]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
act_as(&m);
set_nickname(&bed.relay, &held(), &m.public_key(), "Mine").await.unwrap();
act_as(&owner.keys);
refound_community(&bed.relay, &held(), &[]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
sync_guestbook(&bed.relay, &held()).await.unwrap();
act_as(&m);
carry_my_nickname(&bed.relay, &held()).await.unwrap();
assert_eq!(nick_of(&held(), &m.public_key()).as_deref(), Some("Mine"));
act_as(&owner.keys);
set_everyone(&bed.relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT & !Permissions::CHANGE_NICKNAME).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert_eq!(nick_of(&held(), &m.public_key()), None, "turning Change Nickname off takes it down after a Refounding too");
}
#[tokio::test]
async fn a_carried_nickname_heard_live_moves_to_the_new_epoch() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "LiveCarry", vec!["wss://r".into()], None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let row = |id: u8, entry: guestbook::GuestbookEntry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(0), observed_at: None };
let me = owner.public_key();
let nick = guestbook::GuestbookEntry::Nickname { actor: me, target: me, nick: "Boss".into(), citation: None, at_ms: now_ms() - 1_000 };
let join = guestbook::GuestbookEntry::Join { member: me, invited_by: None, at_ms: now_ms() - 2_000 };
crate::db::community::set_guestbook(&cid_hex, &[row(1, nick.clone()), row(2, join.clone())], 0).unwrap();
let mut moved = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
moved.root_epoch = Epoch(1);
assert!(ingest_guestbook_event(&moved, row(1, nick.clone()), now_ms() / 1000).unwrap(), "the same Nickname on the new plane");
assert!(!ingest_guestbook_event(&moved, row(1, nick), now_ms() / 1000).unwrap(), "once");
assert!(!ingest_guestbook_event(&moved, row(2, join), now_ms() / 1000).unwrap(), "a Join keeps the plane it was first read on");
let (events, _) = crate::db::community::get_guestbook(&cid_hex).unwrap();
assert_eq!(events.iter().map(|e| e.epoch).collect::<Vec<_>>(), vec![Some(1), Some(0)]);
}
#[tokio::test]
async fn a_timed_out_member_cant_rename_themselves() {
let (bed, owner, _x, community) = v2_bed_with_admin("NameTimeout").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let m = Keys::generate();
act_as(&m);
set_nickname(&bed.relay, &held(), &m.public_key(), "Before").await.unwrap();
act_as(&owner.keys);
timeout_member(&bed.relay, &held(), &m.public_key(), 600).await.unwrap();
assert_eq!(nick_of(&held(), &m.public_key()), None, "their own names nobody while it runs");
act_as(&m);
let err = set_nickname(&bed.relay, &held(), &m.public_key(), "Taunt").await.unwrap_err();
assert!(err.contains("timed out"), "{err}");
act_as(&owner.keys);
timeout_member(&bed.relay, &held(), &m.public_key(), 0).await.unwrap();
assert_eq!(nick_of(&held(), &m.public_key()).as_deref(), Some("Before"), "and stands again once it's lifted");
}
#[tokio::test]
async fn a_member_carries_their_own_nickname_when_the_refounder_cant() {
let (bed, _owner, _x, community) = v2_bed_with_admin("SelfCarry").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let bans = create_role_v2(&bed.relay, &held(), "Bans", 0, Permissions::BAN).await.unwrap();
let (z, m) = (Keys::generate(), Keys::generate());
set_member_roles(&bed.relay, &held(), &z.public_key(), vec![bans]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
act_as(&m);
set_nickname(&bed.relay, &held(), &m.public_key(), "Moth").await.unwrap();
let first = standing_nicknames(&held()).unwrap()[&m.public_key()].at_ms;
act_as(&z);
refound_community(&bed.relay, &held(), &[]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
assert_ne!(held().root_epoch, community.root_epoch);
act_as(&m);
// The Refounder holds no Manage Nicknames: m's own device carries it.
carry_my_nickname(&bed.relay, &held()).await.unwrap();
let gb = super::super::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch).pk().to_hex();
let q = Query { kinds: vec![1059], authors: vec![gb], ..Default::default() };
let published = bed.relay.fetch(&q, &held().relays).await.unwrap().len();
carry_my_nickname(&bed.relay, &held()).await.unwrap();
assert_eq!(bed.relay.fetch(&q, &held().relays).await.unwrap().len(), published, "carried once");
reread_guestbook(&bed.relay, &held()).await;
let named = standing_nicknames(&held()).unwrap();
assert_eq!(named.get(&m.public_key()).map(|w| (w.nick.as_str(), w.at_ms)), Some(("Moth", first)), "dated as first issued");
}
async fn invites_to(relay: &MemoryRelay, community: &CommunityV2, pk: &PublicKey) -> usize {
let q = Query { kinds: vec![1059], p_tags: vec![pk.to_hex()], ..Default::default() };
relay.fetch(&q, &community.relays).await.unwrap_or_default().len()
}
#[tokio::test]
async fn a_tenure_vouching_for_unpublished_editions_isnt_resealed() {
// An admin pre-seals a puppet's unpublished edition, then is demoted: the honest
// re-seal leaves that Tenure out, so the puppet can't publish it later on that standing.
let (bed, owner, w, community) = v2_bed_with_admin("PreSeal").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let b = Keys::generate();
let made = "da".repeat(32);
let group = control::ControlPlane::of(&held()).write_group().unwrap();
let content = crate::community::v2::roles::role_v2_content_json(&role_v2(&made, "Puppet", "z", 0)).unwrap();
let binding = Some(crate::community::v2::derive::edition_binding(community.id()));
let rumor = control::build_edition_rumor_bound(b.public_key(), vsk::ROLE_V2, &eid_of(&made), 1, None, &content, 1_000, None, binding);
let (wrap, _) = control::seal_control_edition(&rumor, &group, &b, Timestamp::from_secs(1_000)).unwrap();
let (pre, _) = control::open_control_edition(&wrap, &group).unwrap();
publish_tenure(&bed.relay, &held(), &w, &b.public_key(), vec![entry("y", Permissions::MANAGE_ROLES, &[pre.self_hash])], 1).await;
// A refused successor naming it doesn't make it seen.
let next = control::build_edition_rumor_bound(b.public_key(), vsk::ROLE_V2, &eid_of(&made), 2, Some(&pre.self_hash), &content, 1_001, None, binding);
let (next, _) = control::seal_control_edition(&next, &group, &b, Timestamp::from_secs(1_001)).unwrap();
bed.relay.publish(&next, &held().relays).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
set_member_roles(&bed.relay, &held(), &w.public_key(), vec![]).await.unwrap();
bed.relay.publish(&wrap, &held().relays).await.unwrap();
let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
assert!(f.roles.role(&made).is_none(), "the late edition stands on nothing");
let _ = owner;
}
#[tokio::test]
async fn a_tenure_listing_a_superseded_edition_is_still_resealed() {
let (bed, owner, w, community) = v2_bed_with_admin("Superseded").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let r = create_role_v2(&bed.relay, &held(), "Old", 0, 0).await.unwrap();
let first = fetch_control(&bed.relay, &held()).await.into_iter().find(|e| e.entity_id == eid_of(&r)).unwrap();
let rank = fetch_authority(&bed.relay, &held()).await.roles.role(&r).unwrap().rank.clone().unwrap();
publish_role_v2(&bed.relay, &held(), &owner.keys, &role_v2(&r, "New", &rank, 0), 2).await;
let b = Keys::generate().public_key();
publish_tenure(&bed.relay, &held(), &w, &b, vec![entry("y", Permissions::MANAGE_ROLES, &[first.self_hash])], 1).await;
follow_control(&bed.relay, &held()).await.unwrap();
let tenure = super::super::derive::tenure_locator(community.id(), &b.to_bytes(), &w.public_key().to_bytes());
let w_tenure = fetch_control(&bed.relay, &held()).await.into_iter().find(|e| e.entity_id == tenure).unwrap().self_hash;
// The superseded edition is compacted away; its successor still names it.
let compacted = Hiding { inner: &bed.relay, group: control::ControlPlane::of(&held()).write_group().unwrap(), hide: Box::new(move |e| e.self_hash == first.self_hash) };
set_member_roles(&compacted, &held(), &w.public_key(), vec![]).await.unwrap();
let seal = super::super::derive::tenure_locator(community.id(), &w.public_key().to_bytes(), &owner.keys.public_key().to_bytes());
let mine = fetch_control(&bed.relay, &held()).await.into_iter().filter(|e| e.entity_id == seal).max_by_key(|e| e.version).expect("W's standing was sealed");
let listed = crate::community::v2::roles::parse_tenure_content(&mine.content).unwrap();
assert!(listed.sealed.iter().any(|x| x.heads.contains(&crate::simd::hex::bytes_to_hex_32(&w_tenure))), "W's Tenure is kept");
}
#[tokio::test]
async fn a_member_cant_let_themselves_in() {
let (bed, owner, x, community) = v2_bed_with_admin("SelfIn").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
let o = crate::community::roles::Overwrite { scope: chan.clone(), target: crate::community::roles::OverwriteTarget::Member(x.public_key().to_hex()), allow: Permissions(Permissions::VIEW_CHANNEL), deny: Permissions(0) };
let t = crate::community::v2::roles::overwrite_target_bytes(community.id(), &o.target).unwrap();
publish_marked(&bed.relay, &held(), &x, vsk::CHANNEL_ACL, &crate::community::v2::derive::acl_locator(community.id(), &ch.0, &t), 1, None, &crate::community::v2::roles::overwrite_content_json(&o)).await;
let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
assert!(!f.roles.is_entitled(Some(&owner.keys.public_key().to_hex()), &x.public_key().to_hex(), &chan, &[], &[]), "their own standing sits above nothing of theirs");
// The owner's own allow does let them in.
grant_channel_access(&bed.relay, &held(), &ch, &x.public_key()).await.unwrap();
let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
assert!(f.roles.is_entitled(Some(&owner.keys.public_key().to_hex()), &x.public_key().to_hex(), &chan, &[], &[]));
}
#[tokio::test]
async fn a_role_moved_past_an_overwrites_writer_rekeys_who_it_let_in() {
let (bed, owner, a, community) = v2_bed_with_admin("MovePast").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
let r = create_role_v2(&bed.relay, &held(), "Readers", 0, 0).await.unwrap();
let m = Keys::generate().public_key();
set_member_roles(&bed.relay, &held(), &m, vec![r.clone()]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
act_as(&a);
set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Role(r.clone()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
act_as(&owner.keys);
follow_control(&bed.relay, &held()).await.unwrap();
assert!(crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap().is_entitled(Some(&owner.keys.public_key().to_hex()), &m.to_hex(), &chan, &[], &[]));
let epoch = held().channel(&ch).unwrap().epoch;
// The owner lifts Readers above A: A's allow no longer stands, so M is cut.
move_role_v2(&bed.relay, &held(), &r, 0).await.unwrap();
let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
assert!(!f.roles.is_entitled(Some(&owner.keys.public_key().to_hex()), &m.to_hex(), &chan, &[], &[]), "readers drop the allow");
assert!(held().channel(&ch).unwrap().epoch > epoch, "and the channel rotated without M");
}
/// Serves reads until the first publish, then refuses every one.
struct BreaksAfterPublish<'a> {
inner: &'a MemoryRelay,
broken: std::sync::atomic::AtomicBool,
}
#[async_trait::async_trait]
impl Transport for BreaksAfterPublish<'_> {
async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
Ok(crate::community::transport::PlaneFetch::whole(self.fetch(query, relays).await?))
}
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.broken.store(true, std::sync::atomic::Ordering::SeqCst);
self.inner.publish(e, r).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.broken.store(true, std::sync::atomic::Ordering::SeqCst);
self.inner.publish_durable(e, r).await
}
async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
if self.broken.load(std::sync::atomic::Ordering::SeqCst) {
return Err("offline".into());
}
self.inner.fetch(q, r).await
}
}
#[tokio::test]
async fn ban_severance_on_roles_v2_refuses_a_partial_read() {
let (bed, _owner, _x, community) = v2_bed_with_admin("SeverBlind").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
let b = Keys::generate().public_key();
grant_channel_access(&bed.relay, &held(), &ch, &b).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let before = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
let epoch = held().channel(&ch).unwrap().epoch;
let blind = BreaksAfterPublish { inner: &bed.relay, broken: true.into() };
let err = sever_banned_private_reads(&blind, &held(), &[(b, Vec::new())], Some(&before)).await.unwrap_err();
assert!(err.contains("read whole"), "{err}");
assert_eq!(held().channel(&ch).unwrap().epoch, epoch, "nothing rotated on half a roster");
// The cut is owed, not forgotten: the next whole read rotates without them.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
assert!(has_read_cuts(&cid_hex));
let invited = invites_to(&bed.relay, &held(), &b).await;
assert_eq!(run_read_cuts(&bed.relay, &held()).await.unwrap(), 1);
assert!(held().channel(&ch).unwrap().epoch > epoch, "the channel rotated");
assert_eq!(invites_to(&bed.relay, &held(), &b).await, invited, "and the banned member got no new key");
assert!(!has_read_cuts(&cid_hex), "the cut is settled");
}
#[tokio::test]
async fn a_role_move_settles_on_what_it_knows_when_the_reread_fails() {
let (bed, owner, _x, community) = v2_bed_with_admin("MoveOffline").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
let (r, other) = (create_role_v2(&bed.relay, &held(), "Readers", 0, 0).await.unwrap(), create_role_v2(&bed.relay, &held(), "Other", 0, 0).await.unwrap());
set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Role(r.clone()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
let m = Keys::generate().public_key();
set_member_roles(&bed.relay, &held(), &m, vec![r]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let epoch = held().channel(&ch).unwrap().epoch;
let flaky = BreaksAfterPublish { inner: &bed.relay, broken: false.into() };
for (i, mv) in [(0usize, true), (1, false)] {
flaky.broken.store(false, std::sync::atomic::Ordering::SeqCst);
if mv {
move_role_v2(&flaky, &held(), &other, i).await.unwrap();
} else {
let ranked: Vec<String> = { let v = fetch_authority(&bed.relay, &held()).await; ranked(&v).into_iter().map(|r| r.role_id.clone()).collect() };
let mut order = ranked.clone();
order.rotate_left(1);
reorder_roles_v2(&flaky, &held(), &order).await.unwrap();
}
assert_eq!(held().channel(&ch).unwrap().epoch, epoch, "a failed reread evicts no one");
let stored = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
assert!(stored.is_entitled(Some(&owner.keys.public_key().to_hex()), &m.to_hex(), &crate::simd::hex::bytes_to_hex_32(&ch.0), &[], &[]), "nor drops them from the roster");
assert!(stored.role(&other).is_some(), "nor its Roles");
}
}
#[tokio::test]
async fn a_role_move_whose_reread_fails_owes_the_cut() {
let (bed, owner, a, community) = v2_bed_with_admin("OwedCut").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
let r = create_role_v2(&bed.relay, &held(), "Readers", 0, 0).await.unwrap();
let m = Keys::generate().public_key();
set_member_roles(&bed.relay, &held(), &m, vec![r.clone()]).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
act_as(&a);
set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Role(r.clone()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
act_as(&owner.keys);
follow_control(&bed.relay, &held()).await.unwrap();
let epoch = held().channel(&ch).unwrap().epoch;
// Readers above A: A's allow falls, but the reread fails, so the cut is owed.
let flaky = BreaksAfterPublish { inner: &bed.relay, broken: false.into() };
move_role_v2(&flaky, &held(), &r, 0).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
assert!(has_owed_settle(&cid_hex));
assert_eq!(held().channel(&ch).unwrap().epoch, epoch, "nothing cut on a failed read");
let blind = BreaksAfterPublish { inner: &bed.relay, broken: true.into() };
assert!(run_owed_settle(&blind, &held()).await.is_err(), "a partial read pays nothing");
assert!(has_owed_settle(&cid_hex) && held().channel(&ch).unwrap().epoch == epoch, "and evicts no one");
assert!(run_owed_settle(&bed.relay, &held()).await.unwrap());
assert!(held().channel(&ch).unwrap().epoch > epoch, "the whole read cuts M");
let owner_hex = owner.keys.public_key().to_hex();
assert!(!crate::db::community::get_community_roles(&cid_hex).unwrap().is_entitled(Some(&owner_hex), &m.to_hex(), &chan, &[], &[]));
assert!(!has_owed_settle(&cid_hex), "and the settle is paid");
}
#[tokio::test]
async fn on_roles_v2_a_public_ban_rotates_the_channels_its_target_could_read() {
let (bed, owner, _x, community) = v2_bed_with_admin("PublicBan").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
mint_public_link(&bed.relay, &held(), "https://vectorapp.io", None, None).await.unwrap();
let (inner, other) = (create_private_channel(&bed.relay, &held(), "inner").await.unwrap(), create_private_channel(&bed.relay, &held(), "other").await.unwrap());
let b = Keys::generate().public_key();
grant_channel_access(&bed.relay, &held(), &inner, &b).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let (e_inner, e_other) = (held().channel(&inner).unwrap().epoch, held().channel(&other).unwrap().epoch);
set_members_banned(&bed.relay, held().id(), &[b], true).await.unwrap();
assert_eq!(held().root_epoch, community.root_epoch, "public: no Refounding");
assert!(held().channel(&inner).unwrap().epoch > e_inner, "the ban itself rotated what they could read");
assert_eq!(held().channel(&other).unwrap().epoch, e_other, "and nothing else");
let _ = owner;
}
#[tokio::test]
async fn readers_agree_when_an_overwrites_editor_is_outranked() {
let (bed, owner, x, community) = v2_bed_with_admin("Outranked").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
let r = create_role_v2(&bed.relay, &held(), "Readers", 0, 0).await.unwrap();
let target = crate::community::roles::OverwriteTarget::Role(r.clone());
set_overwrite(&bed.relay, &held(), ch.0, target.clone(), Permissions::VIEW_CHANNEL, 0).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
act_as(&x);
set_overwrite(&bed.relay, &held(), ch.0, target.clone(), Permissions::VIEW_CHANNEL | Permissions::SEND_MESSAGES, 0).await.unwrap();
act_as(&owner.keys);
follow_control(&bed.relay, &held()).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let floors = || -> Floors { crate::db::community::get_all_edition_heads_full(&cid_hex).unwrap().into_iter().filter(|(_, f)| f.0 == held().root_epoch.0).map(|(e, f)| (e, (f.1, f.2, f.3, f.4, f.5))).collect() };
let held_floors = floors();
// Readers lifted above X: X's edit no longer stands.
move_role_v2(&bed.relay, &held(), &r, 0).await.unwrap();
let eds = fetch_control(&bed.relay, &held()).await;
let allow_of = |f: &AuthoritySet| f.roles.overwrites.iter().find(|o| o.target == target).map(|o| o.allow.0);
let (warm, cold) = (fold_authority(&held(), &eds, &held_floors), fold_authority(&held(), &eds, &Floors::default()));
assert_eq!(allow_of(&cold), Some(Permissions::VIEW_CHANNEL), "a cold reader folds the owner's edition");
assert_eq!(allow_of(&warm), allow_of(&cold), "and a reader that held X's edit agrees");
}
#[tokio::test]
async fn an_unsync_out_of_a_superiors_category_is_refused() {
let (bed, _owner, x, community) = v2_bed_with_admin("Unsync").await;
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let top = "f7".repeat(32);
publish_role_v2(&bed.relay, &held(), &_owner.keys, &role_v2(&top, "Top", "1", 0), 1).await;
follow_control(&bed.relay, &held()).await.unwrap();
let k = create_category(&bed.relay, &held(), "Rules").await.unwrap();
set_overwrite(&bed.relay, &held(), k, crate::community::roles::OverwriteTarget::Role(top.clone()), Permissions::SEND_MESSAGES, 0).await.unwrap();
let news = create_channel_in(&bed.relay, &held(), "news", false, Some(k)).await.unwrap();
follow_control(&bed.relay, &held()).await.unwrap();
let eid = crate::community::v2::derive::sync_locator(community.id(), &news);
let prev = head_hash_on_relay(&bed.relay, &held(), &eid).await;
let content = crate::community::v2::roles::sync_content_json(&crate::simd::hex::bytes_to_hex_32(&news.0), None);
publish_marked(&bed.relay, &held(), &x, vsk::CHANNEL_SYNC, &eid, 2, prev, &content).await;
let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
assert_eq!(f.roles.syncs.get(&crate::simd::hex::bytes_to_hex_32(&news.0)), Some(&crate::simd::hex::bytes_to_hex_32(&k)), "X can't swap out a rule naming a Role above them");
}
#[tokio::test]
async fn a_member_denied_send_cannot_post() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "NoSend", vec!["wss://r".into()], None).await.unwrap();
activate_roles_v2(&relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = community.channels[0].id;
set_overwrite(&relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
assert!(send_chat_message(&relay, &held(), &ch, "owner speaks", None, &[], vec![]).await.is_ok(), "the owner holds everything");
let member = Keys::generate();
let open = create_public_channel(&relay, &held(), "open").await.unwrap();
let quiet = create_public_channel(&relay, &held(), "quiet").await.unwrap();
set_overwrite(&relay, &held(), quiet.0, crate::community::roles::OverwriteTarget::Member(member.public_key().to_hex()), 0, Permissions::SEND_MESSAGES).await.unwrap();
crate::state::MY_SECRET_KEY.store_from_keys(&member, &[]);
crate::state::set_my_public_key(member.public_key());
assert!(send_chat_message(&relay, &held(), &open, "fine here", None, &[], vec![]).await.is_ok(), "where Send stands, they post");
let err = send_chat_message(&relay, &held(), &ch, "hi", None, &[], vec![]).await.unwrap_err();
assert!(err.contains("can't send"), "{err}");
assert!(send_chat_message(&relay, &held(), &quiet, "hi", None, &[], vec![]).await.is_err());
// In an open channel readers collapse that member's posts, not the owner's.
use nostr_sdk::prelude::ToBech32;
let (mn, on) = (member.public_key().to_bech32().unwrap(), owner.public_key().to_bech32().unwrap());
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let denied = |c: &ChannelId, who: &[String]| crate::VectorCore.channel_send_denied(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&c.0), who).unwrap();
assert_eq!(denied(&quiet, &[mn.clone(), on.clone()]), vec![mn.clone()]);
assert!(denied(&open, &[mn.clone()]).is_empty());
// A restricted channel judges read-address posts the same way; a writer's stand on their key.
assert!(held().channel(&ch).unwrap().restricted());
assert_eq!(denied(&ch, &[mn, on]), vec![member.public_key().to_bech32().unwrap()]);
crate::state::MY_SECRET_KEY.store_from_keys(&owner, &[]);
crate::state::set_my_public_key(owner.public_key());
}
#[tokio::test]
async fn on_roles_v2_keys_follow_roles_through_the_channel() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "AclRoles", vec!["wss://r".into()], None).await.unwrap();
activate_roles_v2(&relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&relay, &community).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let priv_id = create_private_channel(&relay, &held(), "staff").await.unwrap();
let chan = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let owner_hex = community.owner().unwrap().to_hex();
let m = Keys::generate().public_key();
let roster = || crate::db::community::get_community_roles(&cid_hex).unwrap();
assert!(roster().channel_roles(&chan).is_empty(), "no access role on Roles v2");
assert!(!roster().is_entitled(Some(&owner_hex), &m.to_hex(), &chan, &[], &[]), "@everyone can't view it");
let staff = create_role_v2(&relay, &held(), "Staff", 0, 0).await.unwrap();
set_overwrite(&relay, &held(), priv_id.0, crate::community::roles::OverwriteTarget::Role(staff.clone()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
set_member_roles(&relay, &held(), &m, vec![staff.clone()]).await.unwrap();
assert!(roster().is_entitled(Some(&owner_hex), &m.to_hex(), &chan, &[], &[]), "the role the channel lets through");
assert!(bundle_of(&held(), BundleAudience::Member(m), None, None, None).channels.iter().any(|c| c.id == chan));
assert_eq!(invites_to(&relay, &held(), &m).await, 1, "and a Direct Invite carried it to them");
assert_eq!(held().channel(&priv_id).unwrap().epoch, Epoch(1));
set_member_roles(&relay, &held(), &m, vec![]).await.unwrap();
assert_eq!(held().channel(&priv_id).unwrap().epoch, Epoch(2), "losing the role rotates the channel");
// Deleting the allow overwrite's role does the same for its holders.
let n = Keys::generate().public_key();
set_member_roles(&relay, &held(), &n, vec![staff.clone()]).await.unwrap();
delete_role_v2(&relay, &held(), &staff).await.unwrap();
assert_eq!(held().channel(&priv_id).unwrap().epoch, Epoch(3));
assert!(!roster().is_entitled(Some(&owner_hex), &n.to_hex(), &chan, &[], &[]));
}
#[tokio::test]
async fn an_overwrite_stands_only_on_authority_above_its_target() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "AclJudge", vec!["wss://r".into()], None).await.unwrap();
publish_everyone(&relay, &community, &owner, crate::community::v2::roles::EVERYONE_DEFAULT, 1).await;
let (a, b) = (Keys::generate(), Keys::generate());
let mr = Permissions::MANAGE_ROLES | Permissions::VIEW_CHANNEL | Permissions::SEND_MESSAGES;
let (ra, rb) = ("e3".repeat(32), "e4".repeat(32));
publish_role_v2(&relay, &community, &owner, &role_v2(&ra, "A", "C", mr), 1).await;
publish_role_v2(&relay, &community, &owner, &role_v2(&rb, "B", "F", Permissions::VIEW_CHANNEL), 1).await;
publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
let ch = community.channels[0].id.0;
let put = |target: crate::community::roles::OverwriteTarget, allow: u64, deny: u64| {
let o = crate::community::roles::Overwrite { scope: crate::simd::hex::bytes_to_hex_32(&ch), target, allow: Permissions(allow), deny: Permissions(deny) };
let t = crate::community::v2::roles::overwrite_target_bytes(community.id(), &o.target).unwrap();
(crate::community::v2::derive::acl_locator(community.id(), &ch, &t), crate::community::v2::roles::overwrite_content_json(&o))
};
use crate::community::roles::OverwriteTarget as T;
// A, above B, denies B Send: stands. A denying A's own role: refused (not above it).
let (e1, c1) = put(T::Role(rb.clone()), 0, Permissions::SEND_MESSAGES);
publish_marked(&relay, &community, &a, vsk::CHANNEL_ACL, &e1, 1, None, &c1).await;
let (e2, c2) = put(T::Role(ra.clone()), 0, Permissions::SEND_MESSAGES);
publish_marked(&relay, &community, &a, vsk::CHANNEL_ACL, &e2, 1, None, &c2).await;
// A allowing @everyone a bit A lacks: refused.
let (e3, c3) = put(T::Everyone, Permissions::ATTACH_FILES, 0);
publish_marked(&relay, &community, &a, vsk::CHANNEL_ACL, &e3, 1, None, &c3).await;
// The owner's, at another target's coordinate: ignored. Unmarked: ignored.
let (_, c4) = put(T::Everyone, 0, Permissions::ADD_REACTIONS);
publish_marked(&relay, &community, &owner, vsk::CHANNEL_ACL, &e1, 2, None, &c4).await;
let (e5, c5) = put(T::Member(b.public_key().to_hex()), Permissions::ATTACH_FILES, 0);
publish_fork(&[&relay], &community, &owner, vsk::CHANNEL_ACL, &e5, 1, None, &c5, None).await;
let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
let got: Vec<(T, u64, u64)> = f.roles.overwrites.iter().map(|o| (o.target.clone(), o.allow.0, o.deny.0)).collect();
assert_eq!(got, vec![(T::Role(rb), 0, Permissions::SEND_MESSAGES)]);
}
#[tokio::test]
async fn a_private_channel_mints_its_access_role_and_entitlement_follows_the_grant() {
// CORD-03/04: the roles scoped to a channel ARE its access list. Proven
// against a NON-owner so the owner-is-always-entitled rule can't carry it.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Scoped", vec!["wss://r".into()], None).await.unwrap();
let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
let access = roster.channel_roles(&chan_hex);
assert_eq!(access.len(), 1, "the channel minted exactly one access role");
assert!(
access[0].permissions == crate::community::roles::Permissions::empty(),
"the access role confers READ access (key possession), never authority"
);
assert_eq!(access[0].name, "mods", "named for its channel");
// A stranger holds no scoped role: unentitled, and no key rides their bundle.
let stranger = Keys::generate().public_key();
let owner_hex = community.owner().unwrap().to_hex();
assert!(!roster.is_entitled(Some(&owner_hex), &stranger.to_hex(), &chan_hex, &[], &[]));
// Granting the access role entitles them; revoking un-entitles them. Both
// proven through the roster, which is what routes keys.
let role_id = access[0].role_id.clone();
assert!(
roster.is_entitled(Some(&owner_hex), &stranger.to_hex(), &chan_hex, std::slice::from_ref(&role_id), &[]),
"the grant overlay entitles before the fold catches up"
);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
grant_channel_access(&relay, &held, &priv_id, &stranger).await.unwrap();
let after = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert!(
after.is_entitled(Some(&owner_hex), &stranger.to_hex(), &chan_hex, &[], &[]),
"the grant landed in the local roster (the fold runs later)"
);
let vend = bundle_of(&held, BundleAudience::Member(stranger), None, None, None);
assert!(
vend.channels.iter().any(|c| c.id == chan_hex),
"a now-entitled member's bundle carries the channel key"
);
revoke_channel_access(&relay, &held, &priv_id, &stranger).await.unwrap();
let after = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert!(
!after.is_entitled(Some(&owner_hex), &stranger.to_hex(), &chan_hex, &[], &[]),
"the revoke dropped the access role"
);
let rotated = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(
rotated.channel(&priv_id).unwrap().epoch,
Epoch(2),
"the revoke rotated the channel — a removal that doesn't rekey severs nobody"
);
// The access summary a bot reads back: roles, holders, and key state.
let access = crate::VectorCore.channel_access(&cid_hex, &chan_hex).unwrap();
assert_eq!(access["private"], true);
assert_eq!(access["readable"], true, "we minted it, so we hold its key");
assert_eq!(access["roles"].as_array().unwrap().len(), 1, "one access role");
let holders = access["members"].as_array().unwrap();
let me_npub = {
use nostr_sdk::prelude::ToBech32;
me_pk().unwrap().to_bech32().unwrap()
};
assert_eq!(holders.len(), 1, "only the creator holds it — the revoked member is gone");
assert_eq!(holders[0], serde_json::json!(me_npub), "and that holder is the creator");
}
#[tokio::test]
async fn a_public_ban_severs_the_private_channels_the_member_could_read() {
// CORD-06 §1 per channel: a Public-community ban skips the Refounding
// (CORD-05 §5), so without this rotation the banned member keeps each
// held channel key and reads on forever. Only channels they could
// actually reach rotate — the rest keep their epoch.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Sever", vec!["wss://r".into()], None).await.unwrap();
let mods = create_private_channel(&relay, &community, "mods").await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let vault = create_private_channel(&relay, &held, "vault").await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let spammer = Keys::generate().public_key();
let bystander = Keys::generate().public_key();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
grant_channel_access(&relay, &held, &mods, &spammer).await.unwrap();
grant_channel_access(&relay, &held, &mods, &bystander).await.unwrap();
// The ban composition's capture-then-strip: entitlement must be judged
// from the PRE-strip roles, whether or not the strip has folded.
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
let stripped: Vec<String> = roster.roles_of(&spammer.to_hex()).map(|r| r.role_id.clone()).collect();
assert!(!stripped.is_empty(), "the grant landed before the strip");
grant_roles(&relay, &held, &spammer, vec![]).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let rotated = sever_banned_private_reads(&relay, &held, &[(spammer, stripped)], None).await.unwrap();
assert_eq!(rotated, 1, "exactly the one channel they could read rotated");
let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(after.channel(&mods).unwrap().epoch, Epoch(2), "the reachable channel advanced");
assert_eq!(after.channel(&vault).unwrap().epoch, Epoch(1), "the unreachable channel did not");
// A member who never had reach rotates nothing.
let stranger = Keys::generate().public_key();
let n = sever_banned_private_reads(&relay, &after, &[(stranger, Vec::new())], None).await.unwrap();
assert_eq!(n, 0, "no entitlement, no rotation");
}
#[tokio::test]
async fn ban_severance_refuses_without_a_rotation_bit() {
// Offer-side mirror of `channel_rotator_ok`: readers honor a channel
// rotation only from MANAGE_CHANNELS holders, so a BAN-only moderator
// publishing one would adopt an epoch every reader rejects — a fork.
let (bed, owner, moderator) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Gated", bed.relays.clone(), None).await.unwrap();
create_private_channel(&bed.relay, &community, "mods").await.unwrap();
let rid = "c1".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::KICK), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &moderator.keys.public_key(), vec![rid], 1).await;
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let bundle = bundle_of(&held, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&moderator);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
let target = Keys::generate().public_key();
let err = sever_banned_private_reads(&bed.relay, &joined, &[(target, Vec::new())], None).await.unwrap_err();
assert!(err.contains("permission"), "refused at the gate, not mid-rotation: {err}");
}
#[tokio::test]
async fn set_banlist_refuses_an_author_the_fold_would_reject() {
// The reader gates the banlist head on BAN and each added entry on strict
// outrank. Publishing anyway would be silently void everywhere while the
// author's own echo caches the phantom — fail-closed at the offer instead.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Soap", bed.relays.clone(), None).await.unwrap();
let rid = "c2".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let bundle = bundle_of(&held, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
// A roleless member holds no BAN: refused before any publish.
bed.swap_to(&member);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
let target = Keys::generate().public_key().to_hex();
let err = set_banlist(&bed.relay, &joined, std::slice::from_ref(&target)).await.unwrap_err();
assert!(err.contains("BAN"), "refused for the missing bit: {err}");
assert!(
crate::db::community::get_community_banlist(&crate::simd::hex::bytes_to_hex_32(&joined.id().0)).unwrap().is_empty(),
"no phantom echo cached"
);
// Grant them BAN: adding a peer they don't outrank still refuses (the
// fold drops per-target on outrank), while an unranked target passes.
bed.swap_to(&owner);
publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid.clone()], 1).await;
let peer = Keys::generate().public_key();
publish_grant(&bed.relay, &community, &owner.keys, &peer, vec![rid], 2).await;
bed.swap_to(&member);
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
let err = set_banlist(&bed.relay, &joined, &[peer.to_hex()]).await.unwrap_err();
assert!(err.contains("outrank"), "an equal is not actionable: {err}");
set_banlist(&bed.relay, &joined, std::slice::from_ref(&target)).await.unwrap();
}
#[tokio::test]
async fn metadata_and_link_minting_refuse_unauthorized_authors() {
// Both are reader-gated (MANAGE_METADATA; CREATE_INVITE on the registry) —
// the offer must mirror or the SDK reports success on a void publish.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Locked", bed.relays.clone(), None).await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let bundle = bundle_of(&held, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&member);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
let meta = control::CommunityMetadata {
name: "Hijacked".into(),
description: None,
relays: vec![],
icon: None,
banner: None,
custom: None,
extra: Default::default(),
};
assert!(edit_community_metadata(&bed.relay, &joined, &meta).await.is_err(), "metadata edit refused");
assert!(
mint_public_link(&bed.relay, &joined, "https://vectorapp.io/i/", None, None).await.is_err(),
"link minting refused"
);
}
#[tokio::test]
async fn a_vended_key_parks_until_the_fold_proves_the_grant_then_adopts() {
// JSKitty's race: the vend can land BEFORE the control fold that proves
// the grant. It must park quietly (a lagging fold is not an anomaly) and
// be adopted on the re-judge once the roster catches up.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Vend", bed.relays.clone(), None).await.unwrap();
let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let real_key = held.channel(&priv_id).unwrap().key.unwrap();
let owner_hex = community.owner().unwrap().to_hex();
// Judge as the MEMBER — the owner is always entitled, so only a non-owner
// can exercise the grant rule at all.
bed.swap_to(&member);
let me = member.keys.public_key().to_hex();
// Their fold has the channel (control-follow records it keyless) but not
// yet the grant that entitles them.
let mut member_view = held.clone();
if let Some(c) = member_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
c.key = None;
c.epoch = Epoch(0);
}
// Ungranted → PARK, never refuse: this is exactly the "not synced enough
// to judge" case, and it must stay quiet and retryable.
let empty = crate::community::roles::CommunityRoles::default();
assert!(matches!(
judge_channel_key_vend(&member_view, &empty, &priv_id, Epoch(1), &owner_hex),
VendVerdict::Park(_)
));
// A channel our fold says is PUBLIC never heals — that's a spoof shape.
let mut public_view = member_view.clone();
if let Some(c) = public_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
c.private = false;
}
assert!(matches!(
judge_channel_key_vend(&public_view, &empty, &priv_id, Epoch(1), &owner_hex),
VendVerdict::Refuse(_)
));
// An unknown channel parks (our fold may simply be behind), never refuses.
assert!(matches!(
judge_channel_key_vend(&member_view, &empty, &ChannelId([0x77; 32]), Epoch(1), &owner_hex),
VendVerdict::Park(_)
));
// Park the vend, then re-judge with a roster that still lacks our grant:
// it must SURVIVE, not be discarded.
crate::db::community::park_channel_key(&cid_hex, &chan_hex, 1, &real_key, &owner_hex).unwrap();
crate::db::community::set_community_roles(&cid_hex, &empty, 0).unwrap();
crate::db::community::save_community_v2(&member_view).unwrap();
let session = crate::db::current_session();
let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert!(absorb_parked_channel_keys(&reloaded, &session).is_empty(), "unprovable vend adopts nothing");
assert_eq!(
crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().len(),
1,
"and stays parked for the next fold"
);
// The fold catches up: our grant lands, so the same vend now adopts.
let access = crate::community::roles::Role {
role_id: "44".repeat(32),
name: "mods".into(),
position: u32::MAX - 1,
permissions: crate::community::roles::Permissions::empty(),
scope: crate::community::roles::RoleScope::Channel(chan_hex.clone()),
color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
};
let folded = crate::community::roles::CommunityRoles {
grants: vec![crate::community::roles::MemberGrant { member: me.clone(), role_ids: vec![access.role_id.clone()] }],
roles: vec![access],
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
};
let vendor = Keys::generate().public_key().to_hex();
crate::db::community::set_community_banlist(&cid_hex, &[vendor.clone()], 1).unwrap();
assert!(
matches!(judge_channel_key_vend(&member_view, &folded, &priv_id, Epoch(1), &vendor), VendVerdict::Refuse("vendor is banned")),
"a banned member delivers nothing"
);
crate::db::community::set_community_banlist(&cid_hex, &[], 2).unwrap();
crate::db::community::set_community_roles(&cid_hex, &folded, 1).unwrap();
let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let adopted = absorb_parked_channel_keys(&reloaded, &session);
assert_eq!(adopted.len(), 1, "the re-judge adopts once the grant folds");
let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = after.channel(&priv_id).unwrap();
assert_eq!(ch.key, Some(real_key), "adopted the vended key");
assert_eq!(ch.epoch, Epoch(1));
assert!(
crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().is_empty(),
"and the park is discharged"
);
}
#[tokio::test]
async fn a_vend_from_an_unentitled_sender_is_never_seated_but_survives_for_the_real_one() {
// Vend rule 4: the VENDOR must be entitled too. Every other test sends as
// the owner, which short-circuits the check one line above it, so the rule
// itself has never been exercised. Both halves matter — a stranger must not
// seat a key, and their row must not consume the slot either, which is the
// suppression the candidate table exists to prevent.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Vendors", bed.relays.clone(), None).await.unwrap();
let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let owner_hex = community.owner().unwrap().to_hex();
bed.swap_to(&member);
let mut member_view = held.clone();
if let Some(c) = member_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
c.key = None;
c.epoch = Epoch(0);
}
crate::db::community::save_community_v2(&member_view).unwrap();
// WE are entitled (rule 3 passes, so the judge reaches rule 4). The vendor
// below is not, and is not the owner.
let access = crate::community::roles::Role {
role_id: "66".repeat(32),
name: "mods".into(),
position: u32::MAX - 1,
permissions: crate::community::roles::Permissions::empty(),
scope: crate::community::roles::RoleScope::Channel(chan_hex.clone()),
color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
};
let roster = crate::community::roles::CommunityRoles {
grants: vec![crate::community::roles::MemberGrant {
member: member.keys.public_key().to_hex(),
role_ids: vec![access.role_id.clone()],
}],
roles: vec![access],
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
};
crate::db::community::set_community_roles(&cid_hex, &roster, 1).unwrap();
let stranger_hex = Keys::generate().public_key().to_hex();
let junk = [0x11; 32];
crate::db::community::park_channel_key(&cid_hex, &chan_hex, 0, &junk, &stranger_hex).unwrap();
let session = crate::db::current_session();
let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert!(
absorb_parked_channel_keys(&reloaded, &session).is_empty(),
"an unentitled vendor seats nothing"
);
let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(after.channel(&priv_id).unwrap().key, None, "the channel is still keyless");
assert_eq!(
crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().len(),
1,
"parked, not refused — the vendor's own entitlement may simply not have folded here yet"
);
// The entitled vendor's key lands despite the stranger's row sitting there.
let real = [0x5a; 32];
crate::db::community::park_channel_key(&cid_hex, &chan_hex, 0, &real, &owner_hex).unwrap();
let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(
absorb_parked_channel_keys(&reloaded, &session).len(),
1,
"the genuine vend is seated — a stranger cannot occupy the slot"
);
let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(after.channel(&priv_id).unwrap().key, Some(real), "and it is the ENTITLED vendor's key");
assert!(
crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().is_empty(),
"both candidates discharge once one is seated"
);
}
#[tokio::test]
async fn a_vend_at_epoch_zero_is_adopted_onto_a_keyless_channel() {
// Live cross-client finding: a peer that mints born-private channels at
// epoch 0 vends epoch 0, which collides with our keyless cursor (also 0).
// The monotonic guard (`new > current`) would refuse the only key we are
// ever offered, and refuse it SILENTLY. First delivery is not a rotation.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "EpochZero", bed.relays.clone(), None).await.unwrap();
let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let vended = [0x5a; 32];
let owner_hex = community.owner().unwrap().to_hex();
bed.swap_to(&member);
// The member's view: channel known, keyless, parked at the epoch-0 cursor.
let mut member_view = held.clone();
if let Some(c) = member_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
c.key = None;
c.epoch = Epoch(0);
}
crate::db::community::save_community_v2(&member_view).unwrap();
// Entitle them, then park a vend AT EPOCH 0 (what the peer actually sends).
let access = crate::community::roles::Role {
role_id: "77".repeat(32),
name: "mods".into(),
position: u32::MAX - 1,
permissions: crate::community::roles::Permissions::empty(),
scope: crate::community::roles::RoleScope::Channel(chan_hex.clone()),
color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
};
let roster = crate::community::roles::CommunityRoles {
grants: vec![crate::community::roles::MemberGrant {
member: member.keys.public_key().to_hex(),
role_ids: vec![access.role_id.clone()],
}],
roles: vec![access],
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
};
crate::db::community::set_community_roles(&cid_hex, &roster, 1).unwrap();
crate::db::community::park_channel_key(&cid_hex, &chan_hex, 0, &vended, &owner_hex).unwrap();
let session = crate::db::current_session();
let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let adopted = absorb_parked_channel_keys(&reloaded, &session);
assert_eq!(adopted.len(), 1, "an epoch-0 vend onto a keyless channel is adopted");
let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = after.channel(&priv_id).unwrap();
assert_eq!(ch.key, Some(vended), "the key actually landed on the row");
assert_eq!(ch.epoch, Epoch(0), "at the epoch the vendor named");
assert!(
!after.channel_read_coords(ch).is_empty(),
"and the channel is readable — the whole point"
);
assert!(
crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().is_empty(),
"the park is discharged"
);
}
#[tokio::test]
async fn a_wildly_ahead_vend_epoch_is_refused_not_seated() {
// The channel head is MONOTONIC, so over-advancing it can never be walked
// back: every genuine rotation afterwards lands at head+1, reads as stale,
// and the channel dies for us with no heal path at all. An entitled
// insider vending a garbage key costs isolation (accepted); one vending a
// garbage EPOCH would cost the channel permanently, which is not.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Poison", bed.relays.clone(), None).await.unwrap();
let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let owner_hex = community.owner().unwrap().to_hex();
bed.swap_to(&member);
let mut member_view = held.clone();
if let Some(c) = member_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
c.key = None;
c.epoch = Epoch(0);
}
crate::db::community::save_community_v2(&member_view).unwrap();
let access = crate::community::roles::Role {
role_id: "99".repeat(32),
name: "mods".into(),
position: u32::MAX - 1,
permissions: crate::community::roles::Permissions::empty(),
scope: crate::community::roles::RoleScope::Channel(chan_hex.clone()),
color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
};
let roster = crate::community::roles::CommunityRoles {
grants: vec![crate::community::roles::MemberGrant {
member: member.keys.public_key().to_hex(),
role_ids: vec![access.role_id.clone()],
}],
roles: vec![access],
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
};
crate::db::community::set_community_roles(&cid_hex, &roster, 1).unwrap();
let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
// Everything else about this vend is valid — only the epoch is absurd.
assert!(matches!(
judge_channel_key_vend(&reloaded, &roster, &priv_id, Epoch(1 << 40), &owner_hex),
VendVerdict::Refuse(_)
));
// REFUSED, not parked: a row nothing can ever discharge is its own leak.
crate::db::community::park_channel_key(&cid_hex, &chan_hex, 1 << 40, &[0xEE; 32], &owner_hex).unwrap();
let session = crate::db::current_session();
assert!(absorb_parked_channel_keys(&reloaded, &session).is_empty(), "a poison epoch adopts nothing");
assert!(
crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().is_empty(),
"and the row is discharged rather than parked forever"
);
// The head is untouched, so the genuine vend still lands afterwards.
let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(after.channel(&priv_id).unwrap().epoch, Epoch(0), "head never advanced");
assert!(matches!(
judge_channel_key_vend(&after, &roster, &priv_id, Epoch(1), &owner_hex),
VendVerdict::Accept
));
}
#[tokio::test]
async fn a_channel_rename_lands_locally_without_waiting_for_the_fold() {
// The fold is the authority but runs later, so publishing alone leaves the
// edit reading back stale — it looks like the rename silently failed.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Renames", vec!["wss://r".into()], None).await.unwrap();
let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let key_before = held.channel(&priv_id).unwrap().key;
let mut meta = held.channel(&priv_id).unwrap().metadata();
meta.name = "staff".into();
edit_channel_metadata(&relay, &held, &priv_id, &meta).await.unwrap();
let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = after.channel(&priv_id).unwrap();
assert_eq!(ch.name, "staff", "the rename is visible immediately");
assert!(ch.private, "and privacy survives the edit");
assert_eq!(ch.key, key_before, "as does the key — a rename is not a rotation");
}
#[tokio::test]
async fn a_channel_rename_carries_its_companion_access_role() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Renames", vec!["wss://r".into()], None).await.unwrap();
let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
let before = roster.channel_roles(&chan_hex);
assert_eq!(before.len(), 1, "one companion role, minted at create");
assert_eq!(before[0].name, "mods", "named after the channel it gates");
let role_id = before[0].role_id.clone();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let mut meta = held.channel(&priv_id).unwrap().metadata();
meta.name = "staff".into();
edit_channel_metadata(&relay, &held, &priv_id, &meta).await.unwrap();
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
let after = roster.channel_roles(&chan_hex);
assert_eq!(after.len(), 1, "renamed in place, never duplicated");
assert_eq!(after[0].role_id, role_id, "a rename is a versioned edit of the same id");
assert_eq!(after[0].name, "staff", "the access role followed the channel");
assert_eq!(
after[0].permissions,
crate::community::roles::Permissions::empty(),
"and still confers read access, never authority"
);
}
#[tokio::test]
async fn a_customised_access_role_name_survives_a_channel_rename() {
// The label is cosmetic — entitlement rides the scope. Overwriting a name
// someone chose deliberately is the surprising half of "keep them in step".
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Renames", vec!["wss://r".into()], None).await.unwrap();
let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
let mut role = roster.channel_roles(&chan_hex)[0].clone();
role.name = "Lab Insiders".into();
set_role(&relay, &community, &role).await.unwrap();
merge_local_roster(&cid_hex, Some(&role), None);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let mut meta = held.channel(&priv_id).unwrap().metadata();
meta.name = "staff".into();
edit_channel_metadata(&relay, &held, &priv_id, &meta).await.unwrap();
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert_eq!(
roster.channel_roles(&chan_hex)[0].name,
"Lab Insiders",
"a deliberate name is left alone"
);
}
#[tokio::test]
async fn a_squatted_park_row_cannot_suppress_the_genuine_vend() {
// Parking is reachable by ANY npub that can gift-wrap us — the bundle
// self-certifies and its inputs are public for a public community. With a
// single slot per channel, a stranger could pre-park and the admin's real
// vend would be a silent no-op, leaving the member keyless with no retry.
// Candidates + judge-them-all is what closes that.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Squat", bed.relays.clone(), None).await.unwrap();
let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let real_key = held.channel(&priv_id).unwrap().key.unwrap();
let owner_hex = community.owner().unwrap().to_hex();
bed.swap_to(&member);
let mut member_view = held.clone();
if let Some(c) = member_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
c.key = None;
c.epoch = Epoch(0);
}
crate::db::community::save_community_v2(&member_view).unwrap();
let access = crate::community::roles::Role {
role_id: "aa".repeat(32),
name: "mods".into(),
position: u32::MAX - 1,
permissions: crate::community::roles::Permissions::empty(),
scope: crate::community::roles::RoleScope::Channel(chan_hex.clone()),
color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
};
let roster = crate::community::roles::CommunityRoles {
grants: vec![crate::community::roles::MemberGrant {
member: member.keys.public_key().to_hex(),
role_ids: vec![access.role_id.clone()],
}],
roles: vec![access],
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
};
crate::db::community::set_community_roles(&cid_hex, &roster, 1).unwrap();
// A stranger squats FIRST, at a higher epoch than the genuine vend.
let stranger = Keys::generate().public_key().to_hex();
crate::db::community::park_channel_key(&cid_hex, &chan_hex, 9, &[0xBA; 32], &stranger).unwrap();
// The admin's real vend arrives after, at the true epoch.
crate::db::community::park_channel_key(&cid_hex, &chan_hex, 1, &real_key, &owner_hex).unwrap();
assert_eq!(
crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().len(),
2,
"the squatter never displaces the genuine vend — both are candidates"
);
let session = crate::db::current_session();
let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let adopted = absorb_parked_channel_keys(&reloaded, &session);
assert_eq!(adopted.len(), 1, "exactly one adoption");
let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch = after.channel(&priv_id).unwrap();
assert_eq!(ch.key, Some(real_key), "the OWNER's key won, not the squatter's");
assert_eq!(ch.epoch, Epoch(1), "at the genuine epoch");
assert!(
crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().is_empty(),
"and every candidate for the channel is discharged"
);
}
#[tokio::test]
async fn revoking_without_a_folded_access_role_refuses_instead_of_evicting_everyone() {
// With no access role folded, the retained-set filter matches NOBODY, so
// the rotation would cut off every legitimately entitled member while the
// Grant it published revoked nothing. Reachable with no attacker: the
// channel was made on another admin's client and its role hasn't folded.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "NoRole", vec!["wss://r".into()], None).await.unwrap();
let priv_id = create_private_channel(&relay, &community, "mods").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 before = held.channel(&priv_id).unwrap().epoch;
// Nothing serves the access role, cache, wraps held or plane: a withholding relay, or a
// channel minted on another admin's client.
crate::db::community::set_community_roles(&cid_hex, &crate::community::roles::CommunityRoles::default(), 0).unwrap();
forget_held(&held);
let mut blind = held.clone();
blind.relays = vec!["wss://empty".into()];
let err = revoke_channel_access(&relay, &blind, &priv_id, &Keys::generate().public_key())
.await
.unwrap_err();
assert!(err.contains("has not folded"), "refuses with a retryable reason: {err}");
let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(after.channel(&priv_id).unwrap().epoch, before, "and rotates nothing");
}
// ── Live rekey-follow ────────────────────────────────────────────────────
/// Publish an owner-grammar base rotation (Refounding) delivering `new_root`
/// to each recipient. `rotator` is the seal signer (owner for a legit rotation,
/// a stranger for the authority test); `prev_key` is the root it claims to
/// extend (mismatch → a fork).
async fn publish_base_rotation(
relay: &MemoryRelay,
community: &CommunityV2,
rotator: &Keys,
recipients: &[PublicKey],
new_root: &[u8; 32],
prev_key: &[u8; 32],
) {
let new_epoch = Epoch(community.root_epoch.0 + 1);
let prev_epoch = community.root_epoch;
let prev_commit = super::super::derive::epoch_key_commitment(prev_epoch, prev_key);
let group = base_rekey_group_key(&community.community_root, community.id(), new_epoch);
let blobs: Vec<_> = recipients
.iter()
.map(|r| rekey::build_blob_local(rotator.secret_key(), &rotator.public_key().to_bytes(), r, RekeyScope::Root, new_epoch, new_root).unwrap())
.collect();
let events = rekey::build_rekey_chunks_local(rotator, &group, RekeyScope::Root, new_epoch, prev_epoch, &prev_commit, &blobs, 2_000, my_authority_citation(community, &rotator.public_key()).as_ref(), false).unwrap();
for e in &events {
relay.publish(e, &community.relays).await.unwrap();
}
}
/// A base rotation that carries the containment marker (CORD-06 Severing).
async fn publish_severing_base_rotation(
relay: &MemoryRelay,
community: &CommunityV2,
rotator: &Keys,
recipients: &[PublicKey],
new_root: &[u8; 32],
prev_key: &[u8; 32],
) {
let new_epoch = Epoch(community.root_epoch.0 + 1);
let prev_epoch = community.root_epoch;
let prev_commit = super::super::derive::epoch_key_commitment(prev_epoch, prev_key);
let group = base_rekey_group_key(&community.community_root, community.id(), new_epoch);
let blobs: Vec<_> = recipients
.iter()
.map(|r| rekey::build_blob_local(rotator.secret_key(), &rotator.public_key().to_bytes(), r, RekeyScope::Root, new_epoch, new_root).unwrap())
.collect();
let events = rekey::build_rekey_chunks_local(rotator, &group, RekeyScope::Root, new_epoch, prev_epoch, &prev_commit, &blobs, 2_000, my_authority_citation(community, &rotator.public_key()).as_ref(), true).unwrap();
for e in &events {
relay.publish(e, &community.relays).await.unwrap();
}
}
/// Attach a Private channel (key + epoch) to a held community and persist it.
fn add_private_channel(community: &mut CommunityV2, id: ChannelId, key: [u8; 32], epoch: Epoch) {
community.channels.push(ChannelV2 { id, name: "mods".into(), private: true, key: Some(key), epoch, voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed: None });
crate::db::community::save_community_v2(community).unwrap();
}
#[tokio::test]
async fn follow_rekeys_is_a_noop_without_rotations() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Still", vec!["wss://r".into()], None).await.unwrap();
let session = crate::db::current_session();
let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
assert!(follow.updated.is_none() && !follow.self_removed, "no rotation → nothing to adopt");
}
#[tokio::test]
async fn follow_rekeys_adopts_an_owner_base_rotation() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Refound", vec!["wss://r".into()], None).await.unwrap();
let new_root = [0xB1; 32];
// Owner rotates the base to epoch 1, delivering the new root to me.
publish_base_rotation(&relay, &community, &owner, &[owner.public_key()], &new_root, &community.community_root).await;
let session = crate::db::current_session();
let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("adopted");
assert_eq!(updated.root_epoch, Epoch(1), "advanced one epoch");
assert_eq!(updated.community_root, new_root, "adopted the fresh root");
// The public channel now reads under the NEW root/epoch (its address moved).
let addr = super::super::realtime::plane_authors(std::slice::from_ref(&updated));
let general = updated.channels[0].id;
let new_chat = channel_group_key(&new_root, &general, Epoch(1)).pk();
assert!(addr.contains(&new_chat), "the public channel re-addresses under the new root");
}
#[tokio::test]
async fn follow_rekeys_adopts_an_owner_private_channel_rotation() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let mut community = create_community(&relay, "PrivRot", vec!["wss://r".into()], None).await.unwrap();
let priv_id = ChannelId([0x33; 32]);
add_private_channel(&mut community, priv_id, [0x44; 32], Epoch(0));
// Owner rotates the private channel to epoch 1 with a fresh key, delivered to me.
let new_key = [0x55; 32];
let prev_commit = super::super::derive::epoch_key_commitment(Epoch(0), &[0x44; 32]);
let group = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(1));
let blob = rekey::build_blob_local(owner.secret_key(), &owner.public_key().to_bytes(), &owner.public_key(), RekeyScope::Channel(priv_id), Epoch(1), &new_key).unwrap();
let events = rekey::build_rekey_chunks_local(&owner, &group, RekeyScope::Channel(priv_id), Epoch(1), Epoch(0), &prev_commit, &[blob], 2_000, None, false).unwrap();
for e in &events {
relay.publish(e, &community.relays).await.unwrap();
}
let session = crate::db::current_session();
let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("adopted");
let ch = updated.channel(&priv_id).unwrap();
assert_eq!(ch.epoch, Epoch(1), "the private channel advanced an epoch");
assert_eq!(ch.key, Some(new_key), "adopted the fresh channel key");
assert_eq!(updated.root_epoch, Epoch(0), "the base is untouched by a channel rotation");
}
#[tokio::test]
async fn a_whole_channel_fan_rotates_in_one_hop_without_crossing_keys() {
// The fan is fetched concurrently and keyed by (channel, addressing root). A
// mis-keyed prefetch cannot hand channel A's key to channel B — the blob's
// scope is authenticated, so a wrong batch is refused rather than adopted — but
// it CAN starve a channel of the chunks that are sitting on the plane for it,
// which reads as "that channel never rotates" and strands its members.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let mut community = create_community(&relay, "FanRot", vec!["wss://r".into()], None).await.unwrap();
// Distinct held key AND distinct fresh key per channel — a swap between any
// two is then visible as an equality failure rather than a silent pass.
let fan: Vec<(ChannelId, [u8; 32], [u8; 32])> = (0u8..12)
.map(|i| (ChannelId([0x30 + i; 32]), [0x40 + i; 32], [0x80 + i; 32]))
.collect();
for (id, held, _) in &fan {
add_private_channel(&mut community, *id, *held, Epoch(0));
}
for (id, held, fresh) in &fan {
let prev_commit = super::super::derive::epoch_key_commitment(Epoch(0), held);
let group = channel_rekey_group_key(&community.community_root, id, Epoch(1));
let blob = rekey::build_blob_local(owner.secret_key(), &owner.public_key().to_bytes(), &owner.public_key(), RekeyScope::Channel(*id), Epoch(1), fresh).unwrap();
let events = rekey::build_rekey_chunks_local(&owner, &group, RekeyScope::Channel(*id), Epoch(1), Epoch(0), &prev_commit, &[blob], 2_000, None, false).unwrap();
for e in &events {
relay.publish(e, &community.relays).await.unwrap();
}
}
let session = crate::db::current_session();
let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("adopted");
for (id, _, fresh) in &fan {
let ch = updated.channel(id).expect("channel survived the fan");
assert_eq!(ch.epoch, Epoch(1), "every channel in the fan advanced");
assert_eq!(ch.key, Some(*fresh), "each channel adopted ITS OWN key, not a neighbour's");
}
}
#[tokio::test]
async fn follow_rekeys_ignores_a_non_owner_rotation() {
// A member holds the community_root, so they can derive the rekey group key
// and mint a rotation — but they aren't the owner, so it's not adopted.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Guarded", vec!["wss://r".into()], None).await.unwrap();
let rogue = Keys::generate();
publish_base_rotation(&relay, &community, &rogue, &[rogue.public_key()], &[0xEE; 32], &community.community_root).await;
let session = crate::db::current_session();
let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
assert!(follow.updated.is_none() && !follow.self_removed, "a non-owner rotation is not adopted");
}
#[tokio::test]
async fn follow_rekeys_ignores_a_rotation_off_the_wrong_prev() {
// A rotation whose prevcommit doesn't match the key I hold is a fork, not an
// extension — never adopted (would splice me onto an unrelated chain).
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Forked", vec!["wss://r".into()], None).await.unwrap();
// prev_key ≠ the real community_root → the continuity check reads Fork.
publish_base_rotation(&relay, &community, &owner, &[owner.public_key()], &[0xB2; 32], &[0x00; 32]).await;
let session = crate::db::current_session();
let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
assert!(follow.updated.is_none(), "a fork off the wrong prev is not adopted");
}
#[tokio::test]
async fn follow_rekeys_holds_on_an_incomplete_rotation() {
// A 2-chunk rotation with only chunk 1 present can never conclude — not an
// adoption, and crucially NOT a removal (a missing chunk might carry my blob).
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Partial", vec!["wss://r".into()], None).await.unwrap();
let new_epoch = Epoch(1);
let prev_commit = super::super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
let group = base_rekey_group_key(&community.community_root, community.id(), new_epoch);
// Chunk 1 of a declared 2, carrying someone else's blob (not mine).
let other = Keys::generate();
let blob = rekey::build_blob_local(owner.secret_key(), &owner.public_key().to_bytes(), &other.public_key(), RekeyScope::Root, new_epoch, &[0xB3; 32]).unwrap();
let rumor = rekey::build_rekey_rumor(owner.public_key(), RekeyScope::Root, new_epoch, Epoch(0), &prev_commit, &[blob], 1, 2, 2_000, None, false).unwrap();
let (wrap, _) = rekey::seal_rekey_chunk(&rumor, &group, &owner, Timestamp::from_secs(2_000)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
let session = crate::db::current_session();
let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
assert!(follow.updated.is_none() && !follow.self_removed, "an incomplete rotation neither adopts nor removes");
}
#[tokio::test]
async fn follow_rekeys_removes_a_member_dropped_by_a_base_rotation() {
// Realistic two-actor removal: the owner Refounds the base and delivers the
// new root to a THIRD party, not the member — a complete rotation with no
// blob for the member is a removal.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Evict", bed.relays.clone(), None).await.unwrap();
send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
bed.swap_to(&member);
let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
// Owner rotates, delivering only to a stranger (the member is dropped).
bed.swap_to(&owner);
let stranger = Keys::generate();
publish_base_rotation(&bed.relay, &community, &owner.keys, &[stranger.public_key()], &[0xC4; 32], &community.community_root).await;
// The member's follow concludes removal (a complete rotation without their blob).
bed.swap_to(&member);
let session = crate::db::current_session();
let follow = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
assert!(follow.self_removed, "a complete base rotation dropping the member removes them");
assert!(follow.updated.is_none(), "a removed member adopts nothing");
}
#[tokio::test]
async fn a_ban_holders_channel_rotation_stands_and_a_bitless_ones_doesnt() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Refounder", vec!["wss://r".into()], None).await.unwrap();
let moderator = Keys::generate();
let rid = "b1".repeat(32);
publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::BAN), 1).await;
publish_grant(&relay, &community, &owner, &moderator.public_key(), vec![rid], 1).await;
let mut community = follow_control(&relay, &community).await.unwrap().updated.unwrap_or(community);
let priv_id = ChannelId([0x34; 32]);
let key1 = [0x45; 32];
add_private_channel(&mut community, priv_id, key1, Epoch(1));
let cite = cite_on_relay(&relay, &community, &moderator).await;
let key2 = [0x56; 32];
let prev_commit = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
let group = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
let blob = rekey::build_blob_local(moderator.secret_key(), &moderator.public_key().to_bytes(), &owner.public_key(), RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
for e in rekey::build_rekey_chunks_local(&moderator, &group, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &prev_commit, &[blob], 2_000, cite.as_ref(), false).unwrap() {
relay.publish(&e, &community.relays).await.unwrap();
}
let session = crate::db::current_session();
let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("a BAN holder's rotation stands");
assert_eq!(updated.channel(&priv_id).unwrap().key, Some(key2));
let stranger = Keys::generate();
let prev3 = super::super::derive::epoch_key_commitment(Epoch(2), &key2);
let group3 = channel_rekey_group_key(&updated.community_root, &priv_id, Epoch(3));
let blob3 = rekey::build_blob_local(stranger.secret_key(), &stranger.public_key().to_bytes(), &owner.public_key(), RekeyScope::Channel(priv_id), Epoch(3), &[0x57; 32]).unwrap();
for e in rekey::build_rekey_chunks_local(&stranger, &group3, RekeyScope::Channel(priv_id), Epoch(3), Epoch(2), &prev3, &[blob3], 3_000, None, false).unwrap() {
relay.publish(&e, &updated.relays).await.unwrap();
}
assert!(follow_rekeys(&relay, &updated, &session).await.unwrap().updated.is_none(), "nobody without the bits rotates a Channel");
}
#[tokio::test]
async fn follow_rekeys_finds_a_channel_rekey_under_an_archived_prior_root() {
// PROTO-B2 regression: a Refounding's channel rekeys ride the PRIOR root
// (CORD-06 §3). A follower who adopted the BASE first (the live window:
// the base crate landed and was walked before the channel crates) must
// still find them — the lookup fans across the archived roots, not just
// the current one.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let mut community = create_community(&relay, "Strand", vec!["wss://r".into()], None).await.unwrap();
let root0 = community.community_root;
let priv_id = ChannelId([0x33; 32]);
let key1 = [0x44; 32];
add_private_channel(&mut community, priv_id, key1, Epoch(1));
// The refounder's channel rekey (1 → 2), sealed + addressed under the PRIOR
// root (root0), delivering the fresh key to me.
let key2 = [0x55; 32];
let prev_commit = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
let group = channel_rekey_group_key(&root0, &priv_id, Epoch(2));
let blob = rekey::build_blob_local(owner.secret_key(), &owner.public_key().to_bytes(), &owner.public_key(), RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
for e in rekey::build_rekey_chunks_local(&owner, &group, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &prev_commit, &[blob], 2_000, None, false).unwrap() {
relay.publish(&e, &community.relays).await.unwrap();
}
// Simulate the base having ALREADY advanced (the stranding order): the head
// moved to a fresh root while root0 sits in the epoch-key archive (where
// genesis put it).
community.community_root = [0xB7; 32];
community.root_epoch = Epoch(1);
crate::db::community::save_community_v2(&community).unwrap();
let session = crate::db::current_session();
let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("the prior-root crate is found");
let ch = updated.channel(&priv_id).unwrap();
assert_eq!(ch.epoch, Epoch(2), "the channel advanced despite the moved base");
assert_eq!(ch.key, Some(key2), "adopted the key delivered under the prior root");
}
#[tokio::test]
async fn follow_rekeys_keyless_cursor_walks_past_an_excluding_rotation_then_adopts() {
// A keyless private channel (announced by vsk-2, key not yet held) has no
// chain, so its epoch is a scan cursor: a complete rotation that excludes
// us advances the cursor (never a removal — we were never in); a later
// rotation that includes us is the entry point.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let mut community = create_community(&relay, "Cursor", vec!["wss://r".into()], None).await.unwrap();
let priv_id = ChannelId([0x66; 32]);
community.channels.push(ChannelV2 { id: priv_id, name: "vault".into(), private: true, key: None, epoch: Epoch(0), voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed: None });
crate::db::community::save_community_v2(&community).unwrap();
let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert!(community.channel(&priv_id).unwrap().key.is_none(), "keyless survives the round-trip");
// Epoch 1: the creation delivery went to a stranger only (pre-dates us).
let stranger = Keys::generate();
let key1 = [0x71; 32];
let pc1 = super::super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
let g1 = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(1));
let b1 = rekey::build_blob_local(owner.secret_key(), &owner.public_key().to_bytes(), &stranger.public_key(), RekeyScope::Channel(priv_id), Epoch(1), &key1).unwrap();
for e in rekey::build_rekey_chunks_local(&owner, &g1, RekeyScope::Channel(priv_id), Epoch(1), Epoch(0), &pc1, &[b1], 2_000, None, false).unwrap() {
relay.publish(&e, &community.relays).await.unwrap();
}
// Epoch 2: a later rotation includes ME (e.g. a removal-forced re-mint whose
// recipient set is the CURRENT members).
let key2 = [0x72; 32];
let pc2 = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
let g2 = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
let b2 = rekey::build_blob_local(owner.secret_key(), &owner.public_key().to_bytes(), &owner.public_key(), RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
for e in rekey::build_rekey_chunks_local(&owner, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc2, &[b2], 2_100, None, false).unwrap() {
relay.publish(&e, &community.relays).await.unwrap();
}
// ONE follow: the cursor walks 0→1 (excluded, still keyless) and 1→2 (my
// blob — adopt), because each real step re-loops.
let session = crate::db::current_session();
let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("the walk lands on the included epoch");
let ch = updated.channel(&priv_id).unwrap();
assert_eq!(ch.epoch, Epoch(2), "cursor walked through the excluding epoch to the included one");
assert_eq!(ch.key, Some(key2), "adopted the delivery that includes us");
}
#[tokio::test]
async fn follow_rekeys_honors_an_admin_channel_rotation_but_never_a_strangers() {
// CORD-06 §Authority: a CHANNEL rekey is honored from the owner or a
// MANAGE_CHANNELS holder under the persisted roster — so an admin-run
// rotation keys members up; a mere keyholder's forgery never does.
use crate::community::roles::{CommunityRoles, MemberGrant, Role};
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let mut community = create_community(&relay, "AdminRot", vec!["wss://r".into()], None).await.unwrap();
let priv_id = ChannelId([0x88; 32]);
let key1 = [0x91; 32];
add_private_channel(&mut community, priv_id, key1, Epoch(1));
// Persist a roster granting `admin` the Admin role (MANAGE_CHANNELS ⊂ ADMIN_ALL).
let admin = Keys::generate();
let role = Role::admin("aa".repeat(32));
let roster = CommunityRoles {
roles: vec![role.clone()],
grants: vec![MemberGrant { member: admin.public_key().to_hex(), role_ids: vec![role.role_id.clone()] }],
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
};
seed_roster_with_heads(&community, &roster, 1_000);
// The ADMIN rotates the channel 1 → 2, delivering to me: adopted.
let key2 = [0x92; 32];
let pc = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
let g2 = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
let me_pk = crate::state::MY_SECRET_KEY.to_keys().unwrap().public_key();
let blob = rekey::build_blob_local(admin.secret_key(), &admin.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
for e in rekey::build_rekey_chunks_local(&admin, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[blob], 2_000, my_authority_citation(&community, &admin.public_key()).as_ref(), false).unwrap() {
relay.publish(&e, &community.relays).await.unwrap();
}
let session = crate::db::current_session();
let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("an admin rotation is honored");
assert_eq!(updated.channel(&priv_id).unwrap().key, Some(key2), "adopted the admin's key");
// A STRANGER (keyholder, no roster standing) rotates 2 → 3: refused.
let rogue = Keys::generate();
let key3 = [0x93; 32];
let pc3 = super::super::derive::epoch_key_commitment(Epoch(2), &key2);
let g3 = channel_rekey_group_key(&updated.community_root, &priv_id, Epoch(3));
let rb = rekey::build_blob_local(rogue.secret_key(), &rogue.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(3), &key3).unwrap();
for e in rekey::build_rekey_chunks_local(&rogue, &g3, RekeyScope::Channel(priv_id), Epoch(3), Epoch(2), &pc3, &[rb], 2_100, None, false).unwrap() {
relay.publish(&e, &updated.relays).await.unwrap();
}
let follow = follow_rekeys(&relay, &updated, &session).await.unwrap();
assert!(follow.updated.is_none(), "a stranger's channel rotation is never adopted");
}
#[tokio::test]
async fn a_non_outranking_admins_rotation_never_concludes_my_removal() {
// CORD-06 §Authority: the Rotator must strictly OUTRANK every removed
// target. An equal-rank bit-holder's complete rotation that skips my blob
// must read Stay (my record survives); the OWNER's reads Removed. Needs a
// two-account bed: the follower must be a NON-owner admin.
use crate::community::roles::{CommunityRoles, MemberGrant, Role};
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Outrank", bed.relays.clone(), None).await.unwrap();
// The MEMBER's device: holds the community + the private channel, with a
// persisted roster granting the member AND a peer the same Admin role.
bed.swap_to(&member);
let mut held = community.clone();
let priv_id = ChannelId([0xAB; 32]);
let key1 = [0xA1; 32];
add_private_channel(&mut held, priv_id, key1, Epoch(1));
let peer = Keys::generate();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let role = Role::admin("bb".repeat(32));
let roster = CommunityRoles {
roles: vec![role.clone()],
grants: vec![
MemberGrant { member: peer.public_key().to_hex(), role_ids: vec![role.role_id.clone()] },
MemberGrant { member: member.keys.public_key().to_hex(), role_ids: vec![role.role_id.clone()] },
],
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
};
crate::db::community::set_community_roles(&cid_hex, &roster, 1_000).unwrap();
// The equal-rank PEER rotates 1 → 2 delivering only to themselves.
let key2 = [0xA2; 32];
let pc = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
let g2 = channel_rekey_group_key(&held.community_root, &priv_id, Epoch(2));
let pb = rekey::build_blob_local(peer.secret_key(), &peer.public_key().to_bytes(), &peer.public_key(), RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
for e in rekey::build_rekey_chunks_local(&peer, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[pb], 2_000, my_authority_citation(&held, &peer.public_key()).as_ref(), false).unwrap() {
bed.relay.publish(&e, &held.relays).await.unwrap();
}
let session = crate::db::current_session();
let follow = follow_rekeys(&bed.relay, &held, &session).await.unwrap();
assert!(follow.updated.is_none(), "an equal-rank rotation excluding me is Stay, never my removal");
let reloaded = crate::db::community::load_community_v2(held.id()).unwrap().unwrap();
assert!(reloaded.channel(&priv_id).is_some(), "my channel record survives the peer's rotation");
// The OWNER's rotation excluding me IS a removal (owner outranks everyone).
let key3 = [0xA3; 32];
let stranger = Keys::generate();
let ob = rekey::build_blob_local(owner.keys.secret_key(), &owner.keys.public_key().to_bytes(), &stranger.public_key(), RekeyScope::Channel(priv_id), Epoch(2), &key3).unwrap();
for e in rekey::build_rekey_chunks_local(&owner.keys, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[ob], 2_100, None, false).unwrap() {
bed.relay.publish(&e, &held.relays).await.unwrap();
}
let follow = follow_rekeys(&bed.relay, &held, &session).await.unwrap();
let updated = follow.updated.expect("the owner's removal folds");
let cut = updated.channel(&priv_id).expect("the channel stays known, so a later rotation can name me again");
assert!(cut.key.is_none() && cut.epoch == Epoch(2), "the owner's exclusion cuts my key at its epoch");
}
#[tokio::test]
async fn a_public_channel_made_private_keys_who_it_lets_in_and_keeps_its_past() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, member) = TestBed::new();
let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Convert", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let general = community.channels[0].id;
let m = member.keys.public_key();
send_message(&bed.relay, &held(&community), &general, "said in public").await.unwrap();
send_direct_invite(&bed.relay, &held(&community), &m, None, None).await.unwrap();
bed.swap_to(&member);
accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &m).await).await.unwrap();
follow_control(&bed.relay, &held(&community)).await.unwrap();
let before = held(&community);
// The flag alone is refused: the conversion is its own action.
bed.swap_to(&owner);
let mut meta = held(&community).channel(&general).unwrap().metadata();
meta.private = true;
assert!(edit_channel_metadata(&bed.relay, &held(&community), &general, &meta).await.is_err());
set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Member(m.to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
privatize_channel(&bed.relay, &held(&community), &general).await.unwrap();
let mine = held(&community).channel(&general).cloned().unwrap();
assert!(mine.private && mine.key.is_some() && mine.epoch == Epoch(1) && mine.public_until().is_some());
let editions = fetch_control(&bed.relay, &held(&community)).await;
let head = editions.iter().filter(|e| e.vsk == vsk::CHANNEL_METADATA && e.entity_id == general.0).max_by_key(|e| e.version).unwrap();
assert!(control::parse_sealed_channel_meta(&head.content).is_some() && !head.content.contains("general"), "its details seal at once");
send_message(&bed.relay, &held(&community), &general, "said in private").await.unwrap();
// A member it lets in takes the key from the rotation and reads both eras.
bed.swap_to(&member);
follow_control(&bed.relay, &held(&community)).await.unwrap();
let dark = held(&community).channel(&general).cloned().unwrap();
assert!(dark.private && dark.key.is_none(), "a reader holding it public takes it private, keyless");
follow_rekeys(&bed.relay, &held(&community), &crate::db::current_session()).await.unwrap();
let mut keyed = held(&community);
unseal_held(&mut keyed);
let ch = keyed.channel(&general).cloned().unwrap();
assert!(ch.key.is_some() && ch.name == "general", "{ch:?}");
crate::db::community::save_community_v2(&keyed).unwrap();
let texts = texts_in(&bed.relay, &keyed, &general).await;
assert!(texts.contains(&"said in public".to_string()) && texts.contains(&"said in private".to_string()), "{texts:?}");
// A post at the old public plane after the switch stands nowhere.
send_message(&bed.relay, &before, &general, "too late").await.unwrap();
assert!(!texts_in(&bed.relay, &held(&community), &general).await.contains(&"too late".to_string()));
}
#[tokio::test]
async fn junk_at_a_channels_rekey_address_takes_no_epoch_from_a_conversion() {
let (bed, owner, member) = TestBed::new();
let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Junk", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let general = community.channels[0].id;
// Any root holder can seal a 3303 at epoch 1's address; nobody honors it.
let squatter = Keys::generate();
let group = channel_rekey_group_key(&community.community_root, &general, Epoch(1));
let blob = rekey::build_blob_local(squatter.secret_key(), &squatter.public_key().to_bytes(), &squatter.public_key(), RekeyScope::Channel(general), Epoch(1), &[0x58; 32]).unwrap();
let prev = super::super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
for e in rekey::build_rekey_chunks_local(&squatter, &group, RekeyScope::Channel(general), Epoch(1), Epoch(0), &prev, &[blob], 2_000, None, false).unwrap() {
bed.relay.publish(&e, &community.relays).await.unwrap();
}
let m = member.keys.public_key();
send_direct_invite(&bed.relay, &held(&community), &m, None, None).await.unwrap();
set_overwrite(&bed.relay, &held(&community), general.0, crate::community::roles::OverwriteTarget::Member(m.to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
privatize_channel(&bed.relay, &held(&community), &general).await.unwrap();
assert_eq!(held(&community).channel(&general).unwrap().epoch, Epoch(1), "junk takes no epoch");
bed.swap_to(&member);
accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &m).await).await.unwrap();
follow_control(&bed.relay, &held(&community)).await.unwrap();
follow_rekeys(&bed.relay, &held(&community), &crate::db::current_session()).await.unwrap();
assert!(held(&community).channel(&general).unwrap().key.is_some(), "the member takes the key the conversion minted");
}
#[tokio::test]
async fn privatising_again_climbs_past_an_era_this_converter_never_held() {
let (bed, owner, member) = TestBed::new();
let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Again", bed.relays.clone(), None).await.unwrap();
activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap();
let m = member.keys.public_key();
let managers = create_role_v2(&bed.relay, &held(&community), "Managers", 0, Permissions::MANAGE_CHANNELS | crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
set_member_roles(&bed.relay, &held(&community), &m, vec![managers]).await.unwrap();
let ch = create_private_channel(&bed.relay, &held(&community), "ops").await.unwrap();
let mut public = held(&community).channel(&ch).unwrap().metadata();
public.private = false;
edit_channel_metadata(&bed.relay, &held(&community), &ch, &public).await.unwrap();
send_direct_invite(&bed.relay, &held(&community), &m, None, None).await.unwrap();
bed.swap_to(&member);
accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &m).await).await.unwrap();
follow_control(&bed.relay, &held(&community)).await.unwrap();
assert!(!held(&community).channel(&ch).unwrap().private);
privatize_channel(&bed.relay, &held(&community), &ch).await.unwrap();
let mine = held(&community).channel(&ch).cloned().unwrap();
assert_eq!(mine.epoch, Epoch(2), "the old era's epoch 1 is taken, though this device never held it");
bed.swap_to(&owner);
follow_control(&bed.relay, &held(&community)).await.unwrap();
follow_rekeys(&bed.relay, &held(&community), &crate::db::current_session()).await.unwrap();
let theirs = held(&community).channel(&ch).cloned().unwrap();
assert_eq!((theirs.epoch, theirs.key), (Epoch(2), mine.key), "the owner walks to the same key");
}
/// Publish a 13302 (signed by `me`) carrying a leave tombstone for `cid_hex` at
/// `removed_at` — simulating a sibling device having left that community.
async fn publish_remote_tombstone(relay: &MemoryRelay, me: &Keys, relays: &[String], cid_hex: &str, removed_at: u64) {
let doc = super::super::list::CommunityList {
entries: vec![],
tombstones: vec![super::super::list::Tombstone { community_id: cid_hex.to_string(), removed_at, extra: Default::default() }],
extra: Default::default(),
};
// A sibling device writes fragments, like any §8 client.
for (i, frag) in super::super::list_frag::fragment(&doc).iter().enumerate() {
let event = super::super::list_frag::build_fragment_event_keys(me, frag, i, now_ms() / 1000).unwrap();
relay.publish(&event, relays).await.unwrap();
}
}
#[tokio::test]
async fn joining_one_community_does_not_resurrect_a_sibling_left_community() {
// W1 (send side): a sibling device left X (a remote tombstone). Joining a
// DIFFERENT community must not re-add X to the 13302 with added_at=now,
// which would silently undo the leave everywhere.
let (_tmp, _guard, me) = init_test_db();
let relay = MemoryRelay::new();
let x = create_community(&relay, "X", vec!["wss://r".into()], None).await.unwrap();
let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
// A sibling leaves X: a remote tombstone strictly newer than X's add.
publish_remote_tombstone(&relay, &me, &x.relays, &x_hex, now_ms() + 10_000).await;
// Now join a different community Y → republish(just_joined = Y).
let y = create_community(&relay, "Y", vec!["wss://r".into()], None).await.unwrap();
republish_community_list(&relay, Some(y.id())).await.unwrap();
// X must still read as LEFT in the published list; Y must be live.
let list = fetch_fragments(&relay, &x.relays).await.unwrap().unwrap().list;
assert!(!list.is_live(&x_hex), "joining Y did not resurrect the sibling-left X");
assert!(list.is_live(&crate::simd::hex::bytes_to_hex_32(&y.id().0)), "Y is live");
}
#[tokio::test]
async fn sync_tears_down_a_community_a_sibling_left() {
// W1 (receive side): a community still held locally that the synced 13302
// shows tombstoned-and-not-live is torn down, so a leave propagates.
let (_tmp, _guard, me) = init_test_db();
let relay = MemoryRelay::new();
let x = create_community(&relay, "Leaveme", vec!["wss://r".into()], None).await.unwrap();
let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_some(), "held before sync");
publish_remote_tombstone(&relay, &me, &x.relays, &x_hex, now_ms() + 10_000).await;
sync_community_list(&relay, &x.relays).await.unwrap();
assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_none(), "the sibling's leave tore X down locally");
}
/// Publish a List copy (signed by `me`) written at `at_secs`: a sibling device's, or an older
/// one a relay still serves.
async fn publish_remote_list(
relay: &MemoryRelay,
me: &Keys,
relays: &[String],
entries: Vec<super::super::list::CommunityListEntry>,
tombstones: Vec<super::super::list::Tombstone>,
at_secs: u64,
) {
let doc = super::super::list::CommunityList { entries, tombstones, extra: Default::default() };
// Everywhere the List is read from, so this copy is the one every read finds.
let relays = list_read_relays(relays).await;
for (i, frag) in super::super::list_frag::fragment(&doc).iter().enumerate() {
let event = super::super::list_frag::build_fragment_event_keys(me, frag, i, at_secs).unwrap();
relay.publish(&event, &relays).await.unwrap();
}
}
fn listed(community: &CommunityV2, added_at: u64) -> super::super::list::CommunityListEntry {
let jm = join_material(community);
super::super::list::CommunityListEntry {
community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0),
seed: jm.clone(),
current: jm,
added_at,
extra: Default::default(),
}
}
/// A member holding `X`, and a second device of that member's account that holds nothing yet.
async fn member_with_a_second_device() -> (TestBed, Actor, CommunityV2) {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let x = create_community(&bed.relay, "Synced", bed.relays.clone(), None).await.unwrap();
let link = mint_public_link(&bed.relay, &x, "https://vectorapp.io", None, None).await.unwrap();
bed.swap_to(&member);
let joined = accept_public_link(&bed.relay, &link.url).await.unwrap();
let device = Actor { keys: member.keys.clone(), account: account_name((now_ms() % 1_000_000_000) as u32) };
bed.swap_to(&device);
(bed, device, joined)
}
#[tokio::test]
async fn an_older_copy_of_the_list_never_brings_back_a_community_this_device_left() {
let (bed, device, x) = member_with_a_second_device().await;
let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
let joined_at = now_ms() - 60_000;
// Left on this device; then a relay serves a copy from before the leave.
note_local_removal(&x_hex, joined_at + 30_000);
publish_remote_list(&bed.relay, &device.keys, &bed.relays, vec![listed(&x, joined_at)], vec![], now_ms() / 1000 + 5).await;
let out = sync_community_list(&bed.relay, &bed.relays).await.unwrap();
assert!(out.joined.is_empty() && out.removed.is_empty(), "the stale copy is never adopted, not even briefly");
assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_none(), "the stale copy did not rejoin it");
}
#[tokio::test]
async fn a_leave_made_while_an_adoption_runs_answers_it() {
let (bed, device, x) = member_with_a_second_device().await;
let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
publish_remote_list(&bed.relay, &device.keys, &bed.relays, vec![listed(&x, now_ms() - 60_000)], vec![], now_ms() / 1000 + 5).await;
// The leave lands while the adoption walks the community's planes.
struct LeaveMidAdoption<'a> {
relay: &'a MemoryRelay,
community_id: String,
left: std::sync::atomic::AtomicBool,
}
#[async_trait::async_trait]
impl Transport for LeaveMidAdoption<'_> {
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
self.walked(query);
self.relay.fetch_plane(plane, query, relays).await
}
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.relay.publish(e, r).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.relay.publish_durable(e, r).await
}
async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
self.walked(q);
self.relay.fetch(q, r).await
}
}
impl LeaveMidAdoption<'_> {
/// Past the List read, every fetch is the adoption's own walk.
fn walked(&self, query: &Query) {
if !query.kinds.contains(&crate::community::v2::kind::COMMUNITY_LIST_FRAG) && !self.left.swap(true, std::sync::atomic::Ordering::SeqCst) {
note_local_removal(&self.community_id, now_ms());
}
}
}
let transport = LeaveMidAdoption { relay: &bed.relay, community_id: x_hex.clone(), left: false.into() };
let out = sync_community_list(&transport, &bed.relays).await.unwrap();
assert!(out.joined.is_empty() && out.removed.iter().any(|(id, _)| *id == x_hex), "the adoption is undone, and said so");
assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_none(), "nothing of it is left held");
}
#[tokio::test]
async fn an_adopted_community_dates_from_its_membership_so_a_later_leave_still_removes_it() {
let (bed, device, x) = member_with_a_second_device().await;
let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
let joined_at = now_ms() - 3_600_000;
publish_remote_list(&bed.relay, &device.keys, &bed.relays, vec![listed(&x, joined_at)], vec![], now_ms() / 1000 + 5).await;
sync_community_list(&bed.relay, &bed.relays).await.unwrap();
let held = crate::db::community::load_community_v2(x.id()).unwrap().expect("adopted");
assert!(held.created_at_ms <= joined_at, "held since the membership, not since the adoption");
// A sibling's leave made after that membership, but before this adoption ran.
let leave = super::super::list::Tombstone { community_id: x_hex.clone(), removed_at: joined_at + 5_000, extra: Default::default() };
publish_remote_list(&bed.relay, &device.keys, &bed.relays, vec![listed(&x, joined_at)], vec![leave], now_ms() / 1000 + 10).await;
sync_community_list(&bed.relay, &bed.relays).await.unwrap();
assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_none(), "the leave outranks the adopted copy");
republish_community_list(&bed.relay, None).await.unwrap();
let list = fetch_fragments(&bed.relay, &bed.relays).await.unwrap().unwrap().list;
assert!(!list.is_live(&x_hex), "and nothing writes it back");
}
#[tokio::test]
async fn a_rejoined_community_survives_a_stale_tombstone_on_sync() {
// The re-join case must NOT be torn down: a fresh join re-adds live (beating
// the tombstone), so a later sync keeps it.
let (_tmp, _guard, me) = init_test_db();
let relay = MemoryRelay::new();
let x = create_community(&relay, "Rejoin", vec!["wss://r".into()], None).await.unwrap();
let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
// A stale tombstone from a prior leave (OLDER than the current hold's re-add).
publish_remote_tombstone(&relay, &me, &x.relays, &x_hex, 1).await;
// Re-record the membership (a re-join) → live entry at now >> 1.
republish_community_list(&relay, Some(x.id())).await.unwrap();
sync_community_list(&relay, &x.relays).await.unwrap();
assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_some(), "a re-joined community is not torn down by a stale tombstone");
}
#[tokio::test]
async fn a_join_outranks_a_removal_stamped_after_it() {
// A removal noticed late (or on a skewed clock) can carry a time after a fresh join;
// the join must still stand, here and at the next sync.
let (_tmp, _guard, me) = init_test_db();
let relay = MemoryRelay::new();
let x = create_community(&relay, "Late", vec!["wss://r".into()], None).await.unwrap();
let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
publish_remote_tombstone(&relay, &me, &x.relays, &x_hex, now_ms() + 60_000).await;
assert!(republish_community_list(&relay, Some(x.id())).await.unwrap(), "the join landed");
sync_community_list(&relay, &x.relays).await.unwrap();
assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_some(), "a join is not undone by a removal it already knew of");
}
#[tokio::test]
async fn a_hold_is_never_ruled_older_than_a_removal_in_its_own_second() {
// Rows keep whole seconds: a removal later in the join's second must not read as after it.
let (_tmp, _guard, me) = init_test_db();
let relay = MemoryRelay::new();
let x = create_community(&relay, "Same second", vec!["wss://r".into()], None).await.unwrap();
let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
let held = crate::db::community::load_community_v2(x.id()).unwrap().unwrap();
assert_eq!(held.created_at_ms % 1000, 0, "the row keeps whole seconds");
// Relays that only ever saw a sibling's removal, half a second into the join's second.
let elsewhere = MemoryRelay::new();
publish_remote_tombstone(&elsewhere, &me, &x.relays, &x_hex, held.created_at_ms + 500).await;
sync_community_list(&elsewhere, &x.relays).await.unwrap();
assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_some(), "the hold is not torn down by a removal inside its own second");
}
#[tokio::test]
async fn a_failed_remote_fetch_never_clobbers_the_published_list() {
// W2: a transient fetch failure during republish must not drive the
// replaceable-event write (which would drop other entries / regress seeds).
let (_tmp, _guard, _me) = init_test_db();
let good = MemoryRelay::new();
let community = create_community(&good, "Seeded", vec!["wss://r".into()], None).await.unwrap();
assert!(fetch_fragments(&good, &community.relays).await.unwrap().is_some());
// A transport whose fetch always errors: republish must bail, publishing nothing.
struct FetchErrors;
#[async_trait::async_trait]
impl Transport for FetchErrors {
async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> { Ok(crate::community::transport::PlaneFetch::whole(self.fetch(query, relays).await?)) }
async fn publish(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
panic!("republish must NOT publish when the remote fetch failed");
}
async fn publish_durable(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
Ok(())
}
async fn fetch(&self, _q: &Query, _r: &[String]) -> Result<Vec<Event>, String> {
Err("relay unreachable".to_string())
}
}
// Returns Ok (best-effort) but must not have published (the panic guards it).
republish_community_list(&FetchErrors, Some(community.id())).await.unwrap();
}
#[tokio::test]
async fn a_granted_member_survives_a_refounding_even_with_no_guestbook_join() {
// B1 regression: refound_community's recipient set = memberlist. A member
// the owner GRANTED a role to but who never left a (surviving) Guestbook
// Join — a lurking admin, or one whose Join aged out of the window — must
// still be a rekey recipient, or the Refounding SEVERS them. The folded
// roster's granted members are the consensus-complete backstop.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Backstop", vec!["wss://r".into()], None).await.unwrap();
// A lurker gets an admin grant but publishes NO Guestbook Join and no chat.
let lurker = Keys::generate();
let rid = "b1".repeat(32);
publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
publish_grant(&relay, &community, &owner, &lurker.public_key(), vec![rid.clone()], 1).await;
// memberlist includes the lurker purely via the roster backstop.
let members = memberlist(&relay, &community).await.unwrap();
assert!(members.contains(&lurker.public_key()), "a granted member with no Join is still a member");
// A banned grantee whose grant wasn't stripped is NOT re-admitted.
let banned_grantee = Keys::generate();
publish_grant(&relay, &community, &owner, &banned_grantee.public_key(), vec![rid], 1).await;
set_banlist(&relay, &community, &[banned_grantee.public_key().to_hex()]).await.unwrap();
let members = memberlist(&relay, &community).await.unwrap();
assert!(members.contains(&lurker.public_key()), "the honest grantee still counts");
assert!(!members.contains(&banned_grantee.public_key()), "a banned grantee is not re-admitted by the union");
// And the Refounding actually delivers the new root to the lurker.
let refounded = refound_community(&relay, &community, &[]).await.unwrap();
assert_eq!(refounded.root_epoch, Epoch(1));
let base_group = base_rekey_group_key(&community.community_root, community.id(), Epoch(1));
let chunks = fetch_rekey_chunks(&relay, &community, &base_group).await.unwrap();
let rotations = rekey::collect_rotations(&chunks);
let lurker_x = lurker.public_key().to_bytes();
let delivered = rotations.iter().any(|r| {
rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), &lurker_x, r.scope, r.new_epoch).is_some()
});
assert!(delivered, "the Refounding delivered the new root to the granted lurker");
}
#[tokio::test]
async fn the_memberlist_pages_past_a_guestbook_flood() {
// The roleless-member half of B1: >500 Guestbook events must not evict an
// honest member's Join from the counted set (an insider can flood throwaway
// Joins to force exactly this). The pager sees them all.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "GBFlood", vec!["wss://r".into()], None).await.unwrap();
let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
// An honest member's Join (oldest), then 600 throwaway Joins on top.
let honest = Keys::generate();
let join = guestbook::build_join_rumor(honest.public_key(), None, 1_000);
let (w, _) = guestbook::seal_guestbook_rumor(&join, &gb, &honest, Timestamp::from_secs(1)).unwrap();
relay.publish(&w, &community.relays).await.unwrap();
for i in 0..600u64 {
let throwaway = Keys::generate();
let j = guestbook::build_join_rumor(throwaway.public_key(), None, 2_000 + i);
let (w, _) = guestbook::seal_guestbook_rumor(&j, &gb, &throwaway, Timestamp::from_secs(2 + i)).unwrap();
relay.publish(&w, &community.relays).await.unwrap();
}
let members = memberlist(&relay, &community).await.unwrap();
assert!(members.contains(&honest.public_key()), "the honest member's aged-out Join is still counted past the flood");
}
#[tokio::test]
async fn a_rekey_plane_flood_cannot_bury_a_genuine_rotation() {
// An insider floods the next-epoch rekey address (community_root-derived,
// so any member can seal there) with >200 junk 3303s to push the owner's
// genuine rotation out of a single fetch window. The paginated fetch must
// still recover it and adopt.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Flooded", vec!["wss://r".into()], None).await.unwrap();
let new_root = [0xD9; 32];
let new_epoch = Epoch(1);
let group = base_rekey_group_key(&community.community_root, community.id(), new_epoch);
// The GENUINE owner rotation lands first (oldest).
publish_base_rotation(&relay, &community, &owner, &[owner.public_key()], &new_root, &community.community_root).await;
// Then a member floods 260 well-formed-but-unauthorized junk chunks ON TOP
// (newer), burying the genuine one past the 200 newest.
let rogue = Keys::generate();
let prev_commit = super::super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
for i in 0..260u64 {
let blob = rekey::build_blob_local(rogue.secret_key(), &rogue.public_key().to_bytes(), &rogue.public_key(), RekeyScope::Root, new_epoch, &[0xEE; 32]).unwrap();
let rumor = rekey::build_rekey_rumor(rogue.public_key(), RekeyScope::Root, new_epoch, Epoch(0), &prev_commit, &[blob], 1, 1, 3_000 + i, None, false).unwrap();
let (wrap, _) = rekey::seal_rekey_chunk(&rumor, &group, &rogue, Timestamp::from_secs(3_000 + i)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
let session = crate::db::current_session();
let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("the genuine rotation is recovered past the flood");
assert_eq!(updated.root_epoch, Epoch(1));
assert_eq!(updated.community_root, new_root, "adopted the owner's root, not a junk one");
}
#[tokio::test]
async fn a_swap_during_create_private_channel_lands_in_the_creating_account() {
// create_private_channel publishes the key crate, then the channel
// edition, then whole-row-saves. A swap in that window used to abandon
// the whole thing — leaving the key crate published to relays but no
// local channel to open it, which is the worse of the two outcomes.
//
// The operation is pinned to the account that started it, so it now
// finishes into that account's storage, and the account swapped in gets
// nothing.
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let creator = crate::db::current_session();
let community = create_community(&bed.relay, "SwapCreate", bed.relays.clone(), None).await.unwrap();
let before = crate::db::community::load_community_v2(community.id()).unwrap().unwrap().channels.len();
// The key-crate publish inside create swaps the account mid-flight.
let swap_relay = SwapMidPublish { inner: MemoryRelay::new() };
create_private_channel(&swap_relay, &community, "ghost").await.unwrap();
let mine = crate::db::with_session(creator, async {
crate::db::community::load_community_v2(community.id()).unwrap().unwrap()
})
.await;
assert_eq!(mine.channels.len(), before + 1, "the channel is minted for the account that asked");
assert!(mine.channels.iter().any(|c| c.name == "ghost"), "and it is the one requested");
}
#[tokio::test]
async fn an_uncited_admin_rotation_is_not_adopted() {
// CORD-06 §Authority: "a rotation cites the Grant it acts under like any
// authority action, so a just-demoted admin's rotation is never honored by
// a lagging client." An uncited rotation is skipped entirely — neither
// adopted nor allowed to conclude a removal.
use crate::community::roles::{CommunityRoles, MemberGrant, Role};
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let mut community = create_community(&relay, "Uncited", vec!["wss://r".into()], None).await.unwrap();
let priv_id = ChannelId([0x8A; 32]);
let key1 = [0x93; 32];
add_private_channel(&mut community, priv_id, key1, Epoch(1));
let admin = Keys::generate();
let role = Role::admin("cf".repeat(32));
let roster = CommunityRoles {
roles: vec![role.clone()],
grants: vec![MemberGrant { member: admin.public_key().to_hex(), role_ids: vec![role.role_id.clone()] }],
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
};
seed_roster_with_heads(&community, &roster, 1_000);
let key2 = [0x94; 32];
let pc = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
let g2 = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
let me_pk = crate::state::MY_SECRET_KEY.to_keys().unwrap().public_key();
let blob = rekey::build_blob_local(admin.secret_key(), &admin.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
// Authorized admin, correct continuity, my blob present — but NO citation.
for e in rekey::build_rekey_chunks_local(&admin, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[blob], 2_000, None, false).unwrap() {
relay.publish(&e, &community.relays).await.unwrap();
}
let out = follow_rekeys(&relay, &community, &crate::db::current_session()).await.unwrap();
assert!(out.updated.is_none(), "an uncited rotation is not adopted");
// The SAME rotation, cited, is adopted — proving the refusal was the
// citation and not the rank or the continuity.
let cited = my_authority_citation(&community, &admin.public_key());
assert!(cited.is_some(), "the seeded head yields a citation");
let blob2 = rekey::build_blob_local(admin.secret_key(), &admin.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
for e in rekey::build_rekey_chunks_local(&admin, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[blob2], 2_100, cited.as_ref(), false).unwrap() {
relay.publish(&e, &community.relays).await.unwrap();
}
let out = follow_rekeys(&relay, &community, &crate::db::current_session()).await.unwrap();
assert!(out.updated.is_some(), "the cited rotation IS adopted");
}
#[tokio::test]
async fn two_admins_racing_a_channel_rotation_converge_on_one_key() {
// CORD-06 §Failure-and-races: two DISTINCT authorized rotators mint the
// same channel epoch concurrently (reachable — both hold MANAGE_CHANNELS).
// Every follower must converge on the SAME key (the lexicographically
// lowest), so the community never permanently forks. (Retaining the losing
// fork's key for its race-window messages needs a multi-key-per-epoch
// archive — a deferred refinement; convergence, the
// security-critical property, is what this pins.)
use crate::community::roles::{CommunityRoles, MemberGrant, Role};
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let mut community = create_community(&relay, "Race", vec!["wss://r".into()], None).await.unwrap();
let priv_id = ChannelId([0xC0; 32]);
let key1 = [0xC1; 32];
add_private_channel(&mut community, priv_id, key1, Epoch(1));
// Two admins (a, b) both hold the Admin role; I hold the channel key.
let (a, b) = (Keys::generate(), Keys::generate());
let role = Role::admin("ce".repeat(32));
let roster = CommunityRoles {
roles: vec![role.clone()],
grants: [&a, &b].iter().map(|k| MemberGrant { member: k.public_key().to_hex(), role_ids: vec![role.role_id.clone()] }).collect(),
everyone: None,
overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
};
seed_roster_with_heads(&community, &roster, 1_000);
// Both rotate 1 → 2, each delivering their OWN fresh key to me, off the
// same prevcommit — a genuine same-epoch fork.
let me_pk = crate::state::MY_SECRET_KEY.to_keys().unwrap().public_key();
let pc = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
let group = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
let key_a = [0x0A; 32];
let key_b = [0xFB; 32]; // higher — a's must win regardless of publish order
for (signer, k) in [(&a, &key_a), (&b, &key_b)] {
let blob = rekey::build_blob_local(signer.secret_key(), &signer.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(2), k).unwrap();
for e in rekey::build_rekey_chunks_local(signer, &group, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[blob], 2_000, my_authority_citation(&community, &signer.public_key()).as_ref(), false).unwrap() {
relay.publish(&e, &community.relays).await.unwrap();
}
}
let session = crate::db::current_session();
let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("adopts a winner");
let adopted = updated.channel(&priv_id).unwrap().key.unwrap();
assert_eq!(adopted, key_a, "converges on the lexicographically lowest key (deterministic across clients)");
// A SECOND follower (fresh, holding the same epoch-1 key) converges identically.
let mut peer = community.clone();
if let Some(c) = peer.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
c.key = Some(key1);
c.epoch = Epoch(1);
}
// Re-run the same fold from the peer's identical starting point → same winner.
let updated2 = follow_rekeys(&relay, &peer, &session).await.unwrap().updated.expect("peer adopts");
assert_eq!(updated2.channel(&priv_id).unwrap().key.unwrap(), key_a, "every follower lands on the identical key");
}
#[tokio::test]
async fn create_private_channel_refuses_a_member_without_manage_channels() {
// The local mirror of the reader's gate: an unauthorized member is refused
// BEFORE any publish (no floor pollution, no orphan key crate).
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Gate", bed.relays.clone(), None).await.unwrap();
send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
bed.swap_to(&member);
let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
let err = create_private_channel(&bed.relay, &joined, "sneaky").await.unwrap_err();
assert!(err.contains("MANAGE_CHANNELS"), "refused with the permission it lacks: {err}");
let err = create_public_channel(&bed.relay, &joined, "sneaky-too").await.unwrap_err();
assert!(err.contains("MANAGE_CHANNELS"), "public creation gates identically: {err}");
}
// ── Audit regressions ────────────────────────────────────────────────────
#[tokio::test]
async fn accept_rejects_a_bundle_with_a_forged_community_root() {
// The eclipse: community_id commits only to (owner, salt) — both semi-public
// — so a forged invite pairs the REAL triple with an attacker root, and every
// plane derives from it. The join-time owner-genesis check must refuse.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Real", bed.relays.clone(), None).await.unwrap();
let fake = crate::simd::hex::bytes_to_hex_32(&[0xEE; 32]);
let mut forged = bundle_of(&community, BundleAudience::Link, None, None, None);
forged.community_root = fake.clone();
for ch in &mut forged.channels {
ch.key = fake.clone();
}
let attacker = Keys::generate();
let wrap = invite::build_direct_invite(&attacker, &member.keys.public_key(), &forged).unwrap();
bed.relay.publish(&wrap, &bed.relays).await.unwrap();
bed.swap_to(&member);
let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
let err = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap_err();
assert!(err.contains("could not verify"), "a forged root fails the owner-genesis check: {err}");
assert!(
crate::db::community::load_community_v2(community.id()).unwrap().is_none(),
"a rejected join persists nothing"
);
}
#[tokio::test]
async fn accept_verifies_a_rotated_plane_whose_metadata_head_is_admin_signed() {
// CORD-06 compaction re-wraps CURRENT heads with their original signatures,
// so a rotated plane whose metadata an admin last edited carries no
// owner-signed vsk-0. The join anchor there is the community-bound metadata
// head plus any owner-signed edition under the same root.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Rotated", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
let rotated = rotate_view(&community, [0x5A; 32], 1);
let admin = Keys::generate();
publish_community_meta(&bed.relay, &rotated, &admin, "Rotated", 3).await;
publish_channel_edition(&bed.relay, &rotated, &owner.keys, &general, "general", false, 2, false).await;
bed.swap_to(&member);
let bundle = bundle_of(&rotated, BundleAudience::Link, None, None, None);
let joined = accept_bundle(&bed.relay, &bundle, None, None).await.unwrap();
assert_eq!(joined.root_epoch, Epoch(1), "the rotated root is adopted");
}
#[tokio::test]
async fn only_an_actual_join_publishes_a_guestbook_join() {
// A Guestbook Join is a member's own word that they JOINED. A re-accept of
// a held community and a cross-device key sync (a `member_since`) must
// both stay silent — each re-publish renders as "<user> has joined" spam.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Quiet", bed.relays.clone(), None).await.unwrap();
let gb_pk = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch).pk_hex();
async fn gb_count(relay: &MemoryRelay, gb_pk: &str, relays: &[String]) -> usize {
let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![gb_pk.to_string()], ..Default::default() };
relay.fetch(&q, relays).await.map(|v| v.len()).unwrap_or(0)
}
let baseline = gb_count(&bed.relay, &gb_pk, &bed.relays).await; // the owner's creation Join
bed.swap_to(&member);
let bundle = bundle_of(&community, BundleAudience::Link, None, None, None);
accept_bundle(&bed.relay, &bundle, None, None).await.unwrap();
assert_eq!(gb_count(&bed.relay, &gb_pk, &bed.relays).await, baseline + 1, "a first join announces exactly once");
accept_bundle(&bed.relay, &bundle, None, None).await.unwrap();
assert_eq!(gb_count(&bed.relay, &gb_pk, &bed.relays).await, baseline + 1, "a re-accept of a held community stays silent");
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::delete_community(&cid_hex).unwrap();
// A key sync is not a membership event, and it is not a membership
// RECORD either: the entry was just read from the very list a republish
// would rewrite. A device adopting N entries used to rebuild and
// publish the whole document N times over, concurrently, on boot.
// 13302 is REPLACEABLE, so a republish swaps the stored event rather
// than adding one — the id is the tell, and it always changes on a
// real republish because the list is NIP-44 sealed with a random nonce.
async fn list_id(relay: &MemoryRelay, me: &PublicKey, relays: &[String]) -> Option<String> {
let q = Query { kinds: vec![crate::community::v2::kind::COMMUNITY_LIST_FRAG], authors: vec![me.to_hex()], ..Default::default() };
let mut evs = relay.fetch(&q, relays).await.unwrap_or_default();
evs.sort_by_key(|e| e.created_at.as_secs());
evs.last().map(|e| e.id.to_hex())
}
let my_pk = me_pk().unwrap();
let list_before = list_id(&bed.relay, &my_pk, &bed.relays).await;
accept_bundle(&bed.relay, &bundle, None, Some(now_ms())).await.unwrap();
assert_eq!(gb_count(&bed.relay, &gb_pk, &bed.relays).await, baseline + 1, "a cross-device key sync is not a membership event");
assert_eq!(
list_id(&bed.relay, &my_pk, &bed.relays).await,
list_before,
"adopting an entry FROM the list must not republish the list"
);
// A genuine join still records, so the storm fix can't have muted the
// thing the republish exists for.
crate::db::community::delete_community(&cid_hex).unwrap();
accept_bundle(&bed.relay, &bundle, None, None).await.unwrap();
assert_ne!(
list_id(&bed.relay, &my_pk, &bed.relays).await,
list_before,
"a real join still records the membership across devices"
);
}
#[tokio::test]
async fn accept_refuses_a_rotated_plane_with_no_owner_signed_edition() {
// The fallback's second half is load-bearing: a community-bound metadata
// head alone is self-signable by anyone who knows the (public) community_id.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "NoOwner", bed.relays.clone(), None).await.unwrap();
let rotated = rotate_view(&community, [0x5B; 32], 1);
let attacker = Keys::generate();
publish_community_meta(&bed.relay, &rotated, &attacker, "NoOwner", 3).await;
bed.swap_to(&member);
let bundle = bundle_of(&rotated, BundleAudience::Link, None, None, None);
let err = accept_bundle(&bed.relay, &bundle, None, None).await.unwrap_err();
assert!(err.contains("could not verify"), "no owner-signed edition → refuse: {err}");
}
#[tokio::test]
async fn accept_requires_the_strict_owner_genesis_on_an_epoch_zero_plane() {
// The fallback applies to rotated planes only: at epoch 0 the spec guarantees
// an owner-signed genesis, so owner material without it stays insufficient.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Strict", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
let mut fake = community.clone();
fake.community_root = [0x5C; 32]; // epoch stays 0
let admin = Keys::generate();
publish_community_meta(&bed.relay, &fake, &admin, "Strict", 2).await;
publish_channel_edition(&bed.relay, &fake, &owner.keys, &general, "general", false, 2, false).await;
bed.swap_to(&member);
let bundle = bundle_of(&fake, BundleAudience::Link, None, None, None);
let err = accept_bundle(&bed.relay, &bundle, None, None).await.unwrap_err();
assert!(err.contains("could not verify"), "epoch 0 demands the owner genesis: {err}");
}
#[tokio::test]
async fn follow_control_heals_a_bundle_misclassified_public_channel() {
// A bundle can set a PUBLIC channel's grant key to the attacker's, so the
// joiner addresses it at a plane only the attacker reads. The owner's genuine
// public:false edition must override it on follow.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Heal", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let mut poisoned = community.clone();
poisoned.channels[0].private = true;
poisoned.channels[0].key = Some([0x66; 32]);
crate::db::community::save_community_v2(&poisoned).unwrap();
let healed = follow_control(&relay, &poisoned).await.unwrap().updated.expect("healed");
let ch = healed.channel(&general).unwrap();
assert!(!ch.private, "the owner's public declaration overrides the bundle");
assert_eq!(ch.key, None, "a healed public channel derives from the root");
}
#[tokio::test]
async fn a_deleted_channel_does_not_resurrect_on_reload() {
// save_community_v2 must prune orphan channel rows, or a control-follow delete
// reappears (with a stale key) on the next reload.
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Prune", vec!["wss://r".into()], None).await.unwrap();
let extra = ChannelId([0x77; 32]);
publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 1, false).await;
let with_extra = follow_control(&relay, &community).await.unwrap().updated.unwrap();
assert!(with_extra.channel(&extra).is_some());
publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 2, true).await;
let after = follow_control(&relay, &with_extra).await.unwrap().updated.unwrap();
assert!(after.channel(&extra).is_none());
let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert!(reloaded.channel(&extra).is_none(), "a deleted channel must not resurrect on reload");
assert_eq!(reloaded.channels.len(), 1);
}
#[tokio::test]
async fn a_channel_owned_by_another_community_is_skipped_not_clobbered() {
// channel_id is the sole DB primary key, so a bundle/replay reusing another
// community's channel_id must NOT overwrite that row. It's skipped (not an
// error — erroring would wedge all of this community's control persistence).
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let a = create_community(&relay, "A", vec!["wss://r".into()], None).await.unwrap();
let a_channel = a.channels[0].id;
let mut b = create_community(&relay, "B", vec!["wss://r".into()], None).await.unwrap();
let b_channel = b.channels[0].id;
// B's set includes a phantom whose id collides with A's channel.
b.channels.push(ChannelV2 { id: a_channel, name: "phantom".into(), private: false, key: None, epoch: b.root_epoch, voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed: None });
crate::db::community::save_community_v2(&b).expect("save succeeds, the phantom is skipped");
// A's channel row is untouched.
let a_reloaded = crate::db::community::load_community_v2(a.id()).unwrap().unwrap();
assert!(!a_reloaded.channels.iter().any(|c| c.private), "A's channel is untouched");
assert_eq!(a_reloaded.channels[0].id.0, a_channel.0);
// B keeps its own channel but never acquired a row for the foreign id.
let b_reloaded = crate::db::community::load_community_v2(b.id()).unwrap().unwrap();
assert!(b_reloaded.channel(&b_channel).is_some(), "B's own channel persists");
assert!(b_reloaded.channel(&a_channel).is_none(), "the foreign-owned channel is skipped, not stolen");
}
/// A single relay that CAPS every query below the page size (modelling a real
/// relay's maxFilterLimit) and honors `until` — so the join-verify walk MUST
/// paginate to reach an old genesis. MemoryRelay can't model this (it unions then
/// truncates the whole set), which is why a MemoryRelay flood test gives false
/// confidence about the production `LiveTransport` behaviour.
struct CappedRelay {
events: Vec<Event>,
cap: usize,
}
#[async_trait::async_trait]
impl Transport for CappedRelay {
async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> { Ok(crate::community::transport::PlaneFetch::whole(self.fetch(query, relays).await?)) }
async fn publish(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
Ok(())
}
async fn publish_durable(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
Ok(())
}
async fn fetch(&self, q: &Query, _r: &[String]) -> Result<Vec<Event>, String> {
let mut m: Vec<Event> = self
.events
.iter()
.filter(|e| q.authors.is_empty() || q.authors.contains(&e.pubkey.to_hex()))
.filter(|e| q.until.is_none_or(|u| e.created_at.as_secs() <= u))
.cloned()
.collect();
m.sort_by(|a, b| b.created_at.cmp(&a.created_at)); // newest first
m.truncate(self.cap.min(q.limit.unwrap_or(usize::MAX)));
Ok(m)
}
}
#[tokio::test]
async fn refound_aborts_when_the_control_plane_cannot_be_read_in_full() {
// CORD-06 §3: a Refounder that cannot fold every Control Event must abort.
// `until` is inclusive, so a page-wide block of same-second wraps is a wall
// no cursor steps past — everything older (the genesis editions, a Banlist)
// is unreachable. Compacting THAT view carries only what was read into the
// new epoch, dropping the rest for every member, permanently. Any member can
// build the wall: the plane key comes from the community root they hold.
let (_tmp, _guard, _owner) = init_test_db();
let memory = MemoryRelay::new();
let community = create_community(&memory, "Walled", vec!["wss://r".into()], None).await.unwrap();
// Post-split the plane is staff-write-only, so the wall is built with the
// write group (any control_root holder can still flood; the pager
// property under test is unchanged).
let control = control::ControlPlane::of(&community).write_group().unwrap();
let rogue = Keys::generate();
let mut events: Vec<Event> = Vec::new();
for i in 0..FOLLOW_PAGE {
let content = format!("{{\"name\":\"junk{i}\",\"private\":false}}");
let rumor = control::build_edition_rumor(
rogue.public_key(),
vsk::CHANNEL_METADATA,
&[0xAB; 32],
1,
None,
&content,
9_000,
None,
);
let (w, _) = control::seal_control_edition(&rumor, &control, &rogue, Timestamp::from_secs(9_000)).unwrap();
events.push(w);
}
let relay = CappedRelay { events, cap: FOLLOW_PAGE };
let err = refound_community(&relay, &community, &[])
.await
.expect_err("a plane that can't be read whole must never be compacted");
assert!(err.contains("too deep to read in full"), "unexpected error: {err}");
}
#[tokio::test]
async fn verify_pages_a_capped_relay_past_a_flood_to_the_genesis() {
// The join-verify DoS mitigation, tested against a relay that caps below PAGE
// (production behaviour MemoryRelay hides): a rogue root-holder buries the
// genesis under junk, and the `until`-walk must page past it. Uses fixed OLD
// timestamps so `until = now` includes everything and the walk is deterministic.
let (_tmp, _guard, owner) = init_test_db();
let meta = control::CommunityMetadata { name: "Capped".into(), relays: vec!["wss://r".into()], ..Default::default() };
let g = control::genesis(&owner, meta, 1_000).unwrap();
let community = CommunityV2::from_genesis(&g, "Capped", None, vec!["wss://r".into()], 1_000);
let control = control::ControlPlane::of(&community).write_group().unwrap();
let rogue = Keys::generate();
let mut events: Vec<Event> = g.wraps.to_vec();
for i in 0..250u64 {
let rumor = control::build_edition_rumor(rogue.public_key(), vsk::CHANNEL_METADATA, &[0xAB; 32], 1, None, "{\"name\":\"junk\",\"private\":false}", 1_001 + i, None);
let (wrap, _) = control::seal_control_edition(&rumor, &control, &rogue, Timestamp::from_secs(1_001 + i)).unwrap();
events.push(wrap);
}
// Cap 100/query forces the walk across ~3 pages down to the genesis at ts 1000.
let relay = CappedRelay { events, cap: 100 };
let verified = verify_owner_root_and_reconcile(&relay, community.clone()).await;
assert!(verified.is_ok(), "the until-walk pages a capped relay past the flood to the genesis: {:?}", verified.err());
}
#[tokio::test]
async fn accept_parked_invite_joins_from_the_stored_bundle() {
// The 3313 receive path: an invite is parked as its bundle JSON, then accepted
// from the stored bundle (re-verifying the owner root over the network).
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Parked", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
send_message(&bed.relay, &community, &general, "owner: hi").await.unwrap();
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
let inviter_hex = owner.keys.public_key().to_hex();
bed.swap_to(&member);
let joined = accept_parked_invite(&bed.relay, &bundle_json, Some(&inviter_hex)).await.unwrap();
assert_eq!(joined.id().0, community.id().0, "joined the community from the parked bundle");
assert!(joined.identity.verify());
assert_eq!(texts_in(&bed.relay, &joined, &general).await, vec!["owner: hi"]);
// The join seeded the verified fold as the member's initial floor, so their
// first follow can't roll below the state the join just showed.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
assert!(
crate::db::community::get_edition_head(&cid_hex, &cid_hex).unwrap().is_some(),
"the joiner's control floor is seeded from the join-time fold"
);
// The Guestbook memberlist now folds both participants.
bed.swap_to(&owner);
let members = memberlist(&bed.relay, &community).await.unwrap();
assert!(members.contains(&member.keys.public_key()), "the parked-invite joiner is a member");
}
#[tokio::test]
async fn accept_parked_invite_rejects_a_forged_root() {
// A forged-root parked bundle (real identity triple, attacker-chosen root) fails
// accept — the shared accept path re-verifies the owner root, so a parked invite
// gets the same eclipse protection as a live one.
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Real", vec!["wss://r".into()], None).await.unwrap();
let mut forged = bundle_of(&community, BundleAudience::Link, None, None, None);
let fake = crate::simd::hex::bytes_to_hex_32(&[0xEE; 32]);
forged.community_root = fake.clone();
for ch in &mut forged.channels {
ch.key = fake.clone();
}
let bundle_json = serde_json::to_string(&forged).unwrap();
let err = accept_parked_invite(&relay, &bundle_json, None).await.unwrap_err();
assert!(err.contains("could not verify"), "a forged-root parked bundle fails definitively: {err}");
}
#[tokio::test]
async fn verify_rejects_a_cross_community_owner_edition_replay() {
// The eclipse-via-replay: an owner-signed edition from community X (eid == X.id)
// rewrapped onto a FORGED community T's fake control plane must NOT authenticate
// T. T's genesis has eid == T.id, so X's edition — a genuine owner signature but
// a different eid — is not a valid proof of T's root. This is why "any owner
// edition" is unsound and the eid==community_id genesis pin is required.
let (_tmp, _guard, owner) = init_test_db();
// Community X (real), owned by `owner`.
let gx = control::genesis(&owner, control::CommunityMetadata { name: "X".into(), ..Default::default() }, 1_000).unwrap();
let x_control = control::split_write_group(&gx.control_root, &gx.community_root, &gx.identity.community_id, Epoch(0));
let (_ed, opened) = control::open_control_edition(&gx.wraps[0], &x_control).unwrap();
// Forged community T: the real owner triple but an ATTACKER-chosen root.
let t_identity = control::CommunityIdentity::mint(&owner.public_key());
let fake_root = [0xEE; 32];
let t = CommunityV2 {
identity: t_identity,
community_root: fake_root,
root_epoch: Epoch(0),
control_pk: None,
control_root: None,
name: "T".into(),
description: None,
icon: None,
banner: None,
meta_custom: None,
meta_extra: Default::default(),
relays: vec!["wss://r".into()],
channels: vec![],
categories: Vec::new(),
dissolved: false,
created_at_ms: 0,
};
// Rewrap X's owner-signed genesis onto T's fake control plane (the attacker
// controls the fake root, so they can derive its control group key).
let t_control = control_group_key(&fake_root, t.id(), t.root_epoch);
let (replayed, _) = stream::rewrap_seal(&opened.seal, &t_control, Timestamp::from_secs(1_000)).unwrap();
let relay = MemoryRelay::new();
relay.publish(&replayed, &t.relays).await.unwrap();
let verified = verify_owner_root_and_reconcile(&relay, t.clone()).await;
assert!(verified.is_err(), "a cross-community owner-edition replay must not authenticate a forged root");
}
/// LIVE smoke test (network) — ignored by default. Creates a v2 community on a
/// REAL relay via `LiveTransport`, sends a message, fetches it back, and mints
/// a public link. A fresh throwaway identity in an isolated temp data dir, so
/// it never touches real accounts. Run explicitly:
/// ```sh
/// cargo test -p vector-core -- --ignored --nocapture live_smoke
/// ```
#[tokio::test]
#[ignore = "hits a real relay over the network"]
async fn live_smoke_create_send_fetch_on_a_real_relay() {
use nostr_sdk::prelude::ToBech32;
let relay = std::env::var("VECTOR_SMOKE_RELAY").unwrap_or_else(|_| "wss://jskitty.com/nostr".to_string());
let relays = vec![relay.clone()];
// Isolated account + data dir (a fresh throwaway key — never a real account).
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();
// Bring your own key (VECTOR_SMOKE_NSEC) to create a community you can log
// into elsewhere; otherwise a fresh throwaway.
let keys = match std::env::var("VECTOR_SMOKE_NSEC") {
Ok(n) => Keys::parse(&n).expect("VECTOR_SMOKE_NSEC is not a valid nsec"),
Err(_) => Keys::generate(),
};
let npub = keys.public_key().to_bech32().unwrap();
// Off by default (never leak secrets from a committed test); set
// VECTOR_SMOKE_PRINT_NSEC=1 to print the owner nsec for cross-client login.
if std::env::var("VECTOR_SMOKE_PRINT_NSEC").is_ok() {
println!("[smoke] OWNER nsec (throwaway — do NOT reuse): {}", keys.secret_key().to_bech32().unwrap());
}
std::fs::create_dir_all(tmp.path().join(&npub)).unwrap();
crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
crate::db::set_current_account(npub.clone()).unwrap();
crate::db::init_database(&npub).unwrap();
crate::state::MY_SECRET_KEY.store_from_keys(&keys, &[]);
crate::state::set_my_public_key(keys.public_key());
println!("[smoke] throwaway identity {npub}");
// A live client (LiveTransport rides the global NOSTR_CLIENT + warms relays).
let client = crate::nostr_client_builder().build();
client.add_managed_relay(relay.as_str()).await.ok();
client.connect().await;
crate::state::set_nostr_client(client);
let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
// Create → send → fetch-back → verify.
let community = create_community(&transport, "V2 Live Smoke", relays.clone(), None).await.expect("create");
let general = community.channels[0].id;
println!("[smoke] created community {} on {relay}", crate::simd::hex::bytes_to_hex_32(&community.id().0));
let text = "hello from a Vector Concord v2 live smoke test";
let sent_id = send_message(&transport, &community, &general, text).await.expect("send");
println!("[smoke] sent message {sent_id}");
// Give the relay a moment to store + be ready to serve it.
crate::rt::time::sleep(std::time::Duration::from_secs(3)).await;
let page = fetch_channel(&transport, &community, &general, 50).await.expect("fetch");
let texts: Vec<String> = page
.iter()
.filter_map(|f| match &f.event {
ChatEvent::Message { .. } => Some(f.event.opened().rumor.content.clone()),
_ => None,
})
.collect();
println!("[smoke] fetched {} message(s) back: {texts:?}", texts.len());
assert!(texts.contains(&text.to_string()), "the message did not round-trip through the real relay");
// Mint a shareable v2 link (the thing a bot hands out).
let link = mint_public_link(&transport, &community, "https://vectorapp.io", None, None).await.expect("mint link");
println!("[smoke] invite link: {}", link.url);
println!("[smoke] PASS — v2 create+send+fetch+invite round-tripped on {relay}");
}
#[tokio::test]
async fn chat_ops_react_edit_delete_round_trip() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Ops", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
let me_hex = owner.keys.public_key().to_hex();
let msg_id = send_message(&bed.relay, &community, &general, "original").await.unwrap();
send_reaction(&bed.relay, &community, &general, &msg_id, &me_hex, super::super::kind::MESSAGE, ":fire:", Some(("fire", "https://e/f.png")))
.await
.unwrap();
send_edit(&bed.relay, &community, &general, &msg_id, "edited", &[]).await.unwrap();
send_delete(&bed.relay, &community, &general, &msg_id, super::super::kind::MESSAGE, None).await.unwrap();
let page = fetch_channel(&bed.relay, &community, &general, 50).await.unwrap();
let target = crate::simd::hex::hex_to_bytes_32(&msg_id);
let mut saw = (false, false, false);
for f in &page {
match &f.event {
ChatEvent::Reaction { target: t, emoji, emoji_url, .. } if *t == target => {
assert_eq!(emoji, ":fire:");
assert_eq!(emoji_url.as_deref(), Some("https://e/f.png"));
saw.0 = true;
}
ChatEvent::Edit { target: t, new_content, .. } if *t == target => {
assert_eq!(new_content, "edited");
saw.1 = true;
}
ChatEvent::Delete { target: t, .. } if *t == target => saw.2 = true,
_ => {}
}
}
assert!(saw.0 && saw.1 && saw.2, "reaction/edit/delete all round-trip: {saw:?}");
}
#[tokio::test]
async fn a_typing_signal_rides_the_ephemeral_wrap_and_is_never_stored() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Typ", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
let group = channel_group_key(&community.community_root, &general, community.root_epoch);
// A live subscriber sees the 21059 wrap and it opens as Typing…
let mut sub = bed.relay.subscribe(Query {
kinds: vec![stream::KIND_WRAP_EPHEMERAL],
authors: vec![group.pk_hex()],
..Default::default()
});
send_typing(&bed.relay, &community, &general).await.unwrap();
let wrap = sub.try_recv().expect("the typing wrap streams to a live subscriber");
let opened = match chat::open_chat_event(&wrap, &group, &general, community.root_epoch) {
Ok(ChatEvent::Typing { opened }) => opened,
other => panic!("the ephemeral wrap must open as a Typing event, got {other:?}"),
};
// …while nothing durable is stored (relays never keep the ephemeral tier),
// so channel history stays free of typing noise…
let page = fetch_channel(&bed.relay, &community, &general, 50).await.unwrap();
assert!(page.iter().all(|f| !matches!(f.event, ChatEvent::Typing { .. })));
// …and no delete key is kept (there is no durable wrap to ever delete).
let rumor_hex = opened.rumor_id.to_hex();
assert!(
crate::db::community::get_message_key(&rumor_hex).unwrap().is_none() && !crate::db::community::has_wrap_owner(&rumor_hex).unwrap(),
"ephemeral sends must not keep delete keys"
);
}
/// The owner key my own wrap of `rumor_hex` at `address` derives to.
fn derived_owner_of(me: &Keys, address: &PublicKey, rumor_hex: &str) -> PublicKey {
let secret: [u8; 32] = me.secret_key().as_secret_bytes().try_into().unwrap();
super::super::derive::wrap_owner_key(&secret, address, nostr_sdk::prelude::EventId::from_hex(rumor_hex).unwrap().as_bytes()).public_key()
}
#[tokio::test]
async fn a_send_keeps_both_delete_keys_and_a_delete_takes_it_and_its_edits_off_every_relay() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let relays = vec!["wss://r".to_string(), "wss://s".to_string()];
bed.relay.follow_cord01(&relays[..1]);
let community = create_community(&bed.relay, "Nuke", relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
let group = channel_group_key(&community.community_root, &general, community.root_epoch);
let id = send_message(&bed.relay, &community, &general, "scrub me").await.unwrap();
let edit = send_edit(&bed.relay, &community, &general, &id, "scrub me too", &[]).await.unwrap();
// The wrap is p-tagged to the key this identity derives for it, and both keys are kept.
let owners = crate::db::community::wrap_owners(&id).unwrap();
let (owner_keys, outer_hex, sent_to) = owners.first().expect("a durable send keeps its owner");
assert_eq!(owner_keys.public_key(), derived_owner_of(&owner.keys, &group.pk(), &id));
assert_eq!(sent_to, &community.relays);
let by_id = |ids: Vec<String>| Query { ids, ..Default::default() };
let wrap = bed.relay.fetch(&by_id(vec![outer_hex.clone()]), &relays).await.unwrap().pop().expect("the kept outer id is the published wrap");
assert_eq!(stream::wrap_owner(&wrap), Some(owner_keys.public_key()));
let (plane, plane_outer, _) = crate::db::community::get_message_key(&id).unwrap().expect("and its plane key");
assert_eq!((plane.public_key(), &plane_outer), (group.pk(), outer_hex));
let edit_outer = crate::db::community::wrap_owners(&edit).unwrap().pop().expect("an edit keeps its owner too").1;
// Reactions ride the same keys (a revoke deletes them the same way).
let me_hex = owner.keys.public_key().to_hex();
let rid = send_reaction(&bed.relay, &community, &general, &id, &me_hex, super::super::kind::MESSAGE, "🔥", None)
.await
.unwrap();
assert!(crate::db::community::has_wrap_owner(&rid).unwrap() && crate::db::community::has_message_key(&rid).unwrap());
let scrubbed = crate::community::message_delete::scrub_own(&bed.relay, &community.relays, &id).await.unwrap();
assert!(scrubbed.everywhere());
for relay in &relays {
let left = bed.relay.fetch(&by_id(vec![outer_hex.clone(), edit_outer.clone()]), std::slice::from_ref(relay)).await.unwrap();
assert!(left.is_empty(), "the message and the edit carrying its text leave {relay}");
}
for spent in [&id, &edit] {
assert!(!crate::db::community::has_wrap_owner(spent).unwrap() && !crate::db::community::has_message_key(spent).unwrap(), "keys spent");
}
assert!(crate::community::message_delete::in_plane_delete_expiry(&id, scrubbed).await.is_some(), "so its in-plane delete may leave in time");
}
#[tokio::test]
async fn backfill_keeps_the_owner_my_other_devices_derived_and_never_a_strangers() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Heal", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
let group = channel_group_key(&community.community_root, &general, community.root_epoch);
// Sent and edited from another device of mine: on the relay, nothing kept here.
let id = send_message(&bed.relay, &community, &general, "elsewhere").await.unwrap();
let edit = send_edit(&bed.relay, &community, &general, &id, "edited elsewhere", &[]).await.unwrap();
for sent in [&id, &edit] {
crate::db::community::delete_message_key(sent).unwrap();
crate::db::community::forget_wrap_owners(sent).unwrap();
}
// Mine from before owners were kept: its p key was random and is gone.
let old = chat::build_message_rumor(owner.keys.public_key(), &general, community.root_epoch, "before", None, &[], vec![], 6_000);
let old_id = old.id.unwrap().to_hex();
let (old_wrap, _) = chat::seal_chat_rumor(&old, &group, &owner.keys, Timestamp::from_secs(6), false).unwrap();
bed.relay.publish(&old_wrap, &community.relays).await.unwrap();
// A stranger's.
let mkeys = Keys::generate();
let rumor = chat::build_message_rumor(mkeys.public_key(), &general, community.root_epoch, "foreign", None, &[], vec![], 7_000);
let foreign_id = rumor.id.unwrap().to_hex();
let (fw, _) = chat::seal_chat_rumor(&rumor, &group, &mkeys, Timestamp::from_secs(7), false).unwrap();
bed.relay.publish(&fw, &community.relays).await.unwrap();
fetch_channel(&bed.relay, &community, &general, 50).await.unwrap();
let has = |id: &str| (crate::db::community::has_wrap_owner(id).unwrap(), crate::db::community::has_message_key(id).unwrap());
assert_eq!(has(&id), (true, true), "my other device's send is fully deletable here");
assert_eq!(has(&edit), (true, true), "and so is its edit, which carries its text");
assert_eq!(has(&old_id), (false, true), "an old send keeps only its plane key");
assert_eq!(has(&foreign_id), (false, false), "a stranger's gets nothing");
bed.relay.follow_cord01(&community.relays);
crate::community::message_delete::scrub_own(&bed.relay, &community.relays, &id).await.unwrap();
let old_scrub = crate::community::message_delete::scrub_own(&bed.relay, &community.relays, &old_id).await.unwrap();
assert!(!old_scrub.everywhere());
let left: Vec<String> = fetch_channel(&bed.relay, &community, &general, 50).await.unwrap().iter().map(|f| f.event.opened().rumor_id.to_hex()).collect();
assert!(!left.contains(&id), "the healed owner deletes it where CORD-01 holds");
assert!(!crate::db::community::has_wrap_owner(&edit).unwrap(), "its edit went with it");
assert!(left.contains(&old_id), "where only the in-plane delete can hide an old send");
}
#[tokio::test]
async fn a_remote_signer_keeps_a_random_owner_only_on_the_sending_device() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Bunker", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
let group = channel_group_key(&community.community_root, &general, community.root_epoch);
// A remote signer's account: the vault holds only its client key.
let client = Keys::generate();
crate::state::MY_SECRET_KEY.store_from_keys(&client, &[]);
crate::signer::set_test_signer(Some(crate::signer::ActiveSigner::Keys(owner.keys.clone())));
let sent = send_message(&bed.relay, &community, &general, "signed elsewhere").await;
crate::signer::set_test_signer(None);
crate::state::MY_SECRET_KEY.store_from_keys(&owner.keys, &[]);
let id = sent.unwrap();
let (kept, outer, _) = crate::db::community::wrap_owners(&id).unwrap().pop().expect("the sending device keeps its owner");
assert_ne!(kept.public_key(), derived_owner_of(&owner.keys, &group.pk(), &id), "a remote signer can't derive it");
assert_ne!(kept.public_key(), derived_owner_of(&client, &group.pk(), &id), "nor is it the client key's, which is no one's identity");
let wrap = bed.relay.fetch(&Query { ids: vec![outer], ..Default::default() }, &community.relays).await.unwrap().pop().unwrap();
assert_eq!(stream::wrap_owner(&wrap), Some(kept.public_key()));
}
#[tokio::test]
async fn my_delete_leaves_relays_in_time_only_once_the_message_is_gone_everywhere() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
bed.relay.follow_cord01(&bed.relays);
let community = create_community(&bed.relay, "Expire", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
let group = channel_group_key(&community.community_root, &general, community.root_epoch);
let fresh = send_message(&bed.relay, &community, &general, "deletable everywhere").await.unwrap();
let old = send_message(&bed.relay, &community, &general, "an old send").await.unwrap();
crate::db::community::forget_wrap_owners(&old).unwrap();
let mut sub = bed.relay.subscribe(Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() });
let mut delete_of = |target: &str| {
let wrap = sub.try_recv().expect("the in-plane delete goes out");
match chat::open_chat_event(&wrap, &group, &general, community.root_epoch) {
Ok(ChatEvent::Delete { .. }) => {}
other => panic!("expected the delete of {target}, got {other:?}"),
}
wrap.tags.iter().find_map(|t| {
let s = t.as_slice();
(s.len() >= 2 && s[0] == "expiration").then(|| s[1].parse::<u64>().unwrap())
})
};
delete_own(&bed.relay, &community, &general, &fresh, super::super::kind::MESSAGE).await.unwrap();
let now = Timestamp::now().as_secs();
let until = delete_of(&fresh).expect("its copies are gone, so the delete leaves too");
assert!(until > now + 29 * 24 * 3600 && until <= now + 30 * 24 * 3600 + 5);
delete_own(&bed.relay, &community, &general, &old, super::super::kind::MESSAGE).await.unwrap();
assert_eq!(delete_of(&old), None, "it alone hides a copy a CORD-01 relay still holds");
}
#[tokio::test]
async fn an_owned_delete_leaves_relays_no_later_than_its_self_destructing_message() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Soon", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
let soon = Timestamp::now().as_secs() + 3_600;
let id = send_chat_message(&bed.relay, &community, &general, "brief", None, &[], vec![nostr_sdk::prelude::Tag::expiration(Timestamp::from_secs(soon))]).await.unwrap();
let scrubbed = crate::community::message_delete::scrub_own(&bed.relay, &community.relays, &id).await.unwrap();
assert_eq!(crate::community::message_delete::in_plane_delete_expiry(&id, scrubbed).await, Some(soon));
}
#[tokio::test]
async fn send_chat_message_threads_the_reply_and_extra_tags() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Re", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
let me_hex = owner.keys.public_key().to_hex();
let parent_id = send_message(&bed.relay, &community, &general, "parent").await.unwrap();
let imeta = nostr_sdk::prelude::Tag::custom(
"imeta",
["url https://e/blob".to_string(), "m image/png".to_string()],
);
let child_id = send_chat_message(
&bed.relay, &community, &general, "child",
Some((parent_id.as_str(), me_hex.as_str())), &[], vec![imeta],
)
.await
.unwrap();
let page = fetch_channel(&bed.relay, &community, &general, 50).await.unwrap();
let child = page
.iter()
.find_map(|f| match &f.event {
ChatEvent::Message { opened, reply_to, .. } if opened.rumor_id.to_hex() == child_id => Some((opened, reply_to)),
_ => None,
})
.expect("the reply message round-trips");
let reply = child.1.as_ref().expect("the reply reference is carried");
assert_eq!(crate::simd::hex::bytes_to_hex_32(&reply.id), parent_id);
assert_eq!(reply.author, Some(owner.keys.public_key()));
assert!(
child.0.rumor.tags.iter().any(|t| t.kind() == "imeta"),
"the imeta attachment tag rides the rumor verbatim"
);
}
#[tokio::test]
async fn a_kick_needs_kick_authority_and_removes_the_target() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Kick", bed.relays.clone(), None).await.unwrap();
// The target announces a Join (as an accepted invite would).
let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let join = guestbook::build_join_rumor(member.keys.public_key(), None, 2_000);
let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &member.keys, Timestamp::from_secs(2)).unwrap();
bed.relay.publish(&wrap, &bed.relays).await.unwrap();
let before = memberlist(&bed.relay, &community).await.unwrap();
assert!(before.contains(&member.keys.public_key()), "the join lands first");
// An unprivileged member's kick of the owner is refused locally…
bed.swap_to(&member);
let err = kick_member(&bed.relay, &community, &owner.keys.public_key()).await.unwrap_err();
assert!(err.contains("not authorized"), "unprivileged kick refused: {err}");
// …and the owner (supreme, no grant needed) kicks the member out.
bed.swap_to(&owner);
kick_member(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
let after = memberlist(&bed.relay, &community).await.unwrap();
assert!(!after.contains(&member.keys.public_key()), "the kicked member leaves the fold");
assert!(after.contains(&owner.keys.public_key()), "the owner remains");
}
#[tokio::test]
async fn an_obeyed_kick_is_recorded_at_its_own_time() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Evict", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
record_eviction(&community, 9_000_000);
assert!(load_pending().tombstones.iter().any(|t| t.community_id == cid_hex && t.removed_at == 9_000_000), "the List is told, so no boot re-adopts it");
assert!(tombstone_suppresses(&cid_hex, 8_999), "an invite older than the Kick stays answered");
assert!(!tombstone_suppresses(&cid_hex, 9_001), "a re-invite after the Kick lands");
}
#[tokio::test]
async fn a_rejoin_survives_a_stale_kick_and_an_uncaught_up_store() {
// The self-eviction race: on a REJOIN the guestbook store starts empty while the
// control fold has already re-derived the member's old ban mark, so the MEMBERLIST
// legitimately excludes them for that window. A stale Kick landing there used to
// read as an authorized eviction and the client nuked its own community.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Rejoin", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let (o, m) = (owner.keys.public_key(), member.keys.public_key());
let join = |at: u64, id: u8| guestbook::GuestbookEvent { epoch: None, observed_at: None,
rumor_id: [id; 32],
entry: guestbook::GuestbookEntry::Join { member: m, invited_by: None, at_ms: at },
};
let kick = |at: u64, id: u8| guestbook::GuestbookEvent { epoch: None, observed_at: None,
rumor_id: [id; 32],
entry: guestbook::GuestbookEntry::Kick { actor: o, target: m, citation: None, at_ms: at },
};
// An authorized kick after their join stands.
crate::db::community::set_guestbook(&cid_hex, &[join(1_000, 1), kick(2_000, 2)], 2).unwrap();
assert!(stored_kick_verdict(&community, &m), "an authorized kick after the join is honored");
assert_eq!(stored_kick_at(&community, &m), Some(2_000), "the eviction carries the Kick's own time");
// A rejoin supersedes it — latest entry wins (CORD-02 §5).
crate::db::community::set_guestbook(&cid_hex, &[join(1_000, 1), kick(2_000, 2), join(3_000, 3)], 3).unwrap();
assert!(!stored_kick_verdict(&community, &m), "a Join newer than the kick clears the verdict");
// The catch-up window itself: nothing folded yet decides nothing.
crate::db::community::set_guestbook(&cid_hex, &[], 0).unwrap();
assert!(!stored_kick_verdict(&community, &m), "an empty store is not an eviction");
// And the memberlist is NOT a substitute: with the store empty it excludes them,
// which is exactly the false positive this verdict replaced.
assert!(
!stored_memberlist(&community).unwrap().contains(&m),
"the memberlist excludes an un-caught-up member — why it can't gate a kick"
);
}
/// Seed a roster the way production does: `follow_control` writes the roster
/// AND the folded edition heads in one pass, so a citation against a grant is
/// resolvable. Seeding the roster alone yields a client that can never satisfy
/// any `vac` — a shape no v2 production path produces.
fn seed_roster_with_heads(community: &CommunityV2, roster: &crate::community::roles::CommunityRoles, at: i64) {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::set_community_roles(&cid_hex, roster, at).unwrap();
for g in &roster.grants {
let Some(m) = crate::simd::hex::hex_to_bytes_32_checked(&g.member) else { continue };
let eid = super::super::derive::grant_locator(community.id(), &m);
let entity_hex = crate::simd::hex::bytes_to_hex_32(&eid);
crate::db::community::set_edition_head_at_epoch(&cid_hex, &entity_hex, 1, &[0xA1; 32], &[0xA2; 32], &[0xA3; 32], community.root_epoch.0).unwrap();
}
}
/// Publish an edition CITING a specific grant version (CORD-04 §5's `vac`).
async fn publish_grant_citing(
relay: &MemoryRelay,
community: &CommunityV2,
signer: &Keys,
member: &PublicKey,
role_ids: Vec<String>,
version: u64,
citation: Option<&crate::community::edition::AuthorityCitation>,
) {
let group = control::ControlPlane::of(&community).write_group().unwrap();
let eid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
let prev = head_hash_on_relay(relay, community, &eid).await;
let grant = MemberGrant { member: member.to_hex(), role_ids };
let content = crate::community::v2::roles::grant_content_json(&grant).unwrap();
let rumor = control::build_edition_rumor(signer.public_key(), vsk::GRANT, &eid, version, prev.as_ref(), &content, 1_000, citation);
let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
}
#[tokio::test]
async fn an_uncited_edition_cannot_self_promote_or_outlive_a_demotion() {
// The two ways an ADD could escalate if the citation were the thing holding
// the line. It is not — rank is — and rank is resolved against the CURRENT
// roster, which is precisely what the spec says the verifier must do.
let (bed, owner, admin) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "NoEscalate", bed.relays.clone(), None).await.unwrap();
let admin_pk = admin.keys.public_key();
// An admin at position 3, and a role ABOVE them at position 1.
let mid = "d1".repeat(32);
let mut mid_role = admin_role(&mid, Permissions::admin().0);
mid_role.position = 3;
publish_role(&bed.relay, &community, &owner.keys, &mid_role, 1).await;
let high = "d2".repeat(32);
let mut high_role = admin_role(&high, Permissions::admin().0);
high_role.position = 1;
publish_role(&bed.relay, &community, &owner.keys, &high_role, 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin_pk, vec![mid.clone()], 1).await;
// 1. SELF-PROMOTION, uncited: the admin grants THEMSELVES the higher role.
publish_grant_citing(&bed.relay, &community, &admin.keys, &admin_pk, vec![high.clone(), mid.clone()], 2, None).await;
// Assert the PROPERTY, not the shape: the role must not be held, whether the
// forged edition was refused outright or folded back to the owner's version.
let view = fetch_authority(&bed.relay, &community).await;
assert!(
!view.roles.grants.iter().any(|g| g.member == admin_pk.to_hex() && g.role_ids.contains(&high)),
"an uncited edition must not let an author grant themselves a role they do not \
outrank — you cannot act at or above your own rank, citation or not",
);
// 2. OUTLIVING A DEMOTION, uncited: the owner demotes the admin to nothing,
// and the admin's uncited grant to a bystander must stop being honored the
// moment this client folds the demotion.
let bystander = Keys::generate().public_key();
publish_grant_citing(&bed.relay, &community, &admin.keys, &bystander, vec![mid.clone()], 1, None).await;
let before = fetch_authority(&bed.relay, &community).await;
assert!(
!before.roles.grants.iter().any(|g| g.member == bystander.to_hex()),
"an admin at position 3 cannot grant position 3 — equal cannot act on equal",
);
publish_grant(&bed.relay, &community, &owner.keys, &admin_pk, vec![], 3).await;
let after = fetch_authority(&bed.relay, &community).await;
assert!(
!after.roles.is_admin(&admin_pk.to_hex()),
"the owner's demotion folds",
);
assert!(
!after.roles.grants.iter().any(|g| g.member == bystander.to_hex()),
"and nothing the demoted author wrote is honored afterwards — authority is \
resolved against the CURRENT roster, which is what the citation was only ever \
a scheduling hint for",
);
}
#[tokio::test]
async fn an_uncited_edition_folds_on_rank_alone_and_never_escalates() {
// CORD-04 §5 calls the `vac` a SYNC FLOOR, not the verdict: a verifier waits
// until it has synced the cited Grant, then resolves rank against its CURRENT
// roster. Refusing an edition that cites NOTHING promoted that sync aid into an
// authority requirement — and pre-citation clients emitted no `vac` at all, so
// whole live rosters folded to nothing while a lenient implementation read the
// same plane fine.
//
// What actually prevents escalation is rank, and rank is unchanged. This pins
// both halves: a genuine in-rank edition folds without a citation, and an
// out-of-rank one does not, cited or otherwise.
let (bed, owner, admin) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Uncited", bed.relays.clone(), None).await.unwrap();
let admin_pk = admin.keys.public_key();
let rid = "c3".repeat(32);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::admin().0), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &admin_pk, vec![rid.clone()], 1).await;
// A role BENEATH the admin (they sit at position 1).
let low_rid = "c4".repeat(32);
let mut low = admin_role(&low_rid, Permissions::admin().0);
low.position = 5;
publish_role(&bed.relay, &community, &owner.keys, &low, 1).await;
// 1. GENUINE and in-rank, citing nothing → folds.
let bystander = Keys::generate().public_key();
publish_grant_citing(&bed.relay, &community, &admin.keys, &bystander, vec![low_rid.clone()], 1, None).await;
let view = fetch_authority(&bed.relay, &community).await;
assert!(
view.roles.grants.iter().any(|g| g.member == bystander.to_hex()),
"an uncited edition from an author the roster DOES authorize, acting beneath \
their own rank, is genuine and must fold",
);
assert!(view.roles.is_admin(&admin_pk.to_hex()), "the owner-authored grant still folds");
// 2. ESCALATION, uncited: a stranger the roster authorizes for nothing.
let stranger = Keys::generate();
let victim = Keys::generate().public_key();
publish_grant_citing(&bed.relay, &community, &stranger, &victim, vec![low_rid.clone()], 1, None).await;
let view = fetch_authority(&bed.relay, &community).await;
assert!(
!view.roles.grants.iter().any(|g| g.member == victim.to_hex()),
"an uncited edition from an UNAUTHORIZED author must never fold — dropping the \
citation requirement must not become a way in",
);
// 3. ESCALATION, uncited, by a real admin acting AT their own rank: equal
// cannot act on equal, citation or not.
let peer = Keys::generate().public_key();
publish_grant_citing(&bed.relay, &community, &admin.keys, &peer, vec![rid.clone()], 1, None).await;
let view = fetch_authority(&bed.relay, &community).await;
assert!(
!view.roles.grants.iter().any(|g| g.member == peer.to_hex()),
"an authorized author still cannot grant AT their own rank — rank is what \
stops escalation, and it is untouched",
);
// 4. ESCALATION, uncited REVOCATION — the case that makes the citation
// load-bearing. A strip names no roles, so the rank gate has no position to
// check and passes vacuously; the citation is the only thing standing there.
// An uncited edition may ADD authority, never remove it.
publish_grant_citing(&bed.relay, &community, &stranger, &bystander, vec![], 9, None).await;
let view = fetch_authority(&bed.relay, &community).await;
assert!(
view.roles.grants.iter().any(|g| g.member == bystander.to_hex()),
"an uncited empty grant must NOT strip a member — a revocation's rank check is \
vacuous, so tolerating it uncited hands any stranger a demotion primitive",
);
}
#[tokio::test]
async fn a_join_landing_inside_the_ban_window_survives_the_unban() {
// The invite is deliberately ungated, so a fresh Join can arrive seconds
// BEFORE the unban edition. It must reach the store (banned = a fold
// verdict, not a storage verdict) so the unban resurrects the member —
// dropped at ingest, they stayed invisible forever.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Window", bed.relays.clone(), None).await.unwrap();
let member_pk = member.keys.public_key();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
// Locally banned (edition folded at t=1000s), with the outliving mark.
crate::db::community::set_community_banlist(&cid_hex, &[member_pk.to_hex()], 1_000).unwrap();
crate::db::community::merge_community_ban_marks(&cid_hex, &[(member_pk.to_hex(), 1_000u64)].into_iter().collect()).unwrap();
// Their Join lands 60s after the ban mark, while the banlist still says banned.
let join = guestbook::GuestbookEvent { epoch: None, observed_at: None,
rumor_id: [9u8; 32],
entry: guestbook::GuestbookEntry::Join { member: member_pk, invited_by: None, at_ms: 1_060_000 },
};
assert!(ingest_guestbook_event(&community, join, 1_060).unwrap(), "stored while banned");
assert!(
!stored_memberlist(&community).unwrap().contains(&member_pk),
"while banned, the fold keeps them out"
);
// The unban folds: same store, no refetch needed — the Join resurrects them.
crate::db::community::set_community_banlist(&cid_hex, &[], 2_000).unwrap();
assert!(
stored_memberlist(&community).unwrap().contains(&member_pk),
"after the unban the raced Join makes them a member again"
);
}
#[tokio::test]
async fn lifting_a_ban_writes_its_departure_dated_at_the_ban() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Lift", bed.relays.clone(), None).await.unwrap();
let member_pk = member.keys.public_key();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let join = guestbook::GuestbookEvent { epoch: None, observed_at: None, rumor_id: [7u8; 32],
entry: guestbook::GuestbookEntry::Join { member: member_pk, invited_by: None, at_ms: 1_000_000 },
};
assert!(ingest_guestbook_event(&community, join, 0).unwrap());
set_banlist(&bed.relay, &community, &[member_pk.to_hex()]).await.unwrap();
set_members_banned(&bed.relay, community.id(), &[member_pk], false).await.unwrap();
let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let mark = crate::db::community::get_community_ban_marks(&cid_hex).unwrap()[&member_pk.to_hex()];
assert_eq!(stored_kick_at(&fresh, &member_pk), Some(mark * 1000), "the departure is dated at the ban");
assert!(!stored_memberlist(&fresh).unwrap().contains(&member_pk), "the pre-ban Join no longer counts here");
assert!(!wire_guestbook_members(&bed.relay, &fresh).await.unwrap().contains(&member_pk), "nor for a reader who never saw the ban");
let back = guestbook::GuestbookEvent { epoch: None, observed_at: None, rumor_id: [8u8; 32],
entry: guestbook::GuestbookEntry::Join { member: member_pk, invited_by: None, at_ms: mark * 1000 + 1 },
};
assert!(ingest_guestbook_event(&fresh, back, 0).unwrap());
assert!(stored_memberlist(&fresh).unwrap().contains(&member_pk), "a Join after the ban is a return");
}
/// [`MemoryRelay`] that refuses one plane's publishes, as a relay that never took them.
struct Refuses<'a>(&'a MemoryRelay, PublicKey);
#[async_trait::async_trait]
impl Transport for Refuses<'_> {
async fn publish(&self, event: &Event, relays: &[String]) -> Result<(), String> {
if event.pubkey == self.1 {
return Err("refused".into());
}
self.0.publish(event, relays).await
}
async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
self.0.fetch(query, relays).await
}
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
self.0.fetch_plane(plane, query, relays).await
}
async fn publish_durable(&self, event: &Event, relays: &[String]) -> Result<(), String> {
self.publish(event, relays).await
}
}
#[tokio::test]
async fn a_lost_join_is_restored_once_dated_by_the_plane() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Lost", bed.relays.clone(), None).await.unwrap();
send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
let plane = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch).pk();
bed.swap_to(&member);
let me = member.keys.public_key();
let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &me).await;
let joined = accept_direct_invite(&Refuses(&bed.relay, plane), &invite_wrap).await.unwrap();
assert!(!wire_guestbook_members(&bed.relay, &joined).await.unwrap().contains(&me), "the Join never landed");
sync_guestbook(&bed.relay, &joined).await.unwrap();
assert!(!heal_my_join(&bed.relay, &joined).await.unwrap(), "the session that sent it waits for the next");
// A later session reads the whole plane and finds no Join of theirs.
bed.swap_to(&owner);
bed.swap_to(&member);
sync_guestbook(&bed.relay, &joined).await.unwrap();
assert!(heal_my_join(&bed.relay, &joined).await.unwrap());
assert!(!heal_my_join(&bed.relay, &joined).await.unwrap(), "once a session");
let (events, _, _) = fetch_guestbook_events(&bed.relay, &joined, 0).await.unwrap();
let mine: Vec<u64> = events
.iter()
.filter_map(|e| match &e.entry {
guestbook::GuestbookEntry::Join { member, at_ms, .. } if *member == me => Some(*at_ms),
_ => None,
})
.collect();
let oldest = events.iter().filter(|e| !matches!(&e.entry, guestbook::GuestbookEntry::Join { member, .. } if *member == me)).map(|e| e.entry.at_ms()).min();
assert_eq!(mine.len(), 1, "one Join on the wire");
assert_eq!(Some(mine[0]), oldest, "dated by the plane's oldest entry, the same from any of their devices");
assert!(wire_guestbook_members(&bed.relay, &joined).await.unwrap().contains(&me));
}
#[tokio::test]
async fn a_stale_root_admin_write_is_refused_not_misdirected() {
// The ban→unban race: a Ban's refound buries the old root over several
// publishes while a concurrently-issued command still holds the
// pre-commit struct. That unban used to land on the buried control
// plane — "succeeding" while no reader would ever fold it — and a
// concurrently-minted invite stranded its joiner on the dead epoch.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Race", bed.relays.clone(), None).await.unwrap();
let member_pk = member.keys.public_key();
set_banlist(&bed.relay, &community, &[member_pk.to_hex()]).await.unwrap();
let _rotated = refound_community(&bed.relay, &community, &[member_pk]).await.unwrap();
// The stale-struct unban is REFUSED (retryable), never misdirected.
let err = set_banlist(&bed.relay, &community, &[]).await.unwrap_err();
assert!(err.contains("re-founded"), "unban: {err}");
// A stale invite must not mint dead-epoch key material.
let err = send_direct_invite(&bed.relay, &community, &member_pk, None, None).await.unwrap_err();
assert!(err.contains("re-founded"), "invite: {err}");
// Neither is a kick allowed to ride the buried guestbook.
let err = kick_member(&bed.relay, &community, &member_pk).await.unwrap_err();
assert!(err.contains("re-founded"), "kick: {err}");
// The retry path: a fresh load lands the unban on the LIVING plane.
let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
set_banlist(&bed.relay, &fresh, &[]).await.unwrap();
let view = fetch_authority(&bed.relay, &fresh).await;
assert!(view.banned.is_empty(), "the retried unban actually unbans");
}
/// [`MemoryRelay`] with a cooperative yield before every call, so two units
/// driven by one `join!` genuinely interleave at each network boundary — on
/// the single-threaded test runtime the bare relay resolves without yielding,
/// the first unit runs to completion, and the race never happens.
struct YieldyRelay<'a>(&'a MemoryRelay);
#[async_trait::async_trait]
impl Transport for YieldyRelay<'_> {
async fn publish(&self, event: &Event, relays: &[String]) -> Result<(), String> {
crate::rt::yield_now().await;
self.0.publish(event, relays).await
}
async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
crate::rt::yield_now().await;
self.0.fetch(query, relays).await
}
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
crate::rt::yield_now().await;
self.0.fetch_plane(plane, query, relays).await
}
async fn publish_durable(&self, event: &Event, relays: &[String]) -> Result<(), String> {
crate::rt::yield_now().await;
self.0.publish_durable(event, relays).await
}
}
#[tokio::test]
async fn concurrent_bans_compose_instead_of_erasing_each_other() {
// The SDK spawns a handler task per message, so a spam wave runs N ban
// units concurrently. Unserialized, both read the pre-sibling banlist,
// the second head erases the first target at every reader, and the
// refound compacts that erasure into the new epoch permanently.
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Wave", bed.relays.clone(), None).await.unwrap();
let a = Keys::generate().public_key();
let b = Keys::generate().public_key();
let yieldy = YieldyRelay(&bed.relay);
let (wave_a, wave_b) = ([a], [b]);
let (ra, rb) = tokio::join!(
set_members_banned(&yieldy, community.id(), &wave_a, true),
set_members_banned(&yieldy, community.id(), &wave_b, true),
);
ra.unwrap();
rb.unwrap();
let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(fresh.root_epoch, Epoch(2), "each single ban still performed its own read cut");
let view = fetch_authority(&bed.relay, &fresh).await;
assert!(
view.banned.contains(&a.to_hex()) && view.banned.contains(&b.to_hex()),
"both racing bans landed: {:?}",
view.banned
);
}
#[tokio::test]
async fn bans_stacked_behind_a_rotation_coalesce_into_one_read_cut() {
// Human-speed serial bans: the leader's read cut holds the lock for a
// whole rotation, so bans arriving meanwhile deposit intents. The next
// lock holder drains ALL of them — one edition, one rotation, however
// many stacked. Worst case for a burst of N is 2 rotations, never N.
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Stack", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let banlist_hex = crate::simd::hex::bytes_to_hex_32(&super::super::derive::banlist_locator(community.id()));
let (a, b, c, d) = (
Keys::generate().public_key(),
Keys::generate().public_key(),
Keys::generate().public_key(),
Keys::generate().public_key(),
);
let yieldy = YieldyRelay(&bed.relay);
let (wa, wb, wc, wd) = ([a], [b], [c], [d]);
// The first future drains itself and rotates; the other three stack
// behind that rotation and coalesce under the next leader.
let (ra, rb, rc, rd) = tokio::join!(
set_members_banned(&yieldy, community.id(), &wa, true),
set_members_banned(&yieldy, community.id(), &wb, true),
set_members_banned(&yieldy, community.id(), &wc, true),
set_members_banned(&yieldy, community.id(), &wd, true),
);
ra.unwrap();
rb.unwrap();
rc.unwrap();
rd.unwrap();
let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(fresh.root_epoch, Epoch(2), "leader rotation + ONE coalesced rotation, never four");
let (version, _) = crate::db::community::get_edition_head(&cid_hex, &banlist_hex).unwrap().unwrap();
assert_eq!(version, 2, "two editions total: the leader's and the coalesced drain's");
let view = fetch_authority(&bed.relay, &fresh).await;
for pk in [a, b, c, d] {
assert!(view.banned.contains(&pk.to_hex()), "{} missing from the fold", pk.to_hex());
}
}
#[tokio::test]
async fn a_stacked_ban_and_unban_coalesce_in_arrival_order() {
// The drain applies intents in arrival order over the evolving list, so
// ban(X) … unban(X) stacked behind one rotation nets X out entirely and
// only the net newly-banned member costs a read cut.
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Net", bed.relays.clone(), None).await.unwrap();
let x = Keys::generate().public_key();
let y = Keys::generate().public_key();
let yieldy = YieldyRelay(&bed.relay);
let (wx, wy) = ([x], [y]);
let (rx1, ry, rx2) = tokio::join!(
set_members_banned(&yieldy, community.id(), &wx, true), // leader: rotates on X
set_members_banned(&yieldy, community.id(), &wy, true), // stacked
set_members_banned(&yieldy, community.id(), &wx, false), // stacked: nets X back out
);
rx1.unwrap();
ry.unwrap();
rx2.unwrap();
let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(fresh.root_epoch, Epoch(2), "X's rotation + one coalesced rotation for Y");
let view = fetch_authority(&bed.relay, &fresh).await;
assert!(!view.banned.contains(&x.to_hex()), "the stacked unban netted X out");
assert!(view.banned.contains(&y.to_hex()), "Y's stacked ban landed");
}
#[tokio::test]
async fn a_second_member_folds_every_stacked_ban() {
// Derek's observer divergence, inverted: the whole point of composing the
// batch correctly is that an INDEPENDENT reader folding the same plane
// agrees. A fresh joiner (separate account DB, post-rotation bundle) must
// see every stacked ban — not just the leader's own echo.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Agree", bed.relays.clone(), None).await.unwrap();
let a = Keys::generate().public_key();
let b = Keys::generate().public_key();
let yieldy = YieldyRelay(&bed.relay);
let (wa, wb) = ([a], [b]);
let (ra, rb) = tokio::join!(
set_members_banned(&yieldy, community.id(), &wa, true),
set_members_banned(&yieldy, community.id(), &wb, true),
);
ra.unwrap();
rb.unwrap();
// Post-rotation bundle, exactly what a live link would serve now.
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let bundle = bundle_of(&held, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&member);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
let _ = follow_control(&bed.relay, &joined).await;
let view = fetch_authority(&bed.relay, &joined).await;
assert!(
view.banned.contains(&a.to_hex()) && view.banned.contains(&b.to_hex()),
"an independent reader folds BOTH stacked bans: {:?}",
view.banned
);
}
#[tokio::test]
async fn a_net_zero_batch_publishes_no_edition() {
// ban(X) + unban(X) stacked in one drain nets to the original list — the
// batch must not spend an edition (or a rotation) publishing a no-op.
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Noop", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let banlist_hex = crate::simd::hex::bytes_to_hex_32(&super::super::derive::banlist_locator(community.id()));
let x = Keys::generate().public_key();
// The leader's slot is taken by a harmless real ban so X's ban+unban land
// in ONE coalesced drain together.
let decoy = Keys::generate().public_key();
let yieldy = YieldyRelay(&bed.relay);
let (wd, wx) = ([decoy], [x]);
let (rd, r1, r2) = tokio::join!(
set_members_banned(&yieldy, community.id(), &wd, true),
set_members_banned(&yieldy, community.id(), &wx, true),
set_members_banned(&yieldy, community.id(), &wx, false),
);
rd.unwrap();
r1.unwrap();
r2.unwrap();
let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(fresh.root_epoch, Epoch(1), "only the decoy's rotation — the net-zero drain rotated nothing");
let (version, _) = crate::db::community::get_edition_head(&cid_hex, &banlist_hex).unwrap().unwrap();
assert_eq!(version, 1, "only the decoy's edition — the net-zero drain published nothing");
let view = fetch_authority(&bed.relay, &fresh).await;
assert!(!view.banned.contains(&x.to_hex()));
assert!(view.banned.contains(&decoy.to_hex()));
}
/// Fetches fine, refuses every publish — the dead-network shape.
struct BrokenPublish<'a>(&'a MemoryRelay);
#[async_trait::async_trait]
impl Transport for BrokenPublish<'_> {
async fn publish(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
crate::rt::yield_now().await;
Err("relay refused".to_string())
}
async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
crate::rt::yield_now().await;
self.0.fetch(query, relays).await
}
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
crate::rt::yield_now().await;
self.0.fetch_plane(plane, query, relays).await
}
async fn publish_durable(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
crate::rt::yield_now().await;
Err("relay refused".to_string())
}
}
#[tokio::test]
async fn a_failed_publish_answers_every_stacked_caller_and_never_hangs() {
// The batch's shared fate: when the edition can't land, every stacked
// intent must resolve with the error — a waiter left parked on a dead
// oneshot would hang a moderation bot forever.
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Dead", bed.relays.clone(), None).await.unwrap();
let a = Keys::generate().public_key();
let b = Keys::generate().public_key();
let broken = BrokenPublish(&bed.relay);
let (wa, wb) = ([a], [b]);
let (ra, rb) = crate::rt::time::timeout(
std::time::Duration::from_secs(30),
async {
tokio::join!(
set_members_banned(&broken, community.id(), &wa, true),
set_members_banned(&broken, community.id(), &wb, true),
)
},
)
.await
.expect("stacked callers must resolve, never hang");
assert!(ra.is_err(), "the leader surfaced the publish failure");
assert!(rb.is_err(), "the stacked caller surfaced it too");
// Nothing landed: a later fold shows no bans.
let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let view = fetch_authority(&bed.relay, &fresh).await;
assert!(view.banned.is_empty(), "no half-published state: {:?}", view.banned);
assert_eq!(fresh.root_epoch, Epoch(0), "no rotation on a failed edition");
}
#[tokio::test]
async fn a_poison_intent_fails_alone_not_its_batchmates() {
// Per-intent verdicts: an add that busts the 500 ceiling answers ITS
// caller with the refusal while its batch-mates publish normally.
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Poison", bed.relays.clone(), None).await.unwrap();
// Pre-fill to 498 so the leader lands 499, the first stacked ban lands
// exactly 500, and the second stacked ban would be 501.
let filler: Vec<String> = (0..498).map(|i| format!("{i:064x}")).collect();
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
set_banlist(&bed.relay, &held, &filler).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::set_community_banlist(&cid_hex, &filler, 1).unwrap();
let (a, x, y) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
let yieldy = YieldyRelay(&bed.relay);
let (wa, wx, wy) = ([a], [x], [y]);
let (ra, rx, ry) = tokio::join!(
set_members_banned(&yieldy, community.id(), &wa, true),
set_members_banned(&yieldy, community.id(), &wx, true),
set_members_banned(&yieldy, community.id(), &wy, true),
);
ra.unwrap();
rx.unwrap();
let err = ry.unwrap_err();
assert!(err.contains("ceiling"), "the over-cap intent failed alone: {err}");
let list = crate::db::community::get_community_banlist(&cid_hex).unwrap();
assert_eq!(list.len(), 500, "the batch published up to the ceiling");
assert!(list.contains(&x.to_hex()) && !list.contains(&y.to_hex()));
}
#[tokio::test]
async fn ban_many_is_one_edition_one_refound_for_the_whole_wave() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Purge", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let banlist_hex = crate::simd::hex::bytes_to_hex_32(&super::super::derive::banlist_locator(community.id()));
let wave: Vec<PublicKey> = (0..3).map(|_| Keys::generate().public_key()).collect();
set_members_banned(&bed.relay, community.id(), &wave, true).await.unwrap();
let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(fresh.root_epoch, Epoch(1), "one refound for the whole wave, not one per target");
let (version, _) = crate::db::community::get_edition_head(&cid_hex, &banlist_hex).unwrap().unwrap();
assert_eq!(version, 1, "one banlist edition carried the whole wave");
let view = fetch_authority(&bed.relay, &fresh).await;
for pk in &wave {
assert!(view.banned.contains(&pk.to_hex()), "{} missing from the fold", pk.to_hex());
}
// The reductive mirror: unban two of three in one edition, no read cut.
set_members_banned(&bed.relay, community.id(), &wave[..2], false).await.unwrap();
let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(fresh.root_epoch, Epoch(1), "an unban rotates nothing");
let view = fetch_authority(&bed.relay, &fresh).await;
assert_eq!(view.banned.len(), 1, "reductive: exactly the un-unbanned target remains");
assert!(view.banned.contains(&wave[2].to_hex()));
}
#[tokio::test]
async fn a_batch_past_the_banlist_cap_refuses_before_publishing() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Cap", bed.relays.clone(), None).await.unwrap();
let wave: Vec<PublicKey> = (0..=crate::community::v2::roles::MAX_BANLIST).map(|_| Keys::generate().public_key()).collect();
let err = set_members_banned(&bed.relay, community.id(), &wave, true).await.unwrap_err();
assert!(err.contains("ceiling"), "refused at the cap: {err}");
let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
assert_eq!(fresh.root_epoch, Epoch(0), "nothing rotated");
let view = fetch_authority(&bed.relay, &fresh).await;
assert!(view.banned.is_empty(), "nothing published");
}
#[tokio::test]
async fn an_uncited_kick_from_an_admin_is_not_honored() {
// CORD-04 §5: a non-owner authority action must name the Grant it acts
// under, and the reader refuses until it holds that Grant. Emitting the
// `vac` without checking it buys nothing — a demoted admin's kick would
// still land on any client that hadn't synced the demotion.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Uncited", bed.relays.clone(), None).await.unwrap();
let admin = Keys::generate();
let member_pk = member.keys.public_key();
grant_admin(&bed.relay, &community, &admin.public_key()).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let view = fetch_authority(&bed.relay, &community).await;
crate::db::community::set_community_roles(&cid_hex, &view.roles, 1_000).unwrap();
let entity_id = super::super::derive::grant_locator(community.id(), &admin.public_key().to_bytes());
let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
let (version, edition_hash) = crate::db::community::get_edition_head(&cid_hex, &entity_hex).unwrap().unwrap();
let cite = crate::community::edition::AuthorityCitation { entity_id, version, edition_hash };
let joined = guestbook::GuestbookEvent { epoch: None, observed_at: None,
rumor_id: [1u8; 32],
entry: guestbook::GuestbookEntry::Join { member: member_pk, invited_by: None, at_ms: 1_000 },
};
let kick = |citation, id: u8, at| guestbook::GuestbookEvent { epoch: None, observed_at: None,
rumor_id: [id; 32],
entry: guestbook::GuestbookEntry::Kick { actor: admin.public_key(), target: member_pk, citation, at_ms: at },
};
let roles = crate::db::community::get_community_roles(&cid_hex).unwrap();
let empty_bans = std::collections::BTreeSet::new();
let empty_marks = std::collections::BTreeMap::new();
let fold = |evs: &[guestbook::GuestbookEvent]| {
fold_members(&community, evs, Default::default(), &roles, &empty_bans, &empty_marks).unwrap()
};
assert!(
fold(&[joined.clone(), kick(None, 2, 2_000)]).contains(&member_pk),
"an uncited kick from an admin is not honored"
);
assert!(
!fold(&[joined.clone(), kick(Some(cite.clone()), 3, 3_000)]).contains(&member_pk),
"the same kick WITH its synced citation removes them"
);
crate::db::community::set_community_banlist(&cid_hex, &[admin.public_key().to_hex()], 4_000).unwrap();
assert!(
fold(&[joined, kick(Some(cite), 3, 3_000)]).contains(&member_pk),
"a banned admin's Guestbook events count for nothing (CORD-04 §4)"
);
}
#[tokio::test]
async fn kicking_an_admin_strips_their_roles_first() {
// CORD-04 §6 composition: Role Removal THEN the directive. Kicking without the
// strip leaves the target out of the memberlist but still holding every
// management bit, so every client keeps honoring their control editions.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Compose", bed.relays.clone(), None).await.unwrap();
let member_pk = member.keys.public_key();
let member_hex = member_pk.to_hex();
let owner_hex = owner.keys.public_key().to_hex();
grant_admin(&bed.relay, &community, &member_pk).await.unwrap();
assert!(fetch_authority(&bed.relay, &community).await.roles.is_admin(&member_hex));
kick_member(&bed.relay, &community, &member_pk).await.unwrap();
let view = fetch_authority(&bed.relay, &community).await;
assert!(!view.roles.is_admin(&member_hex), "the kick stripped their rank");
assert!(
!view.roles.is_authorized(&member_hex, Some(&owner_hex), Permissions::MANAGE_ROLES),
"a kicked admin holds no bit"
);
assert!(
!memberlist(&bed.relay, &community).await.unwrap().contains(&member_pk),
"and the directive still removed them"
);
}
#[tokio::test]
async fn grant_admin_mints_one_deterministic_role_and_revoke_strips_it() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Adm", bed.relays.clone(), None).await.unwrap();
let member_pk = member.keys.public_key();
let member_hex = member_pk.to_hex();
let owner_hex = owner.keys.public_key().to_hex();
grant_admin(&bed.relay, &community, &member_pk).await.unwrap();
let view = fetch_authority(&bed.relay, &community).await;
assert!(view.roles.is_admin(&member_hex), "the grant folds as admin");
assert!(view.roles.is_authorized(&member_hex, Some(&owner_hex), Permissions::MANAGE_ROLES));
// A second grant (any device) converges on the SAME role entity — and a
// repeat is a no-op, not a version bump.
let second = Keys::generate().public_key();
grant_admin(&bed.relay, &community, &second).await.unwrap();
grant_admin(&bed.relay, &community, &member_pk).await.unwrap();
let view = fetch_authority(&bed.relay, &community).await;
assert_eq!(view.roles.roles.len(), 1, "one Admin role, never a fork");
assert!(view.roles.is_admin(&member_hex) && view.roles.is_admin(&second.to_hex()));
let grant = view.roles.grants.iter().find(|g| g.member == member_hex).unwrap();
assert_eq!(grant.role_ids.len(), 1, "no duplicate role id in the grant");
// Revoke strips ONLY the admin role and de-authorizes.
revoke_admin(&bed.relay, &community, &member_pk).await.unwrap();
let view = fetch_authority(&bed.relay, &community).await;
assert!(!view.roles.is_admin(&member_hex), "revoked");
assert!(view.roles.is_admin(&second.to_hex()), "the other admin is untouched");
assert!(!view.roles.is_authorized(&member_hex, Some(&owner_hex), Permissions::KICK));
}
#[tokio::test]
async fn follow_control_persists_the_roster_for_sync_local_reads() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Persist", bed.relays.clone(), None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let member_hex = member.keys.public_key().to_hex();
grant_admin(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
// The passive follow folds + persists; the read is then LOCAL.
follow_control(&bed.relay, &community).await.unwrap().updated;
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert!(roster.is_admin(&member_hex), "the persisted roster reads back without a fetch");
// A withholding relay serves nothing — an empty fold raises no gap flag, and
// the stored roster must be RETAINED, never wiped.
let withholding = MemoryRelay::new();
let _ = follow_control(&withholding, &community).await;
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert!(roster.is_admin(&member_hex), "withholding never shrinks standing");
// A real revocation (a NEWER grant edition) does replace it.
revoke_admin(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
follow_control(&bed.relay, &community).await.unwrap().updated;
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
assert!(!roster.is_admin(&member_hex), "the revoke folds + persists");
}
#[tokio::test]
async fn grant_admin_is_refused_for_a_non_owner_and_publishes_nothing() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "NoSquat", bed.relays.clone(), None).await.unwrap();
bed.swap_to(&member);
let err = grant_admin(&bed.relay, &community, &member.keys.public_key()).await.unwrap_err();
assert!(err.contains("owner"), "refused before any publish: {err}");
// The deterministic admin-role entity stays unsquatted — the owner's later
// legitimate mint is version 1 and folds cleanly.
bed.swap_to(&owner);
let view = fetch_authority(&bed.relay, &community).await;
assert!(view.roles.roles.is_empty(), "no role edition landed");
grant_admin(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
let view = fetch_authority(&bed.relay, &community).await;
assert!(view.roles.is_admin(&member.keys.public_key().to_hex()));
}
#[tokio::test]
async fn grant_admin_merges_other_roles_and_refuses_a_withheld_grant() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Merge", bed.relays.clone(), None).await.unwrap();
let member_pk = member.keys.public_key();
// The member already holds a Mod role, granted through the real send path
// (so this device's floors track both entities).
let mod_rid = crate::simd::hex::bytes_to_hex_32(&[0x66; 32]);
set_role(&bed.relay, &community, &admin_role(&mod_rid, Permissions::BAN)).await.unwrap();
grant_roles(&bed.relay, &community, &member_pk, vec![mod_rid.clone()]).await.unwrap();
// With no wrap of the grant held and a relay that serves none, the merge must refuse: a
// blind push would erase the Mod role at a higher version.
let withholding = MemoryRelay::new();
forget_held(&community);
let err = grant_admin(&withholding, &community, &member_pk).await.unwrap_err();
assert!(err.contains("could not be fetched"), "withheld grant refused: {err}");
// Against the full relay the merge preserves the Mod role.
grant_admin(&bed.relay, &community, &member_pk).await.unwrap();
let view = fetch_authority(&bed.relay, &community).await;
let grant = view.roles.grants.iter().find(|g| g.member == member_pk.to_hex()).unwrap();
assert_eq!(grant.role_ids.len(), 2, "admin ADDED to the existing grant, not replacing it");
assert!(grant.role_ids.contains(&mod_rid));
}
#[tokio::test]
async fn fetch_authority_reflects_a_granted_admin() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Auth", bed.relays.clone(), None).await.unwrap();
let rid = crate::simd::hex::bytes_to_hex_32(&[0x5a; 32]);
publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid], 1).await;
let view = fetch_authority(&bed.relay, &community).await;
let member_hex = member.keys.public_key().to_hex();
assert!(view.roles.is_admin(&member_hex), "the granted member folds as admin");
assert!(
view.roles.is_authorized(&member_hex, Some(&owner.keys.public_key().to_hex()), Permissions::KICK),
"an ADMIN_ALL grant carries KICK"
);
assert!(view.banned.is_empty());
}
// ── Pins (CORD-04 §7) — fold, authority, and the silent Admin widening ──
/// The full wire round trip: a real message pinned into a published
/// edition, folded by the control follow, persisted, and read back proven.
#[tokio::test]
async fn a_pin_edition_folds_persists_and_reads_back() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Pinsville", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let ch_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
send_message(&relay, &community, &general, "pin-worthy").await.unwrap();
let page = fetch_channel(&relay, &community, &general, 10).await.unwrap();
let opened = page
.iter()
.find_map(|f| match &f.event {
ChatEvent::Message { opened, .. } => Some(opened.clone()),
_ => None,
})
.expect("the sent message reads back");
let ch = community.channels[0].clone();
let conv = channel_conv_key_at(&community, &ch, 0).expect("owner holds the public plane key");
let entry = crate::community::v2::pins::build_pin_entry(&opened, &conv, &ch_hex).unwrap();
let content = crate::community::v2::pins::serialize_public_pin_list(&[entry]).unwrap();
let eid = crate::community::v2::derive::pins_locator(community.id(), &general);
publish_control_edition(&relay, &community, vsk::PINS, &eid, &content).await.unwrap();
follow_control(&relay, &community).await.unwrap().updated;
let read = read_channel_pins(&community, &general).unwrap();
assert!(!read.sealed);
assert!(read.version >= 1, "the folded head persisted");
assert_eq!(read.pins.len(), 1);
assert_eq!(read.pins[0].content, "pin-worthy");
assert_eq!(read.pins[0].rumor_id, opened.rumor_id.to_hex());
}
#[tokio::test]
async fn a_fresh_join_sees_pins_and_the_banlist_without_waiting_for_a_follow() {
// The join's verification walk already folds the control plane, so pins and
// the banlist must persist FROM THE JOIN — deferring them to the follow
// worker's queued re-walk left a fresh member pins-blind (and rendering a
// banned author) for the whole queue delay.
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "PinJoin", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
let ch_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
send_message(&bed.relay, &community, &general, "pin-worthy").await.unwrap();
let page = fetch_channel(&bed.relay, &community, &general, 10).await.unwrap();
let opened = page
.iter()
.find_map(|f| match &f.event {
ChatEvent::Message { opened, .. } => Some(opened.clone()),
_ => None,
})
.expect("the sent message reads back");
let ch = community.channels[0].clone();
let conv = channel_conv_key_at(&community, &ch, 0).unwrap();
let entry = crate::community::v2::pins::build_pin_entry(&opened, &conv, &ch_hex).unwrap();
let content = crate::community::v2::pins::serialize_public_pin_list(&[entry]).unwrap();
let eid = crate::community::v2::derive::pins_locator(community.id(), &general);
publish_control_edition(&bed.relay, &community, vsk::PINS, &eid, &content).await.unwrap();
let spammer = Keys::generate().public_key().to_hex();
set_banlist(&bed.relay, &community, std::slice::from_ref(&spammer)).await.unwrap();
let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
let bundle_json = serde_json::to_string(&bundle).unwrap();
bed.swap_to(&member);
let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
// Deliberately NO follow_control here — the join alone must suffice.
let read = read_channel_pins(&joined, &general).unwrap();
assert!(!read.sealed);
assert_eq!(read.pins.len(), 1, "pins visible the instant the join returns");
assert_eq!(read.pins[0].content, "pin-worthy");
let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
let banlist = crate::db::community::get_community_banlist(&cid_hex).unwrap();
assert!(banlist.contains(&spammer), "the banlist is enforced from the join, not the first follow");
}
/// CORD-04 §5: a pins edition from an author holding no PIN_MESSAGES never
/// becomes the head — the fold's authority gate covers the new entity.
#[tokio::test]
async fn an_unauthorized_pin_edition_never_folds() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Gated", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let rogue = Keys::generate();
let group = control::ControlPlane::of(&community).write_group().unwrap();
let eid = crate::community::v2::derive::pins_locator(community.id(), &general);
let rumor = control::build_edition_rumor(rogue.public_key(), vsk::PINS, &eid, 1, None, r#"{"entries":[]}"#, 2_000, None);
let (wrap, _) = control::seal_control_edition(&rumor, &group, &rogue, Timestamp::from_secs(2_000)).unwrap();
relay.publish(&wrap, &community.relays).await.unwrap();
follow_control(&relay, &community).await.unwrap().updated;
let read = read_channel_pins(&community, &general).unwrap();
assert_eq!(read.version, 0, "an unauthorized edition never persists a head");
assert!(read.pins.is_empty());
}
/// The silent owner-side widening: a pre-pins Admin role (founding mask)
/// gains PIN_MESSAGES as one edition of the same entity; idempotent after.
#[tokio::test]
async fn owner_silently_widens_a_legacy_admin_role() {
let (_tmp, _guard, owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Legacy", vec!["wss://r".into()], None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let rid = crate::simd::hex::bytes_to_hex_32(&[0x5d; 32]);
// An Admin role exactly as a pre-pins build published it.
let legacy = Role {
role_id: rid.clone(),
name: "Admin".into(),
position: 1,
permissions: Permissions(Permissions::ADMIN_FOUNDING_MASK),
scope: RoleScope::Server,
color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
};
publish_role(&relay, &community, &owner, &legacy, 1).await;
follow_control(&relay, &community).await.unwrap().updated;
assert!(upgrade_admin_role_pin_bit(&relay, &community).await.unwrap(), "the widening publishes");
follow_control(&relay, &community).await.unwrap().updated;
let roles = crate::db::community::get_community_roles(&cid_hex).unwrap();
let widened = roles.roles.iter().find(|r| r.role_id == rid).expect("same entity");
assert!(widened.permissions.contains(Permissions::PIN_MESSAGES), "bit 11 landed");
assert!(widened.permissions.contains(Permissions::ADMIN_FOUNDING_MASK), "nothing stripped");
// Second call: nothing left to widen.
assert!(!upgrade_admin_role_pin_bit(&relay, &community).await.unwrap());
}
/// §7 deletion duty: the author-curator's own deleted message leaves the
/// list as an immediate omitting edition.
#[tokio::test]
async fn the_deletion_duty_omits_a_pinned_message() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Duties", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let ch_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
let rumor_id = send_message(&relay, &community, &general, "soon deleted").await.unwrap();
let page = fetch_channel(&relay, &community, &general, 10).await.unwrap();
let opened = page
.iter()
.find_map(|f| match &f.event {
ChatEvent::Message { opened, .. } => (opened.rumor_id.to_hex() == rumor_id).then(|| opened.clone()),
_ => None,
})
.unwrap();
let ch = community.channels[0].clone();
let conv = channel_conv_key_at(&community, &ch, 0).unwrap();
let entry = crate::community::v2::pins::build_pin_entry(&opened, &conv, &ch_hex).unwrap();
publish_pin_list(&relay, &community, &ch, &[entry]).await.unwrap();
assert_eq!(read_channel_pins(&community, &general).unwrap().pins.len(), 1);
// The author holds the bit (owner) → the duty publishes the omission at once.
run_pin_duty(&relay, &ch_hex, &rumor_id, None).await.unwrap();
let after = read_channel_pins(&community, &general).unwrap();
assert!(after.pins.is_empty(), "the omitting edition landed");
assert!(after.version >= 2, "a NEW edition, not a local erase");
}
/// §7 edit duty: an edited pinned message gets its proof bundle refreshed,
/// so keyless readers see the revision — and the duty is idempotent.
#[tokio::test]
async fn the_edit_duty_refreshes_a_pinned_proof() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Edits", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let ch_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
let rumor_id = send_message(&relay, &community, &general, "first words").await.unwrap();
let page = fetch_channel(&relay, &community, &general, 10).await.unwrap();
let opened = page
.iter()
.find_map(|f| match &f.event {
ChatEvent::Message { opened, .. } => (opened.rumor_id.to_hex() == rumor_id).then(|| opened.clone()),
_ => None,
})
.unwrap();
let ch = community.channels[0].clone();
let conv = channel_conv_key_at(&community, &ch, 0).unwrap();
let entry = crate::community::v2::pins::build_pin_entry(&opened, &conv, &ch_hex).unwrap();
publish_pin_list(&relay, &community, &ch, &[entry]).await.unwrap();
send_edit(&relay, &community, &general, &rumor_id, "second thoughts", &[]).await.unwrap();
let page = fetch_channel(&relay, &community, &general, 10).await.unwrap();
let edit_opened = page
.iter()
.find_map(|f| match &f.event {
ChatEvent::Edit { opened, .. } => Some(opened.clone()),
_ => None,
})
.expect("the edit reads back");
run_pin_duty(&relay, &ch_hex, &rumor_id, Some(edit_opened.clone())).await.unwrap();
let after = read_channel_pins(&community, &general).unwrap();
assert_eq!(after.pins.len(), 1);
assert_eq!(
after.pins[0].content, "second thoughts",
"the refreshed bundle proves the revision"
);
let v = after.version;
// Same revision again → monotonic guard, no new edition.
run_pin_duty(&relay, &ch_hex, &rumor_id, Some(edit_opened)).await.unwrap();
assert_eq!(read_channel_pins(&community, &general).unwrap().version, v, "idempotent");
}
/// §7 author-side trigger: an own edit's relay echo is a dedup'd duplicate
/// at ingest, so publish_chat's SEND echo must decide the duty itself —
/// otherwise the author's own pin lags behind their message while every
/// other client's follows ("the affected author acts at once").
#[tokio::test]
async fn an_own_edit_echo_carries_the_pin_duty_trigger() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "OwnEdit", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let rumor_id = send_message(&relay, &community, &general, "before").await.unwrap();
send_edit(&relay, &community, &general, &rumor_id, "after", &[]).await.unwrap();
let page = fetch_channel(&relay, &community, &general, 10).await.unwrap();
let edit_event = &page.iter().find(|f| matches!(&f.event, ChatEvent::Edit { .. })).expect("the edit reads back").event;
let msg_event = &page.iter().find(|f| matches!(&f.event, ChatEvent::Message { .. })).expect("the message reads back").event;
let updated = crate::community::v2::inbound::ChatPersist::Updated {
message: crate::types::Message::default(),
edit_event: None,
};
let (target_hex, opened) = own_echo_pin_duty(&updated, edit_event).expect("an applied own edit fires the duty");
assert_eq!(target_hex, rumor_id, "the duty targets the EDITED message, not the edit rumor");
assert_ne!(opened.rumor_id.to_hex(), rumor_id, "and carries the edit's own opened stream for the bundle");
// A fresh message echo is not a duty…
let new = crate::community::v2::inbound::ChatPersist::New(crate::types::Message::default());
assert!(own_echo_pin_duty(&new, msg_event).is_none());
// …and neither is a reaction-shaped Updated on a non-edit event.
assert!(own_echo_pin_duty(&updated, msg_event).is_none());
}
/// §7 Rotator duty: a private-channel rotation republishes the Pin List
/// sealed under the NEW epoch — a member who joins after the rotation
/// (holding only the new key) must not read the channel's pins as dark.
#[tokio::test]
async fn a_rotation_reseals_the_pin_list_under_the_new_epoch() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Reseal", vec!["wss://r".into()], None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let chan = create_private_channel(&relay, &community, "vault").await.unwrap();
let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let ch_hex = crate::simd::hex::bytes_to_hex_32(&chan.0);
let rumor_id = send_message(&relay, &community, &chan, "sealed wisdom").await.unwrap();
let page = fetch_channel(&relay, &community, &chan, 10).await.unwrap();
let opened = page
.iter()
.find_map(|f| match &f.event {
ChatEvent::Message { opened, .. } => (opened.rumor_id.to_hex() == rumor_id).then(|| opened.clone()),
_ => None,
})
.unwrap();
let ch = community.channel(&chan).unwrap().clone();
let old_epoch = ch.epoch.0;
let conv = channel_conv_key_at(&community, &ch, old_epoch).unwrap();
let entry = crate::community::v2::pins::build_pin_entry(&opened, &conv, &ch_hex).unwrap();
publish_pin_list(&relay, &community, &ch, &[entry]).await.unwrap();
let (_, v_before) = crate::db::community::get_community_pins(&cid_hex, &ch_hex).unwrap().unwrap();
// Rotate the channel away from a (never-granted) member.
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
rekey_channel_excluding(&relay, &community, &chan, &roster, &[], &[Keys::generate().public_key()])
.await
.unwrap();
// The stored head is a NEW edition, sealed under the NEW epoch.
let (content, version) = crate::db::community::get_community_pins(&cid_hex, &ch_hex).unwrap().unwrap();
let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
assert_eq!(
parsed["epoch"].as_str().unwrap(),
(old_epoch + 1).to_string(),
"the reseal names the rotated epoch"
);
assert!(version > v_before, "a real edition, not a local rewrite");
// The rotator's own post-rotation view still verifies the pin.
let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let read = read_channel_pins(&community, &chan).unwrap();
assert!(!read.sealed);
assert_eq!(read.pins.len(), 1);
assert_eq!(read.pins[0].content, "sealed wisdom");
}
/// The production ban-eraser: set_banlist must ECHO its published list
/// into the local cache immediately. Before this, the cache moved only on
/// a successful control fold — and a composing caller (ban = banlist →
/// grant strip → refound) whose refound tripped re-read the stale list,
/// so each of 19 real bans erased its predecessors.
#[tokio::test]
async fn a_published_banlist_echoes_locally_before_any_fold() {
let (_tmp, _guard, _owner) = init_test_db();
let relay = MemoryRelay::new();
let community = create_community(&relay, "Modtown", vec!["wss://r".into()], None).await.unwrap();
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let spammer_a = "aa".repeat(32);
let spammer_b = "bb".repeat(32);
// Ban A. NO fold runs — the cache must hold the publish regardless.
set_banlist(&relay, &community, &[spammer_a.clone()]).await.unwrap();
assert_eq!(
crate::db::community::get_community_banlist(&cid_hex).unwrap(),
vec![spammer_a.clone()],
"the publish echoes without waiting for a fold"
);
// Ban B composes from the cache, exactly as the SDK does.
let mut list = crate::db::community::get_community_banlist(&cid_hex).unwrap();
list.push(spammer_b.clone());
set_banlist(&relay, &community, &list).await.unwrap();
let held = crate::db::community::get_community_banlist(&cid_hex).unwrap();
assert!(
held.contains(&spammer_a) && held.contains(&spammer_b),
"sequential bans UNION; the second must not erase the first: {held:?}"
);
// The wire agrees: a real fold confirms rather than regresses.
follow_control(&relay, &community).await.unwrap().updated;
let folded = crate::db::community::get_community_banlist(&cid_hex).unwrap();
assert!(folded.contains(&spammer_a) && folded.contains(&spammer_b));
}
/// Publishes everywhere but `refusing`, serves nothing from `hollow`, and has `throttled` turn
/// away every third publish.
struct PickyRelays<'a> {
inner: &'a MemoryRelay,
refusing: Option<&'static str>,
hollow: Option<&'static str>,
throttled: Option<&'static str>,
sent: std::sync::atomic::AtomicUsize,
}
impl PickyRelays<'_> {
fn only(relays: &[String], which: Option<&str>) -> bool {
relays.len() == 1 && which == Some(relays[0].as_str())
}
}
#[async_trait::async_trait]
impl Transport for PickyRelays<'_> {
async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
if Self::only(r, self.refusing) {
return Err("blocked: not on the allow list".into());
}
if Self::only(r, self.throttled) && self.sent.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 3 == 2 {
return Err("rate-limited: slow down".into());
}
self.inner.publish(e, r).await
}
async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
if Self::only(relays, self.hollow) {
return Ok(Vec::new());
}
self.inner.fetch(query, relays).await
}
async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
if Self::only(relays, self.hollow) {
return Ok(crate::community::transport::PlaneFetch::whole(Vec::new()));
}
self.inner.fetch_plane(plane, query, relays).await
}
async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
self.publish(e, r).await
}
}
async fn wraps_by(relay: &MemoryRelay, author: &str, on: &str) -> std::collections::HashSet<nostr_sdk::prelude::EventId> {
let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![author.to_string()], ..Default::default() };
relay.fetch(&q, &[on.to_string()]).await.unwrap().into_iter().map(|e| e.id).collect()
}
#[tokio::test]
async fn a_relay_move_lands_members_on_a_whole_community() {
let (bed, owner, member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
send_message(&bed.relay, &community, &general, "before the move").await.unwrap();
send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
bed.swap_to(&member);
let invite = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
let joined = accept_direct_invite(&bed.relay, &invite).await.unwrap();
// The owner leaves every old relay for one of their own.
bed.swap_to(&owner);
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let new = vec!["wss://new".to_string()];
let moved = move_relays(&bed.relay, &held, &new).await.unwrap();
assert_eq!((moved.relays.clone(), moved.removed.clone()), (new.clone(), bed.relays.clone()));
assert!(moved.copied > 0);
assert_eq!(crate::db::community::load_community_v2(community.id()).unwrap().unwrap().relays, new);
// Every Control edition and Guestbook event the old relay held is on the new one.
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let control = control::ControlPlane::of(&held).pk_hex();
let guestbook = crate::community::v2::derive::guestbook_group_key(&held.community_root, held.id(), held.root_epoch).pk_hex();
for plane in [&control, &guestbook] {
let old = wraps_by(&bed.relay, plane, "wss://r").await;
assert!(!old.is_empty() && old.is_subset(&wraps_by(&bed.relay, plane, "wss://new").await), "the new relay holds the whole plane");
}
// A member still reading only the old relay folds the move from the edition announced there.
bed.swap_to(&member);
assert_eq!(joined.relays, bed.relays);
let followed = follow_control(&bed.relay, &joined).await.unwrap().updated.expect("the move folds");
assert_eq!(followed.relays, new);
assert_eq!(retired_relays(&cid_hex), bed.relays, "and listens a while longer where members who haven't moved still write");
// History moved with it: the member reads the old post from the new relay alone.
assert_eq!(texts_in(&bed.relay, &followed, &general).await, vec!["before the move"]);
}
#[tokio::test]
async fn a_relay_move_carries_a_locked_channels_seal() {
use crate::community::roles::OverwriteTarget;
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Sealed move", bed.relays.clone(), None).await.unwrap();
let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
activate_roles_v2(&bed.relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
let general = community.channels[0].id;
for i in 0..4 {
send_message(&bed.relay, &held(), &general, &format!("kept{i}")).await.unwrap();
}
let nothing = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT;
set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
assert_eq!(sealing::seal_history(&bed.relay, &held(), held().channel(&general).unwrap()).await.unwrap(), Some(4));
let new = vec!["wss://new".to_string()];
let moved = move_relays(&bed.relay, &held(), &new).await.unwrap();
assert_eq!(moved.relays, new);
let after = held();
assert_eq!(after.relays, new);
// Read from the new relay alone: the seal's pages and the ids they name came with it.
let got = fetch_channel_history(&bed.relay, &after, &general, 50, 6, None, Some(now_ms() / 1000 + 3600), crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
let mut texts: Vec<String> = got.into_iter().filter_map(|f| match f.event { ChatEvent::Message { opened, .. } => Some(opened.rumor.content), _ => None }).collect();
texts.sort();
assert_eq!(texts, vec!["kept0", "kept1", "kept2", "kept3"]);
}
#[tokio::test]
async fn a_relay_that_wont_hold_the_community_moves_nobody() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
let control = control::ControlPlane::of(&community).pk_hex();
let before = wraps_by(&bed.relay, &control, "wss://r").await;
let unchanged = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap().relays;
let refusing = PickyRelays { inner: &bed.relay, refusing: Some("wss://new"), hollow: None, throttled: None, sent: Default::default() };
let err = move_relays(&refusing, &community, &["wss://new".to_string()]).await.unwrap_err();
assert!(err.contains("wss://new") && err.contains("nothing was changed"), "{err}");
assert_eq!(unchanged(), bed.relays);
// A relay that takes the events but doesn't serve them back is no home either.
let hollow = PickyRelays { inner: &bed.relay, refusing: None, hollow: Some("wss://new"), throttled: None, sent: Default::default() };
let err = move_relays(&hollow, &community, &["wss://r".to_string(), "wss://new".to_string()]).await.unwrap_err();
assert!(err.contains("doesn't serve"), "{err}");
assert_eq!(unchanged(), bed.relays);
assert_eq!(wraps_by(&bed.relay, &control, "wss://r").await, before, "and no move was announced");
}
#[tokio::test]
async fn the_check_before_a_move_names_a_relay_that_throttles() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
let picky = PickyRelays { inner: &bed.relay, refusing: Some("wss://closed"), hollow: None, throttled: Some("wss://busy"), sent: Default::default() };
let checks = check_relays(&picky, &community, &["wss://r".into(), "wss://fine".into(), "wss://busy".into(), "wss://closed".into()]).await.unwrap();
let by = |r: &str| checks.iter().find(|c| c.relay == r).unwrap();
assert_eq!(checks.len(), 3, "a relay already listed isn't checked");
assert!(by("wss://fine").ok && !by("wss://fine").rate_limited);
assert!(by("wss://busy").ok && by("wss://busy").rate_limited, "a relay that turns away part of a burst is flagged before anything moves");
assert!(!by("wss://closed").ok && by("wss://closed").reason.as_deref().is_some_and(|r| r.contains("blocked")));
assert_eq!(crate::db::community::load_community_v2(community.id()).unwrap().unwrap().relays, bed.relays, "checking moves nothing");
}
#[tokio::test]
async fn dropping_a_relay_tops_up_the_ones_kept() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let both = vec!["wss://r".to_string(), "wss://s".to_string()];
let community = create_community(&bed.relay, "Guild", both.clone(), None).await.unwrap();
// An edit only the relay being dropped took.
let mut only_r = community.clone();
only_r.relays = vec!["wss://r".to_string()];
let mut meta = community.metadata();
meta.description = Some("only on r".into());
edit_community_metadata(&bed.relay, &only_r, &meta).await.unwrap();
let control = control::ControlPlane::of(&community).pk_hex();
assert!(!wraps_by(&bed.relay, &control, "wss://r").await.is_subset(&wraps_by(&bed.relay, &control, "wss://s").await));
let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
move_relays(&bed.relay, &held, &["wss://s".to_string()]).await.unwrap();
assert!(
wraps_by(&bed.relay, &control, "wss://r").await.is_subset(&wraps_by(&bed.relay, &control, "wss://s").await),
"what only the dropped relay held is on the one kept"
);
}
#[tokio::test]
async fn a_move_the_old_relays_wont_hear_moves_nobody() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
let control = control::ControlPlane::of(&community).pk_hex();
// The old relay still serves reads but takes no writes.
let deaf = PickyRelays { inner: &bed.relay, refusing: Some("wss://r"), hollow: None, throttled: None, sent: Default::default() };
let err = move_relays(&deaf, &community, &["wss://new".to_string()]).await.unwrap_err();
assert!(err.contains("None of the current relays took the announcement"), "{err}");
assert_eq!(crate::db::community::load_community_v2(community.id()).unwrap().unwrap().relays, bed.relays, "nothing moved here");
assert_eq!(
wraps_by(&bed.relay, &control, "wss://new").await,
wraps_by(&bed.relay, &control, "wss://r").await,
"and the new relay holds no announcement the old one doesn't"
);
}
#[tokio::test]
async fn a_rename_made_during_a_move_survives_it() {
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let stale = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
let mut meta = stale.metadata();
meta.name = "Guild Two".into();
edit_community_metadata(&bed.relay, &stale, &meta).await.unwrap();
move_relays(&bed.relay, &stale, &["wss://r".to_string(), "wss://new".to_string()]).await.unwrap();
let held = crate::db::community::load_community_v2(stale.id()).unwrap().unwrap();
assert_eq!((held.name.as_str(), held.relays.len()), ("Guild Two", 2), "the move is built on what the community holds now");
}
}
#[cfg(test)]
mod folded_chain_tests {
use super::*;
use nostr_sdk::prelude::Keys;
#[tokio::test]
async fn a_fold_tells_the_feed_each_edition_on_the_heads_chain_since_its_floor() {
let (_tmp, _guard, _owner) = super::tests::init_test_db();
let relay = crate::community::transport::memory::MemoryRelay::new();
let community = create_community(&relay, "Chain", vec!["wss://r".into()], None).await.unwrap();
let entity = [0x5e; 32];
let (a, b, c) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
let edition = |version: u64, hash: u8, prev: Option<u8>, author: PublicKey| ParsedEdition {
author,
vsk: String::new(),
entity_id: entity,
version,
prev_hash: prev.map(|p| [p; 32]),
content: String::new(),
self_hash: [hash; 32],
created_at: version * 10,
inner_id: [hash; 32],
authority: None,
binding: None,
};
// v1 ← v2 (b) ← v3 (a), a rival v2 (c) off the chain, and v2's content re-signed by c.
let mut resigned = edition(2, 2, Some(1), c);
resigned.inner_id = [0x22; 32];
let editions = vec![edition(1, 1, None, a), edition(2, 2, Some(1), b), edition(3, 3, Some(2), a), edition(2, 9, Some(1), c), resigned];
let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity);
let head = FoldedHead { entity_hex: entity_hex.clone(), version: 3, self_hash: [3; 32], inner_id: [3; 32], author: a.to_bytes(), rebased: false };
let mut floors = Floors::default();
floors.insert(entity_hex.clone(), (1, [1; 32], None, None, None));
note_folded_chains(&community, &floors, std::iter::once(&head), &editions, |id| *id != [0x22; 32]);
assert_eq!(super::super::changes::folded_marks(community.id(), &entity_hex), vec![(2, b), (3, a)]);
}
}