1use serde_json::{Value, json};
19use thiserror::Error;
20
21use crate::canonical::{Fingerprint, canonical};
22use crate::catalog::{self, Catalog, CatalogId, ReadRefusal};
23use crate::contract::Contract;
24use crate::grammar::{IfaceId, KindToken, ZkKey, parse};
25
26pub const COMPACT_BYTES: usize = 3;
29
30pub const RESOURCES: usize = 128;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Form {
37 Json,
38 Compact,
39}
40
41impl Form {
42 #[must_use]
44 pub fn of(attachment: &[u8]) -> Form {
45 if attachment.len() == COMPACT_BYTES {
46 Form::Compact
47 } else {
48 Form::Json
49 }
50 }
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub struct Compact {
56 pub index: u16,
58 pub resource: u8,
61 pub confirmed: bool,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
67pub enum Refusal {
68 #[error("extension: the extension bit is 1")]
70 Extension,
71 #[error("reserved: a reserved bit is 1")]
73 Reserved,
74 #[error("unknown_catalog: no held catalog is or succeeds the archive's")]
77 UnknownCatalog,
78 #[error("unknown_index: the index is at or above the count read through")]
80 UnknownIndex,
81 #[error("unknown_revision: no held revision of the pair the index names")]
83 UnknownRevision,
84 #[error("resource: no state of the revision at that place")]
86 Resource,
87 #[error("origin: the origin key is not a key of the resource named")]
89 Origin,
90}
91
92impl Refusal {
93 #[must_use]
95 pub fn token(self) -> &'static str {
96 match self {
97 Self::Extension => "extension",
98 Self::Reserved => "reserved",
99 Self::UnknownCatalog => "unknown_catalog",
100 Self::UnknownIndex => "unknown_index",
101 Self::UnknownRevision => "unknown_revision",
102 Self::Resource => "resource",
103 Self::Origin => "origin",
104 }
105 }
106
107 #[must_use]
110 pub fn leaves_confirmed(self) -> bool {
111 !matches!(self, Self::Extension | Self::Reserved)
112 }
113}
114
115impl From<ReadRefusal> for Refusal {
116 fn from(r: ReadRefusal) -> Self {
117 match r {
118 ReadRefusal::UnknownCatalog => Self::UnknownCatalog,
119 ReadRefusal::UnknownIndex => Self::UnknownIndex,
120 }
121 }
122}
123
124impl Compact {
125 #[must_use]
132 pub fn write(self) -> [u8; COMPACT_BYTES] {
133 assert!(self.index < 1024 && usize::from(self.resource) < RESOURCES);
134 let v = (u32::from(self.index) << 14)
135 | (u32::from(self.resource) << 7)
136 | (u32::from(self.confirmed) << 6);
137 let b = v.to_be_bytes();
138 [b[1], b[2], b[3]]
139 }
140
141 pub fn read(bytes: &[u8]) -> Result<Compact, Refusal> {
150 let [b0, b1, b2] = <[u8; COMPACT_BYTES]>::try_from(bytes).expect("3 bytes");
151 let v = u32::from_be_bytes([0, b0, b1, b2]);
152 if (v >> 5) & 1 == 1 {
153 return Err(Refusal::Extension);
154 }
155 if v & 0x1f != 0 {
156 return Err(Refusal::Reserved);
157 }
158 Ok(Compact {
159 index: u16::try_from(v >> 14).expect("10 bits"),
160 resource: u8::try_from((v >> 7) & 0x7f).expect("7 bits"),
161 confirmed: (v >> 6) & 1 == 1,
162 })
163 }
164}
165
166#[derive(Debug, Clone, PartialEq)]
169pub struct Identity {
170 pub iface: IfaceId,
171 pub contract: Fingerprint,
172 pub r#type: Value,
174}
175
176impl Identity {
177 #[must_use]
179 pub fn to_json(&self) -> Value {
180 json!({
181 "iface": self.iface.to_string(),
182 "contract": self.contract.to_string(),
183 "type": self.r#type,
184 })
185 }
186}
187
188fn place(revision: &Contract, resource: &str) -> Option<usize> {
191 revision
192 .resources
193 .iter()
194 .position(|r| format!("{}/{}", r.token.as_str(), r.template) == resource)
195}
196
197#[must_use]
202pub fn encode(
203 revision: &Contract,
204 resource: &str,
205 confirmed: bool,
206 catalog: &Catalog,
207) -> Option<[u8; COMPACT_BYTES]> {
208 let fp = Fingerprint::of(revision);
209 let index = catalog
210 .entries()
211 .iter()
212 .position(|e| e.iface == revision.iface && e.contract == fp)?;
213 let at = place(revision, resource).filter(|p| *p < RESOURCES)?;
214 Some(
215 Compact {
216 index: u16::try_from(index).ok()?,
217 resource: u8::try_from(at).ok()?,
218 confirmed,
219 }
220 .write(),
221 )
222}
223
224pub fn resolve(
232 c: Compact,
233 origin: &str,
234 archive: Option<CatalogId>,
235 held: &[Catalog],
236 revisions: &[&Contract],
237) -> Result<Identity, Refusal> {
238 let named = archive.ok_or(Refusal::UnknownCatalog)?;
239 let through = catalog::through(held, named)?;
240 let pair = through.entry(c.index)?;
241 let revision = revisions
242 .iter()
243 .find(|r| r.iface == pair.iface && Fingerprint::of(r) == pair.contract)
244 .ok_or(Refusal::UnknownRevision)?;
245 let at = usize::from(c.resource);
246 let r = revision.resources.get(at).ok_or(Refusal::Resource)?;
247 if !matches!(r.token, KindToken::State | KindToken::ExplicitState) {
248 return Err(Refusal::Resource);
249 }
250 let Ok(ZkKey::Data {
251 iface,
252 kind,
253 resource,
254 ..
255 }) = parse(origin)
256 else {
257 return Err(Refusal::Origin);
258 };
259 let chunks: Vec<&str> = resource.iter().map(String::as_str).collect();
260 if iface != pair.iface || kind != r.token || r.template.matches(&chunks).is_none() {
261 return Err(Refusal::Origin);
262 }
263 let ty = canonical(revision)["resources"][at]["type"].clone();
264 Ok(Identity {
265 iface: pair.iface.clone(),
266 contract: pair.contract.clone(),
267 r#type: ty,
268 })
269}
270
271#[derive(Debug, Clone, PartialEq)]
273pub struct Read {
274 pub form: Form,
275 pub confirmed: Option<bool>,
279 pub identity: Result<Value, String>,
282}
283
284#[must_use]
288pub fn read(
289 attachment: &[u8],
290 origin: &str,
291 archive: Option<CatalogId>,
292 held: &[Catalog],
293 revisions: &[&Contract],
294) -> Read {
295 match Form::of(attachment) {
296 Form::Json => {
297 let v: Option<Value> = serde_json::from_slice(attachment)
298 .ok()
299 .filter(Value::is_object);
300 match v {
301 Some(v) => Read {
302 form: Form::Json,
303 confirmed: v["confirmed"].as_bool(),
304 identity: Ok(
305 json!({"iface": v["iface"], "contract": v["contract"], "type": v["type"]}),
306 ),
307 },
308 None => Read {
309 form: Form::Json,
310 confirmed: None,
311 identity: Err(
312 "the attachment is not the JSON form's object (core §4.4)".to_owned()
313 ),
314 },
315 }
316 }
317 Form::Compact => match Compact::read(attachment) {
318 Err(r) => Read {
319 form: Form::Compact,
320 confirmed: None,
321 identity: Err(format!("{}: {r} (core §4.4)", r.token())),
322 },
323 Ok(c) => Read {
324 form: Form::Compact,
325 confirmed: Some(c.confirmed),
326 identity: resolve(c, origin, archive, held, revisions)
327 .map(|i| i.to_json())
328 .map_err(|r| format!("{}: {r} (core §4.4)", r.token())),
329 },
330 },
331 }
332}
333
334#[cfg(test)]
335mod tests {
336 use super::{Compact, Form, Refusal};
337
338 #[test]
339 fn the_layout_writes_back() {
340 for (index, resource, confirmed) in [(0, 0, false), (1023, 127, true), (5, 64, true)] {
341 let c = Compact {
342 index,
343 resource,
344 confirmed,
345 };
346 assert_eq!(Compact::read(&c.write()), Ok(c));
347 assert_eq!(Form::of(&c.write()), Form::Compact);
348 }
349 assert_eq!(Compact::read(&[0, 0, 0x20]), Err(Refusal::Extension));
350 assert_eq!(Compact::read(&[0, 0, 0x01]), Err(Refusal::Reserved));
351 assert_eq!(Form::of(b"{}"), Form::Json);
352 }
353}