Skip to main content

vector_core/community/v2/
guestbook.rs

1//! CORD-02 §5 Guestbook Plane — membership motion, coalesced flat.
2//!
3//! One Stream per Community (community_root-keyed,
4//! [`super::derive::guestbook_group_key`]), carrying membership motion:
5//! self-signed Joins/Leaves (3306), authorized Kicks (3309), and
6//! refounder-signed post-Refounding Snapshots (3312), beside the Timeouts (3314)
7//! and Nicknames (3315) that shape how a member reads without changing who is
8//! one — never messages, never authority (a Ban lives on the Control Plane). The plane is *off-consensus*:
9//! nothing in Control or Chat depends on it, so it loads last and can lag
10//! without harm.
11//!
12//! Everything here is PURE — no DB, no network, no clock reads. The +1h
13//! forward-clock rule takes `now_ms` as a parameter, and the authority
14//! questions arrive from the caller's Control Plane fold: `can_kick` (the
15//! KICK bit + strict outrank), `snapshot_authority` (the npub whose
16//! Refounding minted the epoch being folded), and who may time out or name whom.
17//!
18//! Guestbook seals are ENCRYPTED (20013) by spec: a plaintext seal would make
19//! a member's signed membership record liftable as a standalone public
20//! artifact, so [`parse_guestbook_event`] rejects the plaintext form outright.
21
22use std::collections::{BTreeMap, BTreeSet};
23
24use nostr_sdk::prelude::{Event, Keys, PublicKey, Tag, Timestamp, UnsignedEvent};
25
26use super::super::edition::AuthorityCitation;
27use super::derive::GroupKey;
28use super::kind;
29use super::stream::{self, OpenedStream, SealForm, StreamError};
30
31/// Entries dated further than this ahead of the receiver's clock are dropped
32/// outright (CORD-02 §5) — ample for deep clock skew, and the deterrent
33/// against squatting "latest" with a forged future date.
34pub const MAX_FUTURE_MS: u64 = 3_600_000;
35
36/// Snapshot chunk size: 400 members per event (CORD-02 §5). A full chunk's rumor is
37/// ~27.9 KB, inside the 28,672 bytes a sealed rumor may be and still fit a relay.
38pub const SNAPSHOT_CHUNK: usize = 400;
39
40const TAG_INVITE: &str = "invite";
41const TAG_TARGET: &str = "p";
42const TAG_SNAP: &str = "snap";
43const TAG_UNTIL: &str = "until";
44
45/// The longest a Timeout runs past its own `created_at` (CORD-04 §8).
46pub const MAX_TIMEOUT_SECS: u64 = 28 * 24 * 3600;
47
48/// The most characters (Unicode scalar values) a Nickname holds (CORD-04 §10).
49pub const MAX_NICKNAME_CHARS: usize = 32;
50
51const VERB_JOIN: &str = "join";
52const VERB_LEAVE: &str = "leave";
53
54/// Errors from the guestbook layer (envelope errors ride inside).
55#[derive(Debug)]
56pub enum GuestbookError {
57    Stream(StreamError),
58    /// The rumor kind isn't a guestbook kind (3306 / 3309 / 3312 / 3314 / 3315).
59    NotGuestbook(u16),
60    /// A guestbook rumor arrived in a plaintext seal — CORD-02 §5 requires the
61    /// encrypted form (a plaintext seal is a liftable, publicly verifiable
62    /// membership record), so a strict reader drops it.
63    NotEncryptedSealed,
64    /// A 3306's content isn't exactly `"join"` or `"leave"` — the verb IS the
65    /// state, so anything else is malformed, never interpreted.
66    BadVerb,
67    MissingTag(&'static str),
68    /// A state-bearing tag appears more than once — ambiguous, rejected.
69    DuplicateTag(&'static str),
70    /// A state-bearing tag is present but unparseable (bad target hex, bad
71    /// snap id / chunk indices).
72    BadTag(&'static str),
73    /// Snapshot content isn't a JSON array.
74    BadSnapshotContent,
75    /// A Nickname carries a control character.
76    BadNickname,
77}
78
79impl std::fmt::Display for GuestbookError {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        match self {
82            GuestbookError::Stream(e) => write!(f, "stream: {e}"),
83            GuestbookError::NotGuestbook(k) => write!(f, "rumor kind {k} is not a guestbook event"),
84            GuestbookError::NotEncryptedSealed => write!(f, "guestbook events must ride an encrypted seal"),
85            GuestbookError::BadVerb => write!(f, "3306 content is not exactly join/leave"),
86            GuestbookError::MissingTag(t) => write!(f, "missing guestbook tag: {t}"),
87            GuestbookError::DuplicateTag(t) => write!(f, "duplicate guestbook tag: {t}"),
88            GuestbookError::BadTag(t) => write!(f, "unparseable guestbook tag: {t}"),
89            GuestbookError::BadSnapshotContent => write!(f, "snapshot content is not a JSON array"),
90            GuestbookError::BadNickname => write!(f, "a nickname may not carry control characters"),
91        }
92    }
93}
94
95impl std::error::Error for GuestbookError {}
96
97impl From<StreamError> for GuestbookError {
98    fn from(e: StreamError) -> Self {
99        GuestbookError::Stream(e)
100    }
101}
102
103// ── Rumor builders ───────────────────────────────────────────────────────────
104
105/// A self-signed Join, optionally echoing the invite attribution from the
106/// bundle that admitted the author (`["invite", creator, label]`, CORD-05 §1).
107pub fn build_join_rumor(author: PublicKey, invite_attribution: Option<(&str, &str)>, at_ms: u64) -> UnsignedEvent {
108    let mut tags = Vec::new();
109    if let Some((creator, label)) = invite_attribution {
110        tags.push(Tag::custom(
111            TAG_INVITE,
112            [creator.to_string(), label.to_string()],
113        ));
114    }
115    stream::build_rumor_ms(kind::JOIN_LEAVE, author, VERB_JOIN, tags, at_ms)
116}
117
118/// A self-signed Leave.
119pub fn build_leave_rumor(author: PublicKey, at_ms: u64) -> UnsignedEvent {
120    stream::build_rumor_ms(kind::JOIN_LEAVE, author, VERB_LEAVE, vec![], at_ms)
121}
122
123/// An admin-signed Kick naming its target and citing the Grant it acts under
124/// (the `vac`, CORD-04 §5) — absent when the owner acts (supreme, no grant to
125/// cite). Whether it's *honored* is the reader's call ([`coalesce`]'s
126/// `can_kick`), never the writer's.
127pub fn build_kick_rumor(
128    admin: PublicKey,
129    target: PublicKey,
130    citation: Option<&AuthorityCitation>,
131    at_ms: u64,
132) -> UnsignedEvent {
133    let mut tags = vec![Tag::public_key(target)];
134    if let Some(c) = citation {
135        tags.push(c.to_tag());
136    }
137    stream::build_rumor_ms(kind::KICK, admin, "", tags, at_ms)
138}
139
140/// A Timeout of `target` until `until_secs` (unix seconds); one already past lifts it.
141pub fn build_timeout_rumor(actor: PublicKey, target: PublicKey, until_secs: u64, citation: Option<&AuthorityCitation>, at_ms: u64) -> UnsignedEvent {
142    let mut tags = vec![Tag::public_key(target), Tag::custom(TAG_UNTIL, [until_secs.to_string()])];
143    if let Some(c) = citation {
144        tags.push(c.to_tag());
145    }
146    stream::build_rumor_ms(kind::TIMEOUT, actor, "", tags, at_ms)
147}
148
149/// `actor` names `target` in this Community; `""` clears it. Their own needs no citation.
150pub fn build_nickname_rumor(actor: PublicKey, target: PublicKey, nick: &str, citation: Option<&AuthorityCitation>, at_ms: u64) -> UnsignedEvent {
151    let mut tags = vec![Tag::public_key(target)];
152    if let Some(c) = citation {
153        tags.push(c.to_tag());
154    }
155    stream::build_rumor_ms(kind::NICKNAME, actor, nick, tags, at_ms)
156}
157
158/// Refounder-signed snapshot rumors seeding a new epoch's Guestbook: present
159/// members only, chunked at [`SNAPSHOT_CHUNK`], every chunk carrying
160/// `["snap", <id>, <i>, <n>]` (1-based) and ONE shared timestamp — the
161/// one-id-one-time invariant is what lets readers reject torn chunk sets.
162/// No survivors still yields one empty chunk, so the Refounding's guestbook
163/// step is observable either way.
164pub fn build_snapshot_rumors(
165    refounder: PublicKey,
166    members: &[PublicKey],
167    snapshot_id: [u8; 32],
168    at_ms: u64,
169) -> Vec<UnsignedEvent> {
170    let id_hex = crate::simd::hex::bytes_to_hex_32(&snapshot_id);
171    let chunks: Vec<&[PublicKey]> = if members.is_empty() {
172        vec![&[]]
173    } else {
174        members.chunks(SNAPSHOT_CHUNK).collect()
175    };
176    let n = chunks.len();
177    chunks
178        .iter()
179        .enumerate()
180        .map(|(idx, chunk)| {
181            let hexes: Vec<String> = chunk.iter().map(|p| p.to_hex()).collect();
182            let content = serde_json::to_string(&hexes).expect("a string array always serializes");
183            let tags = vec![Tag::custom(
184                TAG_SNAP,
185                [id_hex.clone(), (idx + 1).to_string(), n.to_string()],
186            )];
187            stream::build_rumor_ms(kind::SNAPSHOT, refounder, &content, tags, at_ms)
188        })
189        .collect()
190}
191
192/// Seal a guestbook rumor (encrypted form) into a wrap at `guestbook_pk`.
193/// Local-keys convenience; bunker accounts use [`stream::seal_content`] +
194/// their remote signer + [`stream::wrap_seal`] for identical wire output.
195pub fn seal_guestbook_rumor(
196    rumor: &UnsignedEvent,
197    group: &GroupKey,
198    author_keys: &Keys,
199    wrap_at: Timestamp,
200) -> Result<(Event, Keys), GuestbookError> {
201    let seal = stream::build_seal(rumor, SealForm::Encrypted, group, author_keys)?;
202    Ok(stream::wrap_seal(&seal, group, stream::KIND_WRAP, wrap_at)?)
203}
204
205/// Signer-driven twin of [`seal_guestbook_rumor`] for bunker / NIP-55 accounts:
206/// the encrypted seal signs through a [`VectorSigner`](crate::signer::VectorSigner). `author` is the identity
207/// the signer signs as (must equal `my_public_key()`). Wire-identical output.
208pub async fn seal_guestbook_rumor_signed<S: crate::signer::VectorSigner + ?Sized>(
209    signer: &S,
210    author: PublicKey,
211    rumor: &UnsignedEvent,
212    group: &GroupKey,
213    wrap_at: Timestamp,
214) -> Result<(Event, Keys), GuestbookError> {
215    Ok(stream::seal_and_wrap_signed(signer, author, rumor, SealForm::Encrypted, group, stream::KIND_WRAP, wrap_at, &[]).await?)
216}
217
218// ── Parse ────────────────────────────────────────────────────────────────────
219
220/// One parsed guestbook event: the entry plus the identity the coalesce
221/// tie-break runs on — the INNER rumor id, never the wrap's (a wrap id differs
222/// per re-wrap, and two clients holding different wraps of one rumor would
223/// fork on ties).
224#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
225pub struct GuestbookEvent {
226    /// The verified inner rumor id ([`OpenedStream::rumor_id`]).
227    pub rumor_id: [u8; 32],
228    pub entry: GuestbookEntry,
229    /// The root epoch this client held when it read the event — which plane it
230    /// came from. `None` for rows stored before stamping existed; the next
231    /// re-read stamps them.
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub epoch: Option<u64>,
234    /// Unix seconds when THIS client first stored the event — an arrival time the
235    /// author cannot write. `at_ms` inside a Join is author-claimed, so a raider can
236    /// backdate it under any window; what we watched arrive, they cannot. Only
237    /// meaningful against a community whose guestbook we were already following
238    /// (see `guestbook_observed_since`) — on a fresh client every event is "new".
239    /// `None` for rows stored before stamping existed.
240    #[serde(default, skip_serializing_if = "Option::is_none")]
241    pub observed_at: Option<u64>,
242}
243
244/// The typed guestbook entries (CORD-02 §5). Authors (`member` / `actor` /
245/// `refounder`) are the seal-verified real keys, proven by
246/// [`stream::open_wrap`] before parsing ever starts.
247#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
248pub enum GuestbookEntry {
249    Join {
250        member: PublicKey,
251        /// Invite attribution echoed from the bundle: `(creator hex, label)`.
252        /// Advisory metadata, carried verbatim — never validated here.
253        invited_by: Option<(String, String)>,
254        at_ms: u64,
255    },
256    Leave {
257        member: PublicKey,
258        at_ms: u64,
259    },
260    Kick {
261        actor: PublicKey,
262        target: PublicKey,
263        /// The Grant the actor claims to act under; `None` covers both the
264        /// owner (no grant to cite) and a corrupt `vac` — the verifier treats
265        /// either as uncited, never trusting a malformed citation.
266        citation: Option<AuthorityCitation>,
267        at_ms: u64,
268    },
269    Snapshot {
270        refounder: PublicKey,
271        members: Vec<PublicKey>,
272        snapshot_id: [u8; 32],
273        /// `(i, n)` — 1-based chunk index over the chunk count.
274        chunk: (u32, u32),
275        at_ms: u64,
276    },
277    /// A Timeout (CORD-04 §8): `target` silenced until `until_secs`.
278    Timeout {
279        actor: PublicKey,
280        target: PublicKey,
281        until_secs: u64,
282        citation: Option<AuthorityCitation>,
283        at_ms: u64,
284    },
285    /// A Nickname (CORD-04 §10): what `target` is called here, `""` when cleared.
286    Nickname {
287        actor: PublicKey,
288        target: PublicKey,
289        nick: String,
290        citation: Option<AuthorityCitation>,
291        at_ms: u64,
292    },
293}
294
295impl GuestbookEntry {
296    /// The entry's millisecond event time (CORD-02 §4).
297    pub fn at_ms(&self) -> u64 {
298        match self {
299            GuestbookEntry::Join { at_ms, .. }
300            | GuestbookEntry::Leave { at_ms, .. }
301            | GuestbookEntry::Kick { at_ms, .. }
302            | GuestbookEntry::Snapshot { at_ms, .. }
303            | GuestbookEntry::Timeout { at_ms, .. }
304            | GuestbookEntry::Nickname { at_ms, .. } => *at_ms,
305        }
306    }
307}
308
309/// Parse a guestbook event from an ALREADY-VERIFIED [`OpenedStream`] (one
310/// produced by [`stream::open_wrap`], which proved the seal signature, the
311/// author binding, the rumor id, and the strict `ms`). Strict on the seal
312/// form: guestbook rumors MUST ride encrypted seals (CORD-02 §5).
313pub fn parse_guestbook_event(opened: &OpenedStream) -> Result<GuestbookEvent, GuestbookError> {
314    if opened.seal_form != SealForm::Encrypted {
315        return Err(GuestbookError::NotEncryptedSealed);
316    }
317    let rumor = &opened.rumor;
318    let at_ms = opened.at_ms;
319
320    let entry = match rumor.kind.as_u16() {
321        kind::JOIN_LEAVE => match rumor.content.as_str() {
322            VERB_JOIN => {
323                let invited_by = rumor.tags.iter().find_map(|t| {
324                    let s = t.as_slice();
325                    (s.len() >= 3 && s[0] == TAG_INVITE).then(|| (s[1].clone(), s[2].clone()))
326                });
327                GuestbookEntry::Join { member: opened.author, invited_by, at_ms }
328            }
329            VERB_LEAVE => GuestbookEntry::Leave { member: opened.author, at_ms },
330            _ => return Err(GuestbookError::BadVerb),
331        },
332        kind::KICK => {
333            // The target must come from a UNIQUE p tag: a second one makes
334            // "who was kicked" pick-your-favorite — reject, never choose.
335            let mut target: Option<PublicKey> = None;
336            for t in rumor.tags.iter() {
337                let s = t.as_slice();
338                if s.len() >= 2 && s[0] == TAG_TARGET {
339                    if target.is_some() {
340                        return Err(GuestbookError::DuplicateTag(TAG_TARGET));
341                    }
342                    target = Some(PublicKey::from_hex(&s[1]).map_err(|_| GuestbookError::BadTag(TAG_TARGET))?);
343                }
344            }
345            let target = target.ok_or(GuestbookError::MissingTag(TAG_TARGET))?;
346            GuestbookEntry::Kick {
347                actor: opened.author,
348                target,
349                citation: AuthorityCitation::from_tags(&rumor.tags),
350                at_ms,
351            }
352        }
353        kind::TIMEOUT => {
354            let (mut target, mut until): (Option<PublicKey>, Option<u64>) = (None, None);
355            for t in rumor.tags.iter() {
356                let s = t.as_slice();
357                if s.len() >= 2 && s[0] == TAG_TARGET {
358                    if target.is_some() {
359                        return Err(GuestbookError::DuplicateTag(TAG_TARGET));
360                    }
361                    target = Some(PublicKey::from_hex(&s[1]).map_err(|_| GuestbookError::BadTag(TAG_TARGET))?);
362                } else if s.len() >= 2 && s[0] == TAG_UNTIL {
363                    if until.is_some() {
364                        return Err(GuestbookError::DuplicateTag(TAG_UNTIL));
365                    }
366                    if s[1].is_empty() || !s[1].bytes().all(|b| b.is_ascii_digit()) {
367                        return Err(GuestbookError::BadTag(TAG_UNTIL));
368                    }
369                    until = Some(s[1].parse().map_err(|_| GuestbookError::BadTag(TAG_UNTIL))?);
370                }
371            }
372            GuestbookEntry::Timeout {
373                actor: opened.author,
374                target: target.ok_or(GuestbookError::MissingTag(TAG_TARGET))?,
375                until_secs: until.ok_or(GuestbookError::MissingTag(TAG_UNTIL))?,
376                citation: AuthorityCitation::from_tags(&rumor.tags),
377                at_ms,
378            }
379        }
380        kind::NICKNAME => {
381            let mut target: Option<PublicKey> = None;
382            for t in rumor.tags.iter() {
383                let s = t.as_slice();
384                if s.len() >= 2 && s[0] == TAG_TARGET {
385                    if target.is_some() {
386                        return Err(GuestbookError::DuplicateTag(TAG_TARGET));
387                    }
388                    target = Some(PublicKey::from_hex(&s[1]).map_err(|_| GuestbookError::BadTag(TAG_TARGET))?);
389                }
390            }
391            if rumor.content.chars().any(char::is_control) {
392                return Err(GuestbookError::BadNickname);
393            }
394            GuestbookEntry::Nickname {
395                actor: opened.author,
396                target: target.ok_or(GuestbookError::MissingTag(TAG_TARGET))?,
397                nick: rumor.content.chars().take(MAX_NICKNAME_CHARS).collect(),
398                citation: AuthorityCitation::from_tags(&rumor.tags),
399                at_ms,
400            }
401        }
402        kind::SNAPSHOT => {
403            let mut snap: Option<(String, String, String)> = None;
404            for t in rumor.tags.iter() {
405                let s = t.as_slice();
406                if s.len() >= 2 && s[0] == TAG_SNAP {
407                    if snap.is_some() {
408                        return Err(GuestbookError::DuplicateTag(TAG_SNAP));
409                    }
410                    if s.len() < 4 {
411                        return Err(GuestbookError::BadTag(TAG_SNAP));
412                    }
413                    snap = Some((s[1].clone(), s[2].clone(), s[3].clone()));
414                }
415            }
416            // The snap tag is load-bearing (the one-id-one-time consistency
417            // rule keys on it), so any malformation rejects the whole event.
418            let (id_hex, i_raw, n_raw) = snap.ok_or(GuestbookError::MissingTag(TAG_SNAP))?;
419            if id_hex.len() != 64 || !id_hex.bytes().all(|b| b.is_ascii_hexdigit()) {
420                return Err(GuestbookError::BadTag(TAG_SNAP));
421            }
422            let snapshot_id = crate::simd::hex::hex_to_bytes_32(&id_hex);
423            let i: u32 = i_raw.parse().map_err(|_| GuestbookError::BadTag(TAG_SNAP))?;
424            let n: u32 = n_raw.parse().map_err(|_| GuestbookError::BadTag(TAG_SNAP))?;
425            if i < 1 || i > n {
426                return Err(GuestbookError::BadTag(TAG_SNAP));
427            }
428            let raw: Vec<serde_json::Value> =
429                serde_json::from_str(&rumor.content).map_err(|_| GuestbookError::BadSnapshotContent)?;
430            // Malformed member entries drop INDIVIDUALLY: a snapshot is
431            // secondhand seeding and absence just means "no seed" (§5), so one
432            // bad entry shouldn't cost the other 399 theirs — the gap heals by
433            // observation or the victim's own fresh Join.
434            let members = raw
435                .iter()
436                .filter_map(|v| v.as_str().and_then(|h| PublicKey::from_hex(h).ok()))
437                .collect();
438            GuestbookEntry::Snapshot {
439                refounder: opened.author,
440                members,
441                snapshot_id,
442                chunk: (i, n),
443                at_ms,
444            }
445        }
446        k => return Err(GuestbookError::NotGuestbook(k)),
447    };
448
449    Ok(GuestbookEvent { epoch: None, observed_at: None, rumor_id: opened.rumor_id.to_bytes(), entry })
450}
451
452// ── Coalesce fold (CORD-02 §5) ───────────────────────────────────────────────
453
454/// An npub's final coalesced state.
455#[derive(Debug, Clone, Copy, PartialEq, Eq)]
456pub enum Verdict {
457    Joined,
458    Left,
459    Kicked,
460    /// Dropped by a Refounding: the epoch's minter published a snapshot that
461    /// does not list them, and nothing newer re-admits them.
462    Refounded,
463}
464
465/// Whether the winning entry was the member's own word or a refounder's
466/// secondhand snapshot seed.
467#[derive(Debug, Clone, Copy, PartialEq, Eq)]
468pub enum Source {
469    Firsthand,
470    Snapshot,
471}
472
473/// One npub's folded guestbook state — the winning entry, flat.
474#[derive(Debug, Clone, PartialEq, Eq)]
475pub struct MemberState {
476    pub verdict: Verdict,
477    /// Millisecond time of the winning entry.
478    pub at_ms: u64,
479    pub source: Source,
480    /// Invite attribution (firsthand Joins only): `(creator hex, label)`.
481    pub invited_by: Option<(String, String)>,
482    /// The winning entry's inner rumor id — the tie-break identity.
483    pub rumor_id: [u8; 32],
484}
485
486/// A span away from the Community: `[from, until)`, `until` open while still away, and whether an
487/// honoured Kick fell in it.
488pub type Span = (u64, Option<u64>, bool);
489
490/// Each member's spans away from the Community: the earliest honoured Leave or Kick after a Join
491/// opens one, and the next Join or snapshot seed closes it. Honoured as [`coalesce`] honours them;
492/// a Refounding's omission opens none.
493pub fn departure_windows(
494    events: &[GuestbookEvent],
495    now_ms: u64,
496    snapshot_authority: Option<&PublicKey>,
497    can_kick: &dyn Fn(&PublicKey, &PublicKey, Option<&AuthorityCitation>) -> bool,
498) -> BTreeMap<PublicKey, Vec<Span>> {
499    let horizon = now_ms.saturating_add(MAX_FUTURE_MS);
500    let held = || events.iter().enumerate().filter(move |(_, e)| e.entry.at_ms() <= horizon);
501    let mut away: std::collections::HashMap<PublicKey, u32> = std::collections::HashMap::new();
502    let mut entries: Vec<Presence> = Vec::new();
503    for (i, ev) in held() {
504        let (member, at, kicked) = match &ev.entry {
505            GuestbookEntry::Leave { member, at_ms } => (member, *at_ms, false),
506            GuestbookEntry::Kick { actor, target, at_ms, citation } if can_kick(actor, target, citation.as_ref()) => (target, *at_ms, true),
507            _ => continue,
508        };
509        let next = away.len() as u32;
510        let who = *away.entry(*member).or_insert(next);
511        entries.push(Presence { who, at, firsthand: true, event: i as u32, away: true, kicked });
512    }
513    if entries.is_empty() {
514        return BTreeMap::new();
515    }
516    // Only a member who went away has a span to close.
517    for (i, ev) in held() {
518        match &ev.entry {
519            GuestbookEntry::Join { member, at_ms, .. } => {
520                if let Some(&who) = away.get(member) {
521                    entries.push(Presence { who, at: *at_ms, firsthand: true, event: i as u32, away: false, kicked: false });
522                }
523            }
524            GuestbookEntry::Snapshot { refounder, members, at_ms, .. } if snapshot_authority == Some(refounder) => {
525                for who in members.iter().filter_map(|m| away.get(m)) {
526                    entries.push(Presence { who: *who, at: *at_ms, firsthand: false, event: i as u32, away: false, kicked: false });
527                }
528            }
529            _ => {}
530        }
531    }
532    let mut members: Vec<PublicKey> = vec![PublicKey::from_byte_array([0; 32]); away.len()];
533    for (member, who) in away {
534        members[who as usize] = member;
535    }
536    entries.sort_unstable_by(|a, b| a.who.cmp(&b.who).then_with(|| a.supersede_order(b, events)));
537    entries
538        .chunk_by(|a, b| a.who == b.who)
539        .filter_map(|run| {
540            let windows = windows_of(run);
541            (!windows.is_empty()).then(|| (members[run[0].who as usize], windows))
542        })
543        .collect()
544}
545
546/// One member's spans away, as [`departure_windows`] finds them: what a write that moves only
547/// that member needs folded again.
548pub fn member_departure_windows(
549    events: &[GuestbookEvent],
550    member: &PublicKey,
551    now_ms: u64,
552    snapshot_authority: Option<&PublicKey>,
553    can_kick: &dyn Fn(&PublicKey, &PublicKey, Option<&AuthorityCitation>) -> bool,
554) -> Vec<Span> {
555    let horizon = now_ms.saturating_add(MAX_FUTURE_MS);
556    let mut entries: Vec<Presence> = Vec::new();
557    for (i, ev) in events.iter().enumerate().filter(|(_, e)| e.entry.at_ms() <= horizon) {
558        let event = i as u32;
559        match &ev.entry {
560            GuestbookEntry::Join { member: m, at_ms, .. } if m == member => entries.push(Presence { who: 0, at: *at_ms, firsthand: true, event, away: false, kicked: false }),
561            GuestbookEntry::Leave { member: m, at_ms } if m == member => entries.push(Presence { who: 0, at: *at_ms, firsthand: true, event, away: true, kicked: false }),
562            GuestbookEntry::Kick { actor, target, at_ms, citation } if target == member && can_kick(actor, target, citation.as_ref()) => {
563                entries.push(Presence { who: 0, at: *at_ms, firsthand: true, event, away: true, kicked: true })
564            }
565            GuestbookEntry::Snapshot { refounder, members, at_ms, .. } if snapshot_authority == Some(refounder) && members.contains(member) => {
566                entries.push(Presence { who: 0, at: *at_ms, firsthand: false, event, away: false, kicked: false })
567            }
568            _ => {}
569        }
570    }
571    if !entries.iter().any(|e| e.away) {
572        return Vec::new();
573    }
574    entries.sort_unstable_by(|a, b| a.supersede_order(b, events));
575    windows_of(&entries)
576}
577
578/// One entry of a member's presence, for folding their spans away.
579struct Presence {
580    who: u32,
581    at: u64,
582    firsthand: bool,
583    /// Index into the events, for the rumor id tie-break and then arrival.
584    event: u32,
585    away: bool,
586    kicked: bool,
587}
588
589impl Presence {
590    /// As [`supersedes`] orders them: time, then a snapshot seed before a member's own word,
591    /// then the higher rumor id first; arrival breaks what is left.
592    fn supersede_order(&self, other: &Presence, events: &[GuestbookEvent]) -> std::cmp::Ordering {
593        self.at
594            .cmp(&other.at)
595            .then(self.firsthand.cmp(&other.firsthand))
596            .then_with(|| events[other.event as usize].rumor_id.cmp(&events[self.event as usize].rumor_id))
597            .then(self.event.cmp(&other.event))
598    }
599}
600
601/// A member's spans from their presence in fold order: the first departure after being here
602/// opens one, the next return closes it.
603fn windows_of(entries: &[Presence]) -> Vec<Span> {
604    let (mut windows, mut open): (Vec<Span>, Option<(u64, bool)>) = (Vec::new(), None);
605    for e in entries {
606        match (e.away, open) {
607            (true, None) => open = Some((e.at, e.kicked)),
608            (true, Some((from, was))) => open = Some((from, was || e.kicked)),
609            (false, Some((from, kicked))) => {
610                windows.push((from, Some(e.at), kicked));
611                open = None;
612            }
613            _ => {}
614        }
615    }
616    if let Some((from, kicked)) = open {
617        windows.push((from, None, kicked));
618    }
619    windows
620}
621
622/// Does `next` beat `prev`? Later ms wins; at a tie a firsthand entry beats a
623/// snapshot seed (a member's own word over the refounder's attestation), then
624/// the lower rumor id. The id tie-break is author-grindable — an accepted
625/// residual: the coalesce is per-npub, so an author only ever grinds ties
626/// against their own entries (CORD-02 §5).
627fn supersedes(prev: &MemberState, next: &Claim<'_>) -> bool {
628    if next.at_ms != prev.at_ms {
629        return next.at_ms > prev.at_ms;
630    }
631    if next.source != prev.source {
632        return next.source == Source::Firsthand;
633    }
634    next.rumor_id < prev.rumor_id
635}
636
637/// An entry's claim on a member's state, its invite attribution copied only if it wins.
638struct Claim<'a> {
639    verdict: Verdict,
640    at_ms: u64,
641    source: Source,
642    invited_by: Option<&'a (String, String)>,
643    rumor_id: [u8; 32],
644}
645
646fn apply(fold: &mut BTreeMap<PublicKey, MemberState>, member: PublicKey, next: Claim<'_>) {
647    let state = || MemberState { verdict: next.verdict, at_ms: next.at_ms, source: next.source, invited_by: next.invited_by.cloned(), rumor_id: next.rumor_id };
648    match fold.entry(member) {
649        std::collections::btree_map::Entry::Vacant(slot) => {
650            slot.insert(state());
651        }
652        std::collections::btree_map::Entry::Occupied(mut slot) => {
653            if supersedes(slot.get(), &next) {
654                *slot.get_mut() = state();
655            }
656        }
657    }
658}
659
660/// Coalesce parsed guestbook events flat: one final [`MemberState`] per npub
661/// (CORD-02 §5), order-independent over `events`.
662///
663///   - entries dated more than [`MAX_FUTURE_MS`] ahead of `now_ms` drop
664///     outright (the forged-future "latest" squat);
665///   - a Kick is honored only when `can_kick(actor, target)` — the caller
666///     closes that over its folded roster (KICK bit + strict outrank);
667///   - a Snapshot is honored ONLY from `snapshot_authority`, the npub whose
668///     Refounding minted the epoch (`None` — unknown or genesis — honors no
669///     snapshots; there is deliberately NO owner fallback, an owner who didn't
670///     mint the epoch has no snapshot authority over it);
671///   - all chunks of one snapshot id must share one `(created_at, ms)`: the
672///     first-seen chunk pins it, disagreeing chunks drop. Pinning `at_ms` pins
673///     the pair — it's a bijection of `(created_at, ms)` under the strict
674///     `0..=999` ms rule [`stream::open_wrap`] already enforced;
675///   - a snapshot merely SEEDS `Joined` at its timestamp: any firsthand entry
676///     (or authorized Kick) newer than it — or tying it — supersedes.
677pub fn coalesce(
678    events: &[GuestbookEvent],
679    now_ms: u64,
680    snapshot_authority: Option<&PublicKey>,
681    can_kick: &dyn Fn(&PublicKey, &PublicKey, Option<&AuthorityCitation>) -> bool,
682) -> BTreeMap<PublicKey, MemberState> {
683    let horizon = now_ms.saturating_add(MAX_FUTURE_MS);
684    let mut fold: BTreeMap<PublicKey, MemberState> = BTreeMap::new();
685
686    for ev in events {
687        if ev.entry.at_ms() > horizon {
688            continue;
689        }
690        match &ev.entry {
691            GuestbookEntry::Join { member, invited_by, at_ms } => apply(
692                &mut fold,
693                *member,
694                Claim {
695                    verdict: Verdict::Joined,
696                    at_ms: *at_ms,
697                    source: Source::Firsthand,
698                    invited_by: invited_by.as_ref(),
699                    rumor_id: ev.rumor_id,
700                },
701            ),
702            GuestbookEntry::Leave { member, at_ms } => apply(
703                &mut fold,
704                *member,
705                Claim {
706                    verdict: Verdict::Left,
707                    at_ms: *at_ms,
708                    source: Source::Firsthand,
709                    invited_by: None,
710                    rumor_id: ev.rumor_id,
711                },
712            ),
713            GuestbookEntry::Kick { actor, target, at_ms, citation } => {
714                if !can_kick(actor, target, citation.as_ref()) {
715                    continue;
716                }
717                apply(
718                    &mut fold,
719                    *target,
720                    Claim {
721                        verdict: Verdict::Kicked,
722                        at_ms: *at_ms,
723                        source: Source::Firsthand,
724                        invited_by: None,
725                        rumor_id: ev.rumor_id,
726                    },
727                );
728            }
729            GuestbookEntry::Snapshot { refounder, members, at_ms, .. } => {
730                if snapshot_authority != Some(refounder) {
731                    continue;
732                }
733                // Each authorized chunk seeds its own members at its own at_ms,
734                // with NO cross-chunk consistency gate. CORD-02 §5: "chunks are
735                // independently useful ... there is no torn state to defend
736                // against." A first-seen timestamp pin would make a maliciously
737                // torn snapshot resolve differently by relay delivery order,
738                // breaking the deterministic-when-synced guarantee; the per-npub
739                // fold below (latest-ms wins, firsthand beats snapshot, lower
740                // rumor id ties) is commutative, so seeding every chunk converges.
741                for m in members {
742                    apply(
743                        &mut fold,
744                        *m,
745                        Claim {
746                            verdict: Verdict::Joined,
747                            at_ms: *at_ms,
748                            source: Source::Snapshot,
749                            invited_by: None,
750                            rumor_id: ev.rumor_id,
751                        },
752                    );
753                }
754            }
755            // Timeouts silence and Nicknames name; neither changes who is a member.
756            GuestbookEntry::Timeout { .. } | GuestbookEntry::Nickname { .. } => {}
757        }
758    }
759
760    supersede_by_refounding(&mut fold, events, horizon, snapshot_authority);
761    fold
762}
763
764/// The Timeouts running at `now_secs` (CORD-04 §8): per target, the newest Timeout whose
765/// signer `may_time_out` that target; one already past lifts it. `until` is capped at 28
766/// days past the Timeout's own time, judged against the rumor so every reader agrees.
767/// Returns target → (from, until) in unix seconds.
768pub fn active_timeouts(events: &[GuestbookEvent], now_secs: u64, may_time_out: &dyn Fn(&PublicKey, &PublicKey, Option<&AuthorityCitation>) -> bool) -> BTreeMap<PublicKey, (u64, u64)> {
769    let mut newest: BTreeMap<PublicKey, (u64, [u8; 32], u64)> = BTreeMap::new();
770    // Newest wins, so a date far ahead would outrank every honest edit until it arrives.
771    let horizon = now_secs.saturating_mul(1000).saturating_add(MAX_FUTURE_MS);
772    for ev in events {
773        let GuestbookEntry::Timeout { actor, target, until_secs, citation, at_ms } = &ev.entry else { continue };
774        if *at_ms > horizon || !may_time_out(actor, target, citation.as_ref()) {
775            continue;
776        }
777        let from = at_ms / 1000;
778        let until = (*until_secs).min(from.saturating_add(MAX_TIMEOUT_SECS));
779        // Newest by ms; a tie goes to the lower rumor id, as everywhere on the Guestbook.
780        if newest.get(target).is_none_or(|(at, id, _)| *at < *at_ms || (*at == *at_ms && ev.rumor_id < *id)) {
781            newest.insert(*target, (*at_ms, ev.rumor_id, until));
782        }
783    }
784    newest.into_iter().filter(|(_, (_, _, until))| *until > now_secs).map(|(t, (at, _, until))| (t, (at / 1000, until))).collect()
785}
786
787/// A member's standing Nickname and the entry it stands on.
788#[derive(Debug, Clone, PartialEq, Eq)]
789pub struct Nickname {
790    pub nick: String,
791    pub actor: PublicKey,
792    pub at_ms: u64,
793    pub rumor_id: [u8; 32],
794}
795
796/// The Nicknames standing at `now_ms` (CORD-04 §10): per target, the newest Nickname whose
797/// signer `may_name` that target, the lower rumor id breaking a tie; a cleared one names
798/// nobody. While a Timeout of theirs runs (`silenced`, the running ones by target), a member's
799/// own Nicknames name nobody, whatever date they carry.
800pub fn standing_nicknames(
801    events: &[GuestbookEvent],
802    now_ms: u64,
803    may_name: &dyn Fn(&PublicKey, &PublicKey, Option<&AuthorityCitation>) -> bool,
804    silenced: &BTreeMap<PublicKey, (u64, u64)>,
805) -> BTreeMap<PublicKey, Nickname> {
806    let horizon = now_ms.saturating_add(MAX_FUTURE_MS);
807    let mut newest: BTreeMap<PublicKey, Nickname> = BTreeMap::new();
808    for ev in events {
809        let GuestbookEntry::Nickname { actor, target, nick, citation, at_ms } = &ev.entry else { continue };
810        if *at_ms > horizon || !may_name(actor, target, citation.as_ref()) {
811            continue;
812        }
813        if actor == target && silenced.contains_key(target) {
814            continue;
815        }
816        if newest.get(target).is_none_or(|n| n.at_ms < *at_ms || (n.at_ms == *at_ms && ev.rumor_id < n.rumor_id)) {
817            newest.insert(*target, Nickname { nick: nick.clone(), actor: *actor, at_ms: *at_ms, rumor_id: ev.rumor_id });
818        }
819    }
820    newest.retain(|_, n| !n.nick.is_empty());
821    newest
822}
823
824/// A Refounding's guestbook replaces the old one. A local store appends across
825/// epochs, so without this a member whose Join predates a Refounding stays
826/// "Joined" forever on any client that never witnessed their Kick — and every
827/// client's count drifts by whatever it happened to miss.
828///
829/// The guest list is the union of every honored snapshot ON THE LIVE EPOCH
830/// (the minter's refound snapshot plus any addendum it publishes later — within
831/// one epoch, snapshots only ever add). Any `Joined` state won by an entry from
832/// an EARLIER epoch, and not in that list, becomes [`Verdict::Refounded`] at the
833/// refound's time. Entries that never got an epoch stamp are judged by time:
834/// older than the refounding means an earlier plane. Forward observation
835/// re-admits as usual — posting after the cut needs the new key.
836///
837/// Nothing happens without an epoch-stamped, honored snapshot: a store that
838/// only knows one plane, or one that has not synced since a rotation, is left
839/// exactly as it was.
840/// The live epoch's refounding, as a guest list plus the moment it took effect.
841/// The base is the union of every honored snapshot ON THE LIVE EPOCH (the refound
842/// snapshot plus any addendum — within one epoch snapshots only add); the cut is
843/// the earliest of them, the refound itself.
844pub struct Refound {
845    pub cut: u64,
846    pub base: BTreeSet<PublicKey>,
847    pub rumor_id: [u8; 32],
848}
849
850pub(super) fn live_refound(
851    events: &[GuestbookEvent],
852    snapshot_authority: Option<&PublicKey>,
853    horizon: u64,
854) -> Option<Refound> {
855    let authority = snapshot_authority?;
856    let live = events.iter().filter_map(|e| e.epoch).max()?;
857    // Per snapshot: the chunks held, the most any claims, and what they carry.
858    let mut snapshots: BTreeMap<[u8; 32], (BTreeSet<u32>, u32, Vec<&GuestbookEvent>)> = BTreeMap::new();
859    for ev in events {
860        if let GuestbookEntry::Snapshot { refounder, snapshot_id, chunk: (i, n), at_ms, .. } = &ev.entry {
861            if ev.epoch == Some(live) && refounder == authority && *at_ms <= horizon {
862                let s = snapshots.entry(*snapshot_id).or_default();
863                s.0.insert(*i);
864                s.1 = s.1.max(*n);
865                s.2.push(ev);
866            }
867        }
868    }
869    // Leaving someone out of a chunk this device lacks is an absence, not a departure: one torn
870    // snapshot and no list of this Refounding is whole, an addendum's least of all.
871    if snapshots.values().any(|(held, n, _)| *n == 0 || !(1..=*n).all(|i| held.contains(&i))) {
872        return None;
873    }
874    let mut base: BTreeSet<PublicKey> = BTreeSet::new();
875    let mut cut: Option<u64> = None;
876    let mut rumor_id: Option<[u8; 32]> = None;
877    for ev in snapshots.into_values().flat_map(|(_, _, evs)| evs) {
878        if let GuestbookEntry::Snapshot { members, at_ms, .. } = &ev.entry {
879            base.extend(members.iter().copied());
880            cut = Some(cut.map_or(*at_ms, |c| c.min(*at_ms)));
881            rumor_id = Some(rumor_id.map_or(ev.rumor_id, |r| r.min(ev.rumor_id)));
882        }
883    }
884    Some(Refound { cut: cut?, base, rumor_id: rumor_id? })
885}
886
887fn supersede_by_refounding(
888    fold: &mut BTreeMap<PublicKey, MemberState>,
889    events: &[GuestbookEvent],
890    horizon: u64,
891    snapshot_authority: Option<&PublicKey>,
892) {
893    let Some(Refound { cut, base, rumor_id }) = live_refound(events, snapshot_authority, horizon) else { return };
894    // A Joined member the refound omitted is gone, whether their Join sits on an
895    // earlier plane (stamp) or simply predates the cut (a lost/legacy stamp, or a
896    // wedged client that posted a Join with a stale timestamp). Base membership is
897    // the authority; forward observation still re-admits (the observed path).
898    let live = events.iter().filter_map(|e| e.epoch).max();
899    let provenance: BTreeMap<[u8; 32], Option<u64>> = events.iter().map(|e| (e.rumor_id, e.epoch)).collect();
900    for (pk, st) in fold.iter_mut() {
901        if st.verdict != Verdict::Joined || base.contains(pk) {
902            continue;
903        }
904        let older_plane = matches!((provenance.get(&st.rumor_id).copied().flatten(), live), (Some(e), Some(l)) if e < l);
905        if st.at_ms < cut || older_plane {
906            *st = MemberState { verdict: Verdict::Refounded, at_ms: cut, source: Source::Snapshot, invited_by: None, rumor_id };
907        }
908    }
909}
910
911// ── Complete Memberlist (CORD-02 §5) ─────────────────────────────────────────
912
913/// The Complete Memberlist: coalesced `Joined` members ∪ observed authors,
914/// minus the Banlist. `observed` maps author → the newest ms they were seen
915/// publishing anywhere in the Community (an author seen publishing is
916/// *observably present*, included even if their Join never arrived).
917/// Observation counts FORWARD only: it re-enters an author whose activity is
918/// strictly newer than their latest departure — a departed member's old
919/// history can never resurrect them.
920pub fn complete_memberlist(
921    coalesced: &BTreeMap<PublicKey, MemberState>,
922    observed: &BTreeMap<PublicKey, u64>,
923    banlist: &BTreeSet<PublicKey>,
924    banned_at: &BTreeMap<PublicKey, u64>,
925    refound: Option<&Refound>,
926) -> BTreeSet<PublicKey> {
927    let parts = memberlist_parts(coalesced, observed, banlist, banned_at, refound);
928    let mut all = parts.counted;
929    all.extend(parts.unlisted.into_keys());
930    all
931}
932
933/// Why someone seen posting stands outside the Guestbook's members.
934#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
935#[serde(rename_all = "snake_case")]
936pub enum Unlisted {
937    /// No Join of theirs stands, nor a snapshot naming them.
938    NoJoin,
939    /// They left or were kicked, and posted since.
940    Departed,
941}
942
943/// The Complete Memberlist split by where each member stands.
944#[derive(Debug, Default)]
945pub struct MemberParts {
946    /// The Guestbook's members, every role-holder and nobody else: a function of the planes
947    /// alone, so every client that has synced them counts the same.
948    pub counted: BTreeSet<PublicKey>,
949    /// Present only by what this client has seen them post, which depends on how much
950    /// history it holds: listed, never counted.
951    pub unlisted: BTreeMap<PublicKey, Unlisted>,
952}
953
954/// [`complete_memberlist`], split into who counts and who is only seen posting.
955pub fn memberlist_parts(
956    coalesced: &BTreeMap<PublicKey, MemberState>,
957    observed: &BTreeMap<PublicKey, u64>,
958    banlist: &BTreeSet<PublicKey>,
959    banned_at: &BTreeMap<PublicKey, u64>,
960    refound: Option<&Refound>,
961) -> MemberParts {
962    // A Refounding's snapshot is the whole guest list. The observed-forward path
963    // (below) re-admits anyone seen publishing — including raid spammers whose Kick
964    // was buried by the rotation, which is how a client's count drifts above the
965    // real membership. So an observed author the refound omitted, whose activity is
966    // no newer than the cut, is suppressed exactly like a pre-ban ghost: only
967    // posting AFTER the refound (which needs the new key) re-admits them.
968    // `ms == 0` is the grantee sentinel (a role-holder present-via-Grant, not by
969    // activity time). A Grant outranks a snapshot omission — the CONSENSUS-COMPLETE
970    // backstop must survive a Refounding — so never suppress it here.
971    let stale_pre_refound = |pk: &PublicKey, ms: u64| {
972        ms != 0 && refound.is_some_and(|r| !r.base.contains(pk) && ms <= r.cut)
973    };
974    // Observation counts forward of a ban (CORD-02 §5). A Join does not consult this: the
975    // banlist edits behind `banned_at` are whatever this client happened to fold, and an
976    // un-ban writes the ban's departure to the Guestbook instead (a Kick dated at the ban).
977    // `banned_at` is SECONDS, entry times are ms.
978    let stale_pre_ban = |pk: &PublicKey, ms: u64| banned_at.get(pk).is_some_and(|at| ms <= at.saturating_mul(1000));
979    let mut parts = MemberParts::default();
980    for (pk, st) in coalesced {
981        if st.verdict == Verdict::Joined && !banlist.contains(pk) {
982            parts.counted.insert(*pk);
983        }
984    }
985    for (pk, seen_ms) in observed {
986        if banlist.contains(pk) || stale_pre_ban(pk, *seen_ms) || stale_pre_refound(pk, *seen_ms) {
987            continue;
988        }
989        match coalesced.get(pk) {
990            Some(st) if st.verdict == Verdict::Joined => {}
991            Some(st) if *seen_ms <= st.at_ms => {}
992            // The grantee sentinel: a Grant proves membership on the consensus plane.
993            _ if *seen_ms == 0 => {
994                parts.counted.insert(*pk);
995            }
996            Some(st) if st.verdict != Verdict::Refounded => {
997                parts.unlisted.insert(*pk, Unlisted::Departed);
998            }
999            _ => {
1000                parts.unlisted.insert(*pk, Unlisted::NoJoin);
1001            }
1002        }
1003    }
1004    parts
1005}
1006
1007/// A stored event's body: the event without its rumor id (the row's key), in a compact binary
1008/// form. `[format = 1][flags: epoch, observed_at][varints for those][entry tag][entry]`, keys as
1009/// 32 raw bytes, numbers as LEB128, strings length-prefixed. Never 32 bytes long, which at-rest
1010/// storage would take for a bare key.
1011pub(crate) fn event_body(ev: &GuestbookEvent) -> Vec<u8> {
1012    fn varint(out: &mut Vec<u8>, mut v: u64) {
1013        while v >= 0x80 {
1014            out.push(v as u8 | 0x80);
1015            v >>= 7;
1016        }
1017        out.push(v as u8);
1018    }
1019    fn text(out: &mut Vec<u8>, s: &str) {
1020        varint(out, s.len() as u64);
1021        out.extend_from_slice(s.as_bytes());
1022    }
1023    fn citation(out: &mut Vec<u8>, c: &Option<AuthorityCitation>) {
1024        match c {
1025            None => out.push(0),
1026            Some(c) => {
1027                out.push(1);
1028                out.extend_from_slice(&c.entity_id);
1029                varint(out, c.version);
1030                out.extend_from_slice(&c.edition_hash);
1031            }
1032        }
1033    }
1034    let mut out = Vec::with_capacity(80);
1035    out.push(1);
1036    out.push(ev.epoch.is_some() as u8 | (ev.observed_at.is_some() as u8) << 1);
1037    if let Some(e) = ev.epoch {
1038        varint(&mut out, e);
1039    }
1040    if let Some(o) = ev.observed_at {
1041        varint(&mut out, o);
1042    }
1043    match &ev.entry {
1044        GuestbookEntry::Join { member, invited_by, at_ms } => {
1045            out.push(0);
1046            out.extend_from_slice(member.as_bytes());
1047            varint(&mut out, *at_ms);
1048            match invited_by {
1049                None => out.push(0),
1050                Some((creator, label)) => {
1051                    out.push(1);
1052                    text(&mut out, creator);
1053                    text(&mut out, label);
1054                }
1055            }
1056        }
1057        GuestbookEntry::Leave { member, at_ms } => {
1058            out.push(1);
1059            out.extend_from_slice(member.as_bytes());
1060            varint(&mut out, *at_ms);
1061        }
1062        GuestbookEntry::Kick { actor, target, citation: c, at_ms } => {
1063            out.push(2);
1064            out.extend_from_slice(actor.as_bytes());
1065            out.extend_from_slice(target.as_bytes());
1066            citation(&mut out, c);
1067            varint(&mut out, *at_ms);
1068        }
1069        GuestbookEntry::Snapshot { refounder, members, snapshot_id, chunk, at_ms } => {
1070            out.push(3);
1071            out.extend_from_slice(refounder.as_bytes());
1072            varint(&mut out, members.len() as u64);
1073            for m in members {
1074                out.extend_from_slice(m.as_bytes());
1075            }
1076            out.extend_from_slice(snapshot_id);
1077            varint(&mut out, chunk.0 as u64);
1078            varint(&mut out, chunk.1 as u64);
1079            varint(&mut out, *at_ms);
1080        }
1081        GuestbookEntry::Timeout { actor, target, until_secs, citation: c, at_ms } => {
1082            out.push(4);
1083            out.extend_from_slice(actor.as_bytes());
1084            out.extend_from_slice(target.as_bytes());
1085            varint(&mut out, *until_secs);
1086            citation(&mut out, c);
1087            varint(&mut out, *at_ms);
1088        }
1089        GuestbookEntry::Nickname { actor, target, nick, citation: c, at_ms } => {
1090            out.push(5);
1091            out.extend_from_slice(actor.as_bytes());
1092            out.extend_from_slice(target.as_bytes());
1093            text(&mut out, nick);
1094            citation(&mut out, c);
1095            varint(&mut out, *at_ms);
1096        }
1097    }
1098    out
1099}
1100
1101/// The event an [`event_body`] holds under `rumor_id`; `None` for a body it can't read whole.
1102pub(crate) fn event_from_body(rumor_id: [u8; 32], body: &[u8]) -> Option<GuestbookEvent> {
1103    struct Reader<'a>(&'a [u8]);
1104    impl<'a> Reader<'a> {
1105        fn byte(&mut self) -> Option<u8> {
1106            let (&b, rest) = self.0.split_first()?;
1107            self.0 = rest;
1108            Some(b)
1109        }
1110        fn take(&mut self, n: usize) -> Option<&'a [u8]> {
1111            if self.0.len() < n {
1112                return None;
1113            }
1114            let (head, rest) = self.0.split_at(n);
1115            self.0 = rest;
1116            Some(head)
1117        }
1118        fn bytes32(&mut self) -> Option<[u8; 32]> {
1119            self.take(32)?.try_into().ok()
1120        }
1121        fn key(&mut self) -> Option<PublicKey> {
1122            PublicKey::from_slice(&self.bytes32()?).ok()
1123        }
1124        fn varint(&mut self) -> Option<u64> {
1125            let mut v = 0u64;
1126            for shift in (0..64).step_by(7) {
1127                let b = self.byte()?;
1128                v |= ((b & 0x7f) as u64).checked_shl(shift)?;
1129                if b & 0x80 == 0 {
1130                    return Some(v);
1131                }
1132            }
1133            None
1134        }
1135        fn text(&mut self) -> Option<String> {
1136            let n = usize::try_from(self.varint()?).ok()?;
1137            String::from_utf8(self.take(n)?.to_vec()).ok()
1138        }
1139        fn citation(&mut self) -> Option<Option<AuthorityCitation>> {
1140            Some(match self.byte()? {
1141                0 => None,
1142                1 => Some(AuthorityCitation { entity_id: self.bytes32()?, version: self.varint()?, edition_hash: self.bytes32()? }),
1143                _ => return None,
1144            })
1145        }
1146    }
1147    let mut r = Reader(body);
1148    if r.byte()? != 1 {
1149        return None;
1150    }
1151    let flags = r.byte()?;
1152    let epoch = if flags & 1 != 0 { Some(r.varint()?) } else { None };
1153    let observed_at = if flags & 2 != 0 { Some(r.varint()?) } else { None };
1154    let entry = match r.byte()? {
1155        0 => {
1156            let member = r.key()?;
1157            let at_ms = r.varint()?;
1158            let invited_by = match r.byte()? {
1159                0 => None,
1160                1 => Some((r.text()?, r.text()?)),
1161                _ => return None,
1162            };
1163            GuestbookEntry::Join { member, invited_by, at_ms }
1164        }
1165        1 => GuestbookEntry::Leave { member: r.key()?, at_ms: r.varint()? },
1166        2 => GuestbookEntry::Kick { actor: r.key()?, target: r.key()?, citation: r.citation()?, at_ms: r.varint()? },
1167        3 => {
1168            let refounder = r.key()?;
1169            let n = usize::try_from(r.varint()?).ok()?;
1170            // Bounded by what the body actually holds, so a corrupt count can't reserve memory.
1171            if n > r.0.len() / 32 {
1172                return None;
1173            }
1174            let members = (0..n).map(|_| r.key()).collect::<Option<Vec<_>>>()?;
1175            let snapshot_id = r.bytes32()?;
1176            let chunk = (u32::try_from(r.varint()?).ok()?, u32::try_from(r.varint()?).ok()?);
1177            GuestbookEntry::Snapshot { refounder, members, snapshot_id, chunk, at_ms: r.varint()? }
1178        }
1179        4 => GuestbookEntry::Timeout { actor: r.key()?, target: r.key()?, until_secs: r.varint()?, citation: r.citation()?, at_ms: r.varint()? },
1180        5 => GuestbookEntry::Nickname { actor: r.key()?, target: r.key()?, nick: r.text()?, citation: r.citation()?, at_ms: r.varint()? },
1181        _ => return None,
1182    };
1183    if !r.0.is_empty() {
1184        return None;
1185    }
1186    Some(GuestbookEvent { rumor_id, entry, epoch, observed_at })
1187}
1188
1189#[cfg(test)]
1190mod tests {
1191
1192    #[test]
1193    fn the_newest_authorized_timeout_stands_capped_at_28_days() {
1194        let (mod_, rogue, target) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
1195        let ev = |actor, until_secs, at_secs: u64, id: u8| GuestbookEvent {
1196            rumor_id: [id; 32],
1197            entry: GuestbookEntry::Timeout { actor, target, until_secs, citation: None, at_ms: at_secs * 1000 },
1198            epoch: None,
1199            observed_at: None,
1200        };
1201        let may = |a: &PublicKey, _: &PublicKey, _: Option<&AuthorityCitation>| *a == mod_;
1202        let far = 1_000 + 10 * MAX_TIMEOUT_SECS;
1203        let got = active_timeouts(&[ev(mod_, far, 1_000, 1)], 2_000, &may);
1204        assert_eq!(got[&target], (1_000, 1_000 + MAX_TIMEOUT_SECS), "capped against the Timeout's own time");
1205        let got = active_timeouts(&[ev(mod_, far, 1_000, 1), ev(rogue, 0, 1_500, 2)], 2_000, &may);
1206        assert!(got.contains_key(&target), "an unauthorized lift lifts nothing");
1207        let got = active_timeouts(&[ev(mod_, far, 1_000, 1), ev(mod_, 1_200, 1_100, 3)], 2_000, &may);
1208        assert!(got.is_empty(), "the newest authorized Timeout stands, here one already over");
1209        for order in [[ev(mod_, far, 1_100, 7), ev(mod_, 0, 1_100, 6)], [ev(mod_, 0, 1_100, 6), ev(mod_, far, 1_100, 7)]] {
1210            assert!(active_timeouts(&order, 2_000, &may).is_empty(), "a same-ms tie goes to the lower rumor id, in any order");
1211        }
1212        let ahead = 2_000 + MAX_FUTURE_MS / 1000 + 1;
1213        let got = active_timeouts(&[ev(mod_, ahead + 100, ahead, 4)], 2_000, &may);
1214        assert!(got.is_empty(), "a Timeout dated past the horizon is ignored");
1215        let got = active_timeouts(&[ev(mod_, far, 1_000, 1), ev(mod_, 0, ahead, 5)], 2_000, &may);
1216        assert!(got.contains_key(&target), "and so is a lift dated past it");
1217        let got = active_timeouts(&[ev(mod_, far, 1_000, 1), ev(mod_, 0, ahead - 1, 5)], 2_000, &may);
1218        assert!(got.is_empty(), "one inside the horizon counts");
1219    }
1220
1221    use super::super::super::{CommunityId, Epoch};
1222    use super::super::derive::guestbook_group_key;
1223    use super::*;
1224
1225    /// [`departure_windows`] as first written: a list per member, each sorted alone.
1226    fn departure_windows_by_member(
1227        events: &[GuestbookEvent],
1228        now_ms: u64,
1229        snapshot_authority: Option<&PublicKey>,
1230        can_kick: &dyn Fn(&PublicKey, &PublicKey, Option<&AuthorityCitation>) -> bool,
1231    ) -> BTreeMap<PublicKey, Vec<Span>> {
1232        let horizon = now_ms.saturating_add(MAX_FUTURE_MS);
1233        // (at, firsthand, rumor id, away, kicked)
1234        type Entry = (u64, bool, [u8; 32], bool, bool);
1235        let mut by_member: BTreeMap<PublicKey, Vec<Entry>> = BTreeMap::new();
1236        for ev in events.iter().filter(|e| e.entry.at_ms() <= horizon) {
1237            match &ev.entry {
1238                GuestbookEntry::Join { member, at_ms, .. } => by_member.entry(*member).or_default().push((*at_ms, true, ev.rumor_id, false, false)),
1239                GuestbookEntry::Leave { member, at_ms } => by_member.entry(*member).or_default().push((*at_ms, true, ev.rumor_id, true, false)),
1240                GuestbookEntry::Kick { actor, target, at_ms, citation } if can_kick(actor, target, citation.as_ref()) => by_member.entry(*target).or_default().push((*at_ms, true, ev.rumor_id, true, true)),
1241                GuestbookEntry::Snapshot { refounder, members, at_ms, .. } if snapshot_authority == Some(refounder) => {
1242                    for m in members {
1243                        by_member.entry(*m).or_default().push((*at_ms, false, ev.rumor_id, false, false));
1244                    }
1245                }
1246                _ => {}
1247            }
1248        }
1249        let mut out = BTreeMap::new();
1250        for (member, mut entries) in by_member {
1251            if !entries.iter().any(|e| e.3) {
1252                continue;
1253            }
1254            entries.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)).then(b.2.cmp(&a.2)));
1255            let (mut windows, mut open): (Vec<Span>, Option<(u64, bool)>) = (Vec::new(), None);
1256            for (at, _, _, away, kicked) in entries {
1257                match (away, open) {
1258                    (true, None) => open = Some((at, kicked)),
1259                    (true, Some((from, was))) => open = Some((from, was || kicked)),
1260                    (false, Some((from, kicked))) => {
1261                        windows.push((from, Some(at), kicked));
1262                        open = None;
1263                    }
1264                    _ => {}
1265                }
1266            }
1267            if let Some((from, kicked)) = open {
1268                windows.push((from, None, kicked));
1269            }
1270            if !windows.is_empty() {
1271                out.insert(member, windows);
1272            }
1273        }
1274        out
1275    }
1276
1277    #[test]
1278    fn departure_windows_agree_with_a_list_per_member() {
1279        let keys: Vec<PublicKey> = (0..6).map(|_| Keys::generate().public_key()).collect();
1280        let mut seed = 0x9e37_79b9_7f4a_7c15u64;
1281        let mut next = move |n: u64| {
1282            seed ^= seed << 13;
1283            seed ^= seed >> 7;
1284            seed ^= seed << 17;
1285            seed % n
1286        };
1287        let now = 1_000_000_000;
1288        for round in 0..4_000 {
1289            let len = next(24) as usize;
1290            let events: Vec<GuestbookEvent> = (0..len)
1291                .map(|_| {
1292                    let k = keys[next(6) as usize];
1293                    // Few times and ids, so ties are common; some too far ahead to count.
1294                    let at_ms = if next(10) == 0 { now + MAX_FUTURE_MS + 1 + next(5) } else { now - next(8) };
1295                    let entry = match next(5) {
1296                        0 => GuestbookEntry::Join { member: k, invited_by: None, at_ms },
1297                        1 => GuestbookEntry::Leave { member: k, at_ms },
1298                        2 => GuestbookEntry::Kick { actor: keys[next(6) as usize], target: k, citation: None, at_ms },
1299                        3 => GuestbookEntry::Snapshot { refounder: keys[next(2) as usize], members: (0..next(4)).map(|_| keys[next(6) as usize]).collect(), snapshot_id: [0; 32], chunk: (1, 1), at_ms },
1300                        _ => GuestbookEntry::Nickname { actor: k, target: k, nick: String::new(), citation: None, at_ms },
1301                    };
1302                    GuestbookEvent { rumor_id: [next(4) as u8; 32], entry, epoch: None, observed_at: None }
1303                })
1304                .collect();
1305            let can_kick = |actor: &PublicKey, target: &PublicKey, _: Option<&AuthorityCitation>| !(actor.as_bytes()[0] ^ target.as_bytes()[1]).is_multiple_of(3);
1306            let authority = (round % 3 != 0).then_some(&keys[0]);
1307            let all = departure_windows(&events, now, authority, &can_kick);
1308            assert_eq!(all, departure_windows_by_member(&events, now, authority, &can_kick), "round {round}");
1309            for k in &keys {
1310                assert_eq!(member_departure_windows(&events, k, now, authority, &can_kick), all.get(k).cloned().unwrap_or_default(), "round {round}: one member alone");
1311            }
1312        }
1313    }
1314
1315    /// A stable "receiver clock" for the fold tests, far above every event time.
1316    const NOW: u64 = 1_722_500_000_000;
1317
1318    fn cid() -> CommunityId {
1319        CommunityId([0x33; 32])
1320    }
1321
1322    fn group() -> GroupKey {
1323        guestbook_group_key(&[0x44; 32], &cid(), Epoch(0))
1324    }
1325
1326    fn pk() -> PublicKey {
1327        Keys::generate().public_key()
1328    }
1329
1330    fn always(_: &PublicKey, _: &PublicKey, _: Option<&AuthorityCitation>) -> bool {
1331        true
1332    }
1333
1334    /// Full wire path: seal → wrap → open → parse.
1335    fn through(rumor: &UnsignedEvent, author: &Keys) -> GuestbookEvent {
1336        let g = group();
1337        let (wrap, _) = seal_guestbook_rumor(rumor, &g, author, Timestamp::from_secs(1_722_400_000)).unwrap();
1338        parse_guestbook_event(&stream::open_wrap(&wrap, &g).unwrap()).unwrap()
1339    }
1340
1341    fn through_err(rumor: &UnsignedEvent, author: &Keys) -> GuestbookError {
1342        let g = group();
1343        let (wrap, _) = seal_guestbook_rumor(rumor, &g, author, Timestamp::from_secs(1_722_400_000)).unwrap();
1344        parse_guestbook_event(&stream::open_wrap(&wrap, &g).unwrap()).unwrap_err()
1345    }
1346
1347    // Direct coalesce-input constructors: `id` fills the rumor id, so tie
1348    // ordering is choosable per test.
1349    fn at_epoch(mut ev: GuestbookEvent, epoch: u64) -> GuestbookEvent {
1350        ev.epoch = Some(epoch);
1351        ev
1352    }
1353
1354    fn join_ev(member: PublicKey, at_ms: u64, id: u8) -> GuestbookEvent {
1355        GuestbookEvent { epoch: None, observed_at: None, rumor_id: [id; 32], entry: GuestbookEntry::Join { member, invited_by: None, at_ms } }
1356    }
1357
1358    fn leave_ev(member: PublicKey, at_ms: u64, id: u8) -> GuestbookEvent {
1359        GuestbookEvent { epoch: None, observed_at: None, rumor_id: [id; 32], entry: GuestbookEntry::Leave { member, at_ms } }
1360    }
1361
1362    fn kick_ev(actor: PublicKey, target: PublicKey, at_ms: u64, id: u8) -> GuestbookEvent {
1363        GuestbookEvent { epoch: None, observed_at: None, rumor_id: [id; 32], entry: GuestbookEntry::Kick { actor, target, citation: None, at_ms } }
1364    }
1365
1366    fn snap_ev(
1367        refounder: PublicKey,
1368        members: Vec<PublicKey>,
1369        snap: u8,
1370        chunk: (u32, u32),
1371        at_ms: u64,
1372        id: u8,
1373    ) -> GuestbookEvent {
1374        GuestbookEvent { epoch: None, observed_at: None,
1375            rumor_id: [id; 32],
1376            entry: GuestbookEntry::Snapshot { refounder, members, snapshot_id: [snap; 32], chunk, at_ms },
1377        }
1378    }
1379
1380    #[test]
1381    fn join_and_leave_round_trip_through_the_stream() {
1382        let member = Keys::generate();
1383        let creator = pk().to_hex();
1384
1385        let join = build_join_rumor(member.public_key(), Some((&creator, "Reddit")), 1_722_400_000_128);
1386        let ev = through(&join, &member);
1387        assert_eq!(
1388            ev.entry,
1389            GuestbookEntry::Join {
1390                member: member.public_key(),
1391                invited_by: Some((creator, "Reddit".into())),
1392                at_ms: 1_722_400_000_128,
1393            }
1394        );
1395
1396        // Attribution is optional on a Join, and a Leave never carries any.
1397        let bare = through(&build_join_rumor(member.public_key(), None, 1_000), &member);
1398        assert!(matches!(bare.entry, GuestbookEntry::Join { invited_by: None, .. }));
1399        let leave = through(&build_leave_rumor(member.public_key(), 1_722_400_000_660), &member);
1400        assert_eq!(leave.entry, GuestbookEntry::Leave { member: member.public_key(), at_ms: 1_722_400_000_660 });
1401    }
1402
1403    #[test]
1404    fn kick_round_trips_with_citation_and_the_inner_rumor_id() {
1405        let admin = Keys::generate();
1406        let target = pk();
1407        let cite = AuthorityCitation { entity_id: [0xab; 32], version: 7, edition_hash: [0xcd; 32] };
1408        let rumor = build_kick_rumor(admin.public_key(), target, Some(&cite), 1_722_410_000_301);
1409
1410        let g = group();
1411        let (wrap, _) = seal_guestbook_rumor(&rumor, &g, &admin, Timestamp::from_secs(1_722_410_000)).unwrap();
1412        let opened = stream::open_wrap(&wrap, &g).unwrap();
1413        let ev = parse_guestbook_event(&opened).unwrap();
1414
1415        assert_eq!(
1416            ev.entry,
1417            GuestbookEntry::Kick {
1418                actor: admin.public_key(),
1419                target,
1420                citation: Some(cite),
1421                at_ms: 1_722_410_000_301,
1422            }
1423        );
1424        // The tie-break identity is the INNER rumor id, never the wrap's
1425        // (which differs per re-wrap and would fork clients on ties).
1426        assert_eq!(ev.rumor_id, opened.rumor_id.to_bytes());
1427        assert_ne!(ev.rumor_id, wrap.id.to_bytes());
1428
1429        // Uncited kick: the owner acting supreme — citation is simply None.
1430        let bare = through(&build_kick_rumor(admin.public_key(), target, None, 1_000), &admin);
1431        assert!(matches!(bare.entry, GuestbookEntry::Kick { citation: None, .. }));
1432    }
1433
1434    #[test]
1435    fn timeout_round_trips_and_refuses_a_malformed_until() {
1436        let (admin, target) = (Keys::generate(), pk());
1437        let ev = through(&build_timeout_rumor(admin.public_key(), target, 1_722_420_000, None, 1_722_410_000_301), &admin);
1438        assert_eq!(ev.entry, GuestbookEntry::Timeout { actor: admin.public_key(), target, until_secs: 1_722_420_000, citation: None, at_ms: 1_722_410_000_301 });
1439        let bad = stream::build_rumor_ms(kind::TIMEOUT, admin.public_key(), "", vec![Tag::public_key(target), Tag::custom(TAG_UNTIL, ["+5"])], 1_000);
1440        assert!(matches!(through_err(&bad, &admin), GuestbookError::BadTag(TAG_UNTIL)));
1441        let missing = stream::build_rumor_ms(kind::TIMEOUT, admin.public_key(), "", vec![Tag::public_key(target)], 1_000);
1442        assert!(matches!(through_err(&missing, &admin), GuestbookError::MissingTag(TAG_UNTIL)));
1443    }
1444
1445    #[test]
1446    fn a_nickname_round_trips_cut_to_32_characters_and_refuses_control_characters() {
1447        let (admin, target) = (Keys::generate(), pk());
1448        let cite = AuthorityCitation { entity_id: [0xab; 32], version: 3, edition_hash: [0xcd; 32] };
1449        let ev = through(&build_nickname_rumor(admin.public_key(), target, "Moth", Some(&cite), 1_722_410_000_301), &admin);
1450        assert_eq!(ev.entry, GuestbookEntry::Nickname { actor: admin.public_key(), target, nick: "Moth".into(), citation: Some(cite), at_ms: 1_722_410_000_301 });
1451        let long = "ü".repeat(MAX_NICKNAME_CHARS + 5);
1452        let GuestbookEntry::Nickname { nick, .. } = through(&build_nickname_rumor(admin.public_key(), target, &long, None, 1_000), &admin).entry else { panic!() };
1453        assert_eq!(nick.chars().count(), MAX_NICKNAME_CHARS, "a reader cuts past 32 characters, never mid-character");
1454        assert!(matches!(through_err(&build_nickname_rumor(admin.public_key(), target, "two\nlines", None, 1_000), &admin), GuestbookError::BadNickname));
1455        let bare = stream::build_rumor_ms(kind::NICKNAME, admin.public_key(), "x", vec![], 1_000);
1456        assert!(matches!(through_err(&bare, &admin), GuestbookError::MissingTag(TAG_TARGET)));
1457        let twice = stream::build_rumor_ms(kind::NICKNAME, admin.public_key(), "x", vec![Tag::public_key(target), Tag::public_key(pk())], 1_000);
1458        assert!(matches!(through_err(&twice, &admin), GuestbookError::DuplicateTag(TAG_TARGET)));
1459    }
1460
1461    #[test]
1462    fn the_newest_nickname_its_signer_may_set_stands() {
1463        let (mod_, rogue, m) = (pk(), pk(), pk());
1464        let ev = |actor, nick: &str, at_secs: u64, id: u8| GuestbookEvent {
1465            rumor_id: [id; 32],
1466            entry: GuestbookEntry::Nickname { actor, target: m, nick: nick.into(), citation: None, at_ms: at_secs * 1000 },
1467            epoch: None,
1468            observed_at: None,
1469        };
1470        let may = |a: &PublicKey, _: &PublicKey, _: Option<&AuthorityCitation>| *a != rogue;
1471        let none = BTreeMap::new();
1472        let now = 10_000_000;
1473        let named = |evs: &[GuestbookEvent], silenced: &BTreeMap<PublicKey, (u64, u64)>| standing_nicknames(evs, now, &may, silenced).get(&m).map(|n| n.nick.clone());
1474        assert_eq!(named(&[ev(m, "Moth", 1_000, 1), ev(mod_, "Fixed", 1_100, 2)], &none).as_deref(), Some("Fixed"), "newest wins");
1475        assert_eq!(named(&[ev(m, "Moth", 1_000, 1), ev(rogue, "Rude", 1_100, 2)], &none).as_deref(), Some("Moth"), "an unauthorized one names nobody");
1476        assert_eq!(named(&[ev(m, "Moth", 1_000, 1), ev(m, "", 1_100, 2)], &none), None, "a cleared one leaves no name");
1477        for order in [[ev(m, "Low", 1_000, 3), ev(m, "High", 1_000, 4)], [ev(m, "High", 1_000, 4), ev(m, "Low", 1_000, 3)]] {
1478            assert_eq!(named(&order, &none).as_deref(), Some("Low"), "a same-ms tie goes to the lower rumor id, in any order");
1479        }
1480        let ahead = now / 1000 + MAX_FUTURE_MS / 1000 + 1;
1481        assert_eq!(named(&[ev(m, "Moth", 1_000, 1), ev(m, "Squat", ahead, 2)], &none).as_deref(), Some("Moth"), "one dated past the horizon is ignored");
1482        assert_eq!(named(&[ev(m, "Moth", 1_000, 1), ev(m, "Soon", ahead - 1, 2)], &none).as_deref(), Some("Soon"), "one inside it counts");
1483        let silenced = BTreeMap::from([(m, (1_050, 1_200))]);
1484        assert_eq!(named(&[ev(m, "Moth", 1_000, 1), ev(m, "Taunt", 1_100, 2)], &silenced), None, "while timed out, their own names nobody");
1485        assert_eq!(named(&[ev(mod_, "Fixed", 1_000, 1), ev(m, "Backdated", 1_040, 2)], &silenced).as_deref(), Some("Fixed"), "however it is dated, and a moderator's still counts");
1486        assert_eq!(named(&[ev(m, "Moth", 1_000, 1), ev(m, "Taunt", 1_100, 2)], &none).as_deref(), Some("Taunt"), "and once it ends, theirs counts again");
1487    }
1488
1489    #[test]
1490    fn snapshot_chunks_401_members_1_based_sharing_one_timestamp() {
1491        let refounder = Keys::generate();
1492        let members: Vec<PublicKey> = (0..401).map(|_| pk()).collect();
1493        let rumors = build_snapshot_rumors(refounder.public_key(), &members, [0x5a; 32], 1_722_500_000_000);
1494        assert_eq!(rumors.len(), 2);
1495
1496        let parsed: Vec<GuestbookEvent> = rumors.iter().map(|r| through(r, &refounder)).collect();
1497        let (GuestbookEntry::Snapshot { members: m1, snapshot_id: id1, chunk: c1, at_ms: t1, refounder: r1 },
1498             GuestbookEntry::Snapshot { members: m2, snapshot_id: id2, chunk: c2, at_ms: t2, .. }) =
1499            (&parsed[0].entry, &parsed[1].entry)
1500        else {
1501            panic!("expected two snapshot entries");
1502        };
1503        assert_eq!((m1.len(), m2.len()), (400, 1));
1504        assert_eq!((*c1, *c2), ((1, 2), (2, 2)), "snap indices are 1-based");
1505        assert_eq!(id1, &[0x5a; 32]);
1506        assert_eq!(id1, id2);
1507        assert_eq!(t1, t2, "all chunks share one timestamp");
1508        assert_eq!(*r1, refounder.public_key());
1509        let all: Vec<PublicKey> = m1.iter().chain(m2.iter()).copied().collect();
1510        assert_eq!(all, members, "membership survives the chunking intact");
1511
1512        let g = super::super::derive::guestbook_group_key(&[3; 32], &crate::community::CommunityId([4; 32]), crate::community::Epoch(u32::MAX as u64));
1513        let full = &build_snapshot_rumors(refounder.public_key(), &members, [0x5a; 32], u64::MAX / 4)[0];
1514        let (wrap, _) = seal_guestbook_rumor(full, &g, &refounder, Timestamp::from_secs(u32::MAX as u64)).unwrap();
1515        assert!(crate::event_size::check(&wrap).is_ok(), "a full snapshot chunk is {} bytes", wrap.as_json().len());
1516
1517        // No survivors still publishes one observable (empty) chunk.
1518        let empty = build_snapshot_rumors(refounder.public_key(), &[], [0x5b; 32], 1_000);
1519        assert_eq!(empty.len(), 1);
1520        let ev = through(&empty[0], &refounder);
1521        assert!(matches!(ev.entry, GuestbookEntry::Snapshot { ref members, chunk: (1, 1), .. } if members.is_empty()));
1522    }
1523
1524    #[test]
1525    fn plaintext_sealed_guestbook_events_are_rejected() {
1526        // An encrypted seal is what keeps a membership record from being a
1527        // liftable public artifact — the plaintext form must never be honored.
1528        let member = Keys::generate();
1529        let g = group();
1530        let rumor = build_join_rumor(member.public_key(), None, 1_000);
1531        let seal = stream::build_seal(&rumor, SealForm::Plaintext, &g, &member).unwrap();
1532        let (wrap, _) = stream::wrap_seal(&seal, &g, stream::KIND_WRAP, Timestamp::from_secs(1)).unwrap();
1533        let opened = stream::open_wrap(&wrap, &g).unwrap();
1534        assert!(matches!(parse_guestbook_event(&opened), Err(GuestbookError::NotEncryptedSealed)));
1535    }
1536
1537    #[test]
1538    fn future_dated_entries_are_dropped_outright() {
1539        let m = pk();
1540        // A +2h forged date squatting "latest": dropped, so the honest +59min
1541        // leave (inside the skew allowance) holds the head.
1542        let squat = join_ev(m, NOW + 2 * 3_600_000, 1);
1543        let ok = leave_ev(m, NOW + 59 * 60_000, 2);
1544        let fold = coalesce(&[squat, ok], NOW, None, &always);
1545        assert_eq!(fold.get(&m).unwrap().verdict, Verdict::Left);
1546
1547        // Exactly +1h is still allowed — only strictly-greater drops.
1548        let edge = join_ev(m, NOW + MAX_FUTURE_MS, 3);
1549        let fold = coalesce(&[edge], NOW, None, &always);
1550        assert_eq!(fold.get(&m).unwrap().verdict, Verdict::Joined);
1551    }
1552
1553    #[test]
1554    fn latest_wins_per_npub_join_leave_rejoin() {
1555        let m = pk();
1556        let evs = [join_ev(m, 1_000, 1), leave_ev(m, 2_000, 2), join_ev(m, 3_000, 3)];
1557
1558        let fold = coalesce(&evs, NOW, None, &always);
1559        let st = fold.get(&m).unwrap();
1560        assert_eq!(st.verdict, Verdict::Joined, "rejoin-after-leave is Joined");
1561        assert_eq!(st.at_ms, 3_000);
1562
1563        // Order-independent: a shuffled delivery folds identically.
1564        let shuffled = [evs[2].clone(), evs[0].clone(), evs[1].clone()];
1565        assert_eq!(coalesce(&shuffled, NOW, None, &always), fold);
1566
1567        // Without the rejoin, leave-after-join is Left.
1568        let fold = coalesce(&evs[..2], NOW, None, &always);
1569        assert_eq!(fold.get(&m).unwrap().verdict, Verdict::Left);
1570    }
1571
1572    #[test]
1573    fn tie_firsthand_beats_snapshot_then_lower_rumor_id() {
1574        let m = pk();
1575        let auth = pk();
1576
1577        // Firsthand vs snapshot at one instant: the member's own word wins even
1578        // though the snapshot holds the lower (would-otherwise-win) rumor id.
1579        let seed = snap_ev(auth, vec![m], 0x01, (1, 1), 5_000, 0x00);
1580        let leave = leave_ev(m, 5_000, 0xff);
1581        for evs in [[seed.clone(), leave.clone()], [leave, seed]] {
1582            let fold = coalesce(&evs, NOW, Some(&auth), &always);
1583            let st = fold.get(&m).unwrap();
1584            assert_eq!(st.verdict, Verdict::Left);
1585            assert_eq!(st.source, Source::Firsthand);
1586        }
1587
1588        // Two firsthand entries at one instant: the lower rumor id wins.
1589        let join = join_ev(m, 6_000, 0x01);
1590        let leave = leave_ev(m, 6_000, 0x02);
1591        for evs in [[join.clone(), leave.clone()], [leave.clone(), join.clone()]] {
1592            let fold = coalesce(&evs, NOW, None, &always);
1593            assert_eq!(fold.get(&m).unwrap().verdict, Verdict::Joined, "lower id takes the tie");
1594        }
1595        // And symmetrically when the leave holds the lower id.
1596        let join = join_ev(m, 7_000, 0x02);
1597        let leave = leave_ev(m, 7_000, 0x01);
1598        let fold = coalesce(&[join, leave], NOW, None, &always);
1599        assert_eq!(fold.get(&m).unwrap().verdict, Verdict::Left);
1600    }
1601
1602    #[test]
1603    fn kick_needs_the_callers_authority_verdict() {
1604        let admin = pk();
1605        let m = pk();
1606        let evs = [join_ev(m, 1_000, 1), kick_ev(admin, m, 2_000, 2)];
1607
1608        let denied = coalesce(&evs, NOW, None, &|_, _, _| false);
1609        assert_eq!(denied.get(&m).unwrap().verdict, Verdict::Joined, "unauthorized kick is ignored");
1610
1611        let granted = coalesce(&evs, NOW, None, &|actor, target, _| *actor == admin && *target == m);
1612        let st = granted.get(&m).unwrap();
1613        assert_eq!(st.verdict, Verdict::Kicked);
1614        assert_eq!(st.at_ms, 2_000);
1615    }
1616
1617    #[test]
1618    fn snapshots_are_honored_only_from_the_epochs_refounder() {
1619        let refounder = pk();
1620        let impostor = pk();
1621        let m = pk();
1622
1623        // Wrong npub: ignored entirely — no owner fallback, no partial honor.
1624        let forged = snap_ev(impostor, vec![m], 0x01, (1, 1), 5_000, 1);
1625        assert!(coalesce(&[forged], NOW, Some(&refounder), &always).is_empty());
1626
1627        // Unknown authority: NO snapshots honored.
1628        let real = snap_ev(refounder, vec![m], 0x02, (1, 1), 5_000, 2);
1629        assert!(coalesce(&[real.clone()], NOW, None, &always).is_empty());
1630
1631        // The minting refounder seeds Joined at the snapshot's time.
1632        let fold = coalesce(&[real], NOW, Some(&refounder), &always);
1633        let st = fold.get(&m).unwrap();
1634        assert_eq!(st.verdict, Verdict::Joined);
1635        assert_eq!(st.source, Source::Snapshot);
1636        assert_eq!(st.at_ms, 5_000);
1637    }
1638
1639    #[test]
1640    fn snapshot_seeds_yield_to_newer_firsthand_but_not_older() {
1641        let refounder = pk();
1642        let m = pk();
1643        let seed = snap_ev(refounder, vec![m], 0x01, (1, 1), 5_000, 1);
1644
1645        // A newer firsthand Leave supersedes the secondhand seed.
1646        let fold = coalesce(&[seed.clone(), leave_ev(m, 6_000, 2)], NOW, Some(&refounder), &always);
1647        assert_eq!(fold.get(&m).unwrap().verdict, Verdict::Left);
1648
1649        // An OLDER firsthand Join does not override the newer seed.
1650        let fold = coalesce(&[join_ev(m, 4_000, 3), seed], NOW, Some(&refounder), &always);
1651        let st = fold.get(&m).unwrap();
1652        assert_eq!(st.source, Source::Snapshot);
1653        assert_eq!(st.at_ms, 5_000);
1654    }
1655
1656    #[test]
1657    fn a_refounding_replaces_the_guestbook_it_supersedes() {
1658        let refounder = pk();
1659        let (kept, stale, wedged, unstamped_current, later) = (pk(), pk(), pk(), pk(), pk());
1660        let events = [
1661            // Pre-refound rows a store carried over (never stamped).
1662            join_ev(kept, 1_000, 1),
1663            join_ev(stale, 1_000, 2),
1664            // A client still on the OLD plane posted this Join AFTER the refound;
1665            // only the stamp can tell it apart from a real one.
1666            at_epoch(join_ev(wedged, 9_000, 3), 6),
1667            // Stored before stamping existed but dated after the refound: a
1668            // current-plane row that was never re-read. Time keeps it.
1669            join_ev(unstamped_current, 5_500, 4),
1670            at_epoch(snap_ev(refounder, vec![kept], 0x01, (1, 1), 5_000, 5), 7),
1671            at_epoch(join_ev(later, 6_000, 6), 7),
1672        ];
1673        let fold = coalesce(&events, NOW, Some(&refounder), &always);
1674        assert_eq!(fold.get(&kept).unwrap().verdict, Verdict::Joined, "listed: stays");
1675        assert_eq!(fold.get(&later).unwrap().verdict, Verdict::Joined, "joined on the new plane");
1676        assert_eq!(fold.get(&unstamped_current).unwrap().verdict, Verdict::Joined, "unstamped but dated after the cut");
1677        for (who, why) in [(&stale, "older plane by time"), (&wedged, "older plane by stamp, whatever its clock says")] {
1678            let st = fold.get(who).unwrap();
1679            assert_eq!(st.verdict, Verdict::Refounded, "{why}");
1680            assert_eq!(st.at_ms, 5_000, "departed at the refound's time");
1681        }
1682
1683        // The memberlist agrees, and forward observation still re-admits:
1684        // posting after the cut needs the new key, so it is proof of membership.
1685        let none = BTreeSet::new();
1686        let list = complete_memberlist(&fold, &BTreeMap::new(), &none, &BTreeMap::new(), None);
1687        assert!(list.contains(&kept) && list.contains(&later) && !list.contains(&stale));
1688        let mut seen = BTreeMap::new();
1689        seen.insert(stale, 4_000u64);
1690        assert!(!complete_memberlist(&fold, &seen, &none, &BTreeMap::new(), None).contains(&stale), "old activity does not resurrect");
1691        seen.insert(stale, 7_000u64);
1692        assert!(complete_memberlist(&fold, &seen, &none, &BTreeMap::new(), None).contains(&stale), "activity after the cut re-admits");
1693    }
1694
1695    #[test]
1696    fn a_refound_suppresses_an_observed_spammer_the_snapshot_omits() {
1697        // The bug behind the raid: a spammer's Kick was buried by the rotation, so
1698        // their spam (observed activity) re-admits them via forward observation even
1699        // though the refound snapshot never listed them. The refound must gate the
1700        // observed path too. No guestbook Join for these — they exist only as authors.
1701        let (kept, spammer, rejoiner) = (pk(), pk(), pk());
1702        let refound = Refound { cut: 5_000, base: BTreeSet::from([kept]), rumor_id: [9u8; 32] };
1703        let none = BTreeSet::new();
1704        let mut observed = BTreeMap::new();
1705        observed.insert(kept, 4_000u64);      // in base: kept regardless of when they last spoke
1706        observed.insert(spammer, 4_000u64);   // omitted + pre-cut: suppressed
1707        observed.insert(rejoiner, 7_000u64);  // omitted BUT posted after the refound: has the key
1708        let list = complete_memberlist(&BTreeMap::new(), &observed, &none, &BTreeMap::new(), Some(&refound));
1709        assert!(list.contains(&kept), "base member stays");
1710        assert!(!list.contains(&spammer), "buried-kick spammer is not re-admitted by old spam");
1711        assert!(list.contains(&rejoiner), "posting after the cut needs the new key, so it re-admits");
1712        // Without the refound the old behavior stands (spammer re-admitted) — the gate
1713        // only ever removes, never adds.
1714        let ungated = complete_memberlist(&BTreeMap::new(), &observed, &none, &BTreeMap::new(), None);
1715        assert!(ungated.contains(&spammer), "no refound, no gate");
1716
1717        // A grantee (present at the ts-0 sentinel) the snapshot omitted still survives:
1718        // a Grant outranks a snapshot omission (the CONSENSUS-COMPLETE backstop).
1719        let grantee = pk();
1720        let mut with_grantee = observed.clone();
1721        with_grantee.insert(grantee, 0);
1722        let list = complete_memberlist(&BTreeMap::new(), &with_grantee, &none, &BTreeMap::new(), Some(&refound));
1723        assert!(list.contains(&grantee), "a grantee survives the refound gate");
1724    }
1725
1726    #[test]
1727    fn within_one_epoch_snapshots_only_add() {
1728        // A refound snapshot plus a later rescue ADDENDUM on the same epoch: the
1729        // addendum names only the rescued, and must not read as the whole list.
1730        let refounder = pk();
1731        let (a, b, c) = (pk(), pk(), pk());
1732        let events = [
1733            join_ev(a, 1_000, 1),
1734            join_ev(b, 1_000, 2),
1735            join_ev(c, 1_000, 3),
1736            at_epoch(snap_ev(refounder, vec![a], 0x01, (1, 1), 5_000, 4), 7),
1737            at_epoch(snap_ev(refounder, vec![b], 0x02, (1, 1), 8_000, 5), 7),
1738        ];
1739        let fold = coalesce(&events, NOW, Some(&refounder), &always);
1740        assert_eq!(fold.get(&a).unwrap().verdict, Verdict::Joined);
1741        assert_eq!(fold.get(&b).unwrap().verdict, Verdict::Joined, "the addendum adds, it never evicts");
1742        assert_eq!(fold.get(&c).unwrap().verdict, Verdict::Refounded);
1743        assert_eq!(fold.get(&c).unwrap().at_ms, 5_000, "the cut is the refound, not the addendum");
1744    }
1745
1746    #[test]
1747    fn a_snapshot_missing_a_chunk_departs_nobody() {
1748        let refounder = pk();
1749        let (a, b, c) = (pk(), pk(), pk());
1750        let torn = vec![join_ev(a, 1_000, 1), join_ev(b, 1_000, 2), join_ev(c, 1_000, 3), at_epoch(snap_ev(refounder, vec![a], 0x01, (1, 2), 5_000, 4), 7)];
1751        let fold = coalesce(&torn, NOW, Some(&refounder), &always);
1752        for m in [&a, &b, &c] {
1753            assert_eq!(fold.get(m).unwrap().verdict, Verdict::Joined, "leaving someone out of a chunk not in is an absence");
1754        }
1755        let whole = [torn, vec![at_epoch(snap_ev(refounder, vec![b], 0x01, (2, 2), 5_000, 5), 7)]].concat();
1756        let fold = coalesce(&whole, NOW, Some(&refounder), &always);
1757        assert_eq!(fold.get(&b).unwrap().verdict, Verdict::Joined);
1758        assert_eq!(fold.get(&c).unwrap().verdict, Verdict::Refounded, "once whole, it departs whom it omits");
1759    }
1760
1761    #[test]
1762    fn a_whole_addendum_never_stands_in_for_a_torn_base() {
1763        let refounder = pk();
1764        let (a, b, c) = (pk(), pk(), pk());
1765        let events = [
1766            join_ev(a, 1_000, 1),
1767            join_ev(b, 1_000, 2),
1768            join_ev(c, 1_000, 3),
1769            at_epoch(snap_ev(refounder, vec![a], 0x01, (1, 2), 5_000, 4), 7),
1770            at_epoch(snap_ev(refounder, vec![b], 0x02, (1, 1), 8_000, 5), 7),
1771        ];
1772        let fold = coalesce(&events, NOW, Some(&refounder), &always);
1773        for m in [&a, &b, &c] {
1774            assert_eq!(fold.get(m).unwrap().verdict, Verdict::Joined, "the Refounding's own list isn't whole");
1775        }
1776    }
1777
1778    #[test]
1779    fn the_latest_refounding_is_the_one_that_counts() {
1780        let refounder = pk();
1781        let (a, b) = (pk(), pk());
1782        // Epoch 3 listed both; epoch 7 listed only `a`. A store holding both
1783        // snapshots must read like a client that only ever saw epoch 7.
1784        let events = [
1785            join_ev(a, 1_000, 1),
1786            join_ev(b, 1_000, 2),
1787            at_epoch(snap_ev(refounder, vec![a, b], 0x03, (1, 1), 3_000, 3), 3),
1788            at_epoch(snap_ev(refounder, vec![a], 0x07, (1, 1), 7_000, 4), 7),
1789        ];
1790        let fold = coalesce(&events, NOW, Some(&refounder), &always);
1791        assert_eq!(fold.get(&a).unwrap().verdict, Verdict::Joined);
1792        assert_eq!(fold.get(&b).unwrap().verdict, Verdict::Refounded);
1793        assert_eq!(fold.get(&b).unwrap().at_ms, 7_000);
1794    }
1795
1796    #[test]
1797    fn only_the_minters_stamped_snapshot_can_evict() {
1798        let (refounder, impostor, m) = (pk(), pk(), pk());
1799        let forged = [join_ev(m, 1_000, 1), at_epoch(snap_ev(impostor, vec![], 0x01, (1, 1), 5_000, 2), 7)];
1800        assert_eq!(coalesce(&forged, NOW, Some(&refounder), &always).get(&m).unwrap().verdict, Verdict::Joined);
1801        assert_eq!(coalesce(&forged, NOW, None, &always).get(&m).unwrap().verdict, Verdict::Joined);
1802        // A genuine snapshot with no epoch stamp (a wire fold, or a store that has
1803        // not synced since the rotation) replaces nothing either.
1804        let unstamped = [join_ev(m, 1_000, 1), snap_ev(refounder, vec![], 0x01, (1, 1), 5_000, 2)];
1805        assert_eq!(coalesce(&unstamped, NOW, Some(&refounder), &always).get(&m).unwrap().verdict, Verdict::Joined);
1806    }
1807
1808    #[test]
1809    fn a_torn_snapshot_coalesces_order_independently() {
1810        // A maliciously (or buggily) torn snapshot — two chunks of one snap id
1811        // carrying DIFFERENT timestamps — must fold to the SAME member set
1812        // regardless of relay delivery order. (A first-seen timestamp pin made
1813        // the dropped chunk order-dependent, violating determinism; per CORD-02
1814        // §5 there is no torn state to defend against — every authorized chunk
1815        // seeds its members.)
1816        let refounder = pk();
1817        let (a, b, c) = (pk(), pk(), pk());
1818        let c1 = snap_ev(refounder, vec![a], 0x01, (1, 2), 5_000, 1);
1819        let torn = snap_ev(refounder, vec![b], 0x01, (2, 2), 6_000, 2);
1820        let other = snap_ev(refounder, vec![c], 0x02, (1, 1), 6_000, 3);
1821
1822        let forward = coalesce(&[c1.clone(), torn.clone(), other.clone()], NOW, Some(&refounder), &always);
1823        let reverse = coalesce(&[other, torn, c1], NOW, Some(&refounder), &always);
1824        // Both orders seed all three members, identically.
1825        for m in [&a, &b, &c] {
1826            assert!(forward.contains_key(m) && reverse.contains_key(m), "every authorized chunk seeds its members");
1827        }
1828        assert_eq!(forward, reverse, "a torn snapshot must coalesce identically regardless of order");
1829    }
1830
1831    #[test]
1832    fn complete_memberlist_merges_observation_forward_only_minus_banlist() {
1833        let (joined, left, silent, banned_joined, banned_observed) = (pk(), pk(), pk(), pk(), pk());
1834        let coalesced = coalesce(
1835            &[
1836                join_ev(joined, 1_000, 1),
1837                join_ev(left, 1_000, 2),
1838                leave_ev(left, 5_000, 3),
1839                join_ev(banned_joined, 1_000, 4),
1840            ],
1841            NOW,
1842            None,
1843            &always,
1844        );
1845        let banlist: BTreeSet<PublicKey> = [banned_joined, banned_observed].into();
1846
1847        // Old activity (pre-Leave) never resurrects; silent observed authors
1848        // ARE members; the banlist subtracts unconditionally.
1849        let observed: BTreeMap<PublicKey, u64> = [(left, 4_000), (silent, 100), (banned_observed, 9_000)].into();
1850        let list = complete_memberlist(&coalesced, &observed, &banlist, &BTreeMap::new(), None);
1851        assert!(list.contains(&joined));
1852        assert!(list.contains(&silent), "an observed author with no guestbook state is present");
1853        assert!(!list.contains(&left), "activity OLDER than the leave does not resurrect");
1854        assert!(!list.contains(&banned_joined));
1855        assert!(!list.contains(&banned_observed));
1856
1857        // Activity strictly newer than the departure re-enters them.
1858        let observed: BTreeMap<PublicKey, u64> = [(left, 6_000)].into();
1859        let list = complete_memberlist(&coalesced, &observed, &banlist, &BTreeMap::new(), None);
1860        assert!(list.contains(&left));
1861        // Equal-to-departure is not "newer" — still out.
1862        let observed: BTreeMap<PublicKey, u64> = [(left, 5_000)].into();
1863        assert!(!complete_memberlist(&coalesced, &observed, &banlist, &BTreeMap::new(), None).contains(&left));
1864    }
1865
1866    #[test]
1867    fn only_the_guestbook_and_grants_count_and_posting_alone_is_listed_apart() {
1868        let (joined, never, left, grantee) = (pk(), pk(), pk(), pk());
1869        let coalesced = coalesce(&[join_ev(joined, 1_000, 1), join_ev(left, 1_000, 2), leave_ev(left, 5_000, 3)], NOW, None, &always);
1870        let observed: BTreeMap<PublicKey, u64> = [(joined, 9_000), (never, 2_000), (left, 6_000), (grantee, 0)].into();
1871        let parts = memberlist_parts(&coalesced, &observed, &BTreeSet::new(), &BTreeMap::new(), None);
1872        assert_eq!(parts.counted, [joined, grantee].into(), "a count no client's history depth can move");
1873        assert_eq!(parts.unlisted.get(&never), Some(&Unlisted::NoJoin));
1874        assert_eq!(parts.unlisted.get(&left), Some(&Unlisted::Departed));
1875        assert!(!parts.unlisted.contains_key(&joined), "a member who posts is a member, not a suspect");
1876    }
1877
1878    #[test]
1879    fn posting_after_a_refound_omitted_you_lists_you_without_a_join() {
1880        let cut_out = pk();
1881        let coalesced: BTreeMap<PublicKey, MemberState> =
1882            [(cut_out, MemberState { verdict: Verdict::Refounded, at_ms: 5_000, source: Source::Snapshot, invited_by: None, rumor_id: [0; 32] })].into();
1883        let refound = Refound { cut: 5_000, base: BTreeSet::new(), rumor_id: [0; 32] };
1884        let observed: BTreeMap<PublicKey, u64> = [(cut_out, 7_000)].into();
1885        let parts = memberlist_parts(&coalesced, &observed, &BTreeSet::new(), &BTreeMap::new(), Some(&refound));
1886        assert!(parts.counted.is_empty());
1887        assert_eq!(parts.unlisted.get(&cut_out), Some(&Unlisted::NoJoin));
1888    }
1889
1890    #[test]
1891    fn a_ban_mark_gates_observation_but_never_a_join() {
1892        // Ban marks come from the banlist edits this client happened to fold, so a Join must
1893        // not consult them: the un-ban writes the departure to the Guestbook instead.
1894        let (member, chatty) = (pk(), pk());
1895        let coalesced = coalesce(&[join_ev(member, 1_000, 1)], NOW, None, &always);
1896        // Banned at t=5s (marks are SECONDS), then un-banned — so the banlist is empty.
1897        let banned_at: BTreeMap<PublicKey, u64> = [(member, 5), (chatty, 5)].into();
1898        let empty: BTreeSet<PublicKey> = BTreeSet::new();
1899
1900        let observed: BTreeMap<PublicKey, u64> = [(chatty, 4_000)].into();
1901        let list = complete_memberlist(&coalesced, &observed, &empty, &banned_at, None);
1902        assert!(list.contains(&member), "the count is the Guestbook's, whatever this client folded");
1903        assert!(!list.contains(&chatty), "pre-ban activity does not resurrect");
1904        let observed: BTreeMap<PublicKey, u64> = [(chatty, 6_000)].into();
1905        assert!(complete_memberlist(&coalesced, &observed, &empty, &banned_at, None).contains(&chatty), "activity newer than the ban does");
1906
1907        // The un-ban's departure: a Kick dated at the ban, which a later Join still beats.
1908        let kicked = coalesce(&[join_ev(member, 1_000, 1), kick_ev(pk(), member, 5_000, 2)], NOW, None, &always);
1909        assert!(!complete_memberlist(&kicked, &BTreeMap::new(), &empty, &banned_at, None).contains(&member));
1910        let rejoined = coalesce(&[join_ev(member, 1_000, 1), kick_ev(pk(), member, 5_000, 2), join_ev(member, 6_000, 3)], NOW, None, &always);
1911        assert!(complete_memberlist(&rejoined, &BTreeMap::new(), &empty, &banned_at, None).contains(&member));
1912        // Still banned stays out regardless.
1913        let banlist: BTreeSet<PublicKey> = [member].into();
1914        assert!(!complete_memberlist(&rejoined, &BTreeMap::new(), &banlist, &banned_at, None).contains(&member));
1915    }
1916
1917    #[test]
1918    fn malformed_verbs_and_foreign_kinds_are_rejected() {
1919        let k = Keys::generate();
1920        // The verb is exact: case variants and paddings are malformed, never
1921        // normalized (a lenient reader would fold state a strict one dropped).
1922        for bad in ["JOIN", "Join", " join", "leave ", "", "rejoin"] {
1923            let rumor = stream::build_rumor_ms(kind::JOIN_LEAVE, k.public_key(), bad, vec![], 1_000);
1924            assert!(matches!(through_err(&rumor, &k), GuestbookError::BadVerb), "verb {bad:?} must reject");
1925        }
1926        let msg = stream::build_rumor_ms(kind::MESSAGE, k.public_key(), "hi", vec![], 1_000);
1927        assert!(matches!(through_err(&msg, &k), GuestbookError::NotGuestbook(9)));
1928    }
1929
1930    #[test]
1931    fn kick_target_must_be_a_unique_valid_p_tag() {
1932        let k = Keys::generate();
1933
1934        let dup = stream::build_rumor_ms(
1935            kind::KICK,
1936            k.public_key(),
1937            "",
1938            vec![Tag::public_key(pk()), Tag::public_key(pk())],
1939            1_000,
1940        );
1941        assert!(matches!(through_err(&dup, &k), GuestbookError::DuplicateTag("p")));
1942
1943        let missing = stream::build_rumor_ms(kind::KICK, k.public_key(), "", vec![], 1_000);
1944        assert!(matches!(through_err(&missing, &k), GuestbookError::MissingTag("p")));
1945
1946        let bad = stream::build_rumor_ms(
1947            kind::KICK,
1948            k.public_key(),
1949            "",
1950            vec![Tag::custom("p", ["not-hex".to_string()])],
1951            1_000,
1952        );
1953        assert!(matches!(through_err(&bad, &k), GuestbookError::BadTag("p")));
1954    }
1955
1956    #[test]
1957    fn snapshot_snap_tag_and_content_are_strict() {
1958        let k = Keys::generate();
1959        let id_hex = crate::simd::hex::bytes_to_hex_32(&[0x5a; 32]);
1960        let snap_rumor = |content: &str, id: &str, i: &str, n: &str| {
1961            stream::build_rumor_ms(
1962                kind::SNAPSHOT,
1963                k.public_key(),
1964                content,
1965                vec![Tag::custom(
1966                    "snap",
1967                    [id.to_string(), i.to_string(), n.to_string()],
1968                )],
1969                1_000,
1970            )
1971        };
1972
1973        // 0-based, out-of-range, or unparseable indices reject the event.
1974        for (i, n) in [("0", "2"), ("3", "2"), ("abc", "2"), ("1", "x")] {
1975            let r = snap_rumor("[]", &id_hex, i, n);
1976            assert!(matches!(through_err(&r, &k), GuestbookError::BadTag("snap")), "snap {i}/{n} must reject");
1977        }
1978        // A bad snapshot id rejects; a missing snap tag rejects; non-array content rejects.
1979        let bad_id = snap_rumor("[]", "zz", "1", "1");
1980        assert!(matches!(through_err(&bad_id, &k), GuestbookError::BadTag("snap")));
1981        let no_tag = stream::build_rumor_ms(kind::SNAPSHOT, k.public_key(), "[]", vec![], 1_000);
1982        assert!(matches!(through_err(&no_tag, &k), GuestbookError::MissingTag("snap")));
1983        let not_array = snap_rumor("{}", &id_hex, "1", "1");
1984        assert!(matches!(through_err(&not_array, &k), GuestbookError::BadSnapshotContent));
1985    }
1986
1987    #[test]
1988    fn snapshot_bad_member_entries_drop_individually() {
1989        let k = Keys::generate();
1990        let good = pk();
1991        // One valid member among garbage hex and a non-string: the good seed
1992        // survives — secondhand seeding never fails wholesale on one entry.
1993        let content = format!(r#"["{}","not-a-pubkey",17]"#, good.to_hex());
1994        let rumor = stream::build_rumor_ms(
1995            kind::SNAPSHOT,
1996            k.public_key(),
1997            &content,
1998            vec![Tag::custom(
1999                "snap",
2000                [crate::simd::hex::bytes_to_hex_32(&[0x5a; 32]), "1".to_string(), "1".to_string()],
2001            )],
2002            1_000,
2003        );
2004        let ev = through(&rumor, &k);
2005        assert!(matches!(ev.entry, GuestbookEntry::Snapshot { ref members, .. } if members == &vec![good]));
2006    }
2007
2008    #[test]
2009    fn every_entry_round_trips_through_its_stored_body() {
2010        let k = || Keys::generate().public_key();
2011        let cite = Some(AuthorityCitation { entity_id: [4; 32], version: 300, edition_hash: [5; 32] });
2012        let entries = vec![
2013            GuestbookEntry::Join { member: k(), invited_by: None, at_ms: 1_790_000_000_123 },
2014            GuestbookEntry::Join { member: k(), invited_by: Some(("ab".repeat(32), "the café link".into())), at_ms: 0 },
2015            GuestbookEntry::Leave { member: k(), at_ms: u64::MAX },
2016            GuestbookEntry::Kick { actor: k(), target: k(), citation: cite.clone(), at_ms: 5 },
2017            GuestbookEntry::Kick { actor: k(), target: k(), citation: None, at_ms: 6 },
2018            GuestbookEntry::Snapshot { refounder: k(), members: (0..40).map(|_| k()).collect(), snapshot_id: [9; 32], chunk: (3, u32::MAX), at_ms: 7 },
2019            GuestbookEntry::Snapshot { refounder: k(), members: Vec::new(), snapshot_id: [1; 32], chunk: (1, 1), at_ms: 8 },
2020            GuestbookEntry::Timeout { actor: k(), target: k(), until_secs: 1 << 40, citation: cite.clone(), at_ms: 9 },
2021            GuestbookEntry::Nickname { actor: k(), target: k(), nick: String::new(), citation: None, at_ms: 10 },
2022            GuestbookEntry::Nickname { actor: k(), target: k(), nick: "ナイト🌙".into(), citation: cite, at_ms: 11 },
2023        ];
2024        for (i, entry) in entries.into_iter().enumerate() {
2025            for (epoch, observed_at) in [(None, None), (Some(0), None), (None, Some(1_790_000_000)), (Some(u64::MAX), Some(u64::MAX))] {
2026                let ev = GuestbookEvent { rumor_id: [i as u8; 32], entry: entry.clone(), epoch, observed_at };
2027                let body = event_body(&ev);
2028                assert_ne!(body.len(), 32, "never the length at-rest storage reads as a bare key");
2029                assert_eq!(event_from_body(ev.rumor_id, &body).as_ref(), Some(&ev));
2030                // Any cut, or any byte past the end, is no event.
2031                for cut in 0..body.len() {
2032                    assert_eq!(event_from_body(ev.rumor_id, &body[..cut]), None, "cut {cut} of {i}");
2033                }
2034                assert_eq!(event_from_body(ev.rumor_id, &[&body[..], &[0]].concat()), None);
2035            }
2036        }
2037        let join = GuestbookEvent { rumor_id: [0; 32], entry: GuestbookEntry::Join { member: k(), invited_by: None, at_ms: 1_790_000_000_123 }, epoch: Some(3), observed_at: Some(1_790_000_000) };
2038        assert!(event_body(&join).len() < 60, "a join is {} bytes", event_body(&join).len());
2039    }
2040
2041}