use std::collections::BTreeSet;
use std::fmt;
use std::str::FromStr;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};
use crate::canonical::Fingerprint;
use crate::chunk::is_lower_hex;
use crate::grammar::IfaceId;
use crate::schema::jcs;
pub const FORMAT: &str = "zk2-catalog/1";
pub const MAX_ENTRIES: usize = 1024;
pub const MAX_EPOCH: i64 = (1 << 53) - 1;
pub const EPOCH_WITHOUT_CATALOG: i64 = 0;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CatalogId([u8; 4]);
impl CatalogId {
#[must_use]
pub fn of_jcs(bytes: &[u8]) -> Self {
let d = Sha256::digest(bytes);
Self([d[0], d[1], d[2], d[3]])
}
#[must_use]
pub fn from_hex(s: &str) -> Option<Self> {
if !is_lower_hex(s, 8) {
return None;
}
let v = u32::from_str_radix(s, 16).ok()?;
Some(Self(v.to_be_bytes()))
}
#[must_use]
pub fn hex(self) -> String {
format!("{:08x}", u32::from_be_bytes(self.0))
}
#[must_use]
pub fn bytes(self) -> [u8; 4] {
self.0
}
}
impl fmt::Display for CatalogId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.hex())
}
}
impl FromStr for CatalogId {
type Err = String;
fn from_str(s: &str) -> Result<Self, String> {
Self::from_hex(s).ok_or_else(|| format!("{s:?} is not 8 lowercase hex digits"))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Entry {
pub iface: IfaceId,
pub contract: Fingerprint,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Ancestor {
pub id: CatalogId,
pub entries: u16,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reason {
Json,
Format,
Member,
Epoch,
Entries,
Index,
Iface,
Contract,
Duplicate,
Lineage,
}
impl Reason {
#[must_use]
pub fn token(self) -> &'static str {
match self {
Self::Json => "json",
Self::Format => "format",
Self::Member => "member",
Self::Epoch => "epoch",
Self::Entries => "entries",
Self::Index => "index",
Self::Iface => "iface",
Self::Contract => "contract",
Self::Duplicate => "duplicate",
Self::Lineage => "lineage",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refusal {
pub reason: Reason,
pub at: String,
pub detail: String,
}
impl Refusal {
fn new(reason: Reason, at: impl Into<String>, detail: impl Into<String>) -> Self {
Self {
reason,
at: at.into(),
detail: detail.into(),
}
}
#[must_use]
pub fn token(&self) -> &'static str {
self.reason.token()
}
}
impl fmt::Display for Refusal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {} ({})", self.at, self.detail, self.token())
}
}
impl std::error::Error for Refusal {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Succession {
EpochMoved,
Reassigned(u16),
Removed(u16),
Lineage,
}
impl Succession {
#[must_use]
pub fn token(self) -> &'static str {
match self {
Self::EpochMoved => "epoch_moved",
Self::Reassigned(_) => "reassigned",
Self::Removed(_) => "removed",
Self::Lineage => "lineage",
}
}
}
impl fmt::Display for Succession {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::EpochMoved => f.write_str("the epoch moved"),
Self::Reassigned(i) => write!(f, "index {i} holds another pair"),
Self::Removed(i) => write!(f, "index {i} is gone"),
Self::Lineage => {
f.write_str("the lineage is not the predecessor's, followed by its id and count")
}
}?;
write!(f, " ({})", self.token())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReadRefusal {
UnknownCatalog,
UnknownIndex,
}
impl ReadRefusal {
#[must_use]
pub fn token(self) -> &'static str {
match self {
Self::UnknownCatalog => "unknown_catalog",
Self::UnknownIndex => "unknown_index",
}
}
}
impl fmt::Display for ReadRefusal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.token())
}
}
impl std::error::Error for ReadRefusal {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Catalog {
epoch: i64,
entries: Vec<Entry>,
lineage: Vec<Ancestor>,
id: CatalogId,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pushed {
Added(u16),
Held(u16),
}
impl Pushed {
#[must_use]
pub fn index(self) -> u16 {
match self {
Self::Added(i) | Self::Held(i) => i,
}
}
}
fn digits(v: &Value) -> Option<u64> {
v.as_u64()
}
const TOP: [&str; 4] = ["format", "epoch", "entries", "lineage"];
const ENTRY: [&str; 3] = ["index", "iface", "contract"];
const ITEM: [&str; 2] = ["id", "entries"];
fn members(m: &Map<String, Value>, required: &[&str], allowed: &[&str]) -> bool {
required.iter().all(|k| m.contains_key(*k)) && m.keys().all(|k| allowed.contains(&k.as_str()))
}
impl Catalog {
pub fn new(epoch: i64) -> Result<Self, Refusal> {
if !(0..=MAX_EPOCH).contains(&epoch) {
return Err(Refusal::new(
Reason::Epoch,
"epoch",
format!("{epoch} is not from 0 to 2^53 - 1"),
));
}
let mut c = Self {
epoch,
entries: Vec::new(),
lineage: Vec::new(),
id: CatalogId([0; 4]),
};
c.id = c.compute_id();
Ok(c)
}
pub fn parse_bytes(bytes: &[u8]) -> Result<Self, Refusal> {
let text = std::str::from_utf8(bytes)
.map_err(|e| Refusal::new(Reason::Json, "catalog", format!("not UTF-8: {e}")))?;
Self::parse(text)
}
pub fn parse(text: &str) -> Result<Self, Refusal> {
let v = crate::strict::parse_json(text)
.map_err(|e| Refusal::new(Reason::Json, "catalog", format!("not strict JSON: {e}")))?;
let top = v
.as_object()
.filter(|m| m.get("format").and_then(Value::as_str) == Some(FORMAT))
.ok_or_else(|| {
Refusal::new(
Reason::Format,
"format",
format!("not an object whose format is {FORMAT:?}"),
)
})?;
if !members(top, &["epoch", "entries"], &TOP) {
return Err(Refusal::new(
Reason::Member,
"catalog",
"epoch or entries missing, or a member besides format, epoch, entries and lineage",
));
}
let epoch = digits(&top["epoch"])
.and_then(|e| i64::try_from(e).ok())
.filter(|e| *e <= MAX_EPOCH)
.ok_or_else(|| {
Refusal::new(
Reason::Epoch,
"epoch",
format!("{} is not an integer from 0 to 2^53 - 1", top["epoch"]),
)
})?;
let items = top["entries"]
.as_array()
.filter(|a| a.len() <= MAX_ENTRIES && a.iter().all(Value::is_object))
.ok_or_else(|| {
Refusal::new(
Reason::Entries,
"entries",
format!("not an array of at most {MAX_ENTRIES} objects"),
)
})?;
let mut entries = Vec::with_capacity(items.len());
let mut seen = BTreeSet::new();
for (i, item) in items.iter().enumerate() {
entries.push(Self::read_entry(i, item, &mut seen)?);
}
let id = CatalogId::of_jcs(&jcs(&v));
let lineage = match top.get("lineage") {
None => Vec::new(),
Some(l) => Self::read_lineage(l, entries.len(), id)?,
};
let c = Self {
epoch,
entries,
lineage,
id,
};
debug_assert_eq!(
c.id,
c.compute_id(),
"the document read writes back to its own bytes"
);
Ok(c)
}
fn read_entry(
i: usize,
item: &Value,
seen: &mut BTreeSet<(String, String)>,
) -> Result<Entry, Refusal> {
let at = format!("entries[{i}]");
let m = item.as_object().expect("entries checked as objects");
if !members(m, &ENTRY, &ENTRY) {
return Err(Refusal::new(
Reason::Member,
at,
"not exactly index, iface and contract",
));
}
if digits(&m["index"]) != Some(i as u64) {
return Err(Refusal::new(
Reason::Index,
at,
format!("index {} is not its position, {i}", m["index"]),
));
}
let iface = m["iface"]
.as_str()
.and_then(|s| s.parse::<IfaceId>().ok())
.ok_or_else(|| {
Refusal::new(
Reason::Iface,
&at,
format!("iface {} is not an interface id", m["iface"]),
)
})?;
let contract = m["contract"]
.as_str()
.and_then(|s| Fingerprint::parse(s).ok())
.ok_or_else(|| {
Refusal::new(
Reason::Contract,
&at,
format!("contract {} is not a fingerprint", m["contract"]),
)
})?;
if !seen.insert((iface.to_string(), contract.to_string())) {
return Err(Refusal::new(
Reason::Duplicate,
at,
format!("{iface} at {contract} is an earlier entry's pair"),
));
}
Ok(Entry { iface, contract })
}
fn read_lineage(l: &Value, count: usize, own: CatalogId) -> Result<Vec<Ancestor>, Refusal> {
let items = l
.as_array()
.filter(|a| !a.is_empty() && a.iter().all(Value::is_object))
.ok_or_else(|| {
Refusal::new(
Reason::Lineage,
"lineage",
"not a non-empty array of objects",
)
})?;
let mut out: Vec<Ancestor> = Vec::with_capacity(items.len());
for (k, item) in items.iter().enumerate() {
let at = format!("lineage[{k}]");
let m = item.as_object().expect("lineage checked as objects");
if !members(m, &ITEM, &ITEM) {
return Err(Refusal::new(
Reason::Member,
at,
"not exactly id and entries",
));
}
let id = m["id"]
.as_str()
.and_then(CatalogId::from_hex)
.ok_or_else(|| {
Refusal::new(
Reason::Lineage,
&at,
format!("id {} is not 8 lowercase hex digits", m["id"]),
)
})?;
if id == own || out.iter().any(|a| a.id == id) {
return Err(Refusal::new(
Reason::Lineage,
at,
format!("id {id} is an earlier item's or the catalog's own"),
));
}
let floor = out.last().map_or(0, |a| u64::from(a.entries));
let entries = digits(&m["entries"])
.filter(|n| *n >= floor && *n <= count as u64)
.and_then(|n| u16::try_from(n).ok())
.ok_or_else(|| {
Refusal::new(
Reason::Lineage,
&at,
format!(
"entries {} is not an integer from {floor} to the catalog's {count}",
m["entries"]
),
)
})?;
out.push(Ancestor { id, entries });
}
Ok(out)
}
#[must_use]
pub fn epoch(&self) -> i64 {
self.epoch
}
#[must_use]
pub fn entries(&self) -> &[Entry] {
&self.entries
}
#[must_use]
pub fn lineage(&self) -> &[Ancestor] {
&self.lineage
}
#[must_use]
pub fn id(&self) -> CatalogId {
self.id
}
#[must_use]
pub fn entry(&self, index: u16) -> Option<&Entry> {
self.entries.get(usize::from(index))
}
#[must_use]
pub fn index_of(&self, iface: &IfaceId, contract: &Fingerprint) -> Option<u16> {
self.entries
.iter()
.position(|e| &e.iface == iface && &e.contract == contract)
.map(|i| u16::try_from(i).expect("at most 1,024 entries"))
}
#[must_use]
pub fn holds(&self, id: CatalogId) -> Option<u16> {
if id == self.id {
return Some(self.count());
}
self.lineage.iter().find(|a| a.id == id).map(|a| a.entries)
}
fn count(&self) -> u16 {
u16::try_from(self.entries.len()).expect("at most 1,024 entries")
}
pub fn succeeds(&self, previous: &Catalog) -> Result<(), Succession> {
if self.epoch != previous.epoch {
return Err(Succession::EpochMoved);
}
for (i, e) in previous.entries.iter().enumerate() {
let i = u16::try_from(i).expect("at most 1,024 entries");
match self.entry(i) {
Some(mine) if mine != e => return Err(Succession::Reassigned(i)),
Some(_) => {}
None => return Err(Succession::Removed(i)),
}
}
let mut want = previous.lineage.clone();
want.push(Ancestor {
id: previous.id,
entries: previous.count(),
});
if self.lineage != want {
return Err(Succession::Lineage);
}
Ok(())
}
#[must_use]
pub fn successor(&self) -> Self {
let mut c = self.clone();
c.lineage.push(Ancestor {
id: self.id,
entries: self.count(),
});
c.id = c.compute_id();
c
}
pub fn push(&mut self, iface: IfaceId, contract: Fingerprint) -> Result<Pushed, Refusal> {
if let Some(i) = self.index_of(&iface, &contract) {
return Ok(Pushed::Held(i));
}
if self.entries.len() >= MAX_ENTRIES {
return Err(Refusal::new(
Reason::Entries,
"entries",
format!("the catalog holds {MAX_ENTRIES} entries already"),
));
}
self.entries.push(Entry { iface, contract });
let id = self.compute_id();
if self.lineage.iter().any(|a| a.id == id) {
self.entries.pop();
return Err(Refusal::new(
Reason::Lineage,
"lineage",
format!("the new id {id} is a lineage item's"),
));
}
self.id = id;
Ok(Pushed::Added(self.count() - 1))
}
#[must_use]
pub fn document(&self) -> Document {
Document {
format: FORMAT.to_owned(),
epoch: u64::try_from(self.epoch).expect("an epoch is from 0"),
entries: self
.entries
.iter()
.enumerate()
.map(|(i, e)| DocumentEntry {
index: u16::try_from(i).expect("at most 1,024 entries"),
iface: e.iface.to_string(),
contract: e.contract.to_string(),
})
.collect(),
lineage: (!self.lineage.is_empty()).then(|| {
self.lineage
.iter()
.map(|a| DocumentAncestor {
id: a.id.hex(),
entries: a.entries,
})
.collect()
}),
}
}
#[must_use]
pub fn to_value(&self) -> Value {
serde_json::to_value(self.document()).expect("a catalog always serializes")
}
#[must_use]
pub fn to_jcs(&self) -> Vec<u8> {
jcs(&self.to_value())
}
fn compute_id(&self) -> CatalogId {
CatalogId::of_jcs(&self.to_jcs())
}
}
#[derive(Debug, Clone, Copy)]
pub struct Through<'a> {
catalog: &'a Catalog,
count: u16,
}
impl<'a> Through<'a> {
#[must_use]
pub fn catalog(&self) -> &'a Catalog {
self.catalog
}
#[must_use]
pub fn count(&self) -> u16 {
self.count
}
#[must_use]
pub fn epoch(&self) -> i64 {
self.catalog.epoch
}
pub fn entry(&self, index: u16) -> Result<&'a Entry, ReadRefusal> {
if index >= self.count {
return Err(ReadRefusal::UnknownIndex);
}
self.catalog.entry(index).ok_or(ReadRefusal::UnknownIndex)
}
}
pub fn through(held: &[Catalog], named: CatalogId) -> Result<Through<'_>, ReadRefusal> {
held.iter()
.find(|c| c.id == named)
.or_else(|| held.iter().find(|c| c.holds(named).is_some()))
.and_then(|catalog| catalog.holds(named).map(|count| Through { catalog, count }))
.ok_or(ReadRefusal::UnknownCatalog)
}
pub fn epoch_of(held: &[Catalog], named: Option<CatalogId>) -> Result<i64, ReadRefusal> {
named.map_or(Ok(EPOCH_WITHOUT_CATALOG), |id| {
through(held, id).map(|t| t.epoch())
})
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(title = "Catalog")]
pub struct Document {
#[schemars(extend("const" = "zk2-catalog/1"))]
pub format: String,
#[schemars(range(max = 9_007_199_254_740_991_u64))]
pub epoch: u64,
#[schemars(length(max = 1024))]
pub entries: Vec<DocumentEntry>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "Vec<DocumentAncestor>", length(min = 1))]
pub lineage: Option<Vec<DocumentAncestor>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DocumentEntry {
#[schemars(range(max = 1023))]
pub index: u16,
pub iface: String,
#[schemars(extend("pattern" = "^sha256:[0-9a-f]{64}$"))]
pub contract: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DocumentAncestor {
#[schemars(extend("pattern" = "^[0-9a-f]{8}$"))]
pub id: String,
#[schemars(range(max = 1024))]
pub entries: u16,
}
#[cfg(test)]
mod tests {
use super::*;
fn fp(n: u32) -> Fingerprint {
Fingerprint::parse(&format!("sha256:{n:064x}")).unwrap()
}
fn iface(s: &str) -> IfaceId {
s.parse().unwrap()
}
#[test]
fn a_catalog_holds_at_most_1024_entries() {
let mut c = Catalog::new(0).unwrap();
for major in 0..1024 {
assert_eq!(
c.push(iface(&format!("a.v{major}")), fp(1)).unwrap(),
Pushed::Added(u16::try_from(major).unwrap())
);
}
let text = String::from_utf8(c.to_jcs()).unwrap();
let read = Catalog::parse(&text).unwrap();
assert_eq!(read, c);
assert_eq!(read.entry(1023).unwrap().iface, iface("a.v1023"));
let before = c.clone();
let r = c.push(iface("b.v1"), fp(1)).unwrap_err();
assert_eq!(r.token(), "entries");
assert_eq!(c, before);
let over = text.replacen("\"entries\":[", "\"entries\":[{},", 1);
assert_eq!(Catalog::parse(&over).unwrap_err().token(), "entries");
}
#[test]
fn a_successor_reads_back_and_succeeds() {
let mut a = Catalog::new(1_767_225_600).unwrap();
a.push(iface("modem.v3"), fp(1)).unwrap();
a.push(iface("config.v1"), fp(2)).unwrap();
assert_eq!(a.push(iface("modem.v3"), fp(1)).unwrap(), Pushed::Held(0));
let mut b = a.successor();
assert_eq!(b.succeeds(&a), Ok(()));
assert_eq!(b.push(iface("health.v1"), fp(3)).unwrap(), Pushed::Added(2));
assert_eq!(b.push(iface("modem.v3"), fp(4)).unwrap(), Pushed::Added(3));
assert_eq!(b.succeeds(&a), Ok(()));
assert_eq!(a.succeeds(&b), Err(Succession::Removed(2)));
assert_eq!(a.succeeds(&a), Err(Succession::Lineage));
let read = Catalog::parse(std::str::from_utf8(&b.to_jcs()).unwrap()).unwrap();
assert_eq!(read, b);
assert_eq!(read.id(), b.id());
assert_eq!(read.index_of(&iface("modem.v3"), &fp(4)), Some(3));
assert_eq!(read.index_of(&iface("modem.v3"), &fp(9)), None);
let held = [b.clone()];
let t = through(&held, a.id()).unwrap();
assert_eq!(t.count(), 2);
assert_eq!(t.entry(1).unwrap().iface, iface("config.v1"));
assert_eq!(t.entry(2).unwrap_err(), ReadRefusal::UnknownIndex);
assert_eq!(
through(&[a.clone()], b.id()).unwrap_err(),
ReadRefusal::UnknownCatalog
);
assert_eq!(epoch_of(&held, Some(a.id())), Ok(1_767_225_600));
assert_eq!(epoch_of(&held, None), Ok(EPOCH_WITHOUT_CATALOG));
}
#[test]
fn a_lineage_never_holds_the_catalogs_own_id() {
let own = CatalogId::from_hex("0a90fd61").unwrap();
let l = serde_json::json!([{"id": "0a90fd61", "entries": 0}]);
let r = Catalog::read_lineage(&l, 0, own).unwrap_err();
assert_eq!(r.token(), "lineage");
let other = CatalogId::from_hex("0a90fd62").unwrap();
assert_eq!(
Catalog::read_lineage(&l, 0, other).unwrap(),
[Ancestor {
id: own,
entries: 0
}]
);
}
#[test]
fn an_id_is_8_lowercase_hex_digits() {
assert_eq!(CatalogId::from_hex("0a90fd61").unwrap().hex(), "0a90fd61");
assert_eq!(
CatalogId::from_hex("0a90fd61").unwrap().bytes(),
[0x0a, 0x90, 0xfd, 0x61]
);
for bad in ["0A90FD61", "0a90fd6", "0a90fd611", "+a90fd61", "0x90fd61"] {
assert!(CatalogId::from_hex(bad).is_none(), "{bad}");
}
assert!(Catalog::new(-1).is_err());
assert!(Catalog::new(MAX_EPOCH + 1).is_err());
assert!(Catalog::new(MAX_EPOCH).is_ok());
}
}