1use std::collections::BTreeSet;
24use std::fmt;
25use std::str::FromStr;
26
27use schemars::JsonSchema;
28use serde::{Deserialize, Serialize};
29use serde_json::{Map, Value};
30use sha2::{Digest, Sha256};
31
32use crate::canonical::Fingerprint;
33use crate::chunk::is_lower_hex;
34use crate::grammar::IfaceId;
35use crate::schema::jcs;
36
37pub const FORMAT: &str = "zk2-catalog/1";
39
40pub const MAX_ENTRIES: usize = 1024;
42
43pub const MAX_EPOCH: i64 = (1 << 53) - 1;
46
47pub const EPOCH_WITHOUT_CATALOG: i64 = 0;
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
54pub struct CatalogId([u8; 4]);
55
56impl CatalogId {
57 #[must_use]
59 pub fn of_jcs(bytes: &[u8]) -> Self {
60 let d = Sha256::digest(bytes);
61 Self([d[0], d[1], d[2], d[3]])
62 }
63
64 #[must_use]
67 pub fn from_hex(s: &str) -> Option<Self> {
68 if !is_lower_hex(s, 8) {
69 return None;
70 }
71 let v = u32::from_str_radix(s, 16).ok()?;
72 Some(Self(v.to_be_bytes()))
73 }
74
75 #[must_use]
77 pub fn hex(self) -> String {
78 format!("{:08x}", u32::from_be_bytes(self.0))
79 }
80
81 #[must_use]
83 pub fn bytes(self) -> [u8; 4] {
84 self.0
85 }
86}
87
88impl fmt::Display for CatalogId {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 f.write_str(&self.hex())
91 }
92}
93
94impl FromStr for CatalogId {
95 type Err = String;
96 fn from_str(s: &str) -> Result<Self, String> {
97 Self::from_hex(s).ok_or_else(|| format!("{s:?} is not 8 lowercase hex digits"))
98 }
99}
100
101#[derive(Debug, Clone, PartialEq, Eq, Hash)]
103pub struct Entry {
104 pub iface: IfaceId,
105 pub contract: Fingerprint,
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub struct Ancestor {
111 pub id: CatalogId,
112 pub entries: u16,
113}
114
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum Reason {
118 Json,
120 Format,
122 Member,
125 Epoch,
127 Entries,
129 Index,
131 Iface,
133 Contract,
135 Duplicate,
137 Lineage,
142}
143
144impl Reason {
145 #[must_use]
147 pub fn token(self) -> &'static str {
148 match self {
149 Self::Json => "json",
150 Self::Format => "format",
151 Self::Member => "member",
152 Self::Epoch => "epoch",
153 Self::Entries => "entries",
154 Self::Index => "index",
155 Self::Iface => "iface",
156 Self::Contract => "contract",
157 Self::Duplicate => "duplicate",
158 Self::Lineage => "lineage",
159 }
160 }
161}
162
163#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct Refusal {
166 pub reason: Reason,
167 pub at: String,
169 pub detail: String,
170}
171
172impl Refusal {
173 fn new(reason: Reason, at: impl Into<String>, detail: impl Into<String>) -> Self {
174 Self {
175 reason,
176 at: at.into(),
177 detail: detail.into(),
178 }
179 }
180
181 #[must_use]
183 pub fn token(&self) -> &'static str {
184 self.reason.token()
185 }
186}
187
188impl fmt::Display for Refusal {
189 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190 write!(f, "{}: {} ({})", self.at, self.detail, self.token())
191 }
192}
193
194impl std::error::Error for Refusal {}
195
196#[derive(Debug, Clone, Copy, PartialEq, Eq)]
199pub enum Succession {
200 EpochMoved,
202 Reassigned(u16),
204 Removed(u16),
206 Lineage,
209}
210
211impl Succession {
212 #[must_use]
214 pub fn token(self) -> &'static str {
215 match self {
216 Self::EpochMoved => "epoch_moved",
217 Self::Reassigned(_) => "reassigned",
218 Self::Removed(_) => "removed",
219 Self::Lineage => "lineage",
220 }
221 }
222}
223
224impl fmt::Display for Succession {
225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226 match self {
227 Self::EpochMoved => f.write_str("the epoch moved"),
228 Self::Reassigned(i) => write!(f, "index {i} holds another pair"),
229 Self::Removed(i) => write!(f, "index {i} is gone"),
230 Self::Lineage => {
231 f.write_str("the lineage is not the predecessor's, followed by its id and count")
232 }
233 }?;
234 write!(f, " ({})", self.token())
235 }
236}
237
238#[derive(Debug, Clone, Copy, PartialEq, Eq)]
240pub enum ReadRefusal {
241 UnknownCatalog,
244 UnknownIndex,
246}
247
248impl ReadRefusal {
249 #[must_use]
251 pub fn token(self) -> &'static str {
252 match self {
253 Self::UnknownCatalog => "unknown_catalog",
254 Self::UnknownIndex => "unknown_index",
255 }
256 }
257}
258
259impl fmt::Display for ReadRefusal {
260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261 f.write_str(self.token())
262 }
263}
264
265impl std::error::Error for ReadRefusal {}
266
267#[derive(Debug, Clone, PartialEq, Eq)]
269pub struct Catalog {
270 epoch: i64,
271 entries: Vec<Entry>,
272 lineage: Vec<Ancestor>,
273 id: CatalogId,
274}
275
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278pub enum Pushed {
279 Added(u16),
281 Held(u16),
283}
284
285impl Pushed {
286 #[must_use]
288 pub fn index(self) -> u16 {
289 match self {
290 Self::Added(i) | Self::Held(i) => i,
291 }
292 }
293}
294
295fn digits(v: &Value) -> Option<u64> {
300 v.as_u64()
301}
302
303const TOP: [&str; 4] = ["format", "epoch", "entries", "lineage"];
304const ENTRY: [&str; 3] = ["index", "iface", "contract"];
305const ITEM: [&str; 2] = ["id", "entries"];
306
307fn members(m: &Map<String, Value>, required: &[&str], allowed: &[&str]) -> bool {
309 required.iter().all(|k| m.contains_key(*k)) && m.keys().all(|k| allowed.contains(&k.as_str()))
310}
311
312impl Catalog {
313 pub fn new(epoch: i64) -> Result<Self, Refusal> {
318 if !(0..=MAX_EPOCH).contains(&epoch) {
319 return Err(Refusal::new(
320 Reason::Epoch,
321 "epoch",
322 format!("{epoch} is not from 0 to 2^53 - 1"),
323 ));
324 }
325 let mut c = Self {
326 epoch,
327 entries: Vec::new(),
328 lineage: Vec::new(),
329 id: CatalogId([0; 4]),
330 };
331 c.id = c.compute_id();
332 Ok(c)
333 }
334
335 pub fn parse_bytes(bytes: &[u8]) -> Result<Self, Refusal> {
340 let text = std::str::from_utf8(bytes)
341 .map_err(|e| Refusal::new(Reason::Json, "catalog", format!("not UTF-8: {e}")))?;
342 Self::parse(text)
343 }
344
345 pub fn parse(text: &str) -> Result<Self, Refusal> {
351 let v = crate::strict::parse_json(text)
352 .map_err(|e| Refusal::new(Reason::Json, "catalog", format!("not strict JSON: {e}")))?;
353 let top = v
354 .as_object()
355 .filter(|m| m.get("format").and_then(Value::as_str) == Some(FORMAT))
356 .ok_or_else(|| {
357 Refusal::new(
358 Reason::Format,
359 "format",
360 format!("not an object whose format is {FORMAT:?}"),
361 )
362 })?;
363 if !members(top, &["epoch", "entries"], &TOP) {
364 return Err(Refusal::new(
365 Reason::Member,
366 "catalog",
367 "epoch or entries missing, or a member besides format, epoch, entries and lineage",
368 ));
369 }
370 let epoch = digits(&top["epoch"])
371 .and_then(|e| i64::try_from(e).ok())
372 .filter(|e| *e <= MAX_EPOCH)
373 .ok_or_else(|| {
374 Refusal::new(
375 Reason::Epoch,
376 "epoch",
377 format!("{} is not an integer from 0 to 2^53 - 1", top["epoch"]),
378 )
379 })?;
380 let items = top["entries"]
381 .as_array()
382 .filter(|a| a.len() <= MAX_ENTRIES && a.iter().all(Value::is_object))
383 .ok_or_else(|| {
384 Refusal::new(
385 Reason::Entries,
386 "entries",
387 format!("not an array of at most {MAX_ENTRIES} objects"),
388 )
389 })?;
390 let mut entries = Vec::with_capacity(items.len());
391 let mut seen = BTreeSet::new();
392 for (i, item) in items.iter().enumerate() {
393 entries.push(Self::read_entry(i, item, &mut seen)?);
394 }
395 let id = CatalogId::of_jcs(&jcs(&v));
396 let lineage = match top.get("lineage") {
397 None => Vec::new(),
398 Some(l) => Self::read_lineage(l, entries.len(), id)?,
399 };
400 let c = Self {
401 epoch,
402 entries,
403 lineage,
404 id,
405 };
406 debug_assert_eq!(
407 c.id,
408 c.compute_id(),
409 "the document read writes back to its own bytes"
410 );
411 Ok(c)
412 }
413
414 fn read_entry(
415 i: usize,
416 item: &Value,
417 seen: &mut BTreeSet<(String, String)>,
418 ) -> Result<Entry, Refusal> {
419 let at = format!("entries[{i}]");
420 let m = item.as_object().expect("entries checked as objects");
421 if !members(m, &ENTRY, &ENTRY) {
422 return Err(Refusal::new(
423 Reason::Member,
424 at,
425 "not exactly index, iface and contract",
426 ));
427 }
428 if digits(&m["index"]) != Some(i as u64) {
429 return Err(Refusal::new(
430 Reason::Index,
431 at,
432 format!("index {} is not its position, {i}", m["index"]),
433 ));
434 }
435 let iface = m["iface"]
436 .as_str()
437 .and_then(|s| s.parse::<IfaceId>().ok())
438 .ok_or_else(|| {
439 Refusal::new(
440 Reason::Iface,
441 &at,
442 format!("iface {} is not an interface id", m["iface"]),
443 )
444 })?;
445 let contract = m["contract"]
446 .as_str()
447 .and_then(|s| Fingerprint::parse(s).ok())
448 .ok_or_else(|| {
449 Refusal::new(
450 Reason::Contract,
451 &at,
452 format!("contract {} is not a fingerprint", m["contract"]),
453 )
454 })?;
455 if !seen.insert((iface.to_string(), contract.to_string())) {
456 return Err(Refusal::new(
457 Reason::Duplicate,
458 at,
459 format!("{iface} at {contract} is an earlier entry's pair"),
460 ));
461 }
462 Ok(Entry { iface, contract })
463 }
464
465 fn read_lineage(l: &Value, count: usize, own: CatalogId) -> Result<Vec<Ancestor>, Refusal> {
466 let items = l
467 .as_array()
468 .filter(|a| !a.is_empty() && a.iter().all(Value::is_object))
469 .ok_or_else(|| {
470 Refusal::new(
471 Reason::Lineage,
472 "lineage",
473 "not a non-empty array of objects",
474 )
475 })?;
476 let mut out: Vec<Ancestor> = Vec::with_capacity(items.len());
477 for (k, item) in items.iter().enumerate() {
478 let at = format!("lineage[{k}]");
479 let m = item.as_object().expect("lineage checked as objects");
480 if !members(m, &ITEM, &ITEM) {
481 return Err(Refusal::new(
482 Reason::Member,
483 at,
484 "not exactly id and entries",
485 ));
486 }
487 let id = m["id"]
488 .as_str()
489 .and_then(CatalogId::from_hex)
490 .ok_or_else(|| {
491 Refusal::new(
492 Reason::Lineage,
493 &at,
494 format!("id {} is not 8 lowercase hex digits", m["id"]),
495 )
496 })?;
497 if id == own || out.iter().any(|a| a.id == id) {
498 return Err(Refusal::new(
499 Reason::Lineage,
500 at,
501 format!("id {id} is an earlier item's or the catalog's own"),
502 ));
503 }
504 let floor = out.last().map_or(0, |a| u64::from(a.entries));
505 let entries = digits(&m["entries"])
506 .filter(|n| *n >= floor && *n <= count as u64)
507 .and_then(|n| u16::try_from(n).ok())
508 .ok_or_else(|| {
509 Refusal::new(
510 Reason::Lineage,
511 &at,
512 format!(
513 "entries {} is not an integer from {floor} to the catalog's {count}",
514 m["entries"]
515 ),
516 )
517 })?;
518 out.push(Ancestor { id, entries });
519 }
520 Ok(out)
521 }
522
523 #[must_use]
525 pub fn epoch(&self) -> i64 {
526 self.epoch
527 }
528
529 #[must_use]
531 pub fn entries(&self) -> &[Entry] {
532 &self.entries
533 }
534
535 #[must_use]
537 pub fn lineage(&self) -> &[Ancestor] {
538 &self.lineage
539 }
540
541 #[must_use]
543 pub fn id(&self) -> CatalogId {
544 self.id
545 }
546
547 #[must_use]
549 pub fn entry(&self, index: u16) -> Option<&Entry> {
550 self.entries.get(usize::from(index))
551 }
552
553 #[must_use]
556 pub fn index_of(&self, iface: &IfaceId, contract: &Fingerprint) -> Option<u16> {
557 self.entries
558 .iter()
559 .position(|e| &e.iface == iface && &e.contract == contract)
560 .map(|i| u16::try_from(i).expect("at most 1,024 entries"))
561 }
562
563 #[must_use]
567 pub fn holds(&self, id: CatalogId) -> Option<u16> {
568 if id == self.id {
569 return Some(self.count());
570 }
571 self.lineage.iter().find(|a| a.id == id).map(|a| a.entries)
572 }
573
574 fn count(&self) -> u16 {
575 u16::try_from(self.entries.len()).expect("at most 1,024 entries")
576 }
577
578 pub fn succeeds(&self, previous: &Catalog) -> Result<(), Succession> {
585 if self.epoch != previous.epoch {
586 return Err(Succession::EpochMoved);
587 }
588 for (i, e) in previous.entries.iter().enumerate() {
589 let i = u16::try_from(i).expect("at most 1,024 entries");
590 match self.entry(i) {
591 Some(mine) if mine != e => return Err(Succession::Reassigned(i)),
592 Some(_) => {}
593 None => return Err(Succession::Removed(i)),
594 }
595 }
596 let mut want = previous.lineage.clone();
597 want.push(Ancestor {
598 id: previous.id,
599 entries: previous.count(),
600 });
601 if self.lineage != want {
602 return Err(Succession::Lineage);
603 }
604 Ok(())
605 }
606
607 #[must_use]
610 pub fn successor(&self) -> Self {
611 let mut c = self.clone();
612 c.lineage.push(Ancestor {
613 id: self.id,
614 entries: self.count(),
615 });
616 c.id = c.compute_id();
617 c
618 }
619
620 pub fn push(&mut self, iface: IfaceId, contract: Fingerprint) -> Result<Pushed, Refusal> {
627 if let Some(i) = self.index_of(&iface, &contract) {
628 return Ok(Pushed::Held(i));
629 }
630 if self.entries.len() >= MAX_ENTRIES {
631 return Err(Refusal::new(
632 Reason::Entries,
633 "entries",
634 format!("the catalog holds {MAX_ENTRIES} entries already"),
635 ));
636 }
637 self.entries.push(Entry { iface, contract });
638 let id = self.compute_id();
639 if self.lineage.iter().any(|a| a.id == id) {
640 self.entries.pop();
641 return Err(Refusal::new(
642 Reason::Lineage,
643 "lineage",
644 format!("the new id {id} is a lineage item's"),
645 ));
646 }
647 self.id = id;
648 Ok(Pushed::Added(self.count() - 1))
649 }
650
651 #[must_use]
653 pub fn document(&self) -> Document {
654 Document {
655 format: FORMAT.to_owned(),
656 epoch: u64::try_from(self.epoch).expect("an epoch is from 0"),
657 entries: self
658 .entries
659 .iter()
660 .enumerate()
661 .map(|(i, e)| DocumentEntry {
662 index: u16::try_from(i).expect("at most 1,024 entries"),
663 iface: e.iface.to_string(),
664 contract: e.contract.to_string(),
665 })
666 .collect(),
667 lineage: (!self.lineage.is_empty()).then(|| {
668 self.lineage
669 .iter()
670 .map(|a| DocumentAncestor {
671 id: a.id.hex(),
672 entries: a.entries,
673 })
674 .collect()
675 }),
676 }
677 }
678
679 #[must_use]
681 pub fn to_value(&self) -> Value {
682 serde_json::to_value(self.document()).expect("a catalog always serializes")
683 }
684
685 #[must_use]
688 pub fn to_jcs(&self) -> Vec<u8> {
689 jcs(&self.to_value())
690 }
691
692 fn compute_id(&self) -> CatalogId {
693 CatalogId::of_jcs(&self.to_jcs())
694 }
695}
696
697#[derive(Debug, Clone, Copy)]
700pub struct Through<'a> {
701 catalog: &'a Catalog,
702 count: u16,
703}
704
705impl<'a> Through<'a> {
706 #[must_use]
708 pub fn catalog(&self) -> &'a Catalog {
709 self.catalog
710 }
711
712 #[must_use]
714 pub fn count(&self) -> u16 {
715 self.count
716 }
717
718 #[must_use]
721 pub fn epoch(&self) -> i64 {
722 self.catalog.epoch
723 }
724
725 pub fn entry(&self, index: u16) -> Result<&'a Entry, ReadRefusal> {
730 if index >= self.count {
731 return Err(ReadRefusal::UnknownIndex);
732 }
733 self.catalog.entry(index).ok_or(ReadRefusal::UnknownIndex)
734 }
735}
736
737pub fn through(held: &[Catalog], named: CatalogId) -> Result<Through<'_>, ReadRefusal> {
744 held.iter()
745 .find(|c| c.id == named)
746 .or_else(|| held.iter().find(|c| c.holds(named).is_some()))
747 .and_then(|catalog| catalog.holds(named).map(|count| Through { catalog, count }))
748 .ok_or(ReadRefusal::UnknownCatalog)
749}
750
751pub fn epoch_of(held: &[Catalog], named: Option<CatalogId>) -> Result<i64, ReadRefusal> {
758 named.map_or(Ok(EPOCH_WITHOUT_CATALOG), |id| {
759 through(held, id).map(|t| t.epoch())
760 })
761}
762
763#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
768#[serde(deny_unknown_fields)]
769#[schemars(title = "Catalog")]
770pub struct Document {
771 #[schemars(extend("const" = "zk2-catalog/1"))]
773 pub format: String,
774 #[schemars(range(max = 9_007_199_254_740_991_u64))]
777 pub epoch: u64,
778 #[schemars(length(max = 1024))]
781 pub entries: Vec<DocumentEntry>,
782 #[serde(default, skip_serializing_if = "Option::is_none")]
785 #[schemars(with = "Vec<DocumentAncestor>", length(min = 1))]
786 pub lineage: Option<Vec<DocumentAncestor>>,
787}
788
789#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
791#[serde(deny_unknown_fields)]
792pub struct DocumentEntry {
793 #[schemars(range(max = 1023))]
795 pub index: u16,
796 pub iface: String,
798 #[schemars(extend("pattern" = "^sha256:[0-9a-f]{64}$"))]
800 pub contract: String,
801}
802
803#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
805#[serde(deny_unknown_fields)]
806pub struct DocumentAncestor {
807 #[schemars(extend("pattern" = "^[0-9a-f]{8}$"))]
809 pub id: String,
810 #[schemars(range(max = 1024))]
813 pub entries: u16,
814}
815
816#[cfg(test)]
817mod tests {
818 use super::*;
819
820 fn fp(n: u32) -> Fingerprint {
821 Fingerprint::parse(&format!("sha256:{n:064x}")).unwrap()
822 }
823
824 fn iface(s: &str) -> IfaceId {
825 s.parse().unwrap()
826 }
827
828 #[test]
831 fn a_catalog_holds_at_most_1024_entries() {
832 let mut c = Catalog::new(0).unwrap();
833 for major in 0..1024 {
834 assert_eq!(
835 c.push(iface(&format!("a.v{major}")), fp(1)).unwrap(),
836 Pushed::Added(u16::try_from(major).unwrap())
837 );
838 }
839 let text = String::from_utf8(c.to_jcs()).unwrap();
840 let read = Catalog::parse(&text).unwrap();
841 assert_eq!(read, c);
842 assert_eq!(read.entry(1023).unwrap().iface, iface("a.v1023"));
843 let before = c.clone();
844 let r = c.push(iface("b.v1"), fp(1)).unwrap_err();
845 assert_eq!(r.token(), "entries");
846 assert_eq!(c, before);
847 let over = text.replacen("\"entries\":[", "\"entries\":[{},", 1);
848 assert_eq!(Catalog::parse(&over).unwrap_err().token(), "entries");
849 }
850
851 #[test]
854 fn a_successor_reads_back_and_succeeds() {
855 let mut a = Catalog::new(1_767_225_600).unwrap();
856 a.push(iface("modem.v3"), fp(1)).unwrap();
857 a.push(iface("config.v1"), fp(2)).unwrap();
858 assert_eq!(a.push(iface("modem.v3"), fp(1)).unwrap(), Pushed::Held(0));
859 let mut b = a.successor();
860 assert_eq!(b.succeeds(&a), Ok(()));
861 assert_eq!(b.push(iface("health.v1"), fp(3)).unwrap(), Pushed::Added(2));
862 assert_eq!(b.push(iface("modem.v3"), fp(4)).unwrap(), Pushed::Added(3));
863 assert_eq!(b.succeeds(&a), Ok(()));
864 assert_eq!(a.succeeds(&b), Err(Succession::Removed(2)));
865 assert_eq!(a.succeeds(&a), Err(Succession::Lineage));
866 let read = Catalog::parse(std::str::from_utf8(&b.to_jcs()).unwrap()).unwrap();
867 assert_eq!(read, b);
868 assert_eq!(read.id(), b.id());
869 assert_eq!(read.index_of(&iface("modem.v3"), &fp(4)), Some(3));
870 assert_eq!(read.index_of(&iface("modem.v3"), &fp(9)), None);
871
872 let held = [b.clone()];
873 let t = through(&held, a.id()).unwrap();
874 assert_eq!(t.count(), 2);
875 assert_eq!(t.entry(1).unwrap().iface, iface("config.v1"));
876 assert_eq!(t.entry(2).unwrap_err(), ReadRefusal::UnknownIndex);
877 assert_eq!(
878 through(&[a.clone()], b.id()).unwrap_err(),
879 ReadRefusal::UnknownCatalog
880 );
881 assert_eq!(epoch_of(&held, Some(a.id())), Ok(1_767_225_600));
882 assert_eq!(epoch_of(&held, None), Ok(EPOCH_WITHOUT_CATALOG));
883 }
884
885 #[test]
889 fn a_lineage_never_holds_the_catalogs_own_id() {
890 let own = CatalogId::from_hex("0a90fd61").unwrap();
891 let l = serde_json::json!([{"id": "0a90fd61", "entries": 0}]);
892 let r = Catalog::read_lineage(&l, 0, own).unwrap_err();
893 assert_eq!(r.token(), "lineage");
894 let other = CatalogId::from_hex("0a90fd62").unwrap();
895 assert_eq!(
896 Catalog::read_lineage(&l, 0, other).unwrap(),
897 [Ancestor {
898 id: own,
899 entries: 0
900 }]
901 );
902 }
903
904 #[test]
905 fn an_id_is_8_lowercase_hex_digits() {
906 assert_eq!(CatalogId::from_hex("0a90fd61").unwrap().hex(), "0a90fd61");
907 assert_eq!(
908 CatalogId::from_hex("0a90fd61").unwrap().bytes(),
909 [0x0a, 0x90, 0xfd, 0x61]
910 );
911 for bad in ["0A90FD61", "0a90fd6", "0a90fd611", "+a90fd61", "0x90fd61"] {
912 assert!(CatalogId::from_hex(bad).is_none(), "{bad}");
913 }
914 assert!(Catalog::new(-1).is_err());
915 assert!(Catalog::new(MAX_EPOCH + 1).is_err());
916 assert!(Catalog::new(MAX_EPOCH).is_ok());
917 }
918}