vector-core 0.13.0

Core library for Vector: the single source of truth for all Vector clients, SDKs and interfaces.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
//! A restricted Channel's Writers ledger (CORD-03 §1): which address takes posts when.
//!
//! The ledger is a Control entity, so every member folds the same answer and a Refounding
//! carries it. Writer secrets travel separately, on the access plane, and a member adopts one
//! only if it derives to the address the ledger names.

use super::derive::{channel_writer_group_key, writer_scope};
use crate::community::{ChannelId, Epoch};

/// The most entries a ledger holds; a longer one is malformed.
pub const MAX_LEDGER: usize = 64;

/// The most writer entries the cap retires before the oldest goes for good.
pub const MAX_RETIRED: usize = 64;

/// Writer epochs stay below this, so every reader's arithmetic agrees.
pub const MAX_EPOCH: u64 = 1 << 53;

/// How far an edition's new entry may sit from the edition's own time.
pub const ENTRY_SKEW_MS: u64 = 10 * 60 * 1000;

/// How far past a reader's clock a new entry may be dated before it waits (CORD-02 §5).
pub const HORIZON_MS: u64 = 60 * 60 * 1000;

/// What one ledger entry moves the Channel to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Spell {
    /// Posts land at this writer epoch's address, minted under root epoch `root` by `by`, whose
    /// writers carry a certificate from `certifier`.
    Writer { epoch: Epoch, pk: [u8; 32], root: Epoch, by: [u8; 32], certifier: Option<[u8; 32]> },
    /// Posts land at the read address again.
    Open,
    /// From here on the live epoch's certificate for `writer` vouches for nothing: a writer the
    /// Channel no longer lets post. Moves no window.
    Stop { writer: [u8; 32] },
    /// An entry of a kind this build doesn't know, carried verbatim: it moves nothing.
    Other,
}

impl Spell {
    /// Whether this entry moves where posts land.
    fn moves(&self) -> bool {
        matches!(self, Spell::Writer { .. } | Spell::Open)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
    /// Unix milliseconds this entry starts holding.
    pub at: u64,
    pub spell: Spell,
    /// Unknown fields, carried through our own editions (CORD-02 §6).
    pub extra: serde_json::Map<String, serde_json::Value>,
}

/// The field a stop carries when it records a departure that came before it was written.
const STOP_FROM: &str = "from";

/// The field of the entry a seal's edition appends: how many ids the seal names.
const SEALED: &str = "sealed";

/// The field a writer entry carries when its window is Locked: every write rides its address,
/// reactions and calls included. A reader that predates it carries it verbatim and reads the
/// window as one that gates posting alone.
const LOCKED: &str = "locked";

impl Entry {
    /// Whether this is a writer entry whose window is Locked.
    pub fn locked(&self) -> bool {
        matches!(self.spell, Spell::Writer { .. }) && self.extra.get(LOCKED) == Some(&serde_json::Value::Bool(true))
    }

    /// When this entry takes effect: its own date, or for a stop, the departure it records if
    /// that came first. A reader that predates `from` applies the stop from its own date.
    pub fn effective(&self) -> u64 {
        match self.spell {
            Spell::Stop { .. } => self.extra.get(STOP_FROM).and_then(|v| v.as_u64()).map_or(self.at, |from| from.min(self.at)),
            _ => self.at,
        }
    }
}

/// A writer entry the cap dropped: its address still reads, its window stays closed, and its
/// writers' certificates still check.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Retired {
    pub epoch: Epoch,
    pub pk: [u8; 32],
    pub from: u64,
    pub to: u64,
    pub certifier: Option<[u8; 32]>,
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Ledger {
    pub channel: [u8; 32],
    pub entries: Vec<Entry>,
    pub retired: Vec<Retired>,
    /// The newest seal of its history.
    pub seal: Option<SealRef>,
    /// Unknown top-level fields, carried through our own editions (CORD-02 §6).
    pub extra: serde_json::Map<String, serde_json::Value>,
}

fn hex32(v: &serde_json::Value) -> Option<[u8; 32]> {
    crate::simd::hex::hex_to_bytes_32_checked(v.as_str()?)
}

/// Which keys a run of parses found to be x-only public keys, each checked once: a ledger names
/// the same writers in every version, and each check is a point decompression.
#[derive(Default)]
pub struct KeyCheck(std::collections::HashMap<[u8; 32], bool>);

impl KeyCheck {
    fn writer_pk(&mut self, v: &serde_json::Value) -> Option<[u8; 32]> {
        let pk = hex32(v)?;
        let valid = *self.0.entry(pk).or_insert_with(|| nostr_sdk::prelude::PublicKey::from_slice(&pk).and_then(|p| p.xonly()).is_ok());
        valid.then_some(pk)
    }
}

fn epoch_of(v: &serde_json::Value) -> Option<Epoch> {
    v.as_u64().filter(|n| *n > 0 && *n < MAX_EPOCH).map(Epoch)
}

/// A Channel's sealed history (CORD-03 §1): what its read address held before `until` (unix ms)
/// is exactly the wrap ids its pages list, from the first, `page`, opened under read epoch `read`.
/// `run` is when the run of Locked windows it was made in began. It rides the ledger's top level,
/// where the cap never reaches.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SealRef {
    /// `None` for a seal of nothing.
    pub page: Option<[u8; 32]>,
    pub read: Epoch,
    pub until: u64,
    pub run: u64,
    pub count: u64,
    /// Fields this build doesn't know, carried through its own editions (CORD-02 §6).
    pub extra: serde_json::Map<String, serde_json::Value>,
}

impl SealRef {
    fn parse(v: &serde_json::Value) -> Option<Self> {
        let mut o = v.as_object()?.clone();
        let page = match o.remove("page")? {
            serde_json::Value::Null => None,
            p => Some(hex32(&p)?),
        };
        let read = Epoch(o.remove("read")?.as_u64()?);
        let (until, run, count) = (o.remove("until")?.as_u64()?, o.remove("run")?.as_u64()?, o.remove("count")?.as_u64()?);
        (until <= run.saturating_add(ENTRY_SKEW_MS)).then_some(SealRef { page, read, until, run, count, extra: o })
    }

    fn to_json(&self) -> serde_json::Value {
        let mut o = self.extra.clone();
        o.insert("page".into(), self.page.map_or(serde_json::Value::Null, |p| crate::simd::hex::bytes_to_hex_32(&p).into()));
        o.insert("read".into(), self.read.0.into());
        o.insert("until".into(), self.until.into());
        o.insert("run".into(), self.run.into());
        o.insert("count".into(), self.count.into());
        serde_json::Value::Object(o)
    }
}

impl Ledger {
    pub fn new(channel: &ChannelId) -> Self {
        Ledger { channel: channel.0, ..Default::default() }
    }

    /// Parse a ledger, `None` when it is malformed: entries out of `at` order, writer epochs
    /// (retired, then live) not strictly rising or out of range, more than [`MAX_LEDGER`]
    /// entries or [`MAX_RETIRED`] retired, or an entry that is neither one thing.
    pub fn parse(content: &str) -> Option<Self> {
        Self::parse_with(content, &mut KeyCheck::default())
    }

    /// [`Self::parse`], sharing `keys` across a run of parses.
    pub fn parse_with(content: &str, keys: &mut KeyCheck) -> Option<Self> {
        let serde_json::Value::Object(mut top) = serde_json::from_str(content).ok()? else { return None };
        let channel = hex32(&top.remove("channel")?)?;
        let serde_json::Value::Array(raw) = top.remove("ledger")? else { return None };
        let retired = match top.remove("retired") {
            None => Vec::new(),
            Some(serde_json::Value::Array(r)) => r
                .iter()
                .map(|x| {
                    let x = x.as_array().filter(|x| x.len() == 4 || x.len() == 5)?;
                    let certifier = match x.get(4) {
                        None => None,
                        Some(c) => Some(keys.writer_pk(c)?),
                    };
                    Some(Retired { epoch: epoch_of(&x[0])?, pk: keys.writer_pk(&x[1])?, from: x[2].as_u64()?, to: x[3].as_u64()?, certifier })
                })
                .collect::<Option<Vec<_>>>()?,
            Some(_) => return None,
        };
        if raw.len() > MAX_LEDGER || retired.len() > MAX_RETIRED {
            return None;
        }
        let mut entries = Vec::with_capacity(raw.len());
        for e in raw {
            let serde_json::Value::Object(mut e) = e else { return None };
            let at = e.remove("at")?.as_u64()?;
            let stop = e.remove("stop");
            let spell = match (e.remove("open"), e.remove("epoch"), e.remove("writer"), e.remove("root"), e.remove("by")) {
                (None, None, None, None, None) if stop.is_some() => Spell::Stop { writer: keys.writer_pk(stop.as_ref()?)? },
                (None, None, None, None, None) => Spell::Other,
                (Some(serde_json::Value::Bool(true)), None, None, None, None) if stop.is_none() => Spell::Open,
                (None, Some(epoch), Some(writer), Some(root), Some(by)) if stop.is_none() => {
                    let certifier = match e.remove("certifier") {
                        None => None,
                        Some(c) => Some(keys.writer_pk(&c)?),
                    };
                    Spell::Writer { epoch: epoch_of(&epoch)?, pk: keys.writer_pk(&writer)?, root: Epoch(root.as_u64()?), by: hex32(&by)?, certifier }
                }
                _ => return None,
            };
            entries.push(Entry { at, spell, extra: e });
        }
        // A seal this reader can't read is carried as it came.
        let seal = top.get("seal").and_then(SealRef::parse);
        if seal.is_some() {
            top.remove("seal");
        }
        let ledger = Ledger { channel, entries, retired, seal, extra: top };
        ledger.well_formed().then_some(ledger)
    }

    fn well_formed(&self) -> bool {
        let ordered = self.entries.windows(2).all(|w| w[0].at <= w[1].at);
        // A stop is a writer window's; an open one has nobody to stop.
        let stops = self.entries.iter().enumerate().all(|(i, e)| {
            !matches!(e.spell, Spell::Stop { .. }) || !matches!(self.entries[..i].iter().rev().find(|e| e.spell.moves()).map(|e| e.spell), Some(Spell::Open))
        });
        let windows = self.retired.iter().all(|r| r.from <= r.to);
        let epochs: Vec<u64> = self.writers().map(|(e, ..)| e.0).collect();
        ordered && stops && windows && epochs.windows(2).all(|w| w[0] < w[1]) && self.entries.len() <= MAX_LEDGER && self.retired.len() <= MAX_RETIRED
    }

    pub fn to_json(&self) -> String {
        let entries: Vec<serde_json::Value> = self
            .entries
            .iter()
            .map(|e| {
                let mut o = e.extra.clone();
                o.insert("at".into(), e.at.into());
                match e.spell {
                    Spell::Writer { epoch, pk, root, by, certifier } => {
                        o.insert("epoch".into(), epoch.0.into());
                        o.insert("writer".into(), crate::simd::hex::bytes_to_hex_32(&pk).into());
                        o.insert("root".into(), root.0.into());
                        o.insert("by".into(), crate::simd::hex::bytes_to_hex_32(&by).into());
                        if let Some(c) = certifier {
                            o.insert("certifier".into(), crate::simd::hex::bytes_to_hex_32(&c).into());
                        }
                    }
                    Spell::Open => {
                        o.insert("open".into(), true.into());
                    }
                    Spell::Stop { writer } => {
                        o.insert("stop".into(), crate::simd::hex::bytes_to_hex_32(&writer).into());
                    }
                    Spell::Other => {}
                }
                serde_json::Value::Object(o)
            })
            .collect();
        let mut top = self.extra.clone();
        top.insert("channel".into(), crate::simd::hex::bytes_to_hex_32(&self.channel).into());
        if let Some(seal) = &self.seal {
            top.insert("seal".into(), seal.to_json());
        }
        top.insert("ledger".into(), entries.into());
        if !self.retired.is_empty() {
            let retired: Vec<serde_json::Value> = self
                .retired
                .iter()
                .map(|r| match r.certifier {
                    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)]),
                    None => serde_json::json!([r.epoch.0, crate::simd::hex::bytes_to_hex_32(&r.pk), r.from, r.to]),
                })
                .collect();
            top.insert("retired".into(), retired.into());
        }
        serde_json::Value::Object(top).to_string()
    }

    /// The newest entry that moved where posts land.
    fn last_move(&self) -> Option<&Entry> {
        self.entries.iter().rev().find(|e| e.spell.moves())
    }

    /// Whether posts land at a writer address now.
    pub fn restricted(&self) -> bool {
        matches!(self.last_move(), Some(Entry { spell: Spell::Writer { .. }, .. }))
    }

    /// Whether every write lands at a writer address now.
    pub fn locked(&self) -> bool {
        self.last_move().is_some_and(Entry::locked)
    }

    /// Whether `at_ms` falls in a Locked window the ledger still holds whole. A retired window
    /// keeps its address and dates, not its flag.
    pub fn locked_at(&self, at_ms: u64) -> bool {
        self.entries.iter().rev().find(|e| e.at <= at_ms && e.spell.moves()).is_some_and(Entry::locked)
    }

    /// The dates the read address holds nothing a reader needs: each run of Locked windows from
    /// ten minutes past its start (a client that hadn't read the lock may still use it until then),
    /// and the seal's stretch from its end to the first window after it that isn't Locked, which
    /// holds the run even once its early entries retire. Sorted, disjoint; `None` while running.
    pub fn quiet_spans(&self) -> Vec<(u64, Option<u64>)> {
        let moves: Vec<&Entry> = self.entries.iter().filter(|e| e.spell.moves()).collect();
        let end_after = |at: u64| moves.iter().find(|e| e.at > at && !e.locked()).map(|e| e.at);
        let mut spans: Vec<(u64, Option<u64>)> = moves
            .iter()
            .enumerate()
            .filter(|(i, e)| e.locked() && (*i == 0 || !moves[i - 1].locked()))
            .map(|(_, e)| (e.at.saturating_add(ENTRY_SKEW_MS), end_after(e.at)))
            .collect();
        // The seal's run, from its first ten minutes on, whatever entries of it remain.
        if let Some(seal) = &self.seal {
            let from = seal.run.saturating_add(ENTRY_SKEW_MS);
            spans.push((from, end_after(seal.run)));
        }
        spans.retain(|(from, to)| to.is_none_or(|t| t > *from));
        spans.sort_by_key(|s| s.0);
        let mut out: Vec<(u64, Option<u64>)> = Vec::with_capacity(spans.len());
        for (from, to) in spans {
            match out.last_mut() {
                Some(last) if last.1.is_none_or(|end| end >= from) => {
                    last.1 = last.1.zip(to).map(|(a, b)| a.max(b));
                }
                _ => out.push((from, to)),
            }
        }
        out
    }

    /// Whether nothing a reader needs sits at the read address at `at_ms`.
    pub fn read_address_quiet(&self, at_ms: u64) -> bool {
        self.quiet_spans().iter().any(|(from, to)| *from <= at_ms && to.is_none_or(|t| at_ms < t))
    }

    /// The dates at or below `top_ms` the read address is read by, as `(floor, top)`: the top
    /// lowered out of any quiet span, the floor the nearest quiet span below or the seal's end.
    /// `None` when nothing above the seal is left.
    pub fn read_range(&self, top_ms: u64) -> Option<(u64, u64)> {
        let spans = self.quiet_spans();
        let mut top = top_ms;
        if let Some((from, _)) = spans.iter().find(|(from, to)| *from <= top && to.is_none_or(|t| top < t)) {
            top = from.checked_sub(1)?;
        }
        let below = spans.iter().filter_map(|(_, to)| *to).filter(|t| *t <= top).max().unwrap_or(0);
        let floor = below.max(self.seal.as_ref().map_or(0, |s| s.until));
        (floor <= top).then_some((floor, top))
    }

    /// When the live run of Locked windows began, while the live window is Locked.
    pub fn run_start(&self) -> Option<u64> {
        let moves: Vec<&Entry> = self.entries.iter().filter(|e| e.spell.moves()).collect();
        let tail = moves.iter().rev().take_while(|e| e.locked()).last()?;
        Some(tail.at)
    }

    /// Where the live run of Locked windows is owed a seal to at `now_ms`, if anywhere: up to its
    /// start once it begins, then across its first ten minutes once they pass. A seal made in an
    /// earlier run, one a window that wasn't Locked has followed since, is this run's no longer.
    pub fn seal_target(&self, now_ms: u64) -> Option<u64> {
        let start = self.run_start()?;
        let in_run = self.seal.as_ref().filter(|s| !self.entries.iter().any(|e| e.spell.moves() && e.at > s.run && !e.locked()));
        match in_run {
            None => Some(start),
            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)),
            _ => None,
        }
    }

    /// When the run the next seal belongs to began: the live seal's own, while it still holds the
    /// run, else the live run's start.
    pub fn seal_run(&self) -> Option<u64> {
        let start = self.run_start()?;
        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))
    }

    /// This ledger sealed by `seal`: the edition appends a marker entry the cap may drop, and the
    /// seal itself rides the top level.
    pub fn appended_seal(&self, at: u64, seal: SealRef) -> Option<Self> {
        let at = self.entries.last().map_or(at, |last| at.max(last.at));
        let mut extra = serde_json::Map::new();
        extra.insert(SEALED.into(), seal.count.into());
        let mut next = self.with(Entry { at, spell: Spell::Other, extra })?;
        next.seal = Some(seal);
        Some(next)
    }

    /// The writer epoch taking posts now.
    pub fn current_writer(&self) -> Option<(Epoch, [u8; 32])> {
        match self.last_move()?.spell {
            Spell::Writer { epoch, pk, .. } => Some((epoch, pk)),
            _ => None,
        }
    }

    /// The live writer entry: its root epoch (a Refounding retires it), its minter, and when it began.
    pub fn live(&self) -> Option<(Epoch, [u8; 32], u64)> {
        let last = self.last_move()?;
        match last.spell {
            Spell::Writer { root, by, .. } => Some((root, by, last.at)),
            _ => None,
        }
    }

    /// Whether `writer` was stopped at writer `epoch` by `at_ms`: a stop entry for them inside
    /// that epoch's window, dated no later. A stop outlives its window's entry retiring; only the
    /// cap dropping the stop itself undoes it.
    pub fn stopped(&self, epoch: Epoch, writer: &[u8; 32], at_ms: u64) -> bool {
        let names = |e: &Entry| e.effective() <= at_ms && matches!(e.spell, Spell::Stop { writer: w } if w == *writer);
        if let Some(start) = self.entries.iter().position(|e| matches!(e.spell, Spell::Writer { epoch: w, .. } if w == epoch)) {
            return self.entries[start + 1..].iter().take_while(|e| !e.spell.moves()).any(names);
        }
        // Retired: the stops left at the front, before the first entry that moves, inside its window.
        // A stop dated with the entry that retired its window was still written inside it.
        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)))
    }

    /// Who minted writer `epoch`, while the ledger still holds its entry.
    pub fn minter(&self, epoch: Epoch) -> Option<[u8; 32]> {
        self.entries.iter().find_map(|e| match e.spell {
            Spell::Writer { epoch: w, by, .. } if w == epoch => Some(by),
            _ => None,
        })
    }

    /// The writer epoch before the live one, if the ledger still names it.
    pub fn previous_writer(&self) -> Option<Epoch> {
        let mut epochs = self.writers().map(|(e, ..)| e).collect::<Vec<_>>();
        epochs.pop();
        epochs.pop()
    }

    /// The epoch a newly minted writer secret takes, `None` once the range is spent.
    pub fn next_epoch(&self) -> Option<Epoch> {
        let next = self.writers().map(|(e, ..)| e.0).max().unwrap_or(0).checked_add(1)?;
        (next < MAX_EPOCH).then_some(Epoch(next))
    }

    /// Every writer address, retired then live, with the millisecond its entry ends, `None` while
    /// it still holds.
    pub fn writers(&self) -> impl Iterator<Item = (Epoch, [u8; 32], Option<u64>)> + '_ {
        let retired = self.retired.iter().map(|r| (r.epoch, r.pk, Some(r.to)));
        let live = self.entries.iter().enumerate().filter_map(|(i, e)| match e.spell {
            Spell::Writer { epoch, pk, .. } => Some((epoch, pk, self.entries[i + 1..].iter().find(|n| n.spell.moves()).map(|n| n.at))),
            _ => None,
        });
        retired.chain(live)
    }

    /// The root epochs its live writer entries were minted under: what they carried is sealed
    /// under each one's read key.
    pub fn roots(&self) -> impl Iterator<Item = Epoch> + '_ {
        self.entries.iter().filter_map(|e| match e.spell {
            Spell::Writer { root, .. } => Some(root),
            _ => None,
        })
    }

    /// When each writer address began, to bound what a read of it can hold.
    pub fn writer_start(&self, epoch: Epoch) -> Option<u64> {
        self.retired
            .iter()
            .find(|r| r.epoch == epoch)
            .map(|r| r.from)
            .or_else(|| self.entries.iter().find(|e| matches!(e.spell, Spell::Writer { epoch: w, .. } if w == epoch)).map(|e| e.at))
    }

    /// Whether a post at the read address dated `at_ms` stands: not inside a writer entry, live
    /// or retired.
    pub fn read_address_takes(&self, at_ms: u64) -> bool {
        if self.retired.iter().any(|r| (r.from..r.to).contains(&at_ms)) {
            return false;
        }
        !matches!(self.entries.iter().rev().find(|e| e.at <= at_ms && e.spell.moves()), Some(Entry { spell: Spell::Writer { .. }, .. }))
    }

    /// The key that certifies writer `epoch`'s writers, live or retired.
    pub fn certifier(&self, epoch: Epoch) -> Option<[u8; 32]> {
        self.retired.iter().find(|r| r.epoch == epoch).and_then(|r| r.certifier).or_else(|| {
            self.entries.iter().find_map(|e| match e.spell {
                Spell::Writer { epoch: w, certifier, .. } if w == epoch => certifier,
                _ => None,
            })
        })
    }

    /// Whether `cert` is the certifier of writer `epoch` vouching for `writer` in this Channel.
    pub fn certifies(&self, community: &[u8; 32], epoch: Epoch, writer: &[u8; 32], cert: &[u8; 64]) -> bool {
        self.certifier(epoch).is_some_and(|c| verify_writer_cert(&c, &cert_digest(community, &self.channel, epoch, writer), cert))
    }

    /// Whether `cert` is the certifier of writer `epoch` vouching for `writer` with only `rights`.
    pub fn certifies_scoped(&self, community: &[u8; 32], epoch: Epoch, writer: &[u8; 32], rights: u64, cert: &[u8; 64]) -> bool {
        self.certifier(epoch).is_some_and(|c| verify_writer_cert(&c, &scoped_cert_digest(community, &self.channel, epoch, writer, rights), cert))
    }

    /// Whether a post at writer `epoch`'s address dated `at_ms` stands: before its entry ends.
    pub fn writer_address_takes(&self, epoch: Epoch, at_ms: u64) -> bool {
        self.writers().any(|(e, _, end)| e == epoch && end.is_none_or(|end| at_ms < end))
    }

    /// This ledger with `entry` appended verbatim; at the cap the oldest entry goes, a writer one
    /// into `retired`. `None` when that leaves it malformed.
    fn with(&self, entry: Entry) -> Option<Self> {
        let mut next = self.clone();
        next.entries.push(entry);
        if next.entries.len() > MAX_LEDGER {
            let gone = next.entries.remove(0);
            if let Spell::Writer { epoch, pk, certifier, .. } = gone.spell {
                // Its window runs to the next entry that moves posts; the live one never retires.
                let to = next.entries.iter().find(|e| e.spell.moves())?.at;
                next.retired.push(Retired { epoch, pk, from: gone.at, to, certifier });
                if next.retired.len() > MAX_RETIRED {
                    next.retired.remove(0);
                }
            }
        }
        next.well_formed().then_some(next)
    }

    /// This ledger with `spell` appended at `at`, never before the last entry. `None` when a
    /// writer epoch isn't above the last.
    pub fn appended(&self, at: u64, spell: Spell) -> Option<Self> {
        self.appended_from(at, spell, None)
    }

    /// [`Self::appended`] for a writer entry, its window Locked when `locked`.
    pub fn appended_writer(&self, at: u64, spell: Spell, locked: bool) -> Option<Self> {
        let at = self.entries.last().map_or(at, |last| at.max(last.at));
        let mut extra = serde_json::Map::new();
        if locked && matches!(spell, Spell::Writer { .. }) {
            extra.insert(LOCKED.into(), true.into());
        }
        self.with(Entry { at, spell, extra })
    }

    /// [`Self::appended`]; a stop dated `at` that records a departure from `from`.
    pub fn appended_from(&self, at: u64, spell: Spell, from: Option<u64>) -> Option<Self> {
        let at = self.entries.last().map_or(at, |last| at.max(last.at));
        let mut extra = serde_json::Map::new();
        if let (Spell::Stop { .. }, Some(from)) = (spell, from.filter(|f| *f < at)) {
            extra.insert(STOP_FROM.into(), from.into());
        }
        self.with(Entry { at, spell, extra })
    }

    /// Whether this ledger is `prev` with exactly one entry appended.
    pub fn extends(&self, prev: &Ledger) -> bool {
        let Some(last) = self.entries.last() else { return false };
        prev.with(last.clone()).is_some_and(|grown| grown.channel == self.channel && grown.entries == self.entries && grown.retired == self.retired)
    }

    /// Whether this ledger could be a Channel's first: one entry and nothing retired.
    pub fn is_first(&self) -> bool {
        self.entries.len() == 1 && self.retired.is_empty()
    }

    /// Whether this ledger's newest entry sits within [`ENTRY_SKEW_MS`] of `edition_secs`, and,
    /// when it is a writer entry, names `author` as its minter: an edition appends its own.
    pub fn tail_fits(&self, edition_secs: u64, author: &[u8; 32]) -> bool {
        let Some(last) = self.entries.last() else { return false };
        let near = last.at.abs_diff(edition_secs.saturating_mul(1000)) <= ENTRY_SKEW_MS;
        near && !matches!(last.spell, Spell::Writer { by, .. } if by != *author)
    }

    /// Whether the newest entry is dated within [`HORIZON_MS`] of `now_ms`: a later one waits.
    pub fn not_ahead(&self, now_ms: u64) -> bool {
        self.entries.last().is_some_and(|e| e.at <= now_ms.saturating_add(HORIZON_MS))
    }
}

/// What a writer certificate signs: one member's place among a Channel's writers at one epoch.
pub fn cert_digest(community: &[u8; 32], channel: &[u8; 32], epoch: Epoch, writer: &[u8; 32]) -> [u8; 32] {
    use sha2::Digest;
    let mut h = sha2::Sha256::new();
    h.update(b"concord/writer-cert");
    h.update(community);
    h.update(channel);
    h.update(epoch.0.to_be_bytes());
    h.update(writer);
    h.finalize().into()
}

/// What a scoped writer certificate signs: one member's place among a Channel's writers at one
/// epoch, for only the writes `rights` names (CORD-04 bits). A post never stands on one.
pub fn scoped_cert_digest(community: &[u8; 32], channel: &[u8; 32], epoch: Epoch, writer: &[u8; 32], rights: u64) -> [u8; 32] {
    use sha2::Digest;
    let mut h = sha2::Sha256::new();
    h.update(b"concord/writer-cert-scoped");
    h.update(community);
    h.update(channel);
    h.update(epoch.0.to_be_bytes());
    h.update(writer);
    h.update(rights.to_be_bytes());
    h.finalize().into()
}

/// The never-published event a writer certificate signs: [`cert_digest`] under the certifier.
fn cert_event(certifier: nostr_sdk::prelude::PublicKey, digest: &[u8; 32]) -> nostr_sdk::prelude::UnsignedEvent {
    use nostr_sdk::prelude::{Kind, Tag, Timestamp, UnsignedEvent};
    UnsignedEvent::new(certifier, Timestamp::from_secs(0), Kind::Custom(CERT_KIND), [Tag::custom("digest", [crate::simd::hex::bytes_to_hex_32(digest)])], "")
}

/// The kind of the event a writer certificate signs; never published.
const CERT_KIND: u16 = 3320;

/// A certifier's signature over [`cert_digest`].
pub fn sign_writer_cert(certifier: &[u8; 32], digest: &[u8; 32]) -> Option<[u8; 64]> {
    let keys = nostr_sdk::prelude::Keys::new(nostr_sdk::prelude::SecretKey::from_slice(certifier).ok()?);
    let e = cert_event(keys.public_key(), digest);
    let id = nostr_sdk::prelude::EventId::compute(&e.pubkey, &e.created_at, &e.kind, &e.tags, &e.content);
    Some(keys.sign_schnorr(id.as_bytes()).to_bytes())
}

pub fn verify_writer_cert(certifier: &[u8; 32], digest: &[u8; 32], cert: &[u8; 64]) -> bool {
    use nostr_sdk::prelude::{Event, EventId, PublicKey, Signature};
    let (Ok(pk), Ok(sig)) = (PublicKey::from_slice(certifier), Signature::from_slice(cert)) else { return false };
    let unsigned = cert_event(pk, digest);
    let id = EventId::compute(&pk, &unsigned.created_at, &unsigned.kind, &unsigned.tags, &unsigned.content);
    Event::new(id, pk, unsigned.created_at, unsigned.kind, unsigned.tags, unsigned.content, sig).verify_signature()
}

/// The certifier key a certifier secret yields.
pub fn certifier_of(secret: &[u8; 32]) -> Option<[u8; 32]> {
    nostr_sdk::prelude::SecretKey::from_slice(secret).ok().map(|s| nostr_sdk::prelude::Keys::new(s).public_key().to_bytes())
}

/// The writer address a secret yields for `epoch`.
pub fn writer_address(secret: &[u8; 32], channel: &ChannelId, epoch: Epoch) -> [u8; 32] {
    channel_writer_group_key(secret, channel, epoch).pk().to_bytes()
}

/// The rekey scope writer blobs bind to.
pub fn writer_rekey_scope(channel: &ChannelId) -> super::rekey::RekeyScope {
    super::rekey::RekeyScope::Channel(ChannelId(writer_scope(channel)))
}

/// The access-plane scope a Channel's writer certifier secrets ride to its managers.
pub fn certifier_rekey_scope(channel: &ChannelId) -> super::rekey::RekeyScope {
    super::rekey::RekeyScope::Channel(ChannelId(super::derive::certifier_scope(channel)))
}

/// Where a Channel's writer secrets are archived, by writer epoch.
pub fn secret_scope(channel: &ChannelId) -> String {
    format!("wr:{}", crate::simd::hex::bytes_to_hex_32(&channel.0))
}

/// Where a minter keeps the secrets it minted, so a retry reuses its own and never one it
/// was delivered.
pub fn minted_scope(channel: &ChannelId) -> String {
    format!("wrmint:{}", crate::simd::hex::bytes_to_hex_32(&channel.0))
}

/// Where a minter keeps the secret that certifies its epoch's writers.
pub fn certifier_scope(channel: &ChannelId) -> String {
    format!("wrcert:{}", crate::simd::hex::bytes_to_hex_32(&channel.0))
}

#[cfg(test)]
mod tests {
    use super::*;

    const CH: ChannelId = ChannelId([0x42; 32]);
    const BY: [u8; 32] = [0x0b; 32];

    fn pk(n: u8) -> [u8; 32] {
        writer_address(&[n; 32], &CH, Epoch(n as u64))
    }

    fn w(e: u64, n: u8) -> Spell {
        Spell::Writer { epoch: Epoch(e), pk: pk(n), root: Epoch(0), by: BY, certifier: None }
    }

    #[test]
    fn a_locked_window_is_carried_whole_and_ends_at_the_next_move() {
        let with = |l: &Ledger, at: u64, s: Spell, locked: bool| l.appended_writer(at, s, locked).unwrap();
        let l = with(&Ledger::new(&CH), 100, w(1, 1), false);
        assert!(l.restricted() && !l.locked(), "a writer entry gates posting alone by default");
        let l = with(&l, 200, w(2, 2), true);
        assert!(l.locked() && l.locked_at(200) && l.locked_at(10_000) && !l.locked_at(150), "locked from its own date");
        let back = Ledger::parse(&l.to_json()).unwrap();
        assert_eq!(back, l, "the flag round-trips");
        assert!(back.extends(&Ledger::parse(&with(&Ledger::new(&CH), 100, w(1, 1), false).to_json()).unwrap()), "and is part of what verbatim compares");
        let l = l.appended(300, Spell::Open).unwrap();
        assert!(!l.locked() && !l.locked_at(300) && l.locked_at(250));
        // Only the flag set to true locks: anything else reads as a window that gates posting.
        let odd = l.to_json().replace("\"locked\":true", "\"locked\":\"yes\"");
        assert!(!Ledger::parse(&odd).unwrap().locked_at(250));
        // A stop sits inside the window without ending it.
        let l = with(&Ledger::new(&CH), 100, w(1, 1), true).appended(150, Spell::Stop { writer: pk(9) }).unwrap();
        assert!(l.locked() && l.locked_at(160));
    }

    const MIN: u64 = 60_000;

    #[test]
    fn a_run_of_locked_windows_is_one_quiet_stretch_from_ten_minutes_in() {
        let with = |l: &Ledger, at: u64, s: Spell, locked: bool| l.appended_writer(at, s, locked).unwrap();
        let l = with(&Ledger::new(&CH), 100 * MIN, w(1, 1), false);
        let l = with(&l, 200 * MIN, w(2, 2), true);
        // A fresh epoch while still Locked, as a member losing their rights takes: the same run.
        let l = with(&l, 300 * MIN, w(3, 3), true);
        assert_eq!(l.quiet_spans(), vec![(210 * MIN, None)]);
        assert_eq!(l.run_start(), Some(200 * MIN));
        assert!(l.read_address_quiet(250 * MIN) && l.read_address_quiet(305 * MIN) && !l.read_address_quiet(205 * MIN));
        // Read from below the run: down from its first ten minutes, never inside it.
        assert_eq!(l.read_range(400 * MIN), Some((0, 210 * MIN - 1)));
        assert_eq!(l.read_range(150 * MIN), Some((0, 150 * MIN)));
        let l = l.appended(500 * MIN, Spell::Open).unwrap();
        assert_eq!(l.quiet_spans(), vec![(210 * MIN, Some(500 * MIN))]);
        assert_eq!(l.read_range(600 * MIN), Some((500 * MIN, 600 * MIN)), "above the run, down to where it ended");
        assert_eq!(l.read_range(499 * MIN), Some((0, 210 * MIN - 1)), "and past it, from below it");
        assert_eq!(l.run_start(), None);
    }

    #[test]
    fn a_seal_holds_its_stretch_past_the_cap() {
        let mut l = Ledger::new(&CH).appended_writer(200 * MIN, w(1, 1), true).unwrap();
        assert_eq!(l.seal_target(201 * MIN), Some(200 * MIN), "sealed to its start at once");
        let first = SealRef { page: Some([6; 32]), read: Epoch(2), until: 200 * MIN, run: 200 * MIN, count: 4, extra: Default::default() };
        l = l.appended_seal(200 * MIN, first).unwrap();
        assert_eq!(l.seal_target(205 * MIN), None, "then nothing until its first minutes pass");
        assert_eq!(l.seal_target(210 * MIN), Some(210 * MIN), "then across them");
        assert_eq!(l.read_range(209 * MIN), Some((200 * MIN, 209 * MIN)), "its first minutes still read by date meanwhile");
        let seal = SealRef { page: Some([7; 32]), read: Epoch(2), until: 210 * MIN, run: 200 * MIN, count: 5, extra: Default::default() };
        l = l.appended_seal(211 * MIN, seal.clone()).unwrap();
        assert_eq!(l.seal_target(10_000 * MIN), None);
        assert_eq!(Ledger::parse(&l.to_json()).unwrap(), l, "the seal round-trips at the top level");
        assert_eq!(l.read_range(400 * MIN), None, "everything below the seal is read by id");
        // Fresh epochs, still Locked, until the run's first entries and the seal's own marker go.
        for e in 2..=70u64 {
            l = l.appended_writer((211 + e) * MIN, w(e, (e % 200) as u8 + 1), true).unwrap();
        }
        assert!(l.retired.iter().any(|r| r.epoch == Epoch(1)), "the run's first window retired");
        assert!(!l.entries.iter().any(|e| e.extra.contains_key(SEALED)), "and the seal's marker with it");
        assert_eq!(l.seal, Some(seal));
        assert!(l.seal_target(10_000 * MIN).is_none() && l.read_address_quiet(212 * MIN), "the seal still holds the stretch");
        assert_eq!(l.read_range(10_000 * MIN), None);
        // Opened and Locked again, the new run is the seal's no longer.
        let l = l.appended(400 * MIN, Spell::Open).unwrap().appended_writer(500 * MIN, w(71, 9), true).unwrap();
        assert_eq!(l.seal_target(10_000 * MIN), Some(500 * MIN));
        assert_eq!(l.quiet_spans(), vec![(210 * MIN, Some(400 * MIN)), (510 * MIN, None)]);
        assert_eq!(l.read_range(10_000 * MIN), Some((400 * MIN, 510 * MIN - 1)), "only what came between the runs");
    }

    #[test]
    fn a_scoped_certificate_vouches_only_for_its_rights() {
        let secret = [0x31; 32];
        let certifier = certifier_of(&secret).unwrap();
        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();
        l.channel = CH.0;
        let (community, writer) = ([1; 32], pk(5));
        let react = crate::community::roles::Permissions::ADD_REACTIONS;
        let cert = sign_writer_cert(&secret, &scoped_cert_digest(&community, &CH.0, Epoch(1), &writer, react)).unwrap();
        assert!(l.certifies_scoped(&community, Epoch(1), &writer, react, &cert));
        assert!(!l.certifies(&community, Epoch(1), &writer, &cert), "a scoped certificate is never a whole one");
        assert!(!l.certifies_scoped(&community, Epoch(1), &writer, react | crate::community::roles::Permissions::CONNECT, &cert), "its rights are what it signs");
        assert!(!l.certifies_scoped(&community, Epoch(1), &pk(6), react, &cert), "for one member");
        let whole = sign_writer_cert(&secret, &cert_digest(&community, &CH.0, Epoch(1), &writer)).unwrap();
        assert!(!l.certifies_scoped(&community, Epoch(1), &writer, react, &whole), "nor a whole one a scoped one");
    }

    /// The certificate test vector CORD-03 §1 publishes: what every client must compute alike.
    #[test]
    fn a_writer_certificate_matches_the_published_vector() {
        let (community, channel, writer, secret) = ([0x01; 32], [0x02; 32], [0x04; 32], [0x05; 32]);
        let d = cert_digest(&community, &channel, Epoch(3), &writer);
        assert_eq!(crate::simd::hex::bytes_to_hex_32(&d), "f49b5c7359b09366b5b96e074d2b7c5a84bd714a04bf0e6270d13c02d453e619");
        let certifier = certifier_of(&secret).unwrap();
        assert_eq!(crate::simd::hex::bytes_to_hex_32(&certifier), "62c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f7");
        let e = cert_event(nostr_sdk::prelude::PublicKey::from_slice(&certifier).unwrap(), &d);
        let id = nostr_sdk::prelude::EventId::compute(&e.pubkey, &e.created_at, &e.kind, &e.tags, &e.content);
        assert_eq!(id.to_hex(), "1b6fcc32de4a485d7b0109b0e5dd91b7c676fcb26f7dc41c8c2bdc7e3f2cbe90");
        let published: [u8; 64] = crate::simd::hex::hex_string_to_bytes_checked("cd1c3030e1220c539f1efb50d32e5b83432baa20eaa8709aa935050dc11a6ac6e25c3f9555b729cee65829fdbf1ba5e7656865a4fca860e42b05c8341922895a").unwrap().try_into().unwrap();
        assert!(verify_writer_cert(&certifier, &d, &published));
        assert!(verify_writer_cert(&certifier, &d, &sign_writer_cert(&secret, &d).unwrap()));
    }

    /// The scoped certificate test vector CORD-03 §1 publishes, rights = ADD_REACTIONS.
    #[test]
    fn a_scoped_certificate_matches_the_published_vector() {
        let (community, channel, writer, secret) = ([0x01; 32], [0x02; 32], [0x04; 32], [0x05; 32]);
        let d = scoped_cert_digest(&community, &channel, Epoch(3), &writer, crate::community::roles::Permissions::ADD_REACTIONS);
        assert_eq!(crate::simd::hex::bytes_to_hex_32(&d), "14129a75435ce645cd6c76d170f4ad61e88f54c0168a2deed48c9213b5eba10c");
        let certifier = certifier_of(&secret).unwrap();
        let e = cert_event(nostr_sdk::prelude::PublicKey::from_slice(&certifier).unwrap(), &d);
        let id = nostr_sdk::prelude::EventId::compute(&e.pubkey, &e.created_at, &e.kind, &e.tags, &e.content);
        assert_eq!(id.to_hex(), "418f80ff45b3122867c508997774858af6ab99bc12f18afb97ff2c99ad8a7db0");
        let published: [u8; 64] = crate::simd::hex::hex_string_to_bytes_checked("ec9f4cf12a0f5f09f199fdf776e4416859531e60e70c66ec477711c1f184fad59c913e6378b2be73d632c17223dc70a9acfcc930bd351bac461e2b521682c145").unwrap().try_into().unwrap();
        assert!(verify_writer_cert(&certifier, &d, &published));
    }

    #[test]
    fn a_writer_certificate_vouches_for_one_member_at_one_epoch_in_one_channel() {
        let secret = [0x31; 32];
        let certifier = certifier_of(&secret).unwrap();
        let (community, channel, writer) = ([1; 32], [2; 32], pk(5));
        let cert = sign_writer_cert(&secret, &cert_digest(&community, &channel, Epoch(3), &writer)).unwrap();
        assert!(verify_writer_cert(&certifier, &cert_digest(&community, &channel, Epoch(3), &writer), &cert));
        for (why, digest) in [
            ("another member", cert_digest(&community, &channel, Epoch(3), &pk(6))),
            ("another epoch", cert_digest(&community, &channel, Epoch(4), &writer)),
            ("another channel", cert_digest(&community, &[9; 32], Epoch(3), &writer)),
            ("another community", cert_digest(&[8; 32], &channel, Epoch(3), &writer)),
        ] {
            assert!(!verify_writer_cert(&certifier, &digest, &cert), "{why}");
        }
        assert!(!verify_writer_cert(&certifier_of(&[0x32; 32]).unwrap(), &cert_digest(&community, &channel, Epoch(3), &writer), &cert), "another certifier");
    }

    #[test]
    fn a_full_ledger_fits_one_relay_event() {
        let c = certifier_of(&[0x41; 32]).unwrap();
        let mut l = Ledger { channel: [7; 32], ..Default::default() };
        let mut epoch = 0u64;
        while l.retired.len() < MAX_RETIRED || l.entries.len() < MAX_LEDGER {
            epoch += 1;
            let spell = Spell::Writer { epoch: Epoch(epoch), pk: pk((epoch % 200) as u8 + 1), root: Epoch(epoch), by: BY, certifier: Some(c) };
            l = l.appended(1_792_256_141_843 + epoch * 1_000, spell).unwrap();
        }
        let keys = nostr_sdk::prelude::Keys::generate();
        let group = super::super::derive::channel_group_key(&[1; 32], &ChannelId([7; 32]), Epoch(1));
        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]));
        let (wrap, _) = super::super::control::seal_control_edition(&rumor, &group, &keys, nostr_sdk::prelude::Timestamp::from_secs(1_792_256_141)).unwrap();
        assert!(wrap.as_json().len() <= 65_536, "{} bytes: a full ledger must fit a 64KB relay event", wrap.as_json().len());
    }

    #[test]
    fn a_ledger_carries_its_certifiers_live_and_retired() {
        let c = certifier_of(&[0x41; 32]).unwrap();
        let mut l = Ledger { channel: [7; 32], ..Default::default() };
        for i in 0..MAX_LEDGER as u64 + 1 {
            let spell = Spell::Writer { epoch: Epoch(i + 1), pk: pk((i % 200) as u8 + 1), root: Epoch(0), by: BY, certifier: Some(c) };
            l = l.appended(1_000 + i, spell).unwrap();
        }
        assert_eq!(l.retired.len(), 1);
        assert_eq!((l.certifier(Epoch(1)), l.certifier(Epoch(2))), (Some(c), Some(c)), "retired and live");
        let back = Ledger::parse(&l.to_json()).unwrap();
        assert_eq!(back, l, "a round trip keeps every certifier");
        let old = ledger(&[(100, w(1, 1))]);
        assert_eq!(Ledger::parse(&old.to_json()).unwrap().certifier(Epoch(1)), None, "an entry from before certifiers reads");
    }

    #[test]
    fn a_stop_voids_one_writer_inside_its_epoch_and_moves_no_window() {
        let (a, b) = (pk(30), pk(31));
        let l = ledger(&[(100, w(1, 1)), (200, Spell::Stop { writer: a }), (300, w(2, 2)), (400, Spell::Open)]);
        assert!(l.well_formed());
        assert_eq!(Ledger::parse(&l.to_json()).unwrap(), l, "round trips");
        let ends: Vec<Option<u64>> = l.writers().map(|(.., end)| end).collect();
        assert_eq!(ends, vec![Some(300), Some(400)], "a window runs to the next entry that moves posts");
        assert!(!l.read_address_takes(250), "a stop opens nothing");
        assert!(l.stopped(Epoch(1), &a, 200) && l.stopped(Epoch(1), &a, 299));
        assert!(!l.stopped(Epoch(1), &a, 199), "posts before it stand");
        assert!(!l.stopped(Epoch(1), &b, 250), "it names one writer");
        assert!(!l.stopped(Epoch(2), &a, 350), "and one epoch");
        let later = ledger(&[(100, w(1, 1)), (200, w(2, 2)), (300, Spell::Stop { writer: a })]);
        assert!(!later.stopped(Epoch(1), &a, 400) && later.stopped(Epoch(2), &a, 400), "a stop is the window's it sits in");
        let live = ledger(&[(100, w(1, 1)), (200, Spell::Stop { writer: a })]);
        assert!(live.restricted() && live.current_writer() == Some((Epoch(1), pk(1))) && live.live().map(|l| l.2) == Some(100));
        assert!(!ledger(&[(100, w(1, 1)), (150, Spell::Open), (200, Spell::Stop { writer: a })]).well_formed(), "an open window has nobody to stop");
        assert!(ledger(&[(200, Spell::Stop { writer: a }), (300, w(2, 2))]).well_formed(), "one whose epoch retired still parses");
        let mut both: serde_json::Value = serde_json::from_str(&live.to_json()).unwrap();
        both["ledger"][1]["open"] = true.into();
        assert!(Ledger::parse(&both.to_string()).is_none(), "an entry is one thing");
        let mut unknown: serde_json::Value = serde_json::from_str(&live.to_json()).unwrap();
        unknown["ledger"].as_array_mut().unwrap().push(serde_json::json!({ "at": 300, "future": "kind" }));
        let carried = Ledger::parse(&unknown.to_string()).expect("a kind this build doesn't know is carried");
        assert_eq!(carried.current_writer(), live.current_writer(), "and moves nothing");
        assert_eq!(serde_json::from_str::<serde_json::Value>(&carried.to_json()).unwrap()["ledger"][2], serde_json::json!({ "at": 300, "future": "kind" }), "verbatim");
    }

    #[test]
    fn a_stop_never_pushes_the_live_writer_out_and_a_retired_window_skips_stops() {
        let mut l = ledger(&[(1_000, w(1, 1))]);
        for i in 1..MAX_LEDGER as u64 {
            l = l.appended(1_000 + i, Spell::Stop { writer: pk((i % 200) as u8 + 20) }).unwrap();
        }
        assert_eq!(l.entries.len(), MAX_LEDGER);
        assert!(l.appended(5_000, Spell::Stop { writer: pk(9) }).is_none(), "at the cap a stop would retire the live entry");
        let next = l.appended(5_000, w(2, 2)).unwrap();
        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");
        assert!(next.stopped(Epoch(1), &pk(21), 4_000), "a stop outlives its window's entry retiring");
        assert!(!next.stopped(Epoch(1), &pk(21), 1_000), "and still only from its date");
        let mut later = next.clone();
        for i in 0..MAX_LEDGER as u64 {
            later = later.appended(6_000 + i, Spell::Open).and_then(|l| l.appended(6_000 + i, w(3 + i, 3))).unwrap_or(later);
        }
        assert!(!later.stopped(Epoch(1), &pk(21), 4_000), "a stop the cap dropped stops nothing");
    }

    fn ledger(entries: &[(u64, Spell)]) -> Ledger {
        let mut l = Ledger::new(&CH);
        l.entries = entries.iter().map(|(at, spell)| Entry { at: *at, spell: *spell, extra: Default::default() }).collect();
        l
    }

    #[test]
    fn a_ledger_round_trips_with_its_unknown_fields() {
        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 })]);
        l.extra.insert("future".into(), serde_json::json!({"x": 1}));
        l.entries[1].extra.insert("note".into(), "kept".into());
        l.retired = vec![Retired { epoch: Epoch(1), pk: pk(3), from: 10, to: 50, certifier: None }];
        let back = Ledger::parse(&l.to_json()).unwrap();
        assert_eq!(back, l);
        assert!(back.restricted() && back.current_writer() == Some((Epoch(3), pk(2))) && back.next_epoch() == Some(Epoch(4)));
        assert_eq!(back.live(), Some((Epoch(3), BY, 300)));
        assert_eq!((back.previous_writer(), back.minter(Epoch(2)), back.minter(Epoch(1))), (Some(Epoch(2)), Some(BY), None));
    }

    #[test]
    fn a_run_of_parses_judges_each_key_as_one_parse_would() {
        let good = ledger(&[(100, w(1, 1)), (150, w(2, 2))]).to_json();
        let off_curve = good.replace(&crate::simd::hex::bytes_to_hex_32(&pk(2)), &"ff".repeat(32));
        assert!(Ledger::parse(&off_curve).is_none());
        let mut keys = KeyCheck::default();
        for (content, parses) in [(&good, true), (&off_curve, false), (&good, true), (&off_curve, false)] {
            assert_eq!(Ledger::parse_with(content, &mut keys).is_some(), parses);
        }
        let mut keys = KeyCheck::default();
        assert!(Ledger::parse_with(&off_curve, &mut keys).is_none());
        assert!(Ledger::parse_with(&good, &mut keys).is_some(), "a key judged bad leaves the good ones alone");
    }

    #[test]
    fn a_malformed_ledger_reads_as_none() {
        let ok = ledger(&[(100, w(1, 1)), (100, Spell::Open), (150, w(2, 2))]);
        assert!(Ledger::parse(&ok.to_json()).is_some(), "equal times keep order");
        let mut stale = ok.clone();
        stale.retired = vec![Retired { epoch: Epoch(5), pk: pk(5), from: 1, to: 2, certifier: None }];
        for (why, bad) in [
            ("out of order", ledger(&[(200, w(1, 1)), (100, Spell::Open)])),
            ("epoch repeats", ledger(&[(100, w(1, 1)), (200, w(1, 2))])),
            ("epoch falls", ledger(&[(100, w(2, 2)), (200, w(1, 1))])),
            ("epoch out of range", ledger(&[(100, w(MAX_EPOCH, 1))])),
            ("a retired epoch above a live one", stale),
        ] {
            assert!(Ledger::parse(&bad.to_json()).is_none(), "{why}");
        }
        let full = ledger(&(0..=MAX_LEDGER as u64).map(|i| (i, Spell::Open)).collect::<Vec<_>>());
        assert!(Ledger::parse(&full.to_json()).is_none(), "too long");
        let ch = crate::simd::hex::bytes_to_hex_32(&CH.0);
        let hex = crate::simd::hex::bytes_to_hex_32(&pk(1));
        let by = crate::simd::hex::bytes_to_hex_32(&BY);
        for (why, raw) in [
            ("epoch zero", format!(r#"{{"channel":"{ch}","ledger":[{{"at":1,"epoch":0,"writer":"{hex}","root":0,"by":"{by}"}}]}}"#)),
            ("both at once", format!(r#"{{"channel":"{ch}","ledger":[{{"at":1,"open":true,"epoch":1,"writer":"{hex}","root":0,"by":"{by}"}}]}}"#)),
            ("no root", format!(r#"{{"channel":"{ch}","ledger":[{{"at":1,"epoch":1,"writer":"{hex}","by":"{by}"}}]}}"#)),
            ("no minter", format!(r#"{{"channel":"{ch}","ledger":[{{"at":1,"epoch":1,"writer":"{hex}","root":0}}]}}"#)),
            ("open false", format!(r#"{{"channel":"{ch}","ledger":[{{"at":1,"open":false}}]}}"#)),
            ("no point", format!(r#"{{"channel":"{ch}","ledger":[{{"at":1,"epoch":1,"writer":"{}","root":0,"by":"{by}"}}]}}"#, "00".repeat(32))),
            ("a retired window backwards", format!(r#"{{"channel":"{ch}","ledger":[],"retired":[[1,"{hex}",9,3]]}}"#)),
            ("no channel", r#"{"ledger":[]}"#.to_string()),
        ] {
            assert!(Ledger::parse(&raw).is_none(), "{why}");
        }
    }

    #[test]
    fn each_entry_holds_until_the_next() {
        let l = ledger(&[(100_000, w(1, 1)), (200_000, Spell::Open), (300_000, w(2, 2))]);
        assert!(l.read_address_takes(99_999), "before the first entry the Channel is open");
        assert!(!l.read_address_takes(100_000) && !l.read_address_takes(199_999), "inside a writer entry");
        assert!(l.read_address_takes(200_000) && l.read_address_takes(299_999), "the open stretch");
        assert!(!l.read_address_takes(5_000_000), "the live writer entry");
        assert!(l.writer_address_takes(Epoch(1), 150_000) && l.writer_address_takes(Epoch(1), 1_000), "a writer's past posts stay");
        assert!(!l.writer_address_takes(Epoch(1), 200_000), "nothing after its entry ends");
        assert!(l.writer_address_takes(Epoch(2), u64::MAX), "the live address takes everything");
        assert!(!l.writer_address_takes(Epoch(3), 0), "an epoch the ledger never named");
    }

    #[test]
    fn the_cap_retires_writer_entries_and_forgets_open_ones() {
        // A writer entry, then an open stretch, then entries to the cap.
        let mut entries: Vec<(u64, Spell)> = vec![(1_000, w(1, 1)), (2_000, Spell::Open)];
        entries.extend((2..MAX_LEDGER as u64).map(|i| (1_000 + i * 1_000, Spell::Open)));
        let at_cap = ledger(&entries);
        let once = at_cap.appended(500_000, w(2, 2)).unwrap();
        assert_eq!(once.retired, vec![Retired { epoch: Epoch(1), pk: pk(1), from: 1_000, to: 2_000, certifier: None }]);
        assert!(!once.read_address_takes(1_500), "the dropped writer entry's window stays closed");
        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");
        assert!(once.writers().any(|(e, ..)| e == Epoch(1)), "history still fetches it");
        assert_eq!(once.writer_start(Epoch(1)), Some(1_000));
        let twice = once.appended(600_000, Spell::Open).unwrap();
        assert_eq!(twice.retired.len(), 1, "a dropped open entry leaves nothing");
        assert!(twice.read_address_takes(2_500), "and its open stretch stays open");
        assert!(once.extends(&at_cap) && twice.extends(&once), "a cap drop still carries the ledger forward");
        assert!(Ledger::parse(&twice.to_json()).is_some());
    }

    #[test]
    fn a_ledger_extends_only_by_one_entry() {
        let a = ledger(&[(100, w(1, 1))]);
        let b = a.appended(200, Spell::Open).unwrap();
        assert!(b.extends(&a) && !a.extends(&b) && !a.extends(&a), "exactly one new entry");
        let c = b.appended(300, w(2, 2)).unwrap();
        assert!(!c.extends(&a), "two at once is no extension");
        let rewritten = ledger(&[(100, w(1, 2)), (200, Spell::Open)]);
        assert!(!rewritten.extends(&a), "a carried entry can't change");
        let shed = ledger(&[(200, Spell::Open)]);
        assert!(!shed.extends(&a), "below the cap nothing is dropped");
        assert!(a.is_first() && !b.is_first());
    }

    #[test]
    fn an_editions_newest_entry_is_its_own_and_dated_with_it() {
        let l = ledger(&[(100_000, w(1, 1))]);
        let far = ledger(&[(HORIZON_MS + 10_000_000, w(1, 1))]);
        assert!(far.not_ahead(10_000_000) && !far.not_ahead(10_000_000 - 1), "a far-future entry waits");
        assert!(l.tail_fits(100, &BY));
        assert!(!l.tail_fits(100, &[0x0c; 32]), "a writer entry names the edition's signer");
        assert!(!l.tail_fits(100 + ENTRY_SKEW_MS / 1000 + 1, &BY), "nor sits far from the edition's time");
        let opened = l.appended(150_000, Spell::Open).unwrap();
        assert!(opened.tail_fits(150, &[0x0c; 32]), "an open entry names nobody");
    }

    #[test]
    fn appending_never_backdates_and_keeps_epochs_rising() {
        let l = ledger(&[(100, w(1, 1))]);
        let next = l.appended(50, Spell::Open).unwrap();
        assert_eq!(next.entries[1].at, 100, "clamped to the last entry");
        assert!(l.appended(200, w(1, 2)).is_none());
        assert_eq!(next.next_epoch(), Some(Epoch(2)));
        assert_eq!(ledger(&[(1, w(MAX_EPOCH - 1, 1))]).next_epoch(), None, "the range is spent");
    }

    #[test]
    fn a_channel_without_a_ledger_reads_only_its_read_address() {
        use nostr_sdk::prelude::{Keys, Timestamp};
        let k = Keys::generate();
        let g = crate::community::v2::derive::channel_group_key(&[1; 32], &CH, Epoch(0));
        let rumor = super::super::chat::build_message_rumor(k.public_key(), &CH, Epoch(0), "x", None, &[], vec![], 1_000);
        let (wrap, _) = super::super::chat::seal_chat_rumor(&rumor, &g, &k, Timestamp::from_secs(1), false).unwrap();
        let ev = super::super::chat::open_chat_event(&wrap, &g, &CH, Epoch(0)).unwrap();
        use crate::community::v2::service::{sort_arrival, Arrival};
        assert!(matches!(sort_arrival(None, ev.clone(), None), Arrival::Stands(_)));
        assert!(matches!(sort_arrival(None, ev, Some(Epoch(1))), Arrival::Held(None)), "no ledger names a writer address");
    }
}