Skip to main content

zenkey_model/
attachment.rs

1//! An archive reply's attachment (core §4.4; #980 C3): its two forms, told
2//! apart by their length.
3//!
4//! - **The JSON form** is an object, `{"iface", "contract", "type",
5//!   "confirmed"}`: the archived value's type identity (§7.1) and whether
6//!   alignment confirmed its key.
7//! - **The compact form** is 3 bytes ([`Compact`]): the value's revision by
8//!   its index in the archive's catalog (§8.6), its resource by its place
9//!   in that revision (§9.5), the `confirmed` bit, an extension bit and 5
10//!   reserved bits. An archive given a catalog writes it ([`encode`]).
11//!
12//! A reader reads both ([`read`]). The `confirmed` bit needs no catalog;
13//! the identity is read through the catalog the archive's descriptor names
14//! and from the revision its index names ([`resolve`]), never through
15//! another catalog nor another revision. Every [`Refusal`] is the first in
16//! §4.4's order. `spec/conformance/archive/attachments.json` pins them.
17
18use 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
26/// The compact form's length: exactly 3 bytes, by which it is told from the
27/// JSON form.
28pub const COMPACT_BYTES: usize = 3;
29
30/// The resources a compact attachment can name: its resource is 7 bits.
31pub const RESOURCES: usize = 128;
32
33/// An attachment's form, told by its length alone (§4.4, "Read by its
34/// length").
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Form {
37    Json,
38    Compact,
39}
40
41impl Form {
42    /// `Compact` for exactly 3 bytes, `Json` for any other length.
43    #[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/// The compact form's fields (§4.4, "The compact attachment").
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub struct Compact {
56    /// The value's revision, by its index in the archive's catalog: 10 bits.
57    pub index: u16,
58    /// The value's resource, by its place among the revision's resources
59    /// in the canonical form's order: 7 bits.
60    pub resource: u8,
61    pub confirmed: bool,
62}
63
64/// Why a reader refuses a compact attachment (core §4.4, "Reading"), in
65/// the text's order.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
67pub enum Refusal {
68    /// The extension bit is 1.
69    #[error("extension: the extension bit is 1")]
70    Extension,
71    /// A reserved bit is 1.
72    #[error("reserved: a reserved bit is 1")]
73    Reserved,
74    /// The reader holds neither the archive's catalog nor a successor, or
75    /// the archive names none (core §8.6).
76    #[error("unknown_catalog: no held catalog is or succeeds the archive's")]
77    UnknownCatalog,
78    /// The index is at or above the count read through (core §8.6).
79    #[error("unknown_index: the index is at or above the count read through")]
80    UnknownIndex,
81    /// No held revision of the pair the index names.
82    #[error("unknown_revision: no held revision of the pair the index names")]
83    UnknownRevision,
84    /// The resource is past the revision's, or is not a state.
85    #[error("resource: no state of the revision at that place")]
86    Resource,
87    /// The origin key is not a key of that resource.
88    #[error("origin: the origin key is not a key of the resource named")]
89    Origin,
90}
91
92impl Refusal {
93    /// The fixtures' token.
94    #[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    /// Whether the `confirmed` bit was read before it: every refusal but
108    /// the first two (§4.4, "What a refusal leaves").
109    #[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    /// Its 3 bytes: index 10, resource 7, confirmed 1, extension 1 (0),
126    /// reserved 5 (0), most significant bit first.
127    ///
128    /// # Panics
129    /// If the index is past 1,023 or the resource past 127, which no
130    /// catalog and no compact attachment holds.
131    #[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    /// Reads the 3 bytes of a compact attachment: its fields, or the first
142    /// two refusals, which leave nothing read.
143    ///
144    /// # Errors
145    /// [`Refusal::Extension`] or [`Refusal::Reserved`].
146    ///
147    /// # Panics
148    /// If `bytes` is not 3 bytes long: any other length is the JSON form.
149    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/// An archived value's type identity (core §7.1), as the JSON form states
167/// it.
168#[derive(Debug, Clone, PartialEq)]
169pub struct Identity {
170    pub iface: IfaceId,
171    pub contract: Fingerprint,
172    /// The resource's type object, in its revision's canonical form (§9.5).
173    pub r#type: Value,
174}
175
176impl Identity {
177    /// `{"iface", "contract", "type"}`, as the JSON form writes them.
178    #[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
188/// `revision`'s resource `resource` (`<kind token>/<template>`), and its
189/// place in the canonical form's order.
190fn 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/// The compact attachment an archive writing under `catalog` gives a value
198/// of `resource` (`<kind token>/<template>`) in `revision` (core §4.4,
199/// "Writing it"). `None` where it writes the JSON form: the catalog does
200/// not list the revision, or the resource is past its 128th.
201#[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
224/// The identity a compact attachment states for a reply on `origin` (core
225/// §4.4, "Decoding", "Reading"): read through `archive`, the catalog the
226/// archive's descriptor names, among the catalogs `held`, and from the
227/// revision its index names among `revisions`.
228///
229/// # Errors
230/// The first refusal past the bits, in §4.4's order.
231pub 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/// An attachment as a reader reads it (core §4.4, "Reading it").
272#[derive(Debug, Clone, PartialEq)]
273pub struct Read {
274    pub form: Form,
275    /// Its `confirmed`, where it was read: `None` for a JSON attachment
276    /// that is not the form's object, or a compact one refused for its
277    /// bits. A reader takes `None` as unconfirmed (§4.4).
278    pub confirmed: Option<bool>,
279    /// `{"iface", "contract", "type"}`, or why it is not known: a compact
280    /// one's refusal, never a guess.
281    pub identity: Result<Value, String>,
282}
283
284/// Reads an archive reply's attachment on `origin`, either form: a compact
285/// one through `archive`, the catalog the archive's descriptor names,
286/// among the catalogs `held`, and the revisions `revisions`.
287#[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}