Skip to main content

datumesh_core/
receipt.rs

1//! Receipts (8): members, the signed payload and the receipt hash.
2
3use crate::error::{err, index, member, ErrorCode, Result};
4use crate::json::{self, jcs_sorted, Value};
5use crate::lexical::{self, limits};
6use crate::model::{self, Arg, Args, Cell, Scalar, Type};
7use crate::schema;
8
9const MEMBERS: [&str; 14] = [
10    "asof",
11    "cell",
12    "computed_by",
13    "inputs",
14    "issued",
15    "licence",
16    "proto",
17    "publisher",
18    "sig",
19    "summary",
20    "tx",
21    "type",
22    "valid",
23    "value",
24];
25
26/// Where a stored receipt's value was taken from (8.1, `spec-0.6.0`): the optional `source`
27/// member, present only on a receipt with no `inputs`. The signer relays the value of another
28/// party; the signature covers `source`, and verification does not fetch `url` (the trust
29/// value `relayed`, 5.5). Built with [`Source::new`] and the `with_*` methods; a receipt holding
30/// one is checked by [`Receipt::from_json`] or by `ReceiptBuilder::sign` (feature `sign`).
31#[derive(Clone, Debug, PartialEq, Eq, Hash)]
32pub struct Source {
33    name: String,
34    url: String,
35    retrieved: String,
36    sha256: Option<String>,
37    takeover: Option<String>,
38}
39
40impl Source {
41    /// A source with its required members: `name` (the source's DNS name, 2.1), `url` (where the
42    /// value was taken from) and `retrieved` (an instant, when it was fetched). Not checked here:
43    /// the receipt check (10.1 step 3) and `sign` report what is wrong with it.
44    pub fn new(name: &str, url: &str, retrieved: &str) -> Source {
45        Source { name: name.into(), url: url.into(), retrieved: retrieved.into(), sha256: None, takeover: None }
46    }
47
48    /// With `sha256`: 64 lowercase hex digits, the SHA-256 of the bytes fetched from `url`.
49    pub fn with_sha256(self, sha256: &str) -> Source {
50        Source { sha256: Some(sha256.into()), ..self }
51    }
52
53    /// With `takeover`: an `https://` URL where the source can take over publishing these cells.
54    pub fn with_takeover(self, takeover: &str) -> Source {
55        Source { takeover: Some(takeover.into()), ..self }
56    }
57
58    /// The source's DNS name.
59    pub fn name(&self) -> &str {
60        &self.name
61    }
62
63    /// Where the value was taken from.
64    pub fn url(&self) -> &str {
65        &self.url
66    }
67
68    /// When the publisher fetched the value.
69    pub fn retrieved(&self) -> &str {
70        &self.retrieved
71    }
72
73    /// The SHA-256 of the bytes fetched from `url`, when given.
74    pub fn sha256(&self) -> Option<&str> {
75        self.sha256.as_deref()
76    }
77
78    /// Where the source can take over publishing these cells, when given.
79    pub fn takeover(&self) -> Option<&str> {
80        self.takeover.as_deref()
81    }
82
83    #[cfg(feature = "sign")]
84    pub(crate) fn to_value(&self) -> Value {
85        let s = |x: &str| Value::String(x.into());
86        let mut m = vec![("name".to_string(), s(&self.name)), ("retrieved".to_string(), s(&self.retrieved))];
87        if let Some(h) = &self.sha256 {
88            m.push(("sha256".into(), s(h)));
89        }
90        if let Some(t) = &self.takeover {
91            m.push(("takeover".into(), s(t)));
92        }
93        m.push(("url".into(), s(&self.url)));
94        Value::Object(m)
95    }
96}
97
98/// A receipt (8.1) that has passed verification steps 1-4: strict JSON, structure, canonical
99/// form and consistency. Its signature has not been checked; use [`crate::verify`].
100///
101/// The members are private and read through getters, so the cached [`payload`](Self::payload)
102/// and [`hash`](Self::hash) always describe them. A `Receipt` comes only from
103/// [`from_json`](Self::from_json) (or [`from_value`](Self::from_value) for JSON already
104/// parsed) and, with feature `sign`, from `ReceiptBuilder::sign`.
105#[derive(Clone, Debug, PartialEq, Eq, Hash)]
106pub struct Receipt {
107    asof: String,
108    cell: Cell,
109    computed_by: String,
110    inputs: Vec<String>,
111    issued: String,
112    licence: String,
113    publisher: String,
114    sig: String,
115    summary: String,
116    tx: String,
117    value: Scalar,
118    valid: Args,
119    source: Option<Source>,
120    payload: Vec<u8>,
121    hash: String,
122}
123
124impl Receipt {
125    /// Parses a receipt and runs verification steps 1-4 (10.1).
126    pub fn from_json(bytes: &[u8]) -> Result<Receipt> {
127        Receipt::from_value(&json::parse(bytes)?)
128    }
129
130    /// Runs verification steps 2-4 on a parsed JSON value.
131    pub fn from_value(v: &Value) -> Result<Receipt> {
132        json::check_value_depth(v)?;
133        structure(v)?;
134        let r = canonical(v)?;
135        r.consistency()?;
136        Ok(r)
137    }
138
139    /// The signed payload: canonical bytes of the receipt without `sig` (8.3).
140    pub fn payload(&self) -> &[u8] {
141        &self.payload
142    }
143
144    /// The receipt hash: SHA-256 of the payload, lowercase hex (8.3).
145    pub fn hash(&self) -> &str {
146        &self.hash
147    }
148
149    /// The transaction time answered as of.
150    pub fn asof(&self) -> &str {
151        &self.asof
152    }
153
154    /// The cell answered (no slices).
155    pub fn cell(&self) -> &Cell {
156        &self.cell
157    }
158
159    /// `<host>#<key id>` of the signing key.
160    pub fn computed_by(&self) -> &str {
161        &self.computed_by
162    }
163
164    /// The inputs entries, ascending: receipt hashes and, since `spec-0.4.0`, slice entries
165    /// `slice:<slice id>:<members hash>` (which sort after every receipt hash).
166    pub fn inputs(&self) -> &[String] {
167        &self.inputs
168    }
169
170    /// When the receipt was signed.
171    pub fn issued(&self) -> &str {
172        &self.issued
173    }
174
175    /// An SPDX identifier or an https URL.
176    pub fn licence(&self) -> &str {
177        &self.licence
178    }
179
180    /// The namespace that owns the function; equals `cell.ns`.
181    pub fn publisher(&self) -> &str {
182        &self.publisher
183    }
184
185    /// The Ed25519 signature, 128 lowercase hex digits.
186    pub fn sig(&self) -> &str {
187        &self.sig
188    }
189
190    /// One human sentence.
191    pub fn summary(&self) -> &str {
192        &self.summary
193    }
194
195    /// When the value was recorded.
196    pub fn tx(&self) -> &str {
197        &self.tx
198    }
199
200    /// The value, typed.
201    pub fn value(&self) -> &Scalar {
202        &self.value
203    }
204
205    /// The valid-time arguments, echoed from `cell.args`.
206    pub fn valid(&self) -> &Args {
207        &self.valid
208    }
209
210    /// The value's type (the `type` member).
211    pub fn ty(&self) -> Type {
212        self.value.ty()
213    }
214
215    /// The host of `computed_by`.
216    pub fn signer_host(&self) -> &str {
217        self.computed_by.split_once('#').map_or("", |(h, _)| h)
218    }
219
220    /// The key id of `computed_by`.
221    pub fn key_id(&self) -> &str {
222        self.computed_by.split_once('#').map_or("", |(_, k)| k)
223    }
224
225    /// The `source` member (8.1, `spec-0.6.0`), when the receipt is relayed: a stored receipt
226    /// whose value was taken from another party. `None` on every receipt before 0.6.0.
227    pub fn source(&self) -> Option<&Source> {
228        self.source.as_ref()
229    }
230
231    /// The same receipt with `sig` replaced; payload and hash do not cover `sig`.
232    #[cfg(feature = "sign")]
233    pub(crate) fn with_sig(mut self, sig: String) -> Receipt {
234        self.sig = sig;
235        self
236    }
237
238    fn consistency(&self) -> Result<()> {
239        for (k, a) in &self.cell.args {
240            if *a == Arg::Slice {
241                return err(ErrorCode::Slice, &member("$.cell.args", k), "a receipt is for one cell, not a slice");
242            }
243        }
244        for (k, a) in &self.valid {
245            if *a == Arg::Slice {
246                return err(ErrorCode::Slice, &member("$.valid", k), "a receipt is for one cell, not a slice");
247            }
248        }
249        if self.publisher != self.cell.ns {
250            return err(ErrorCode::PublisherMismatch, "$.publisher", "publisher must equal cell.ns");
251        }
252        for (k, a) in &self.valid {
253            if self.cell.args.get(k) != Some(a) {
254                return err(ErrorCode::ValidMismatch, "$.valid", format!("valid.{k} does not echo cell.args.{k}"));
255            }
256            if !a.scalar().is_some_and(|s| s.ty().may_be_valid_time()) {
257                return err(ErrorCode::ValidMismatch, "$.valid", "valid-time arguments are dates, instants or strings");
258            }
259        }
260        if !(self.tx <= self.asof && self.asof <= self.issued) {
261            return err(ErrorCode::TimeOrder, "$", "requires tx <= asof <= issued");
262        }
263        if let Some(s) = &self.source {
264            if s.retrieved > self.issued {
265                return err(ErrorCode::TimeOrder, "$.source.retrieved", "requires retrieved <= issued");
266            }
267        }
268        Ok(())
269    }
270}
271
272fn structure(v: &Value) -> Result<()> {
273    let m = schema::object(v, "$")?;
274    schema::exact(m, &MEMBERS, &["source"], "$", ErrorCode::Schema)?;
275    if schema::get(m, "proto").as_str() != Some("datumesh/1") {
276        return err(ErrorCode::Schema, "$.proto", "proto must be 'datumesh/1'");
277    }
278    let has_inputs = matches!(schema::get(m, "inputs"), Value::Array(a) if !a.is_empty());
279    let publisher = schema::get(m, "publisher").as_str().unwrap_or("");
280    for (k, val) in jcs_sorted(m) {
281        let p = member("$", k);
282        match k.as_str() {
283            "cell" => model::cell_structure(val, &p)?,
284            "source" => source_structure(val, &p, publisher, has_inputs)?,
285            "valid" => model::args_structure(val, &p)?,
286            "inputs" => {
287                if !matches!(val, Value::Array(a) if a.iter().all(|x| matches!(x, Value::String(_)))) {
288                    return err(ErrorCode::Schema, &p, "inputs must be an array of strings");
289                }
290            }
291            "value" => {
292                if !matches!(val, Value::String(_) | Value::Bool(_)) {
293                    return err(ErrorCode::Schema, &p, "value must be a string or a boolean");
294                }
295            }
296            _ => {
297                if !matches!(val, Value::String(_)) {
298                    return err(ErrorCode::Schema, &p, format!("{k} must be a string"));
299                }
300            }
301        }
302    }
303    Ok(())
304}
305
306/// `source` (8.1, `spec-0.6.0`), its shape: an object of exactly `name`, `retrieved` and `url`,
307/// with `sha256` and `takeover` optional, all strings (`E_SCHEMA`). It is only on a receipt with
308/// no inputs, and never names the publisher's own host (`E_SCHEMA`).
309fn source_structure(v: &Value, path: &str, publisher: &str, has_inputs: bool) -> Result<()> {
310    if has_inputs {
311        return err(ErrorCode::Schema, path, "source is only on a receipt with no inputs");
312    }
313    let m = schema::object_or(v, path, ErrorCode::Schema, "source")?;
314    schema::exact(m, &["name", "retrieved", "url"], &["sha256", "takeover"], path, ErrorCode::Schema)?;
315    for (k, val) in m {
316        if !matches!(val, Value::String(_)) {
317            return err(ErrorCode::Schema, &member(path, k), format!("{k} must be a string"));
318        }
319    }
320    if schema::get(m, "name").as_str() == Some(lexical::host_of(publisher)) {
321        return err(ErrorCode::Schema, &member(path, "name"), "a publisher does not relay itself");
322    }
323    Ok(())
324}
325
326/// `source` after structure (8.1, 10.1 step 3), members in the order `name`, `retrieved`,
327/// `sha256`, `takeover`, `url`.
328fn source_canonical(v: &Value, path: &str) -> Result<Source> {
329    let m = schema::object(v, path)?;
330    let s = |name: &str| schema::string(m, name, path);
331    let name = s("name")?;
332    lexical::check_dns_name(name, &member(path, "name"))?;
333    let retrieved = s("retrieved")?;
334    lexical::check_instant(retrieved, &member(path, "retrieved"))?;
335    let mut out = Source::new(name, "", retrieved);
336    if let Some(h) = schema::opt(m, "sha256") {
337        let h = h.as_str().unwrap_or("");
338        lexical::check_hex(h, 64, &member(path, "sha256"))?;
339        out = out.with_sha256(h);
340    }
341    let url_check = |u: &str, at: &str| -> Result<()> {
342        if !u.starts_with("https://") {
343            return err(ErrorCode::CanonLicence, at, "a source URL is https://");
344        }
345        lexical::check_licence(u, at)
346    };
347    if let Some(t) = schema::opt(m, "takeover") {
348        let t = t.as_str().unwrap_or("");
349        url_check(t, &member(path, "takeover"))?;
350        out = out.with_takeover(t);
351    }
352    let url = s("url")?;
353    url_check(url, &member(path, "url"))?;
354    Ok(Source { url: url.into(), ..out })
355}
356
357fn canonical(v: &Value) -> Result<Receipt> {
358    let m = schema::object(v, "$")?;
359    let s = |name: &str| schema::string(m, name, "$");
360    let asof = s("asof")?;
361    lexical::check_instant(asof, "$.asof")?;
362    let cell = model::cell_canonical(schema::get(m, "cell"), "$.cell")?;
363    let computed_by = s("computed_by")?;
364    lexical::check_key_ref(computed_by, "$.computed_by")?;
365    let inputs: Vec<&str> = match schema::get(m, "inputs") {
366        Value::Array(a) => a.iter().filter_map(Value::as_str).collect(),
367        _ => Vec::new(),
368    };
369    for (i, h) in inputs.iter().enumerate() {
370        lexical::check_input_entry(h, &index("$.inputs", i))?;
371    }
372    if inputs.windows(2).any(|w| w[0] >= w[1]) {
373        return err(ErrorCode::CanonSet, "$.inputs", "entries must be strictly ascending");
374    }
375    if inputs.len() > limits::INPUTS {
376        return err(ErrorCode::CanonLimit, "$.inputs", "more than 4096 inputs");
377    }
378    let issued = s("issued")?;
379    lexical::check_instant(issued, "$.issued")?;
380    let licence = s("licence")?;
381    lexical::check_licence(licence, "$.licence")?;
382    let publisher = s("publisher")?;
383    lexical::check_namespace(publisher, "$.publisher")?;
384    let sig = s("sig")?;
385    lexical::check_hex(sig, 128, "$.sig")?;
386    let summary = s("summary")?;
387    lexical::check_text(summary, limits::SUMMARY, false, "$.summary")?;
388    if summary.is_empty() {
389        return err(ErrorCode::CanonString, "$.summary", "summary must not be empty");
390    }
391    let tx = s("tx")?;
392    lexical::check_instant(tx, "$.tx")?;
393    let ty = Type::parse(s("type")?, "$.type")?;
394    let valid = model::args_canonical(schema::get(m, "valid"), "$.valid")?;
395    let value = match (ty, schema::get(m, "value")) {
396        (Type::Boolean, Value::Bool(b)) => Scalar::Boolean(*b),
397        (Type::Boolean, _) => return err(ErrorCode::CanonType, "$.value", "boolean value must be JSON true or false"),
398        (t, Value::String(text)) => {
399            model::check_lexical(t, text, "$.value")?;
400            model::unchecked(t, text)
401        }
402        (t, _) => return err(ErrorCode::CanonType, "$.value", format!("{} value must be a JSON string", t.as_str())),
403    };
404    let source = match schema::opt(m, "source") {
405        Some(sv) => Some(source_canonical(sv, "$.source")?),
406        None => None,
407    };
408    let without_sig: Vec<(String, Value)> = m.iter().filter(|(k, _)| k != "sig").cloned().collect();
409    let payload = Value::Object(without_sig).to_jcs();
410    let hash = crate::crypto::sha256_hex(&payload);
411    Ok(Receipt {
412        asof: asof.into(),
413        cell,
414        computed_by: computed_by.into(),
415        inputs: inputs.iter().map(|x| x.to_string()).collect(),
416        issued: issued.into(),
417        licence: licence.into(),
418        publisher: publisher.into(),
419        sig: sig.into(),
420        summary: summary.into(),
421        tx: tx.into(),
422        value,
423        valid,
424        source,
425        payload,
426        hash,
427    })
428}
429
430/// The canonical bytes of a receipt without `sig` (8.3), after steps 1-4.
431pub fn receipt_payload(bytes: &[u8]) -> Result<Vec<u8>> {
432    Ok(Receipt::from_json(bytes)?.payload)
433}
434
435/// The receipt hash (8.3), after steps 1-4.
436pub fn receipt_hash(bytes: &[u8]) -> Result<String> {
437    Ok(Receipt::from_json(bytes)?.hash)
438}