use serde_json::{Value, json};
use thiserror::Error;
use crate::canonical::{Fingerprint, canonical};
use crate::catalog::{self, Catalog, CatalogId, ReadRefusal};
use crate::contract::Contract;
use crate::grammar::{IfaceId, KindToken, ZkKey, parse};
pub const COMPACT_BYTES: usize = 3;
pub const RESOURCES: usize = 128;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Form {
Json,
Compact,
}
impl Form {
#[must_use]
pub fn of(attachment: &[u8]) -> Form {
if attachment.len() == COMPACT_BYTES {
Form::Compact
} else {
Form::Json
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Compact {
pub index: u16,
pub resource: u8,
pub confirmed: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum Refusal {
#[error("extension: the extension bit is 1")]
Extension,
#[error("reserved: a reserved bit is 1")]
Reserved,
#[error("unknown_catalog: no held catalog is or succeeds the archive's")]
UnknownCatalog,
#[error("unknown_index: the index is at or above the count read through")]
UnknownIndex,
#[error("unknown_revision: no held revision of the pair the index names")]
UnknownRevision,
#[error("resource: no state of the revision at that place")]
Resource,
#[error("origin: the origin key is not a key of the resource named")]
Origin,
}
impl Refusal {
#[must_use]
pub fn token(self) -> &'static str {
match self {
Self::Extension => "extension",
Self::Reserved => "reserved",
Self::UnknownCatalog => "unknown_catalog",
Self::UnknownIndex => "unknown_index",
Self::UnknownRevision => "unknown_revision",
Self::Resource => "resource",
Self::Origin => "origin",
}
}
#[must_use]
pub fn leaves_confirmed(self) -> bool {
!matches!(self, Self::Extension | Self::Reserved)
}
}
impl From<ReadRefusal> for Refusal {
fn from(r: ReadRefusal) -> Self {
match r {
ReadRefusal::UnknownCatalog => Self::UnknownCatalog,
ReadRefusal::UnknownIndex => Self::UnknownIndex,
}
}
}
impl Compact {
#[must_use]
pub fn write(self) -> [u8; COMPACT_BYTES] {
assert!(self.index < 1024 && usize::from(self.resource) < RESOURCES);
let v = (u32::from(self.index) << 14)
| (u32::from(self.resource) << 7)
| (u32::from(self.confirmed) << 6);
let b = v.to_be_bytes();
[b[1], b[2], b[3]]
}
pub fn read(bytes: &[u8]) -> Result<Compact, Refusal> {
let [b0, b1, b2] = <[u8; COMPACT_BYTES]>::try_from(bytes).expect("3 bytes");
let v = u32::from_be_bytes([0, b0, b1, b2]);
if (v >> 5) & 1 == 1 {
return Err(Refusal::Extension);
}
if v & 0x1f != 0 {
return Err(Refusal::Reserved);
}
Ok(Compact {
index: u16::try_from(v >> 14).expect("10 bits"),
resource: u8::try_from((v >> 7) & 0x7f).expect("7 bits"),
confirmed: (v >> 6) & 1 == 1,
})
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Identity {
pub iface: IfaceId,
pub contract: Fingerprint,
pub r#type: Value,
}
impl Identity {
#[must_use]
pub fn to_json(&self) -> Value {
json!({
"iface": self.iface.to_string(),
"contract": self.contract.to_string(),
"type": self.r#type,
})
}
}
fn place(revision: &Contract, resource: &str) -> Option<usize> {
revision
.resources
.iter()
.position(|r| format!("{}/{}", r.token.as_str(), r.template) == resource)
}
#[must_use]
pub fn encode(
revision: &Contract,
resource: &str,
confirmed: bool,
catalog: &Catalog,
) -> Option<[u8; COMPACT_BYTES]> {
let fp = Fingerprint::of(revision);
let index = catalog
.entries()
.iter()
.position(|e| e.iface == revision.iface && e.contract == fp)?;
let at = place(revision, resource).filter(|p| *p < RESOURCES)?;
Some(
Compact {
index: u16::try_from(index).ok()?,
resource: u8::try_from(at).ok()?,
confirmed,
}
.write(),
)
}
pub fn resolve(
c: Compact,
origin: &str,
archive: Option<CatalogId>,
held: &[Catalog],
revisions: &[&Contract],
) -> Result<Identity, Refusal> {
let named = archive.ok_or(Refusal::UnknownCatalog)?;
let through = catalog::through(held, named)?;
let pair = through.entry(c.index)?;
let revision = revisions
.iter()
.find(|r| r.iface == pair.iface && Fingerprint::of(r) == pair.contract)
.ok_or(Refusal::UnknownRevision)?;
let at = usize::from(c.resource);
let r = revision.resources.get(at).ok_or(Refusal::Resource)?;
if !matches!(r.token, KindToken::State | KindToken::ExplicitState) {
return Err(Refusal::Resource);
}
let Ok(ZkKey::Data {
iface,
kind,
resource,
..
}) = parse(origin)
else {
return Err(Refusal::Origin);
};
let chunks: Vec<&str> = resource.iter().map(String::as_str).collect();
if iface != pair.iface || kind != r.token || r.template.matches(&chunks).is_none() {
return Err(Refusal::Origin);
}
let ty = canonical(revision)["resources"][at]["type"].clone();
Ok(Identity {
iface: pair.iface.clone(),
contract: pair.contract.clone(),
r#type: ty,
})
}
#[derive(Debug, Clone, PartialEq)]
pub struct Read {
pub form: Form,
pub confirmed: Option<bool>,
pub identity: Result<Value, String>,
}
#[must_use]
pub fn read(
attachment: &[u8],
origin: &str,
archive: Option<CatalogId>,
held: &[Catalog],
revisions: &[&Contract],
) -> Read {
match Form::of(attachment) {
Form::Json => {
let v: Option<Value> = serde_json::from_slice(attachment)
.ok()
.filter(Value::is_object);
match v {
Some(v) => Read {
form: Form::Json,
confirmed: v["confirmed"].as_bool(),
identity: Ok(
json!({"iface": v["iface"], "contract": v["contract"], "type": v["type"]}),
),
},
None => Read {
form: Form::Json,
confirmed: None,
identity: Err(
"the attachment is not the JSON form's object (core §4.4)".to_owned()
),
},
}
}
Form::Compact => match Compact::read(attachment) {
Err(r) => Read {
form: Form::Compact,
confirmed: None,
identity: Err(format!("{}: {r} (core §4.4)", r.token())),
},
Ok(c) => Read {
form: Form::Compact,
confirmed: Some(c.confirmed),
identity: resolve(c, origin, archive, held, revisions)
.map(|i| i.to_json())
.map_err(|r| format!("{}: {r} (core §4.4)", r.token())),
},
},
}
}
#[cfg(test)]
mod tests {
use super::{Compact, Form, Refusal};
#[test]
fn the_layout_writes_back() {
for (index, resource, confirmed) in [(0, 0, false), (1023, 127, true), (5, 64, true)] {
let c = Compact {
index,
resource,
confirmed,
};
assert_eq!(Compact::read(&c.write()), Ok(c));
assert_eq!(Form::of(&c.write()), Form::Compact);
}
assert_eq!(Compact::read(&[0, 0, 0x20]), Err(Refusal::Extension));
assert_eq!(Compact::read(&[0, 0, 0x01]), Err(Refusal::Reserved));
assert_eq!(Form::of(b"{}"), Form::Json);
}
}