1use super::derive::{channel_writer_group_key, writer_scope};
8use crate::community::{ChannelId, Epoch};
9
10pub const MAX_LEDGER: usize = 64;
12
13pub const MAX_RETIRED: usize = 64;
15
16pub const MAX_EPOCH: u64 = 1 << 53;
18
19pub const ENTRY_SKEW_MS: u64 = 10 * 60 * 1000;
21
22pub const HORIZON_MS: u64 = 60 * 60 * 1000;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Spell {
28 Writer { epoch: Epoch, pk: [u8; 32], root: Epoch, by: [u8; 32], certifier: Option<[u8; 32]> },
31 Open,
33 Stop { writer: [u8; 32] },
36 Other,
38}
39
40impl Spell {
41 fn moves(&self) -> bool {
43 matches!(self, Spell::Writer { .. } | Spell::Open)
44 }
45}
46
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct Entry {
49 pub at: u64,
51 pub spell: Spell,
52 pub extra: serde_json::Map<String, serde_json::Value>,
54}
55
56const STOP_FROM: &str = "from";
58
59impl Entry {
60 pub fn effective(&self) -> u64 {
63 match self.spell {
64 Spell::Stop { .. } => self.extra.get(STOP_FROM).and_then(|v| v.as_u64()).map_or(self.at, |from| from.min(self.at)),
65 _ => self.at,
66 }
67 }
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub struct Retired {
74 pub epoch: Epoch,
75 pub pk: [u8; 32],
76 pub from: u64,
77 pub to: u64,
78 pub certifier: Option<[u8; 32]>,
79}
80
81#[derive(Debug, Clone, PartialEq, Eq, Default)]
82pub struct Ledger {
83 pub channel: [u8; 32],
84 pub entries: Vec<Entry>,
85 pub retired: Vec<Retired>,
86 pub extra: serde_json::Map<String, serde_json::Value>,
88}
89
90fn hex32(v: &serde_json::Value) -> Option<[u8; 32]> {
91 crate::simd::hex::hex_to_bytes_32_checked(v.as_str()?)
92}
93
94#[derive(Default)]
97pub struct KeyCheck(std::collections::HashMap<[u8; 32], bool>);
98
99impl KeyCheck {
100 fn writer_pk(&mut self, v: &serde_json::Value) -> Option<[u8; 32]> {
101 let pk = hex32(v)?;
102 let valid = *self.0.entry(pk).or_insert_with(|| nostr_sdk::prelude::PublicKey::from_slice(&pk).and_then(|p| p.xonly()).is_ok());
103 valid.then_some(pk)
104 }
105}
106
107fn epoch_of(v: &serde_json::Value) -> Option<Epoch> {
108 v.as_u64().filter(|n| *n > 0 && *n < MAX_EPOCH).map(Epoch)
109}
110
111impl Ledger {
112 pub fn new(channel: &ChannelId) -> Self {
113 Ledger { channel: channel.0, ..Default::default() }
114 }
115
116 pub fn parse(content: &str) -> Option<Self> {
120 Self::parse_with(content, &mut KeyCheck::default())
121 }
122
123 pub fn parse_with(content: &str, keys: &mut KeyCheck) -> Option<Self> {
125 let serde_json::Value::Object(mut top) = serde_json::from_str(content).ok()? else { return None };
126 let channel = hex32(&top.remove("channel")?)?;
127 let serde_json::Value::Array(raw) = top.remove("ledger")? else { return None };
128 let retired = match top.remove("retired") {
129 None => Vec::new(),
130 Some(serde_json::Value::Array(r)) => r
131 .iter()
132 .map(|x| {
133 let x = x.as_array().filter(|x| x.len() == 4 || x.len() == 5)?;
134 let certifier = match x.get(4) {
135 None => None,
136 Some(c) => Some(keys.writer_pk(c)?),
137 };
138 Some(Retired { epoch: epoch_of(&x[0])?, pk: keys.writer_pk(&x[1])?, from: x[2].as_u64()?, to: x[3].as_u64()?, certifier })
139 })
140 .collect::<Option<Vec<_>>>()?,
141 Some(_) => return None,
142 };
143 if raw.len() > MAX_LEDGER || retired.len() > MAX_RETIRED {
144 return None;
145 }
146 let mut entries = Vec::with_capacity(raw.len());
147 for e in raw {
148 let serde_json::Value::Object(mut e) = e else { return None };
149 let at = e.remove("at")?.as_u64()?;
150 let stop = e.remove("stop");
151 let spell = match (e.remove("open"), e.remove("epoch"), e.remove("writer"), e.remove("root"), e.remove("by")) {
152 (None, None, None, None, None) if stop.is_some() => Spell::Stop { writer: keys.writer_pk(stop.as_ref()?)? },
153 (None, None, None, None, None) => Spell::Other,
154 (Some(serde_json::Value::Bool(true)), None, None, None, None) if stop.is_none() => Spell::Open,
155 (None, Some(epoch), Some(writer), Some(root), Some(by)) if stop.is_none() => {
156 let certifier = match e.remove("certifier") {
157 None => None,
158 Some(c) => Some(keys.writer_pk(&c)?),
159 };
160 Spell::Writer { epoch: epoch_of(&epoch)?, pk: keys.writer_pk(&writer)?, root: Epoch(root.as_u64()?), by: hex32(&by)?, certifier }
161 }
162 _ => return None,
163 };
164 entries.push(Entry { at, spell, extra: e });
165 }
166 let ledger = Ledger { channel, entries, retired, extra: top };
167 ledger.well_formed().then_some(ledger)
168 }
169
170 fn well_formed(&self) -> bool {
171 let ordered = self.entries.windows(2).all(|w| w[0].at <= w[1].at);
172 let stops = self.entries.iter().enumerate().all(|(i, e)| {
174 !matches!(e.spell, Spell::Stop { .. }) || !matches!(self.entries[..i].iter().rev().find(|e| e.spell.moves()).map(|e| e.spell), Some(Spell::Open))
175 });
176 let windows = self.retired.iter().all(|r| r.from <= r.to);
177 let epochs: Vec<u64> = self.writers().map(|(e, ..)| e.0).collect();
178 ordered && stops && windows && epochs.windows(2).all(|w| w[0] < w[1]) && self.entries.len() <= MAX_LEDGER && self.retired.len() <= MAX_RETIRED
179 }
180
181 pub fn to_json(&self) -> String {
182 let entries: Vec<serde_json::Value> = self
183 .entries
184 .iter()
185 .map(|e| {
186 let mut o = e.extra.clone();
187 o.insert("at".into(), e.at.into());
188 match e.spell {
189 Spell::Writer { epoch, pk, root, by, certifier } => {
190 o.insert("epoch".into(), epoch.0.into());
191 o.insert("writer".into(), crate::simd::hex::bytes_to_hex_32(&pk).into());
192 o.insert("root".into(), root.0.into());
193 o.insert("by".into(), crate::simd::hex::bytes_to_hex_32(&by).into());
194 if let Some(c) = certifier {
195 o.insert("certifier".into(), crate::simd::hex::bytes_to_hex_32(&c).into());
196 }
197 }
198 Spell::Open => {
199 o.insert("open".into(), true.into());
200 }
201 Spell::Stop { writer } => {
202 o.insert("stop".into(), crate::simd::hex::bytes_to_hex_32(&writer).into());
203 }
204 Spell::Other => {}
205 }
206 serde_json::Value::Object(o)
207 })
208 .collect();
209 let mut top = self.extra.clone();
210 top.insert("channel".into(), crate::simd::hex::bytes_to_hex_32(&self.channel).into());
211 top.insert("ledger".into(), entries.into());
212 if !self.retired.is_empty() {
213 let retired: Vec<serde_json::Value> = self
214 .retired
215 .iter()
216 .map(|r| match r.certifier {
217 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)]),
218 None => serde_json::json!([r.epoch.0, crate::simd::hex::bytes_to_hex_32(&r.pk), r.from, r.to]),
219 })
220 .collect();
221 top.insert("retired".into(), retired.into());
222 }
223 serde_json::Value::Object(top).to_string()
224 }
225
226 fn last_move(&self) -> Option<&Entry> {
228 self.entries.iter().rev().find(|e| e.spell.moves())
229 }
230
231 pub fn restricted(&self) -> bool {
233 matches!(self.last_move(), Some(Entry { spell: Spell::Writer { .. }, .. }))
234 }
235
236 pub fn current_writer(&self) -> Option<(Epoch, [u8; 32])> {
238 match self.last_move()?.spell {
239 Spell::Writer { epoch, pk, .. } => Some((epoch, pk)),
240 _ => None,
241 }
242 }
243
244 pub fn live(&self) -> Option<(Epoch, [u8; 32], u64)> {
246 let last = self.last_move()?;
247 match last.spell {
248 Spell::Writer { root, by, .. } => Some((root, by, last.at)),
249 _ => None,
250 }
251 }
252
253 pub fn stopped(&self, epoch: Epoch, writer: &[u8; 32], at_ms: u64) -> bool {
257 let names = |e: &Entry| e.effective() <= at_ms && matches!(e.spell, Spell::Stop { writer: w } if w == *writer);
258 if let Some(start) = self.entries.iter().position(|e| matches!(e.spell, Spell::Writer { epoch: w, .. } if w == epoch)) {
259 return self.entries[start + 1..].iter().take_while(|e| !e.spell.moves()).any(names);
260 }
261 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)))
264 }
265
266 pub fn minter(&self, epoch: Epoch) -> Option<[u8; 32]> {
268 self.entries.iter().find_map(|e| match e.spell {
269 Spell::Writer { epoch: w, by, .. } if w == epoch => Some(by),
270 _ => None,
271 })
272 }
273
274 pub fn previous_writer(&self) -> Option<Epoch> {
276 let mut epochs = self.writers().map(|(e, ..)| e).collect::<Vec<_>>();
277 epochs.pop();
278 epochs.pop()
279 }
280
281 pub fn next_epoch(&self) -> Option<Epoch> {
283 let next = self.writers().map(|(e, ..)| e.0).max().unwrap_or(0).checked_add(1)?;
284 (next < MAX_EPOCH).then_some(Epoch(next))
285 }
286
287 pub fn writers(&self) -> impl Iterator<Item = (Epoch, [u8; 32], Option<u64>)> + '_ {
290 let retired = self.retired.iter().map(|r| (r.epoch, r.pk, Some(r.to)));
291 let live = self.entries.iter().enumerate().filter_map(|(i, e)| match e.spell {
292 Spell::Writer { epoch, pk, .. } => Some((epoch, pk, self.entries[i + 1..].iter().find(|n| n.spell.moves()).map(|n| n.at))),
293 _ => None,
294 });
295 retired.chain(live)
296 }
297
298 pub fn writer_start(&self, epoch: Epoch) -> Option<u64> {
300 self.retired
301 .iter()
302 .find(|r| r.epoch == epoch)
303 .map(|r| r.from)
304 .or_else(|| self.entries.iter().find(|e| matches!(e.spell, Spell::Writer { epoch: w, .. } if w == epoch)).map(|e| e.at))
305 }
306
307 pub fn read_address_takes(&self, at_ms: u64) -> bool {
310 if self.retired.iter().any(|r| (r.from..r.to).contains(&at_ms)) {
311 return false;
312 }
313 !matches!(self.entries.iter().rev().find(|e| e.at <= at_ms && e.spell.moves()), Some(Entry { spell: Spell::Writer { .. }, .. }))
314 }
315
316 pub fn certifier(&self, epoch: Epoch) -> Option<[u8; 32]> {
318 self.retired.iter().find(|r| r.epoch == epoch).and_then(|r| r.certifier).or_else(|| {
319 self.entries.iter().find_map(|e| match e.spell {
320 Spell::Writer { epoch: w, certifier, .. } if w == epoch => certifier,
321 _ => None,
322 })
323 })
324 }
325
326 pub fn certifies(&self, community: &[u8; 32], epoch: Epoch, writer: &[u8; 32], cert: &[u8; 64]) -> bool {
328 self.certifier(epoch).is_some_and(|c| verify_writer_cert(&c, &cert_digest(community, &self.channel, epoch, writer), cert))
329 }
330
331 pub fn writer_address_takes(&self, epoch: Epoch, at_ms: u64) -> bool {
333 self.writers().any(|(e, _, end)| e == epoch && end.is_none_or(|end| at_ms < end))
334 }
335
336 fn with(&self, entry: Entry) -> Option<Self> {
339 let mut next = self.clone();
340 next.entries.push(entry);
341 if next.entries.len() > MAX_LEDGER {
342 let gone = next.entries.remove(0);
343 if let Spell::Writer { epoch, pk, certifier, .. } = gone.spell {
344 let to = next.entries.iter().find(|e| e.spell.moves())?.at;
346 next.retired.push(Retired { epoch, pk, from: gone.at, to, certifier });
347 if next.retired.len() > MAX_RETIRED {
348 next.retired.remove(0);
349 }
350 }
351 }
352 next.well_formed().then_some(next)
353 }
354
355 pub fn appended(&self, at: u64, spell: Spell) -> Option<Self> {
358 self.appended_from(at, spell, None)
359 }
360
361 pub fn appended_from(&self, at: u64, spell: Spell, from: Option<u64>) -> Option<Self> {
363 let at = self.entries.last().map_or(at, |last| at.max(last.at));
364 let mut extra = serde_json::Map::new();
365 if let (Spell::Stop { .. }, Some(from)) = (spell, from.filter(|f| *f < at)) {
366 extra.insert(STOP_FROM.into(), from.into());
367 }
368 self.with(Entry { at, spell, extra })
369 }
370
371 pub fn extends(&self, prev: &Ledger) -> bool {
373 let Some(last) = self.entries.last() else { return false };
374 prev.with(last.clone()).is_some_and(|grown| grown.channel == self.channel && grown.entries == self.entries && grown.retired == self.retired)
375 }
376
377 pub fn is_first(&self) -> bool {
379 self.entries.len() == 1 && self.retired.is_empty()
380 }
381
382 pub fn tail_fits(&self, edition_secs: u64, author: &[u8; 32]) -> bool {
385 let Some(last) = self.entries.last() else { return false };
386 let near = last.at.abs_diff(edition_secs.saturating_mul(1000)) <= ENTRY_SKEW_MS;
387 near && !matches!(last.spell, Spell::Writer { by, .. } if by != *author)
388 }
389
390 pub fn not_ahead(&self, now_ms: u64) -> bool {
392 self.entries.last().is_some_and(|e| e.at <= now_ms.saturating_add(HORIZON_MS))
393 }
394}
395
396pub fn cert_digest(community: &[u8; 32], channel: &[u8; 32], epoch: Epoch, writer: &[u8; 32]) -> [u8; 32] {
398 use sha2::Digest;
399 let mut h = sha2::Sha256::new();
400 h.update(b"concord/writer-cert");
401 h.update(community);
402 h.update(channel);
403 h.update(epoch.0.to_be_bytes());
404 h.update(writer);
405 h.finalize().into()
406}
407
408fn cert_event(certifier: nostr_sdk::prelude::PublicKey, digest: &[u8; 32]) -> nostr_sdk::prelude::UnsignedEvent {
410 use nostr_sdk::prelude::{Kind, Tag, Timestamp, UnsignedEvent};
411 UnsignedEvent::new(certifier, Timestamp::from_secs(0), Kind::Custom(CERT_KIND), [Tag::custom("digest", [crate::simd::hex::bytes_to_hex_32(digest)])], "")
412}
413
414const CERT_KIND: u16 = 3320;
416
417pub fn sign_writer_cert(certifier: &[u8; 32], digest: &[u8; 32]) -> Option<[u8; 64]> {
419 let keys = nostr_sdk::prelude::Keys::new(nostr_sdk::prelude::SecretKey::from_slice(certifier).ok()?);
420 let e = cert_event(keys.public_key(), digest);
421 let id = nostr_sdk::prelude::EventId::compute(&e.pubkey, &e.created_at, &e.kind, &e.tags, &e.content);
422 Some(keys.sign_schnorr(id.as_bytes()).to_bytes())
423}
424
425pub fn verify_writer_cert(certifier: &[u8; 32], digest: &[u8; 32], cert: &[u8; 64]) -> bool {
426 use nostr_sdk::prelude::{Event, EventId, PublicKey, Signature};
427 let (Ok(pk), Ok(sig)) = (PublicKey::from_slice(certifier), Signature::from_slice(cert)) else { return false };
428 let unsigned = cert_event(pk, digest);
429 let id = EventId::compute(&pk, &unsigned.created_at, &unsigned.kind, &unsigned.tags, &unsigned.content);
430 Event::new(id, pk, unsigned.created_at, unsigned.kind, unsigned.tags, unsigned.content, sig).verify_signature()
431}
432
433pub fn certifier_of(secret: &[u8; 32]) -> Option<[u8; 32]> {
435 nostr_sdk::prelude::SecretKey::from_slice(secret).ok().map(|s| nostr_sdk::prelude::Keys::new(s).public_key().to_bytes())
436}
437
438pub fn writer_address(secret: &[u8; 32], channel: &ChannelId, epoch: Epoch) -> [u8; 32] {
440 channel_writer_group_key(secret, channel, epoch).pk().to_bytes()
441}
442
443pub fn writer_rekey_scope(channel: &ChannelId) -> super::rekey::RekeyScope {
445 super::rekey::RekeyScope::Channel(ChannelId(writer_scope(channel)))
446}
447
448pub fn certifier_rekey_scope(channel: &ChannelId) -> super::rekey::RekeyScope {
450 super::rekey::RekeyScope::Channel(ChannelId(super::derive::certifier_scope(channel)))
451}
452
453pub fn secret_scope(channel: &ChannelId) -> String {
455 format!("wr:{}", crate::simd::hex::bytes_to_hex_32(&channel.0))
456}
457
458pub fn minted_scope(channel: &ChannelId) -> String {
461 format!("wrmint:{}", crate::simd::hex::bytes_to_hex_32(&channel.0))
462}
463
464pub fn certifier_scope(channel: &ChannelId) -> String {
466 format!("wrcert:{}", crate::simd::hex::bytes_to_hex_32(&channel.0))
467}
468
469#[cfg(test)]
470mod tests {
471 use super::*;
472
473 const CH: ChannelId = ChannelId([0x42; 32]);
474 const BY: [u8; 32] = [0x0b; 32];
475
476 fn pk(n: u8) -> [u8; 32] {
477 writer_address(&[n; 32], &CH, Epoch(n as u64))
478 }
479
480 fn w(e: u64, n: u8) -> Spell {
481 Spell::Writer { epoch: Epoch(e), pk: pk(n), root: Epoch(0), by: BY, certifier: None }
482 }
483
484 #[test]
486 fn a_writer_certificate_matches_the_published_vector() {
487 let (community, channel, writer, secret) = ([0x01; 32], [0x02; 32], [0x04; 32], [0x05; 32]);
488 let d = cert_digest(&community, &channel, Epoch(3), &writer);
489 assert_eq!(crate::simd::hex::bytes_to_hex_32(&d), "f49b5c7359b09366b5b96e074d2b7c5a84bd714a04bf0e6270d13c02d453e619");
490 let certifier = certifier_of(&secret).unwrap();
491 assert_eq!(crate::simd::hex::bytes_to_hex_32(&certifier), "62c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f7");
492 let e = cert_event(nostr_sdk::prelude::PublicKey::from_slice(&certifier).unwrap(), &d);
493 let id = nostr_sdk::prelude::EventId::compute(&e.pubkey, &e.created_at, &e.kind, &e.tags, &e.content);
494 assert_eq!(id.to_hex(), "1b6fcc32de4a485d7b0109b0e5dd91b7c676fcb26f7dc41c8c2bdc7e3f2cbe90");
495 let published: [u8; 64] = crate::simd::hex::hex_string_to_bytes_checked("cd1c3030e1220c539f1efb50d32e5b83432baa20eaa8709aa935050dc11a6ac6e25c3f9555b729cee65829fdbf1ba5e7656865a4fca860e42b05c8341922895a").unwrap().try_into().unwrap();
496 assert!(verify_writer_cert(&certifier, &d, &published));
497 assert!(verify_writer_cert(&certifier, &d, &sign_writer_cert(&secret, &d).unwrap()));
498 }
499
500 #[test]
501 fn a_writer_certificate_vouches_for_one_member_at_one_epoch_in_one_channel() {
502 let secret = [0x31; 32];
503 let certifier = certifier_of(&secret).unwrap();
504 let (community, channel, writer) = ([1; 32], [2; 32], pk(5));
505 let cert = sign_writer_cert(&secret, &cert_digest(&community, &channel, Epoch(3), &writer)).unwrap();
506 assert!(verify_writer_cert(&certifier, &cert_digest(&community, &channel, Epoch(3), &writer), &cert));
507 for (why, digest) in [
508 ("another member", cert_digest(&community, &channel, Epoch(3), &pk(6))),
509 ("another epoch", cert_digest(&community, &channel, Epoch(4), &writer)),
510 ("another channel", cert_digest(&community, &[9; 32], Epoch(3), &writer)),
511 ("another community", cert_digest(&[8; 32], &channel, Epoch(3), &writer)),
512 ] {
513 assert!(!verify_writer_cert(&certifier, &digest, &cert), "{why}");
514 }
515 assert!(!verify_writer_cert(&certifier_of(&[0x32; 32]).unwrap(), &cert_digest(&community, &channel, Epoch(3), &writer), &cert), "another certifier");
516 }
517
518 #[test]
519 fn a_full_ledger_fits_one_relay_event() {
520 let c = certifier_of(&[0x41; 32]).unwrap();
521 let mut l = Ledger { channel: [7; 32], ..Default::default() };
522 let mut epoch = 0u64;
523 while l.retired.len() < MAX_RETIRED || l.entries.len() < MAX_LEDGER {
524 epoch += 1;
525 let spell = Spell::Writer { epoch: Epoch(epoch), pk: pk((epoch % 200) as u8 + 1), root: Epoch(epoch), by: BY, certifier: Some(c) };
526 l = l.appended(1_792_256_141_843 + epoch * 1_000, spell).unwrap();
527 }
528 let keys = nostr_sdk::prelude::Keys::generate();
529 let group = super::super::derive::channel_group_key(&[1; 32], &ChannelId([7; 32]), Epoch(1));
530 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]));
531 let (wrap, _) = super::super::control::seal_control_edition(&rumor, &group, &keys, nostr_sdk::prelude::Timestamp::from_secs(1_792_256_141)).unwrap();
532 assert!(wrap.as_json().len() <= 65_536, "{} bytes: a full ledger must fit a 64KB relay event", wrap.as_json().len());
533 }
534
535 #[test]
536 fn a_ledger_carries_its_certifiers_live_and_retired() {
537 let c = certifier_of(&[0x41; 32]).unwrap();
538 let mut l = Ledger { channel: [7; 32], ..Default::default() };
539 for i in 0..MAX_LEDGER as u64 + 1 {
540 let spell = Spell::Writer { epoch: Epoch(i + 1), pk: pk((i % 200) as u8 + 1), root: Epoch(0), by: BY, certifier: Some(c) };
541 l = l.appended(1_000 + i, spell).unwrap();
542 }
543 assert_eq!(l.retired.len(), 1);
544 assert_eq!((l.certifier(Epoch(1)), l.certifier(Epoch(2))), (Some(c), Some(c)), "retired and live");
545 let back = Ledger::parse(&l.to_json()).unwrap();
546 assert_eq!(back, l, "a round trip keeps every certifier");
547 let old = ledger(&[(100, w(1, 1))]);
548 assert_eq!(Ledger::parse(&old.to_json()).unwrap().certifier(Epoch(1)), None, "an entry from before certifiers reads");
549 }
550
551 #[test]
552 fn a_stop_voids_one_writer_inside_its_epoch_and_moves_no_window() {
553 let (a, b) = (pk(30), pk(31));
554 let l = ledger(&[(100, w(1, 1)), (200, Spell::Stop { writer: a }), (300, w(2, 2)), (400, Spell::Open)]);
555 assert!(l.well_formed());
556 assert_eq!(Ledger::parse(&l.to_json()).unwrap(), l, "round trips");
557 let ends: Vec<Option<u64>> = l.writers().map(|(.., end)| end).collect();
558 assert_eq!(ends, vec![Some(300), Some(400)], "a window runs to the next entry that moves posts");
559 assert!(!l.read_address_takes(250), "a stop opens nothing");
560 assert!(l.stopped(Epoch(1), &a, 200) && l.stopped(Epoch(1), &a, 299));
561 assert!(!l.stopped(Epoch(1), &a, 199), "posts before it stand");
562 assert!(!l.stopped(Epoch(1), &b, 250), "it names one writer");
563 assert!(!l.stopped(Epoch(2), &a, 350), "and one epoch");
564 let later = ledger(&[(100, w(1, 1)), (200, w(2, 2)), (300, Spell::Stop { writer: a })]);
565 assert!(!later.stopped(Epoch(1), &a, 400) && later.stopped(Epoch(2), &a, 400), "a stop is the window's it sits in");
566 let live = ledger(&[(100, w(1, 1)), (200, Spell::Stop { writer: a })]);
567 assert!(live.restricted() && live.current_writer() == Some((Epoch(1), pk(1))) && live.live().map(|l| l.2) == Some(100));
568 assert!(!ledger(&[(100, w(1, 1)), (150, Spell::Open), (200, Spell::Stop { writer: a })]).well_formed(), "an open window has nobody to stop");
569 assert!(ledger(&[(200, Spell::Stop { writer: a }), (300, w(2, 2))]).well_formed(), "one whose epoch retired still parses");
570 let mut both: serde_json::Value = serde_json::from_str(&live.to_json()).unwrap();
571 both["ledger"][1]["open"] = true.into();
572 assert!(Ledger::parse(&both.to_string()).is_none(), "an entry is one thing");
573 let mut unknown: serde_json::Value = serde_json::from_str(&live.to_json()).unwrap();
574 unknown["ledger"].as_array_mut().unwrap().push(serde_json::json!({ "at": 300, "future": "kind" }));
575 let carried = Ledger::parse(&unknown.to_string()).expect("a kind this build doesn't know is carried");
576 assert_eq!(carried.current_writer(), live.current_writer(), "and moves nothing");
577 assert_eq!(serde_json::from_str::<serde_json::Value>(&carried.to_json()).unwrap()["ledger"][2], serde_json::json!({ "at": 300, "future": "kind" }), "verbatim");
578 }
579
580 #[test]
581 fn a_stop_never_pushes_the_live_writer_out_and_a_retired_window_skips_stops() {
582 let mut l = ledger(&[(1_000, w(1, 1))]);
583 for i in 1..MAX_LEDGER as u64 {
584 l = l.appended(1_000 + i, Spell::Stop { writer: pk((i % 200) as u8 + 20) }).unwrap();
585 }
586 assert_eq!(l.entries.len(), MAX_LEDGER);
587 assert!(l.appended(5_000, Spell::Stop { writer: pk(9) }).is_none(), "at the cap a stop would retire the live entry");
588 let next = l.appended(5_000, w(2, 2)).unwrap();
589 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");
590 assert!(next.stopped(Epoch(1), &pk(21), 4_000), "a stop outlives its window's entry retiring");
591 assert!(!next.stopped(Epoch(1), &pk(21), 1_000), "and still only from its date");
592 let mut later = next.clone();
593 for i in 0..MAX_LEDGER as u64 {
594 later = later.appended(6_000 + i, Spell::Open).and_then(|l| l.appended(6_000 + i, w(3 + i, 3))).unwrap_or(later);
595 }
596 assert!(!later.stopped(Epoch(1), &pk(21), 4_000), "a stop the cap dropped stops nothing");
597 }
598
599 fn ledger(entries: &[(u64, Spell)]) -> Ledger {
600 let mut l = Ledger::new(&CH);
601 l.entries = entries.iter().map(|(at, spell)| Entry { at: *at, spell: *spell, extra: Default::default() }).collect();
602 l
603 }
604
605 #[test]
606 fn a_ledger_round_trips_with_its_unknown_fields() {
607 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 })]);
608 l.extra.insert("future".into(), serde_json::json!({"x": 1}));
609 l.entries[1].extra.insert("note".into(), "kept".into());
610 l.retired = vec![Retired { epoch: Epoch(1), pk: pk(3), from: 10, to: 50, certifier: None }];
611 let back = Ledger::parse(&l.to_json()).unwrap();
612 assert_eq!(back, l);
613 assert!(back.restricted() && back.current_writer() == Some((Epoch(3), pk(2))) && back.next_epoch() == Some(Epoch(4)));
614 assert_eq!(back.live(), Some((Epoch(3), BY, 300)));
615 assert_eq!((back.previous_writer(), back.minter(Epoch(2)), back.minter(Epoch(1))), (Some(Epoch(2)), Some(BY), None));
616 }
617
618 #[test]
619 fn a_run_of_parses_judges_each_key_as_one_parse_would() {
620 let good = ledger(&[(100, w(1, 1)), (150, w(2, 2))]).to_json();
621 let off_curve = good.replace(&crate::simd::hex::bytes_to_hex_32(&pk(2)), &"ff".repeat(32));
622 assert!(Ledger::parse(&off_curve).is_none());
623 let mut keys = KeyCheck::default();
624 for (content, parses) in [(&good, true), (&off_curve, false), (&good, true), (&off_curve, false)] {
625 assert_eq!(Ledger::parse_with(content, &mut keys).is_some(), parses);
626 }
627 let mut keys = KeyCheck::default();
628 assert!(Ledger::parse_with(&off_curve, &mut keys).is_none());
629 assert!(Ledger::parse_with(&good, &mut keys).is_some(), "a key judged bad leaves the good ones alone");
630 }
631
632 #[test]
633 fn a_malformed_ledger_reads_as_none() {
634 let ok = ledger(&[(100, w(1, 1)), (100, Spell::Open), (150, w(2, 2))]);
635 assert!(Ledger::parse(&ok.to_json()).is_some(), "equal times keep order");
636 let mut stale = ok.clone();
637 stale.retired = vec![Retired { epoch: Epoch(5), pk: pk(5), from: 1, to: 2, certifier: None }];
638 for (why, bad) in [
639 ("out of order", ledger(&[(200, w(1, 1)), (100, Spell::Open)])),
640 ("epoch repeats", ledger(&[(100, w(1, 1)), (200, w(1, 2))])),
641 ("epoch falls", ledger(&[(100, w(2, 2)), (200, w(1, 1))])),
642 ("epoch out of range", ledger(&[(100, w(MAX_EPOCH, 1))])),
643 ("a retired epoch above a live one", stale),
644 ] {
645 assert!(Ledger::parse(&bad.to_json()).is_none(), "{why}");
646 }
647 let full = ledger(&(0..=MAX_LEDGER as u64).map(|i| (i, Spell::Open)).collect::<Vec<_>>());
648 assert!(Ledger::parse(&full.to_json()).is_none(), "too long");
649 let ch = crate::simd::hex::bytes_to_hex_32(&CH.0);
650 let hex = crate::simd::hex::bytes_to_hex_32(&pk(1));
651 let by = crate::simd::hex::bytes_to_hex_32(&BY);
652 for (why, raw) in [
653 ("epoch zero", format!(r#"{{"channel":"{ch}","ledger":[{{"at":1,"epoch":0,"writer":"{hex}","root":0,"by":"{by}"}}]}}"#)),
654 ("both at once", format!(r#"{{"channel":"{ch}","ledger":[{{"at":1,"open":true,"epoch":1,"writer":"{hex}","root":0,"by":"{by}"}}]}}"#)),
655 ("no root", format!(r#"{{"channel":"{ch}","ledger":[{{"at":1,"epoch":1,"writer":"{hex}","by":"{by}"}}]}}"#)),
656 ("no minter", format!(r#"{{"channel":"{ch}","ledger":[{{"at":1,"epoch":1,"writer":"{hex}","root":0}}]}}"#)),
657 ("open false", format!(r#"{{"channel":"{ch}","ledger":[{{"at":1,"open":false}}]}}"#)),
658 ("no point", format!(r#"{{"channel":"{ch}","ledger":[{{"at":1,"epoch":1,"writer":"{}","root":0,"by":"{by}"}}]}}"#, "00".repeat(32))),
659 ("a retired window backwards", format!(r#"{{"channel":"{ch}","ledger":[],"retired":[[1,"{hex}",9,3]]}}"#)),
660 ("no channel", r#"{"ledger":[]}"#.to_string()),
661 ] {
662 assert!(Ledger::parse(&raw).is_none(), "{why}");
663 }
664 }
665
666 #[test]
667 fn each_entry_holds_until_the_next() {
668 let l = ledger(&[(100_000, w(1, 1)), (200_000, Spell::Open), (300_000, w(2, 2))]);
669 assert!(l.read_address_takes(99_999), "before the first entry the Channel is open");
670 assert!(!l.read_address_takes(100_000) && !l.read_address_takes(199_999), "inside a writer entry");
671 assert!(l.read_address_takes(200_000) && l.read_address_takes(299_999), "the open stretch");
672 assert!(!l.read_address_takes(5_000_000), "the live writer entry");
673 assert!(l.writer_address_takes(Epoch(1), 150_000) && l.writer_address_takes(Epoch(1), 1_000), "a writer's past posts stay");
674 assert!(!l.writer_address_takes(Epoch(1), 200_000), "nothing after its entry ends");
675 assert!(l.writer_address_takes(Epoch(2), u64::MAX), "the live address takes everything");
676 assert!(!l.writer_address_takes(Epoch(3), 0), "an epoch the ledger never named");
677 }
678
679 #[test]
680 fn the_cap_retires_writer_entries_and_forgets_open_ones() {
681 let mut entries: Vec<(u64, Spell)> = vec![(1_000, w(1, 1)), (2_000, Spell::Open)];
683 entries.extend((2..MAX_LEDGER as u64).map(|i| (1_000 + i * 1_000, Spell::Open)));
684 let at_cap = ledger(&entries);
685 let once = at_cap.appended(500_000, w(2, 2)).unwrap();
686 assert_eq!(once.retired, vec![Retired { epoch: Epoch(1), pk: pk(1), from: 1_000, to: 2_000, certifier: None }]);
687 assert!(!once.read_address_takes(1_500), "the dropped writer entry's window stays closed");
688 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");
689 assert!(once.writers().any(|(e, ..)| e == Epoch(1)), "history still fetches it");
690 assert_eq!(once.writer_start(Epoch(1)), Some(1_000));
691 let twice = once.appended(600_000, Spell::Open).unwrap();
692 assert_eq!(twice.retired.len(), 1, "a dropped open entry leaves nothing");
693 assert!(twice.read_address_takes(2_500), "and its open stretch stays open");
694 assert!(once.extends(&at_cap) && twice.extends(&once), "a cap drop still carries the ledger forward");
695 assert!(Ledger::parse(&twice.to_json()).is_some());
696 }
697
698 #[test]
699 fn a_ledger_extends_only_by_one_entry() {
700 let a = ledger(&[(100, w(1, 1))]);
701 let b = a.appended(200, Spell::Open).unwrap();
702 assert!(b.extends(&a) && !a.extends(&b) && !a.extends(&a), "exactly one new entry");
703 let c = b.appended(300, w(2, 2)).unwrap();
704 assert!(!c.extends(&a), "two at once is no extension");
705 let rewritten = ledger(&[(100, w(1, 2)), (200, Spell::Open)]);
706 assert!(!rewritten.extends(&a), "a carried entry can't change");
707 let shed = ledger(&[(200, Spell::Open)]);
708 assert!(!shed.extends(&a), "below the cap nothing is dropped");
709 assert!(a.is_first() && !b.is_first());
710 }
711
712 #[test]
713 fn an_editions_newest_entry_is_its_own_and_dated_with_it() {
714 let l = ledger(&[(100_000, w(1, 1))]);
715 let far = ledger(&[(HORIZON_MS + 10_000_000, w(1, 1))]);
716 assert!(far.not_ahead(10_000_000) && !far.not_ahead(10_000_000 - 1), "a far-future entry waits");
717 assert!(l.tail_fits(100, &BY));
718 assert!(!l.tail_fits(100, &[0x0c; 32]), "a writer entry names the edition's signer");
719 assert!(!l.tail_fits(100 + ENTRY_SKEW_MS / 1000 + 1, &BY), "nor sits far from the edition's time");
720 let opened = l.appended(150_000, Spell::Open).unwrap();
721 assert!(opened.tail_fits(150, &[0x0c; 32]), "an open entry names nobody");
722 }
723
724 #[test]
725 fn appending_never_backdates_and_keeps_epochs_rising() {
726 let l = ledger(&[(100, w(1, 1))]);
727 let next = l.appended(50, Spell::Open).unwrap();
728 assert_eq!(next.entries[1].at, 100, "clamped to the last entry");
729 assert!(l.appended(200, w(1, 2)).is_none());
730 assert_eq!(next.next_epoch(), Some(Epoch(2)));
731 assert_eq!(ledger(&[(1, w(MAX_EPOCH - 1, 1))]).next_epoch(), None, "the range is spent");
732 }
733
734 #[test]
735 fn a_channel_without_a_ledger_reads_only_its_read_address() {
736 use nostr_sdk::prelude::{Keys, Timestamp};
737 let k = Keys::generate();
738 let g = crate::community::v2::derive::channel_group_key(&[1; 32], &CH, Epoch(0));
739 let rumor = super::super::chat::build_message_rumor(k.public_key(), &CH, Epoch(0), "x", None, &[], vec![], 1_000);
740 let (wrap, _) = super::super::chat::seal_chat_rumor(&rumor, &g, &k, Timestamp::from_secs(1), false).unwrap();
741 let ev = super::super::chat::open_chat_event(&wrap, &g, &CH, Epoch(0)).unwrap();
742 use crate::community::v2::service::{sort_arrival, Arrival};
743 assert!(matches!(sort_arrival(None, ev.clone(), None), Arrival::Stands(_)));
744 assert!(matches!(sort_arrival(None, ev, Some(Epoch(1))), Arrival::Held(None)), "no ledger names a writer address");
745 }
746}