Skip to main content

vector_core/community/v2/
writers.rs

1//! A restricted Channel's Writers ledger (CORD-03 §1): which address takes posts when.
2//!
3//! The ledger is a Control entity, so every member folds the same answer and a Refounding
4//! carries it. Writer secrets travel separately, on the access plane, and a member adopts one
5//! only if it derives to the address the ledger names.
6
7use super::derive::{channel_writer_group_key, writer_scope};
8use crate::community::{ChannelId, Epoch};
9
10/// The most entries a ledger holds; a longer one is malformed.
11pub const MAX_LEDGER: usize = 64;
12
13/// The most writer entries the cap retires before the oldest goes for good.
14pub const MAX_RETIRED: usize = 64;
15
16/// Writer epochs stay below this, so every reader's arithmetic agrees.
17pub const MAX_EPOCH: u64 = 1 << 53;
18
19/// How far an edition's new entry may sit from the edition's own time.
20pub const ENTRY_SKEW_MS: u64 = 10 * 60 * 1000;
21
22/// How far past a reader's clock a new entry may be dated before it waits (CORD-02 §5).
23pub const HORIZON_MS: u64 = 60 * 60 * 1000;
24
25/// What one ledger entry moves the Channel to.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Spell {
28    /// Posts land at this writer epoch's address, minted under root epoch `root` by `by`, whose
29    /// writers carry a certificate from `certifier`.
30    Writer { epoch: Epoch, pk: [u8; 32], root: Epoch, by: [u8; 32], certifier: Option<[u8; 32]> },
31    /// Posts land at the read address again.
32    Open,
33    /// From here on the live epoch's certificate for `writer` vouches for nothing: a writer the
34    /// Channel no longer lets post. Moves no window.
35    Stop { writer: [u8; 32] },
36    /// An entry of a kind this build doesn't know, carried verbatim: it moves nothing.
37    Other,
38}
39
40impl Spell {
41    /// Whether this entry moves where posts land.
42    fn moves(&self) -> bool {
43        matches!(self, Spell::Writer { .. } | Spell::Open)
44    }
45}
46
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct Entry {
49    /// Unix milliseconds this entry starts holding.
50    pub at: u64,
51    pub spell: Spell,
52    /// Unknown fields, carried through our own editions (CORD-02 §6).
53    pub extra: serde_json::Map<String, serde_json::Value>,
54}
55
56/// The field a stop carries when it records a departure that came before it was written.
57const STOP_FROM: &str = "from";
58
59/// The field of the entry a seal's edition appends: how many ids the seal names.
60const SEALED: &str = "sealed";
61
62/// The field a writer entry carries when its window is Locked: every write rides its address,
63/// reactions and calls included. A reader that predates it carries it verbatim and reads the
64/// window as one that gates posting alone.
65const LOCKED: &str = "locked";
66
67impl Entry {
68    /// Whether this is a writer entry whose window is Locked.
69    pub fn locked(&self) -> bool {
70        matches!(self.spell, Spell::Writer { .. }) && self.extra.get(LOCKED) == Some(&serde_json::Value::Bool(true))
71    }
72
73    /// When this entry takes effect: its own date, or for a stop, the departure it records if
74    /// that came first. A reader that predates `from` applies the stop from its own date.
75    pub fn effective(&self) -> u64 {
76        match self.spell {
77            Spell::Stop { .. } => self.extra.get(STOP_FROM).and_then(|v| v.as_u64()).map_or(self.at, |from| from.min(self.at)),
78            _ => self.at,
79        }
80    }
81}
82
83/// A writer entry the cap dropped: its address still reads, its window stays closed, and its
84/// writers' certificates still check.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub struct Retired {
87    pub epoch: Epoch,
88    pub pk: [u8; 32],
89    pub from: u64,
90    pub to: u64,
91    pub certifier: Option<[u8; 32]>,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq, Default)]
95pub struct Ledger {
96    pub channel: [u8; 32],
97    pub entries: Vec<Entry>,
98    pub retired: Vec<Retired>,
99    /// The newest seal of its history.
100    pub seal: Option<SealRef>,
101    /// Unknown top-level fields, carried through our own editions (CORD-02 §6).
102    pub extra: serde_json::Map<String, serde_json::Value>,
103}
104
105fn hex32(v: &serde_json::Value) -> Option<[u8; 32]> {
106    crate::simd::hex::hex_to_bytes_32_checked(v.as_str()?)
107}
108
109/// Which keys a run of parses found to be x-only public keys, each checked once: a ledger names
110/// the same writers in every version, and each check is a point decompression.
111#[derive(Default)]
112pub struct KeyCheck(std::collections::HashMap<[u8; 32], bool>);
113
114impl KeyCheck {
115    fn writer_pk(&mut self, v: &serde_json::Value) -> Option<[u8; 32]> {
116        let pk = hex32(v)?;
117        let valid = *self.0.entry(pk).or_insert_with(|| nostr_sdk::prelude::PublicKey::from_slice(&pk).and_then(|p| p.xonly()).is_ok());
118        valid.then_some(pk)
119    }
120}
121
122fn epoch_of(v: &serde_json::Value) -> Option<Epoch> {
123    v.as_u64().filter(|n| *n > 0 && *n < MAX_EPOCH).map(Epoch)
124}
125
126/// A Channel's sealed history (CORD-03 §1): what its read address held before `until` (unix ms)
127/// is exactly the wrap ids its pages list, from the first, `page`, opened under read epoch `read`.
128/// `run` is when the run of Locked windows it was made in began. It rides the ledger's top level,
129/// where the cap never reaches.
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct SealRef {
132    /// `None` for a seal of nothing.
133    pub page: Option<[u8; 32]>,
134    pub read: Epoch,
135    pub until: u64,
136    pub run: u64,
137    pub count: u64,
138    /// Fields this build doesn't know, carried through its own editions (CORD-02 §6).
139    pub extra: serde_json::Map<String, serde_json::Value>,
140}
141
142impl SealRef {
143    fn parse(v: &serde_json::Value) -> Option<Self> {
144        let mut o = v.as_object()?.clone();
145        let page = match o.remove("page")? {
146            serde_json::Value::Null => None,
147            p => Some(hex32(&p)?),
148        };
149        let read = Epoch(o.remove("read")?.as_u64()?);
150        let (until, run, count) = (o.remove("until")?.as_u64()?, o.remove("run")?.as_u64()?, o.remove("count")?.as_u64()?);
151        (until <= run.saturating_add(ENTRY_SKEW_MS)).then_some(SealRef { page, read, until, run, count, extra: o })
152    }
153
154    fn to_json(&self) -> serde_json::Value {
155        let mut o = self.extra.clone();
156        o.insert("page".into(), self.page.map_or(serde_json::Value::Null, |p| crate::simd::hex::bytes_to_hex_32(&p).into()));
157        o.insert("read".into(), self.read.0.into());
158        o.insert("until".into(), self.until.into());
159        o.insert("run".into(), self.run.into());
160        o.insert("count".into(), self.count.into());
161        serde_json::Value::Object(o)
162    }
163}
164
165impl Ledger {
166    pub fn new(channel: &ChannelId) -> Self {
167        Ledger { channel: channel.0, ..Default::default() }
168    }
169
170    /// Parse a ledger, `None` when it is malformed: entries out of `at` order, writer epochs
171    /// (retired, then live) not strictly rising or out of range, more than [`MAX_LEDGER`]
172    /// entries or [`MAX_RETIRED`] retired, or an entry that is neither one thing.
173    pub fn parse(content: &str) -> Option<Self> {
174        Self::parse_with(content, &mut KeyCheck::default())
175    }
176
177    /// [`Self::parse`], sharing `keys` across a run of parses.
178    pub fn parse_with(content: &str, keys: &mut KeyCheck) -> Option<Self> {
179        let serde_json::Value::Object(mut top) = serde_json::from_str(content).ok()? else { return None };
180        let channel = hex32(&top.remove("channel")?)?;
181        let serde_json::Value::Array(raw) = top.remove("ledger")? else { return None };
182        let retired = match top.remove("retired") {
183            None => Vec::new(),
184            Some(serde_json::Value::Array(r)) => r
185                .iter()
186                .map(|x| {
187                    let x = x.as_array().filter(|x| x.len() == 4 || x.len() == 5)?;
188                    let certifier = match x.get(4) {
189                        None => None,
190                        Some(c) => Some(keys.writer_pk(c)?),
191                    };
192                    Some(Retired { epoch: epoch_of(&x[0])?, pk: keys.writer_pk(&x[1])?, from: x[2].as_u64()?, to: x[3].as_u64()?, certifier })
193                })
194                .collect::<Option<Vec<_>>>()?,
195            Some(_) => return None,
196        };
197        if raw.len() > MAX_LEDGER || retired.len() > MAX_RETIRED {
198            return None;
199        }
200        let mut entries = Vec::with_capacity(raw.len());
201        for e in raw {
202            let serde_json::Value::Object(mut e) = e else { return None };
203            let at = e.remove("at")?.as_u64()?;
204            let stop = e.remove("stop");
205            let spell = match (e.remove("open"), e.remove("epoch"), e.remove("writer"), e.remove("root"), e.remove("by")) {
206                (None, None, None, None, None) if stop.is_some() => Spell::Stop { writer: keys.writer_pk(stop.as_ref()?)? },
207                (None, None, None, None, None) => Spell::Other,
208                (Some(serde_json::Value::Bool(true)), None, None, None, None) if stop.is_none() => Spell::Open,
209                (None, Some(epoch), Some(writer), Some(root), Some(by)) if stop.is_none() => {
210                    let certifier = match e.remove("certifier") {
211                        None => None,
212                        Some(c) => Some(keys.writer_pk(&c)?),
213                    };
214                    Spell::Writer { epoch: epoch_of(&epoch)?, pk: keys.writer_pk(&writer)?, root: Epoch(root.as_u64()?), by: hex32(&by)?, certifier }
215                }
216                _ => return None,
217            };
218            entries.push(Entry { at, spell, extra: e });
219        }
220        // A seal this reader can't read is carried as it came.
221        let seal = top.get("seal").and_then(SealRef::parse);
222        if seal.is_some() {
223            top.remove("seal");
224        }
225        let ledger = Ledger { channel, entries, retired, seal, extra: top };
226        ledger.well_formed().then_some(ledger)
227    }
228
229    fn well_formed(&self) -> bool {
230        let ordered = self.entries.windows(2).all(|w| w[0].at <= w[1].at);
231        // A stop is a writer window's; an open one has nobody to stop.
232        let stops = self.entries.iter().enumerate().all(|(i, e)| {
233            !matches!(e.spell, Spell::Stop { .. }) || !matches!(self.entries[..i].iter().rev().find(|e| e.spell.moves()).map(|e| e.spell), Some(Spell::Open))
234        });
235        let windows = self.retired.iter().all(|r| r.from <= r.to);
236        let epochs: Vec<u64> = self.writers().map(|(e, ..)| e.0).collect();
237        ordered && stops && windows && epochs.windows(2).all(|w| w[0] < w[1]) && self.entries.len() <= MAX_LEDGER && self.retired.len() <= MAX_RETIRED
238    }
239
240    pub fn to_json(&self) -> String {
241        let entries: Vec<serde_json::Value> = self
242            .entries
243            .iter()
244            .map(|e| {
245                let mut o = e.extra.clone();
246                o.insert("at".into(), e.at.into());
247                match e.spell {
248                    Spell::Writer { epoch, pk, root, by, certifier } => {
249                        o.insert("epoch".into(), epoch.0.into());
250                        o.insert("writer".into(), crate::simd::hex::bytes_to_hex_32(&pk).into());
251                        o.insert("root".into(), root.0.into());
252                        o.insert("by".into(), crate::simd::hex::bytes_to_hex_32(&by).into());
253                        if let Some(c) = certifier {
254                            o.insert("certifier".into(), crate::simd::hex::bytes_to_hex_32(&c).into());
255                        }
256                    }
257                    Spell::Open => {
258                        o.insert("open".into(), true.into());
259                    }
260                    Spell::Stop { writer } => {
261                        o.insert("stop".into(), crate::simd::hex::bytes_to_hex_32(&writer).into());
262                    }
263                    Spell::Other => {}
264                }
265                serde_json::Value::Object(o)
266            })
267            .collect();
268        let mut top = self.extra.clone();
269        top.insert("channel".into(), crate::simd::hex::bytes_to_hex_32(&self.channel).into());
270        if let Some(seal) = &self.seal {
271            top.insert("seal".into(), seal.to_json());
272        }
273        top.insert("ledger".into(), entries.into());
274        if !self.retired.is_empty() {
275            let retired: Vec<serde_json::Value> = self
276                .retired
277                .iter()
278                .map(|r| match r.certifier {
279                    Some(c) => serde_json::json!([r.epoch.0, crate::simd::hex::bytes_to_hex_32(&r.pk), r.from, r.to, crate::simd::hex::bytes_to_hex_32(&c)]),
280                    None => serde_json::json!([r.epoch.0, crate::simd::hex::bytes_to_hex_32(&r.pk), r.from, r.to]),
281                })
282                .collect();
283            top.insert("retired".into(), retired.into());
284        }
285        serde_json::Value::Object(top).to_string()
286    }
287
288    /// The newest entry that moved where posts land.
289    fn last_move(&self) -> Option<&Entry> {
290        self.entries.iter().rev().find(|e| e.spell.moves())
291    }
292
293    /// Whether posts land at a writer address now.
294    pub fn restricted(&self) -> bool {
295        matches!(self.last_move(), Some(Entry { spell: Spell::Writer { .. }, .. }))
296    }
297
298    /// Whether every write lands at a writer address now.
299    pub fn locked(&self) -> bool {
300        self.last_move().is_some_and(Entry::locked)
301    }
302
303    /// Whether `at_ms` falls in a Locked window the ledger still holds whole. A retired window
304    /// keeps its address and dates, not its flag.
305    pub fn locked_at(&self, at_ms: u64) -> bool {
306        self.entries.iter().rev().find(|e| e.at <= at_ms && e.spell.moves()).is_some_and(Entry::locked)
307    }
308
309    /// The dates the read address holds nothing a reader needs: each run of Locked windows from
310    /// ten minutes past its start (a client that hadn't read the lock may still use it until then),
311    /// and the seal's stretch from its end to the first window after it that isn't Locked, which
312    /// holds the run even once its early entries retire. Sorted, disjoint; `None` while running.
313    pub fn quiet_spans(&self) -> Vec<(u64, Option<u64>)> {
314        let moves: Vec<&Entry> = self.entries.iter().filter(|e| e.spell.moves()).collect();
315        let end_after = |at: u64| moves.iter().find(|e| e.at > at && !e.locked()).map(|e| e.at);
316        let mut spans: Vec<(u64, Option<u64>)> = moves
317            .iter()
318            .enumerate()
319            .filter(|(i, e)| e.locked() && (*i == 0 || !moves[i - 1].locked()))
320            .map(|(_, e)| (e.at.saturating_add(ENTRY_SKEW_MS), end_after(e.at)))
321            .collect();
322        // The seal's run, from its first ten minutes on, whatever entries of it remain.
323        if let Some(seal) = &self.seal {
324            let from = seal.run.saturating_add(ENTRY_SKEW_MS);
325            spans.push((from, end_after(seal.run)));
326        }
327        spans.retain(|(from, to)| to.is_none_or(|t| t > *from));
328        spans.sort_by_key(|s| s.0);
329        let mut out: Vec<(u64, Option<u64>)> = Vec::with_capacity(spans.len());
330        for (from, to) in spans {
331            match out.last_mut() {
332                Some(last) if last.1.is_none_or(|end| end >= from) => {
333                    last.1 = last.1.zip(to).map(|(a, b)| a.max(b));
334                }
335                _ => out.push((from, to)),
336            }
337        }
338        out
339    }
340
341    /// Whether nothing a reader needs sits at the read address at `at_ms`.
342    pub fn read_address_quiet(&self, at_ms: u64) -> bool {
343        self.quiet_spans().iter().any(|(from, to)| *from <= at_ms && to.is_none_or(|t| at_ms < t))
344    }
345
346    /// The dates at or below `top_ms` the read address is read by, as `(floor, top)`: the top
347    /// lowered out of any quiet span, the floor the nearest quiet span below or the seal's end.
348    /// `None` when nothing above the seal is left.
349    pub fn read_range(&self, top_ms: u64) -> Option<(u64, u64)> {
350        let spans = self.quiet_spans();
351        let mut top = top_ms;
352        if let Some((from, _)) = spans.iter().find(|(from, to)| *from <= top && to.is_none_or(|t| top < t)) {
353            top = from.checked_sub(1)?;
354        }
355        let below = spans.iter().filter_map(|(_, to)| *to).filter(|t| *t <= top).max().unwrap_or(0);
356        let floor = below.max(self.seal.as_ref().map_or(0, |s| s.until));
357        (floor <= top).then_some((floor, top))
358    }
359
360    /// When the live run of Locked windows began, while the live window is Locked.
361    pub fn run_start(&self) -> Option<u64> {
362        let moves: Vec<&Entry> = self.entries.iter().filter(|e| e.spell.moves()).collect();
363        let tail = moves.iter().rev().take_while(|e| e.locked()).last()?;
364        Some(tail.at)
365    }
366
367    /// Where the live run of Locked windows is owed a seal to at `now_ms`, if anywhere: up to its
368    /// start once it begins, then across its first ten minutes once they pass. A seal made in an
369    /// earlier run, one a window that wasn't Locked has followed since, is this run's no longer.
370    pub fn seal_target(&self, now_ms: u64) -> Option<u64> {
371        let start = self.run_start()?;
372        let in_run = self.seal.as_ref().filter(|s| !self.entries.iter().any(|e| e.spell.moves() && e.at > s.run && !e.locked()));
373        match in_run {
374            None => Some(start),
375            Some(s) if s.until < s.run.saturating_add(ENTRY_SKEW_MS) && now_ms >= s.run.saturating_add(ENTRY_SKEW_MS) => Some(s.run.saturating_add(ENTRY_SKEW_MS)),
376            _ => None,
377        }
378    }
379
380    /// When the run the next seal belongs to began: the live seal's own, while it still holds the
381    /// run, else the live run's start.
382    pub fn seal_run(&self) -> Option<u64> {
383        let start = self.run_start()?;
384        Some(self.seal.as_ref().filter(|s| !self.entries.iter().any(|e| e.spell.moves() && e.at > s.run && !e.locked())).map_or(start, |s| s.run))
385    }
386
387    /// This ledger sealed by `seal`: the edition appends a marker entry the cap may drop, and the
388    /// seal itself rides the top level.
389    pub fn appended_seal(&self, at: u64, seal: SealRef) -> Option<Self> {
390        let at = self.entries.last().map_or(at, |last| at.max(last.at));
391        let mut extra = serde_json::Map::new();
392        extra.insert(SEALED.into(), seal.count.into());
393        let mut next = self.with(Entry { at, spell: Spell::Other, extra })?;
394        next.seal = Some(seal);
395        Some(next)
396    }
397
398    /// The writer epoch taking posts now.
399    pub fn current_writer(&self) -> Option<(Epoch, [u8; 32])> {
400        match self.last_move()?.spell {
401            Spell::Writer { epoch, pk, .. } => Some((epoch, pk)),
402            _ => None,
403        }
404    }
405
406    /// The live writer entry: its root epoch (a Refounding retires it), its minter, and when it began.
407    pub fn live(&self) -> Option<(Epoch, [u8; 32], u64)> {
408        let last = self.last_move()?;
409        match last.spell {
410            Spell::Writer { root, by, .. } => Some((root, by, last.at)),
411            _ => None,
412        }
413    }
414
415    /// Whether `writer` was stopped at writer `epoch` by `at_ms`: a stop entry for them inside
416    /// that epoch's window, dated no later. A stop outlives its window's entry retiring; only the
417    /// cap dropping the stop itself undoes it.
418    pub fn stopped(&self, epoch: Epoch, writer: &[u8; 32], at_ms: u64) -> bool {
419        let names = |e: &Entry| e.effective() <= at_ms && matches!(e.spell, Spell::Stop { writer: w } if w == *writer);
420        if let Some(start) = self.entries.iter().position(|e| matches!(e.spell, Spell::Writer { epoch: w, .. } if w == epoch)) {
421            return self.entries[start + 1..].iter().take_while(|e| !e.spell.moves()).any(names);
422        }
423        // Retired: the stops left at the front, before the first entry that moves, inside its window.
424        // A stop dated with the entry that retired its window was still written inside it.
425        self.retired.iter().find(|r| r.epoch == epoch).is_some_and(|r| self.entries.iter().take_while(|e| !e.spell.moves()).any(|e| (r.from..=r.to).contains(&e.at) && names(e)))
426    }
427
428    /// Who minted writer `epoch`, while the ledger still holds its entry.
429    pub fn minter(&self, epoch: Epoch) -> Option<[u8; 32]> {
430        self.entries.iter().find_map(|e| match e.spell {
431            Spell::Writer { epoch: w, by, .. } if w == epoch => Some(by),
432            _ => None,
433        })
434    }
435
436    /// The writer epoch before the live one, if the ledger still names it.
437    pub fn previous_writer(&self) -> Option<Epoch> {
438        let mut epochs = self.writers().map(|(e, ..)| e).collect::<Vec<_>>();
439        epochs.pop();
440        epochs.pop()
441    }
442
443    /// The epoch a newly minted writer secret takes, `None` once the range is spent.
444    pub fn next_epoch(&self) -> Option<Epoch> {
445        let next = self.writers().map(|(e, ..)| e.0).max().unwrap_or(0).checked_add(1)?;
446        (next < MAX_EPOCH).then_some(Epoch(next))
447    }
448
449    /// Every writer address, retired then live, with the millisecond its entry ends, `None` while
450    /// it still holds.
451    pub fn writers(&self) -> impl Iterator<Item = (Epoch, [u8; 32], Option<u64>)> + '_ {
452        let retired = self.retired.iter().map(|r| (r.epoch, r.pk, Some(r.to)));
453        let live = self.entries.iter().enumerate().filter_map(|(i, e)| match e.spell {
454            Spell::Writer { epoch, pk, .. } => Some((epoch, pk, self.entries[i + 1..].iter().find(|n| n.spell.moves()).map(|n| n.at))),
455            _ => None,
456        });
457        retired.chain(live)
458    }
459
460    /// The root epochs its live writer entries were minted under: what they carried is sealed
461    /// under each one's read key.
462    pub fn roots(&self) -> impl Iterator<Item = Epoch> + '_ {
463        self.entries.iter().filter_map(|e| match e.spell {
464            Spell::Writer { root, .. } => Some(root),
465            _ => None,
466        })
467    }
468
469    /// When each writer address began, to bound what a read of it can hold.
470    pub fn writer_start(&self, epoch: Epoch) -> Option<u64> {
471        self.retired
472            .iter()
473            .find(|r| r.epoch == epoch)
474            .map(|r| r.from)
475            .or_else(|| self.entries.iter().find(|e| matches!(e.spell, Spell::Writer { epoch: w, .. } if w == epoch)).map(|e| e.at))
476    }
477
478    /// Whether a post at the read address dated `at_ms` stands: not inside a writer entry, live
479    /// or retired.
480    pub fn read_address_takes(&self, at_ms: u64) -> bool {
481        if self.retired.iter().any(|r| (r.from..r.to).contains(&at_ms)) {
482            return false;
483        }
484        !matches!(self.entries.iter().rev().find(|e| e.at <= at_ms && e.spell.moves()), Some(Entry { spell: Spell::Writer { .. }, .. }))
485    }
486
487    /// The key that certifies writer `epoch`'s writers, live or retired.
488    pub fn certifier(&self, epoch: Epoch) -> Option<[u8; 32]> {
489        self.retired.iter().find(|r| r.epoch == epoch).and_then(|r| r.certifier).or_else(|| {
490            self.entries.iter().find_map(|e| match e.spell {
491                Spell::Writer { epoch: w, certifier, .. } if w == epoch => certifier,
492                _ => None,
493            })
494        })
495    }
496
497    /// Whether `cert` is the certifier of writer `epoch` vouching for `writer` in this Channel.
498    pub fn certifies(&self, community: &[u8; 32], epoch: Epoch, writer: &[u8; 32], cert: &[u8; 64]) -> bool {
499        self.certifier(epoch).is_some_and(|c| verify_writer_cert(&c, &cert_digest(community, &self.channel, epoch, writer), cert))
500    }
501
502    /// Whether `cert` is the certifier of writer `epoch` vouching for `writer` with only `rights`.
503    pub fn certifies_scoped(&self, community: &[u8; 32], epoch: Epoch, writer: &[u8; 32], rights: u64, cert: &[u8; 64]) -> bool {
504        self.certifier(epoch).is_some_and(|c| verify_writer_cert(&c, &scoped_cert_digest(community, &self.channel, epoch, writer, rights), cert))
505    }
506
507    /// Whether a post at writer `epoch`'s address dated `at_ms` stands: before its entry ends.
508    pub fn writer_address_takes(&self, epoch: Epoch, at_ms: u64) -> bool {
509        self.writers().any(|(e, _, end)| e == epoch && end.is_none_or(|end| at_ms < end))
510    }
511
512    /// This ledger with `entry` appended verbatim; at the cap the oldest entry goes, a writer one
513    /// into `retired`. `None` when that leaves it malformed.
514    fn with(&self, entry: Entry) -> Option<Self> {
515        let mut next = self.clone();
516        next.entries.push(entry);
517        if next.entries.len() > MAX_LEDGER {
518            let gone = next.entries.remove(0);
519            if let Spell::Writer { epoch, pk, certifier, .. } = gone.spell {
520                // Its window runs to the next entry that moves posts; the live one never retires.
521                let to = next.entries.iter().find(|e| e.spell.moves())?.at;
522                next.retired.push(Retired { epoch, pk, from: gone.at, to, certifier });
523                if next.retired.len() > MAX_RETIRED {
524                    next.retired.remove(0);
525                }
526            }
527        }
528        next.well_formed().then_some(next)
529    }
530
531    /// This ledger with `spell` appended at `at`, never before the last entry. `None` when a
532    /// writer epoch isn't above the last.
533    pub fn appended(&self, at: u64, spell: Spell) -> Option<Self> {
534        self.appended_from(at, spell, None)
535    }
536
537    /// [`Self::appended`] for a writer entry, its window Locked when `locked`.
538    pub fn appended_writer(&self, at: u64, spell: Spell, locked: bool) -> Option<Self> {
539        let at = self.entries.last().map_or(at, |last| at.max(last.at));
540        let mut extra = serde_json::Map::new();
541        if locked && matches!(spell, Spell::Writer { .. }) {
542            extra.insert(LOCKED.into(), true.into());
543        }
544        self.with(Entry { at, spell, extra })
545    }
546
547    /// [`Self::appended`]; a stop dated `at` that records a departure from `from`.
548    pub fn appended_from(&self, at: u64, spell: Spell, from: Option<u64>) -> Option<Self> {
549        let at = self.entries.last().map_or(at, |last| at.max(last.at));
550        let mut extra = serde_json::Map::new();
551        if let (Spell::Stop { .. }, Some(from)) = (spell, from.filter(|f| *f < at)) {
552            extra.insert(STOP_FROM.into(), from.into());
553        }
554        self.with(Entry { at, spell, extra })
555    }
556
557    /// Whether this ledger is `prev` with exactly one entry appended.
558    pub fn extends(&self, prev: &Ledger) -> bool {
559        let Some(last) = self.entries.last() else { return false };
560        prev.with(last.clone()).is_some_and(|grown| grown.channel == self.channel && grown.entries == self.entries && grown.retired == self.retired)
561    }
562
563    /// Whether this ledger could be a Channel's first: one entry and nothing retired.
564    pub fn is_first(&self) -> bool {
565        self.entries.len() == 1 && self.retired.is_empty()
566    }
567
568    /// Whether this ledger's newest entry sits within [`ENTRY_SKEW_MS`] of `edition_secs`, and,
569    /// when it is a writer entry, names `author` as its minter: an edition appends its own.
570    pub fn tail_fits(&self, edition_secs: u64, author: &[u8; 32]) -> bool {
571        let Some(last) = self.entries.last() else { return false };
572        let near = last.at.abs_diff(edition_secs.saturating_mul(1000)) <= ENTRY_SKEW_MS;
573        near && !matches!(last.spell, Spell::Writer { by, .. } if by != *author)
574    }
575
576    /// Whether the newest entry is dated within [`HORIZON_MS`] of `now_ms`: a later one waits.
577    pub fn not_ahead(&self, now_ms: u64) -> bool {
578        self.entries.last().is_some_and(|e| e.at <= now_ms.saturating_add(HORIZON_MS))
579    }
580}
581
582/// What a writer certificate signs: one member's place among a Channel's writers at one epoch.
583pub fn cert_digest(community: &[u8; 32], channel: &[u8; 32], epoch: Epoch, writer: &[u8; 32]) -> [u8; 32] {
584    use sha2::Digest;
585    let mut h = sha2::Sha256::new();
586    h.update(b"concord/writer-cert");
587    h.update(community);
588    h.update(channel);
589    h.update(epoch.0.to_be_bytes());
590    h.update(writer);
591    h.finalize().into()
592}
593
594/// What a scoped writer certificate signs: one member's place among a Channel's writers at one
595/// epoch, for only the writes `rights` names (CORD-04 bits). A post never stands on one.
596pub fn scoped_cert_digest(community: &[u8; 32], channel: &[u8; 32], epoch: Epoch, writer: &[u8; 32], rights: u64) -> [u8; 32] {
597    use sha2::Digest;
598    let mut h = sha2::Sha256::new();
599    h.update(b"concord/writer-cert-scoped");
600    h.update(community);
601    h.update(channel);
602    h.update(epoch.0.to_be_bytes());
603    h.update(writer);
604    h.update(rights.to_be_bytes());
605    h.finalize().into()
606}
607
608/// The never-published event a writer certificate signs: [`cert_digest`] under the certifier.
609fn cert_event(certifier: nostr_sdk::prelude::PublicKey, digest: &[u8; 32]) -> nostr_sdk::prelude::UnsignedEvent {
610    use nostr_sdk::prelude::{Kind, Tag, Timestamp, UnsignedEvent};
611    UnsignedEvent::new(certifier, Timestamp::from_secs(0), Kind::Custom(CERT_KIND), [Tag::custom("digest", [crate::simd::hex::bytes_to_hex_32(digest)])], "")
612}
613
614/// The kind of the event a writer certificate signs; never published.
615const CERT_KIND: u16 = 3320;
616
617/// A certifier's signature over [`cert_digest`].
618pub fn sign_writer_cert(certifier: &[u8; 32], digest: &[u8; 32]) -> Option<[u8; 64]> {
619    let keys = nostr_sdk::prelude::Keys::new(nostr_sdk::prelude::SecretKey::from_slice(certifier).ok()?);
620    let e = cert_event(keys.public_key(), digest);
621    let id = nostr_sdk::prelude::EventId::compute(&e.pubkey, &e.created_at, &e.kind, &e.tags, &e.content);
622    Some(keys.sign_schnorr(id.as_bytes()).to_bytes())
623}
624
625pub fn verify_writer_cert(certifier: &[u8; 32], digest: &[u8; 32], cert: &[u8; 64]) -> bool {
626    use nostr_sdk::prelude::{Event, EventId, PublicKey, Signature};
627    let (Ok(pk), Ok(sig)) = (PublicKey::from_slice(certifier), Signature::from_slice(cert)) else { return false };
628    let unsigned = cert_event(pk, digest);
629    let id = EventId::compute(&pk, &unsigned.created_at, &unsigned.kind, &unsigned.tags, &unsigned.content);
630    Event::new(id, pk, unsigned.created_at, unsigned.kind, unsigned.tags, unsigned.content, sig).verify_signature()
631}
632
633/// The certifier key a certifier secret yields.
634pub fn certifier_of(secret: &[u8; 32]) -> Option<[u8; 32]> {
635    nostr_sdk::prelude::SecretKey::from_slice(secret).ok().map(|s| nostr_sdk::prelude::Keys::new(s).public_key().to_bytes())
636}
637
638/// The writer address a secret yields for `epoch`.
639pub fn writer_address(secret: &[u8; 32], channel: &ChannelId, epoch: Epoch) -> [u8; 32] {
640    channel_writer_group_key(secret, channel, epoch).pk().to_bytes()
641}
642
643/// The rekey scope writer blobs bind to.
644pub fn writer_rekey_scope(channel: &ChannelId) -> super::rekey::RekeyScope {
645    super::rekey::RekeyScope::Channel(ChannelId(writer_scope(channel)))
646}
647
648/// The access-plane scope a Channel's writer certifier secrets ride to its managers.
649pub fn certifier_rekey_scope(channel: &ChannelId) -> super::rekey::RekeyScope {
650    super::rekey::RekeyScope::Channel(ChannelId(super::derive::certifier_scope(channel)))
651}
652
653/// Where a Channel's writer secrets are archived, by writer epoch.
654pub fn secret_scope(channel: &ChannelId) -> String {
655    format!("wr:{}", crate::simd::hex::bytes_to_hex_32(&channel.0))
656}
657
658/// Where a minter keeps the secrets it minted, so a retry reuses its own and never one it
659/// was delivered.
660pub fn minted_scope(channel: &ChannelId) -> String {
661    format!("wrmint:{}", crate::simd::hex::bytes_to_hex_32(&channel.0))
662}
663
664/// Where a minter keeps the secret that certifies its epoch's writers.
665pub fn certifier_scope(channel: &ChannelId) -> String {
666    format!("wrcert:{}", crate::simd::hex::bytes_to_hex_32(&channel.0))
667}
668
669#[cfg(test)]
670mod tests {
671    use super::*;
672
673    const CH: ChannelId = ChannelId([0x42; 32]);
674    const BY: [u8; 32] = [0x0b; 32];
675
676    fn pk(n: u8) -> [u8; 32] {
677        writer_address(&[n; 32], &CH, Epoch(n as u64))
678    }
679
680    fn w(e: u64, n: u8) -> Spell {
681        Spell::Writer { epoch: Epoch(e), pk: pk(n), root: Epoch(0), by: BY, certifier: None }
682    }
683
684    #[test]
685    fn a_locked_window_is_carried_whole_and_ends_at_the_next_move() {
686        let with = |l: &Ledger, at: u64, s: Spell, locked: bool| l.appended_writer(at, s, locked).unwrap();
687        let l = with(&Ledger::new(&CH), 100, w(1, 1), false);
688        assert!(l.restricted() && !l.locked(), "a writer entry gates posting alone by default");
689        let l = with(&l, 200, w(2, 2), true);
690        assert!(l.locked() && l.locked_at(200) && l.locked_at(10_000) && !l.locked_at(150), "locked from its own date");
691        let back = Ledger::parse(&l.to_json()).unwrap();
692        assert_eq!(back, l, "the flag round-trips");
693        assert!(back.extends(&Ledger::parse(&with(&Ledger::new(&CH), 100, w(1, 1), false).to_json()).unwrap()), "and is part of what verbatim compares");
694        let l = l.appended(300, Spell::Open).unwrap();
695        assert!(!l.locked() && !l.locked_at(300) && l.locked_at(250));
696        // Only the flag set to true locks: anything else reads as a window that gates posting.
697        let odd = l.to_json().replace("\"locked\":true", "\"locked\":\"yes\"");
698        assert!(!Ledger::parse(&odd).unwrap().locked_at(250));
699        // A stop sits inside the window without ending it.
700        let l = with(&Ledger::new(&CH), 100, w(1, 1), true).appended(150, Spell::Stop { writer: pk(9) }).unwrap();
701        assert!(l.locked() && l.locked_at(160));
702    }
703
704    const MIN: u64 = 60_000;
705
706    #[test]
707    fn a_run_of_locked_windows_is_one_quiet_stretch_from_ten_minutes_in() {
708        let with = |l: &Ledger, at: u64, s: Spell, locked: bool| l.appended_writer(at, s, locked).unwrap();
709        let l = with(&Ledger::new(&CH), 100 * MIN, w(1, 1), false);
710        let l = with(&l, 200 * MIN, w(2, 2), true);
711        // A fresh epoch while still Locked, as a member losing their rights takes: the same run.
712        let l = with(&l, 300 * MIN, w(3, 3), true);
713        assert_eq!(l.quiet_spans(), vec![(210 * MIN, None)]);
714        assert_eq!(l.run_start(), Some(200 * MIN));
715        assert!(l.read_address_quiet(250 * MIN) && l.read_address_quiet(305 * MIN) && !l.read_address_quiet(205 * MIN));
716        // Read from below the run: down from its first ten minutes, never inside it.
717        assert_eq!(l.read_range(400 * MIN), Some((0, 210 * MIN - 1)));
718        assert_eq!(l.read_range(150 * MIN), Some((0, 150 * MIN)));
719        let l = l.appended(500 * MIN, Spell::Open).unwrap();
720        assert_eq!(l.quiet_spans(), vec![(210 * MIN, Some(500 * MIN))]);
721        assert_eq!(l.read_range(600 * MIN), Some((500 * MIN, 600 * MIN)), "above the run, down to where it ended");
722        assert_eq!(l.read_range(499 * MIN), Some((0, 210 * MIN - 1)), "and past it, from below it");
723        assert_eq!(l.run_start(), None);
724    }
725
726    #[test]
727    fn a_seal_holds_its_stretch_past_the_cap() {
728        let mut l = Ledger::new(&CH).appended_writer(200 * MIN, w(1, 1), true).unwrap();
729        assert_eq!(l.seal_target(201 * MIN), Some(200 * MIN), "sealed to its start at once");
730        let first = SealRef { page: Some([6; 32]), read: Epoch(2), until: 200 * MIN, run: 200 * MIN, count: 4, extra: Default::default() };
731        l = l.appended_seal(200 * MIN, first).unwrap();
732        assert_eq!(l.seal_target(205 * MIN), None, "then nothing until its first minutes pass");
733        assert_eq!(l.seal_target(210 * MIN), Some(210 * MIN), "then across them");
734        assert_eq!(l.read_range(209 * MIN), Some((200 * MIN, 209 * MIN)), "its first minutes still read by date meanwhile");
735        let seal = SealRef { page: Some([7; 32]), read: Epoch(2), until: 210 * MIN, run: 200 * MIN, count: 5, extra: Default::default() };
736        l = l.appended_seal(211 * MIN, seal.clone()).unwrap();
737        assert_eq!(l.seal_target(10_000 * MIN), None);
738        assert_eq!(Ledger::parse(&l.to_json()).unwrap(), l, "the seal round-trips at the top level");
739        assert_eq!(l.read_range(400 * MIN), None, "everything below the seal is read by id");
740        // Fresh epochs, still Locked, until the run's first entries and the seal's own marker go.
741        for e in 2..=70u64 {
742            l = l.appended_writer((211 + e) * MIN, w(e, (e % 200) as u8 + 1), true).unwrap();
743        }
744        assert!(l.retired.iter().any(|r| r.epoch == Epoch(1)), "the run's first window retired");
745        assert!(!l.entries.iter().any(|e| e.extra.contains_key(SEALED)), "and the seal's marker with it");
746        assert_eq!(l.seal, Some(seal));
747        assert!(l.seal_target(10_000 * MIN).is_none() && l.read_address_quiet(212 * MIN), "the seal still holds the stretch");
748        assert_eq!(l.read_range(10_000 * MIN), None);
749        // Opened and Locked again, the new run is the seal's no longer.
750        let l = l.appended(400 * MIN, Spell::Open).unwrap().appended_writer(500 * MIN, w(71, 9), true).unwrap();
751        assert_eq!(l.seal_target(10_000 * MIN), Some(500 * MIN));
752        assert_eq!(l.quiet_spans(), vec![(210 * MIN, Some(400 * MIN)), (510 * MIN, None)]);
753        assert_eq!(l.read_range(10_000 * MIN), Some((400 * MIN, 510 * MIN - 1)), "only what came between the runs");
754    }
755
756    #[test]
757    fn a_scoped_certificate_vouches_only_for_its_rights() {
758        let secret = [0x31; 32];
759        let certifier = certifier_of(&secret).unwrap();
760        let mut l = Ledger::new(&CH).appended_writer(100, Spell::Writer { epoch: Epoch(1), pk: pk(1), root: Epoch(0), by: BY, certifier: Some(certifier) }, true).unwrap();
761        l.channel = CH.0;
762        let (community, writer) = ([1; 32], pk(5));
763        let react = crate::community::roles::Permissions::ADD_REACTIONS;
764        let cert = sign_writer_cert(&secret, &scoped_cert_digest(&community, &CH.0, Epoch(1), &writer, react)).unwrap();
765        assert!(l.certifies_scoped(&community, Epoch(1), &writer, react, &cert));
766        assert!(!l.certifies(&community, Epoch(1), &writer, &cert), "a scoped certificate is never a whole one");
767        assert!(!l.certifies_scoped(&community, Epoch(1), &writer, react | crate::community::roles::Permissions::CONNECT, &cert), "its rights are what it signs");
768        assert!(!l.certifies_scoped(&community, Epoch(1), &pk(6), react, &cert), "for one member");
769        let whole = sign_writer_cert(&secret, &cert_digest(&community, &CH.0, Epoch(1), &writer)).unwrap();
770        assert!(!l.certifies_scoped(&community, Epoch(1), &writer, react, &whole), "nor a whole one a scoped one");
771    }
772
773    /// The certificate test vector CORD-03 §1 publishes: what every client must compute alike.
774    #[test]
775    fn a_writer_certificate_matches_the_published_vector() {
776        let (community, channel, writer, secret) = ([0x01; 32], [0x02; 32], [0x04; 32], [0x05; 32]);
777        let d = cert_digest(&community, &channel, Epoch(3), &writer);
778        assert_eq!(crate::simd::hex::bytes_to_hex_32(&d), "f49b5c7359b09366b5b96e074d2b7c5a84bd714a04bf0e6270d13c02d453e619");
779        let certifier = certifier_of(&secret).unwrap();
780        assert_eq!(crate::simd::hex::bytes_to_hex_32(&certifier), "62c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f7");
781        let e = cert_event(nostr_sdk::prelude::PublicKey::from_slice(&certifier).unwrap(), &d);
782        let id = nostr_sdk::prelude::EventId::compute(&e.pubkey, &e.created_at, &e.kind, &e.tags, &e.content);
783        assert_eq!(id.to_hex(), "1b6fcc32de4a485d7b0109b0e5dd91b7c676fcb26f7dc41c8c2bdc7e3f2cbe90");
784        let published: [u8; 64] = crate::simd::hex::hex_string_to_bytes_checked("cd1c3030e1220c539f1efb50d32e5b83432baa20eaa8709aa935050dc11a6ac6e25c3f9555b729cee65829fdbf1ba5e7656865a4fca860e42b05c8341922895a").unwrap().try_into().unwrap();
785        assert!(verify_writer_cert(&certifier, &d, &published));
786        assert!(verify_writer_cert(&certifier, &d, &sign_writer_cert(&secret, &d).unwrap()));
787    }
788
789    /// The scoped certificate test vector CORD-03 §1 publishes, rights = ADD_REACTIONS.
790    #[test]
791    fn a_scoped_certificate_matches_the_published_vector() {
792        let (community, channel, writer, secret) = ([0x01; 32], [0x02; 32], [0x04; 32], [0x05; 32]);
793        let d = scoped_cert_digest(&community, &channel, Epoch(3), &writer, crate::community::roles::Permissions::ADD_REACTIONS);
794        assert_eq!(crate::simd::hex::bytes_to_hex_32(&d), "14129a75435ce645cd6c76d170f4ad61e88f54c0168a2deed48c9213b5eba10c");
795        let certifier = certifier_of(&secret).unwrap();
796        let e = cert_event(nostr_sdk::prelude::PublicKey::from_slice(&certifier).unwrap(), &d);
797        let id = nostr_sdk::prelude::EventId::compute(&e.pubkey, &e.created_at, &e.kind, &e.tags, &e.content);
798        assert_eq!(id.to_hex(), "418f80ff45b3122867c508997774858af6ab99bc12f18afb97ff2c99ad8a7db0");
799        let published: [u8; 64] = crate::simd::hex::hex_string_to_bytes_checked("ec9f4cf12a0f5f09f199fdf776e4416859531e60e70c66ec477711c1f184fad59c913e6378b2be73d632c17223dc70a9acfcc930bd351bac461e2b521682c145").unwrap().try_into().unwrap();
800        assert!(verify_writer_cert(&certifier, &d, &published));
801    }
802
803    #[test]
804    fn a_writer_certificate_vouches_for_one_member_at_one_epoch_in_one_channel() {
805        let secret = [0x31; 32];
806        let certifier = certifier_of(&secret).unwrap();
807        let (community, channel, writer) = ([1; 32], [2; 32], pk(5));
808        let cert = sign_writer_cert(&secret, &cert_digest(&community, &channel, Epoch(3), &writer)).unwrap();
809        assert!(verify_writer_cert(&certifier, &cert_digest(&community, &channel, Epoch(3), &writer), &cert));
810        for (why, digest) in [
811            ("another member", cert_digest(&community, &channel, Epoch(3), &pk(6))),
812            ("another epoch", cert_digest(&community, &channel, Epoch(4), &writer)),
813            ("another channel", cert_digest(&community, &[9; 32], Epoch(3), &writer)),
814            ("another community", cert_digest(&[8; 32], &channel, Epoch(3), &writer)),
815        ] {
816            assert!(!verify_writer_cert(&certifier, &digest, &cert), "{why}");
817        }
818        assert!(!verify_writer_cert(&certifier_of(&[0x32; 32]).unwrap(), &cert_digest(&community, &channel, Epoch(3), &writer), &cert), "another certifier");
819    }
820
821    #[test]
822    fn a_full_ledger_fits_one_relay_event() {
823        let c = certifier_of(&[0x41; 32]).unwrap();
824        let mut l = Ledger { channel: [7; 32], ..Default::default() };
825        let mut epoch = 0u64;
826        while l.retired.len() < MAX_RETIRED || l.entries.len() < MAX_LEDGER {
827            epoch += 1;
828            let spell = Spell::Writer { epoch: Epoch(epoch), pk: pk((epoch % 200) as u8 + 1), root: Epoch(epoch), by: BY, certifier: Some(c) };
829            l = l.appended(1_792_256_141_843 + epoch * 1_000, spell).unwrap();
830        }
831        let keys = nostr_sdk::prelude::Keys::generate();
832        let group = super::super::derive::channel_group_key(&[1; 32], &ChannelId([7; 32]), Epoch(1));
833        let rumor = super::super::control::build_edition_rumor_bound(keys.public_key(), super::super::vsk::WRITERS, &[8; 32], 999, Some(&[9; 32]), &l.to_json(), 1_792_256_141, None, Some([10; 32]));
834        let (wrap, _) = super::super::control::seal_control_edition(&rumor, &group, &keys, nostr_sdk::prelude::Timestamp::from_secs(1_792_256_141)).unwrap();
835        assert!(wrap.as_json().len() <= 65_536, "{} bytes: a full ledger must fit a 64KB relay event", wrap.as_json().len());
836    }
837
838    #[test]
839    fn a_ledger_carries_its_certifiers_live_and_retired() {
840        let c = certifier_of(&[0x41; 32]).unwrap();
841        let mut l = Ledger { channel: [7; 32], ..Default::default() };
842        for i in 0..MAX_LEDGER as u64 + 1 {
843            let spell = Spell::Writer { epoch: Epoch(i + 1), pk: pk((i % 200) as u8 + 1), root: Epoch(0), by: BY, certifier: Some(c) };
844            l = l.appended(1_000 + i, spell).unwrap();
845        }
846        assert_eq!(l.retired.len(), 1);
847        assert_eq!((l.certifier(Epoch(1)), l.certifier(Epoch(2))), (Some(c), Some(c)), "retired and live");
848        let back = Ledger::parse(&l.to_json()).unwrap();
849        assert_eq!(back, l, "a round trip keeps every certifier");
850        let old = ledger(&[(100, w(1, 1))]);
851        assert_eq!(Ledger::parse(&old.to_json()).unwrap().certifier(Epoch(1)), None, "an entry from before certifiers reads");
852    }
853
854    #[test]
855    fn a_stop_voids_one_writer_inside_its_epoch_and_moves_no_window() {
856        let (a, b) = (pk(30), pk(31));
857        let l = ledger(&[(100, w(1, 1)), (200, Spell::Stop { writer: a }), (300, w(2, 2)), (400, Spell::Open)]);
858        assert!(l.well_formed());
859        assert_eq!(Ledger::parse(&l.to_json()).unwrap(), l, "round trips");
860        let ends: Vec<Option<u64>> = l.writers().map(|(.., end)| end).collect();
861        assert_eq!(ends, vec![Some(300), Some(400)], "a window runs to the next entry that moves posts");
862        assert!(!l.read_address_takes(250), "a stop opens nothing");
863        assert!(l.stopped(Epoch(1), &a, 200) && l.stopped(Epoch(1), &a, 299));
864        assert!(!l.stopped(Epoch(1), &a, 199), "posts before it stand");
865        assert!(!l.stopped(Epoch(1), &b, 250), "it names one writer");
866        assert!(!l.stopped(Epoch(2), &a, 350), "and one epoch");
867        let later = ledger(&[(100, w(1, 1)), (200, w(2, 2)), (300, Spell::Stop { writer: a })]);
868        assert!(!later.stopped(Epoch(1), &a, 400) && later.stopped(Epoch(2), &a, 400), "a stop is the window's it sits in");
869        let live = ledger(&[(100, w(1, 1)), (200, Spell::Stop { writer: a })]);
870        assert!(live.restricted() && live.current_writer() == Some((Epoch(1), pk(1))) && live.live().map(|l| l.2) == Some(100));
871        assert!(!ledger(&[(100, w(1, 1)), (150, Spell::Open), (200, Spell::Stop { writer: a })]).well_formed(), "an open window has nobody to stop");
872        assert!(ledger(&[(200, Spell::Stop { writer: a }), (300, w(2, 2))]).well_formed(), "one whose epoch retired still parses");
873        let mut both: serde_json::Value = serde_json::from_str(&live.to_json()).unwrap();
874        both["ledger"][1]["open"] = true.into();
875        assert!(Ledger::parse(&both.to_string()).is_none(), "an entry is one thing");
876        let mut unknown: serde_json::Value = serde_json::from_str(&live.to_json()).unwrap();
877        unknown["ledger"].as_array_mut().unwrap().push(serde_json::json!({ "at": 300, "future": "kind" }));
878        let carried = Ledger::parse(&unknown.to_string()).expect("a kind this build doesn't know is carried");
879        assert_eq!(carried.current_writer(), live.current_writer(), "and moves nothing");
880        assert_eq!(serde_json::from_str::<serde_json::Value>(&carried.to_json()).unwrap()["ledger"][2], serde_json::json!({ "at": 300, "future": "kind" }), "verbatim");
881    }
882
883    #[test]
884    fn a_stop_never_pushes_the_live_writer_out_and_a_retired_window_skips_stops() {
885        let mut l = ledger(&[(1_000, w(1, 1))]);
886        for i in 1..MAX_LEDGER as u64 {
887            l = l.appended(1_000 + i, Spell::Stop { writer: pk((i % 200) as u8 + 20) }).unwrap();
888        }
889        assert_eq!(l.entries.len(), MAX_LEDGER);
890        assert!(l.appended(5_000, Spell::Stop { writer: pk(9) }).is_none(), "at the cap a stop would retire the live entry");
891        let next = l.appended(5_000, w(2, 2)).unwrap();
892        assert_eq!(next.retired, vec![Retired { epoch: Epoch(1), pk: pk(1), from: 1_000, to: 5_000, certifier: None }], "its window ends where the next epoch begins");
893        assert!(next.stopped(Epoch(1), &pk(21), 4_000), "a stop outlives its window's entry retiring");
894        assert!(!next.stopped(Epoch(1), &pk(21), 1_000), "and still only from its date");
895        let mut later = next.clone();
896        for i in 0..MAX_LEDGER as u64 {
897            later = later.appended(6_000 + i, Spell::Open).and_then(|l| l.appended(6_000 + i, w(3 + i, 3))).unwrap_or(later);
898        }
899        assert!(!later.stopped(Epoch(1), &pk(21), 4_000), "a stop the cap dropped stops nothing");
900    }
901
902    fn ledger(entries: &[(u64, Spell)]) -> Ledger {
903        let mut l = Ledger::new(&CH);
904        l.entries = entries.iter().map(|(at, spell)| Entry { at: *at, spell: *spell, extra: Default::default() }).collect();
905        l
906    }
907
908    #[test]
909    fn a_ledger_round_trips_with_its_unknown_fields() {
910        let mut l = ledger(&[(100, w(2, 1)), (200, Spell::Open), (300, Spell::Writer { epoch: Epoch(3), pk: pk(2), root: Epoch(3), by: BY, certifier: None })]);
911        l.extra.insert("future".into(), serde_json::json!({"x": 1}));
912        l.entries[1].extra.insert("note".into(), "kept".into());
913        l.retired = vec![Retired { epoch: Epoch(1), pk: pk(3), from: 10, to: 50, certifier: None }];
914        let back = Ledger::parse(&l.to_json()).unwrap();
915        assert_eq!(back, l);
916        assert!(back.restricted() && back.current_writer() == Some((Epoch(3), pk(2))) && back.next_epoch() == Some(Epoch(4)));
917        assert_eq!(back.live(), Some((Epoch(3), BY, 300)));
918        assert_eq!((back.previous_writer(), back.minter(Epoch(2)), back.minter(Epoch(1))), (Some(Epoch(2)), Some(BY), None));
919    }
920
921    #[test]
922    fn a_run_of_parses_judges_each_key_as_one_parse_would() {
923        let good = ledger(&[(100, w(1, 1)), (150, w(2, 2))]).to_json();
924        let off_curve = good.replace(&crate::simd::hex::bytes_to_hex_32(&pk(2)), &"ff".repeat(32));
925        assert!(Ledger::parse(&off_curve).is_none());
926        let mut keys = KeyCheck::default();
927        for (content, parses) in [(&good, true), (&off_curve, false), (&good, true), (&off_curve, false)] {
928            assert_eq!(Ledger::parse_with(content, &mut keys).is_some(), parses);
929        }
930        let mut keys = KeyCheck::default();
931        assert!(Ledger::parse_with(&off_curve, &mut keys).is_none());
932        assert!(Ledger::parse_with(&good, &mut keys).is_some(), "a key judged bad leaves the good ones alone");
933    }
934
935    #[test]
936    fn a_malformed_ledger_reads_as_none() {
937        let ok = ledger(&[(100, w(1, 1)), (100, Spell::Open), (150, w(2, 2))]);
938        assert!(Ledger::parse(&ok.to_json()).is_some(), "equal times keep order");
939        let mut stale = ok.clone();
940        stale.retired = vec![Retired { epoch: Epoch(5), pk: pk(5), from: 1, to: 2, certifier: None }];
941        for (why, bad) in [
942            ("out of order", ledger(&[(200, w(1, 1)), (100, Spell::Open)])),
943            ("epoch repeats", ledger(&[(100, w(1, 1)), (200, w(1, 2))])),
944            ("epoch falls", ledger(&[(100, w(2, 2)), (200, w(1, 1))])),
945            ("epoch out of range", ledger(&[(100, w(MAX_EPOCH, 1))])),
946            ("a retired epoch above a live one", stale),
947        ] {
948            assert!(Ledger::parse(&bad.to_json()).is_none(), "{why}");
949        }
950        let full = ledger(&(0..=MAX_LEDGER as u64).map(|i| (i, Spell::Open)).collect::<Vec<_>>());
951        assert!(Ledger::parse(&full.to_json()).is_none(), "too long");
952        let ch = crate::simd::hex::bytes_to_hex_32(&CH.0);
953        let hex = crate::simd::hex::bytes_to_hex_32(&pk(1));
954        let by = crate::simd::hex::bytes_to_hex_32(&BY);
955        for (why, raw) in [
956            ("epoch zero", format!(r#"{{"channel":"{ch}","ledger":[{{"at":1,"epoch":0,"writer":"{hex}","root":0,"by":"{by}"}}]}}"#)),
957            ("both at once", format!(r#"{{"channel":"{ch}","ledger":[{{"at":1,"open":true,"epoch":1,"writer":"{hex}","root":0,"by":"{by}"}}]}}"#)),
958            ("no root", format!(r#"{{"channel":"{ch}","ledger":[{{"at":1,"epoch":1,"writer":"{hex}","by":"{by}"}}]}}"#)),
959            ("no minter", format!(r#"{{"channel":"{ch}","ledger":[{{"at":1,"epoch":1,"writer":"{hex}","root":0}}]}}"#)),
960            ("open false", format!(r#"{{"channel":"{ch}","ledger":[{{"at":1,"open":false}}]}}"#)),
961            ("no point", format!(r#"{{"channel":"{ch}","ledger":[{{"at":1,"epoch":1,"writer":"{}","root":0,"by":"{by}"}}]}}"#, "00".repeat(32))),
962            ("a retired window backwards", format!(r#"{{"channel":"{ch}","ledger":[],"retired":[[1,"{hex}",9,3]]}}"#)),
963            ("no channel", r#"{"ledger":[]}"#.to_string()),
964        ] {
965            assert!(Ledger::parse(&raw).is_none(), "{why}");
966        }
967    }
968
969    #[test]
970    fn each_entry_holds_until_the_next() {
971        let l = ledger(&[(100_000, w(1, 1)), (200_000, Spell::Open), (300_000, w(2, 2))]);
972        assert!(l.read_address_takes(99_999), "before the first entry the Channel is open");
973        assert!(!l.read_address_takes(100_000) && !l.read_address_takes(199_999), "inside a writer entry");
974        assert!(l.read_address_takes(200_000) && l.read_address_takes(299_999), "the open stretch");
975        assert!(!l.read_address_takes(5_000_000), "the live writer entry");
976        assert!(l.writer_address_takes(Epoch(1), 150_000) && l.writer_address_takes(Epoch(1), 1_000), "a writer's past posts stay");
977        assert!(!l.writer_address_takes(Epoch(1), 200_000), "nothing after its entry ends");
978        assert!(l.writer_address_takes(Epoch(2), u64::MAX), "the live address takes everything");
979        assert!(!l.writer_address_takes(Epoch(3), 0), "an epoch the ledger never named");
980    }
981
982    #[test]
983    fn the_cap_retires_writer_entries_and_forgets_open_ones() {
984        // A writer entry, then an open stretch, then entries to the cap.
985        let mut entries: Vec<(u64, Spell)> = vec![(1_000, w(1, 1)), (2_000, Spell::Open)];
986        entries.extend((2..MAX_LEDGER as u64).map(|i| (1_000 + i * 1_000, Spell::Open)));
987        let at_cap = ledger(&entries);
988        let once = at_cap.appended(500_000, w(2, 2)).unwrap();
989        assert_eq!(once.retired, vec![Retired { epoch: Epoch(1), pk: pk(1), from: 1_000, to: 2_000, certifier: None }]);
990        assert!(!once.read_address_takes(1_500), "the dropped writer entry's window stays closed");
991        assert!(once.writer_address_takes(Epoch(1), 1_500) && !once.writer_address_takes(Epoch(1), 2_000), "and its address still reads, up to its end");
992        assert!(once.writers().any(|(e, ..)| e == Epoch(1)), "history still fetches it");
993        assert_eq!(once.writer_start(Epoch(1)), Some(1_000));
994        let twice = once.appended(600_000, Spell::Open).unwrap();
995        assert_eq!(twice.retired.len(), 1, "a dropped open entry leaves nothing");
996        assert!(twice.read_address_takes(2_500), "and its open stretch stays open");
997        assert!(once.extends(&at_cap) && twice.extends(&once), "a cap drop still carries the ledger forward");
998        assert!(Ledger::parse(&twice.to_json()).is_some());
999    }
1000
1001    #[test]
1002    fn a_ledger_extends_only_by_one_entry() {
1003        let a = ledger(&[(100, w(1, 1))]);
1004        let b = a.appended(200, Spell::Open).unwrap();
1005        assert!(b.extends(&a) && !a.extends(&b) && !a.extends(&a), "exactly one new entry");
1006        let c = b.appended(300, w(2, 2)).unwrap();
1007        assert!(!c.extends(&a), "two at once is no extension");
1008        let rewritten = ledger(&[(100, w(1, 2)), (200, Spell::Open)]);
1009        assert!(!rewritten.extends(&a), "a carried entry can't change");
1010        let shed = ledger(&[(200, Spell::Open)]);
1011        assert!(!shed.extends(&a), "below the cap nothing is dropped");
1012        assert!(a.is_first() && !b.is_first());
1013    }
1014
1015    #[test]
1016    fn an_editions_newest_entry_is_its_own_and_dated_with_it() {
1017        let l = ledger(&[(100_000, w(1, 1))]);
1018        let far = ledger(&[(HORIZON_MS + 10_000_000, w(1, 1))]);
1019        assert!(far.not_ahead(10_000_000) && !far.not_ahead(10_000_000 - 1), "a far-future entry waits");
1020        assert!(l.tail_fits(100, &BY));
1021        assert!(!l.tail_fits(100, &[0x0c; 32]), "a writer entry names the edition's signer");
1022        assert!(!l.tail_fits(100 + ENTRY_SKEW_MS / 1000 + 1, &BY), "nor sits far from the edition's time");
1023        let opened = l.appended(150_000, Spell::Open).unwrap();
1024        assert!(opened.tail_fits(150, &[0x0c; 32]), "an open entry names nobody");
1025    }
1026
1027    #[test]
1028    fn appending_never_backdates_and_keeps_epochs_rising() {
1029        let l = ledger(&[(100, w(1, 1))]);
1030        let next = l.appended(50, Spell::Open).unwrap();
1031        assert_eq!(next.entries[1].at, 100, "clamped to the last entry");
1032        assert!(l.appended(200, w(1, 2)).is_none());
1033        assert_eq!(next.next_epoch(), Some(Epoch(2)));
1034        assert_eq!(ledger(&[(1, w(MAX_EPOCH - 1, 1))]).next_epoch(), None, "the range is spent");
1035    }
1036
1037    #[test]
1038    fn a_channel_without_a_ledger_reads_only_its_read_address() {
1039        use nostr_sdk::prelude::{Keys, Timestamp};
1040        let k = Keys::generate();
1041        let g = crate::community::v2::derive::channel_group_key(&[1; 32], &CH, Epoch(0));
1042        let rumor = super::super::chat::build_message_rumor(k.public_key(), &CH, Epoch(0), "x", None, &[], vec![], 1_000);
1043        let (wrap, _) = super::super::chat::seal_chat_rumor(&rumor, &g, &k, Timestamp::from_secs(1), false).unwrap();
1044        let ev = super::super::chat::open_chat_event(&wrap, &g, &CH, Epoch(0)).unwrap();
1045        use crate::community::v2::service::{sort_arrival, Arrival};
1046        assert!(matches!(sort_arrival(None, ev.clone(), None), Arrival::Stands(_)));
1047        assert!(matches!(sort_arrival(None, ev, Some(Epoch(1))), Arrival::Held(None)), "no ledger names a writer address");
1048    }
1049}