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        check_consistency(
240            &self.cell,
241            &self.valid,
242            &self.publisher,
243            &self.asof,
244            &self.tx,
245            &self.issued,
246            self.source.as_ref(),
247        )
248    }
249}
250
251/// Step 4 (consistency) for a receipt or a withdrawal: the cell and `valid` are for one cell, `publisher`
252/// is its namespace, `valid` echoes `cell.args` and holds valid-time arguments, and the times are ordered.
253fn check_consistency(
254    cell: &Cell,
255    valid: &Args,
256    publisher: &str,
257    asof: &str,
258    tx: &str,
259    issued: &str,
260    source: Option<&Source>,
261) -> Result<()> {
262    {
263        for (k, a) in &cell.args {
264            if *a == Arg::Slice {
265                return err(ErrorCode::Slice, &member("$.cell.args", k), "a receipt is for one cell, not a slice");
266            }
267        }
268        for (k, a) in valid {
269            if *a == Arg::Slice {
270                return err(ErrorCode::Slice, &member("$.valid", k), "a receipt is for one cell, not a slice");
271            }
272        }
273        if publisher != cell.ns {
274            return err(ErrorCode::PublisherMismatch, "$.publisher", "publisher must equal cell.ns");
275        }
276        for (k, a) in valid {
277            if cell.args.get(k) != Some(a) {
278                return err(ErrorCode::ValidMismatch, "$.valid", format!("valid.{k} does not echo cell.args.{k}"));
279            }
280            if !a.scalar().is_some_and(|s| s.ty().may_be_valid_time()) {
281                return err(ErrorCode::ValidMismatch, "$.valid", "valid-time arguments are dates, instants or strings");
282            }
283        }
284        if !(tx <= asof && asof <= issued) {
285            return err(ErrorCode::TimeOrder, "$", "requires tx <= asof <= issued");
286        }
287        if let Some(s) = source {
288            if s.retrieved.as_str() > issued {
289                return err(ErrorCode::TimeOrder, "$.source.retrieved", "requires retrieved <= issued");
290            }
291        }
292        Ok(())
293    }
294}
295
296fn structure(v: &Value) -> Result<()> {
297    let m = schema::object(v, "$")?;
298    schema::exact(m, &MEMBERS, &["source"], "$", ErrorCode::Schema)?;
299    if schema::get(m, "proto").as_str() != Some("datumesh/1") {
300        return err(ErrorCode::Schema, "$.proto", "proto must be 'datumesh/1'");
301    }
302    let has_inputs = matches!(schema::get(m, "inputs"), Value::Array(a) if !a.is_empty());
303    let publisher = schema::get(m, "publisher").as_str().unwrap_or("");
304    for (k, val) in jcs_sorted(m) {
305        let p = member("$", k);
306        match k.as_str() {
307            "cell" => model::cell_structure(val, &p)?,
308            "source" => source_structure(val, &p, publisher, has_inputs)?,
309            "valid" => model::args_structure(val, &p)?,
310            "inputs" => {
311                if !matches!(val, Value::Array(a) if a.iter().all(|x| matches!(x, Value::String(_)))) {
312                    return err(ErrorCode::Schema, &p, "inputs must be an array of strings");
313                }
314            }
315            "value" => {
316                if !matches!(val, Value::String(_) | Value::Bool(_)) {
317                    return err(ErrorCode::Schema, &p, "value must be a string or a boolean");
318                }
319            }
320            _ => {
321                if !matches!(val, Value::String(_)) {
322                    return err(ErrorCode::Schema, &p, format!("{k} must be a string"));
323                }
324            }
325        }
326    }
327    Ok(())
328}
329
330/// `source` (8.1, `spec-0.6.0`), its shape: an object of exactly `name`, `retrieved` and `url`,
331/// with `sha256` and `takeover` optional, all strings (`E_SCHEMA`). It is only on a receipt with
332/// no inputs, and never names the publisher's own host (`E_SCHEMA`).
333fn source_structure(v: &Value, path: &str, publisher: &str, has_inputs: bool) -> Result<()> {
334    if has_inputs {
335        return err(ErrorCode::Schema, path, "source is only on a receipt with no inputs");
336    }
337    let m = schema::object_or(v, path, ErrorCode::Schema, "source")?;
338    schema::exact(m, &["name", "retrieved", "url"], &["sha256", "takeover"], path, ErrorCode::Schema)?;
339    for (k, val) in m {
340        if !matches!(val, Value::String(_)) {
341            return err(ErrorCode::Schema, &member(path, k), format!("{k} must be a string"));
342        }
343    }
344    if schema::get(m, "name").as_str() == Some(lexical::host_of(publisher)) {
345        return err(ErrorCode::Schema, &member(path, "name"), "a publisher does not relay itself");
346    }
347    Ok(())
348}
349
350/// `source` after structure (8.1, 10.1 step 3), members in the order `name`, `retrieved`,
351/// `sha256`, `takeover`, `url`.
352fn source_canonical(v: &Value, path: &str) -> Result<Source> {
353    let m = schema::object(v, path)?;
354    let s = |name: &str| schema::string(m, name, path);
355    let name = s("name")?;
356    lexical::check_dns_name(name, &member(path, "name"))?;
357    let retrieved = s("retrieved")?;
358    lexical::check_instant(retrieved, &member(path, "retrieved"))?;
359    let mut out = Source::new(name, "", retrieved);
360    if let Some(h) = schema::opt(m, "sha256") {
361        let h = h.as_str().unwrap_or("");
362        lexical::check_hex(h, 64, &member(path, "sha256"))?;
363        out = out.with_sha256(h);
364    }
365    let url_check = |u: &str, at: &str| -> Result<()> {
366        if !u.starts_with("https://") {
367            return err(ErrorCode::CanonLicence, at, "a source URL is https://");
368        }
369        lexical::check_licence(u, at)
370    };
371    if let Some(t) = schema::opt(m, "takeover") {
372        let t = t.as_str().unwrap_or("");
373        url_check(t, &member(path, "takeover"))?;
374        out = out.with_takeover(t);
375    }
376    let url = s("url")?;
377    url_check(url, &member(path, "url"))?;
378    Ok(Source { url: url.into(), ..out })
379}
380
381fn canonical(v: &Value) -> Result<Receipt> {
382    let m = schema::object(v, "$")?;
383    let s = |name: &str| schema::string(m, name, "$");
384    let asof = s("asof")?;
385    lexical::check_instant(asof, "$.asof")?;
386    let cell = model::cell_canonical(schema::get(m, "cell"), "$.cell")?;
387    let computed_by = s("computed_by")?;
388    lexical::check_key_ref(computed_by, "$.computed_by")?;
389    let inputs: Vec<&str> = match schema::get(m, "inputs") {
390        Value::Array(a) => a.iter().filter_map(Value::as_str).collect(),
391        _ => Vec::new(),
392    };
393    for (i, h) in inputs.iter().enumerate() {
394        lexical::check_input_entry(h, &index("$.inputs", i))?;
395    }
396    if inputs.windows(2).any(|w| w[0] >= w[1]) {
397        return err(ErrorCode::CanonSet, "$.inputs", "entries must be strictly ascending");
398    }
399    if inputs.len() > limits::INPUTS {
400        return err(ErrorCode::CanonLimit, "$.inputs", "more than 4096 inputs");
401    }
402    let issued = s("issued")?;
403    lexical::check_instant(issued, "$.issued")?;
404    let licence = s("licence")?;
405    lexical::check_licence(licence, "$.licence")?;
406    let publisher = s("publisher")?;
407    lexical::check_namespace(publisher, "$.publisher")?;
408    let sig = s("sig")?;
409    lexical::check_hex(sig, 128, "$.sig")?;
410    let summary = s("summary")?;
411    lexical::check_text(summary, limits::SUMMARY, false, "$.summary")?;
412    if summary.is_empty() {
413        return err(ErrorCode::CanonString, "$.summary", "summary must not be empty");
414    }
415    let tx = s("tx")?;
416    lexical::check_instant(tx, "$.tx")?;
417    let ty = Type::parse(s("type")?, "$.type")?;
418    let valid = model::args_canonical(schema::get(m, "valid"), "$.valid")?;
419    let value = match (ty, schema::get(m, "value")) {
420        (Type::Boolean, Value::Bool(b)) => Scalar::Boolean(*b),
421        (Type::Boolean, _) => return err(ErrorCode::CanonType, "$.value", "boolean value must be JSON true or false"),
422        (t, Value::String(text)) => {
423            model::check_lexical(t, text, "$.value")?;
424            model::unchecked(t, text)
425        }
426        (t, _) => return err(ErrorCode::CanonType, "$.value", format!("{} value must be a JSON string", t.as_str())),
427    };
428    let source = match schema::opt(m, "source") {
429        Some(sv) => Some(source_canonical(sv, "$.source")?),
430        None => None,
431    };
432    let without_sig: Vec<(String, Value)> = m.iter().filter(|(k, _)| k != "sig").cloned().collect();
433    let payload = Value::Object(without_sig).to_jcs();
434    let hash = crate::crypto::sha256_hex(&payload);
435    Ok(Receipt {
436        asof: asof.into(),
437        cell,
438        computed_by: computed_by.into(),
439        inputs: inputs.iter().map(|x| x.to_string()).collect(),
440        issued: issued.into(),
441        licence: licence.into(),
442        publisher: publisher.into(),
443        sig: sig.into(),
444        summary: summary.into(),
445        tx: tx.into(),
446        value,
447        valid,
448        source,
449        payload,
450        hash,
451    })
452}
453
454/// The canonical bytes of a receipt or withdrawal without `sig` (8.3), after steps 1-4.
455pub fn receipt_payload(bytes: &[u8]) -> Result<Vec<u8>> {
456    Ok(any_from_value(&json::parse(bytes)?)?.payload().to_vec())
457}
458
459/// The receipt or withdrawal hash (8.3), after steps 1-4.
460pub fn receipt_hash(bytes: &[u8]) -> Result<String> {
461    Ok(any_from_value(&json::parse(bytes)?)?.hash().to_string())
462}
463
464/// The members of a withdrawal (8.1, `spec-0.7.0`): `withdrawn` in place of `type` and `value`.
465const WITHDRAWAL_MEMBERS: [&str; 13] = [
466    "asof",
467    "cell",
468    "computed_by",
469    "inputs",
470    "issued",
471    "licence",
472    "proto",
473    "publisher",
474    "sig",
475    "summary",
476    "tx",
477    "valid",
478    "withdrawn",
479];
480
481/// A withdrawal (8.1, `spec-0.7.0`, R1): the null version of a stored cell. The cell has no value from its
482/// `asof` on, and `withdrawn` says why. It has `withdrawn` in place of `type` and `value`, and `inputs` is
483/// empty. It is signed and verified like a stored receipt, and it is never a [`Receipt`]: a [`Receipt`]
484/// always holds a value. Parsed by [`Withdrawal::from_json`]; verified by [`crate::verify`]; answered as
485/// `not_covered` with the `withdrawn` member of an envelope ([`crate::Answer::withdrawn`]).
486#[derive(Clone, Debug, PartialEq, Eq, Hash)]
487pub struct Withdrawal {
488    asof: String,
489    cell: Cell,
490    computed_by: String,
491    issued: String,
492    licence: String,
493    publisher: String,
494    sig: String,
495    summary: String,
496    tx: String,
497    valid: Args,
498    withdrawn: String,
499    source: Option<Source>,
500    payload: Vec<u8>,
501    hash: String,
502    canonical: Vec<u8>,
503}
504
505impl Withdrawal {
506    /// Parses a withdrawal and runs verification steps 1-4 (10.1). A receipt with a value is refused (`E_SCHEMA`).
507    pub fn from_json(bytes: &[u8]) -> Result<Withdrawal> {
508        Withdrawal::from_value(&json::parse(bytes)?)
509    }
510
511    /// Runs verification steps 2-4 on a parsed JSON value.
512    pub fn from_value(v: &Value) -> Result<Withdrawal> {
513        json::check_value_depth(v)?;
514        withdrawal_structure(v)?;
515        let w = withdrawal_canonical(v)?;
516        check_consistency(&w.cell, &w.valid, &w.publisher, &w.asof, &w.tx, &w.issued, w.source.as_ref())?;
517        Ok(w)
518    }
519
520    /// The signed payload: canonical bytes without `sig` (8.3).
521    pub fn payload(&self) -> &[u8] {
522        &self.payload
523    }
524
525    /// The canonical bytes of the whole withdrawal, `sig` included (JCS, as on the wire).
526    pub fn canonical(&self) -> &[u8] {
527        &self.canonical
528    }
529
530    /// The receipt hash: SHA-256 of the payload, lowercase hex (8.3).
531    pub fn hash(&self) -> &str {
532        &self.hash
533    }
534
535    /// The transaction time answered as of.
536    pub fn asof(&self) -> &str {
537        &self.asof
538    }
539
540    /// The cell withdrawn.
541    pub fn cell(&self) -> &Cell {
542        &self.cell
543    }
544
545    /// `<host>#<key id>` of the signing key.
546    pub fn computed_by(&self) -> &str {
547        &self.computed_by
548    }
549
550    /// When the withdrawal was signed.
551    pub fn issued(&self) -> &str {
552        &self.issued
553    }
554
555    /// An SPDX identifier or an https URL.
556    pub fn licence(&self) -> &str {
557        &self.licence
558    }
559
560    /// The namespace that owns the function; equals `cell.ns`.
561    pub fn publisher(&self) -> &str {
562        &self.publisher
563    }
564
565    /// The Ed25519 signature, 128 lowercase hex digits.
566    pub fn sig(&self) -> &str {
567        &self.sig
568    }
569
570    /// One human sentence.
571    pub fn summary(&self) -> &str {
572        &self.summary
573    }
574
575    /// When the withdrawal was recorded.
576    pub fn tx(&self) -> &str {
577        &self.tx
578    }
579
580    /// The valid-time arguments, echoed from `cell.args`.
581    pub fn valid(&self) -> &Args {
582        &self.valid
583    }
584
585    /// The reason: the `withdrawn` member, a non-empty string under the summary limit.
586    pub fn withdrawn(&self) -> &str {
587        &self.withdrawn
588    }
589
590    /// The host of `computed_by`.
591    pub fn signer_host(&self) -> &str {
592        self.computed_by.split_once('#').map_or("", |(h, _)| h)
593    }
594
595    /// The key id of `computed_by`.
596    pub fn key_id(&self) -> &str {
597        self.computed_by.split_once('#').map_or("", |(_, k)| k)
598    }
599
600    /// The `source` member (8.1, `spec-0.6.0`), when the withdrawn value was relayed from another party.
601    pub fn source(&self) -> Option<&Source> {
602        self.source.as_ref()
603    }
604}
605
606/// A receipt or a withdrawal, as the verifier handles either (crate-internal).
607#[derive(Clone, Debug, PartialEq, Eq, Hash)]
608pub(crate) enum AnyReceipt {
609    Value(Receipt),
610    Withdrawal(Withdrawal),
611}
612
613/// The getters verification reads of either kind (crate-internal).
614pub(crate) trait Stored {
615    fn asof(&self) -> &str;
616    fn tx(&self) -> &str;
617    fn issued(&self) -> &str;
618    fn cell(&self) -> &Cell;
619    fn valid(&self) -> &Args;
620    fn inputs(&self) -> &[String];
621    fn signer_host(&self) -> &str;
622    fn key_id(&self) -> &str;
623    fn computed_by(&self) -> &str;
624    fn sig(&self) -> &str;
625    fn payload(&self) -> &[u8];
626    fn hash(&self) -> &str;
627    fn source(&self) -> Option<&Source>;
628    /// The value, or `None` for a withdrawal.
629    fn scalar(&self) -> Option<&Scalar>;
630    fn is_withdrawal(&self) -> bool;
631}
632
633impl Stored for Receipt {
634    fn asof(&self) -> &str {
635        Receipt::asof(self)
636    }
637    fn tx(&self) -> &str {
638        Receipt::tx(self)
639    }
640    fn issued(&self) -> &str {
641        Receipt::issued(self)
642    }
643    fn cell(&self) -> &Cell {
644        Receipt::cell(self)
645    }
646    fn valid(&self) -> &Args {
647        Receipt::valid(self)
648    }
649    fn inputs(&self) -> &[String] {
650        Receipt::inputs(self)
651    }
652    fn signer_host(&self) -> &str {
653        Receipt::signer_host(self)
654    }
655    fn key_id(&self) -> &str {
656        Receipt::key_id(self)
657    }
658    fn computed_by(&self) -> &str {
659        Receipt::computed_by(self)
660    }
661    fn sig(&self) -> &str {
662        Receipt::sig(self)
663    }
664    fn payload(&self) -> &[u8] {
665        Receipt::payload(self)
666    }
667    fn hash(&self) -> &str {
668        Receipt::hash(self)
669    }
670    fn source(&self) -> Option<&Source> {
671        Receipt::source(self)
672    }
673    fn scalar(&self) -> Option<&Scalar> {
674        Some(Receipt::value(self))
675    }
676    fn is_withdrawal(&self) -> bool {
677        false
678    }
679}
680
681impl Stored for Withdrawal {
682    fn asof(&self) -> &str {
683        Withdrawal::asof(self)
684    }
685    fn tx(&self) -> &str {
686        Withdrawal::tx(self)
687    }
688    fn issued(&self) -> &str {
689        Withdrawal::issued(self)
690    }
691    fn cell(&self) -> &Cell {
692        Withdrawal::cell(self)
693    }
694    fn valid(&self) -> &Args {
695        Withdrawal::valid(self)
696    }
697    fn inputs(&self) -> &[String] {
698        &[]
699    }
700    fn signer_host(&self) -> &str {
701        Withdrawal::signer_host(self)
702    }
703    fn key_id(&self) -> &str {
704        Withdrawal::key_id(self)
705    }
706    fn computed_by(&self) -> &str {
707        Withdrawal::computed_by(self)
708    }
709    fn sig(&self) -> &str {
710        Withdrawal::sig(self)
711    }
712    fn payload(&self) -> &[u8] {
713        Withdrawal::payload(self)
714    }
715    fn hash(&self) -> &str {
716        Withdrawal::hash(self)
717    }
718    fn source(&self) -> Option<&Source> {
719        Withdrawal::source(self)
720    }
721    fn scalar(&self) -> Option<&Scalar> {
722        None
723    }
724    fn is_withdrawal(&self) -> bool {
725        true
726    }
727}
728
729impl Stored for AnyReceipt {
730    fn asof(&self) -> &str {
731        self.as_stored().asof()
732    }
733    fn tx(&self) -> &str {
734        self.as_stored().tx()
735    }
736    fn issued(&self) -> &str {
737        self.as_stored().issued()
738    }
739    fn cell(&self) -> &Cell {
740        self.as_stored().cell()
741    }
742    fn valid(&self) -> &Args {
743        self.as_stored().valid()
744    }
745    fn inputs(&self) -> &[String] {
746        self.as_stored().inputs()
747    }
748    fn signer_host(&self) -> &str {
749        self.as_stored().signer_host()
750    }
751    fn key_id(&self) -> &str {
752        self.as_stored().key_id()
753    }
754    fn computed_by(&self) -> &str {
755        self.as_stored().computed_by()
756    }
757    fn sig(&self) -> &str {
758        self.as_stored().sig()
759    }
760    fn payload(&self) -> &[u8] {
761        self.as_stored().payload()
762    }
763    fn hash(&self) -> &str {
764        self.as_stored().hash()
765    }
766    fn source(&self) -> Option<&Source> {
767        self.as_stored().source()
768    }
769    fn scalar(&self) -> Option<&Scalar> {
770        self.as_stored().scalar()
771    }
772    fn is_withdrawal(&self) -> bool {
773        self.as_stored().is_withdrawal()
774    }
775}
776
777impl AnyReceipt {
778    fn as_stored(&self) -> &dyn Stored {
779        match self {
780            AnyReceipt::Value(r) => r,
781            AnyReceipt::Withdrawal(w) => w,
782        }
783    }
784}
785
786/// Whether a parsed receipt is a withdrawal: it has `withdrawn` (8.1). Decides before any other check.
787pub(crate) fn is_withdrawal_value(v: &Value) -> bool {
788    matches!(v, Value::Object(m) if m.iter().any(|(k, _)| k == "withdrawn"))
789}
790
791/// Steps 2-4 for either kind, decided by the presence of `withdrawn` (crate-internal).
792pub(crate) fn any_from_value(v: &Value) -> Result<AnyReceipt> {
793    if is_withdrawal_value(v) {
794        Withdrawal::from_value(v).map(AnyReceipt::Withdrawal)
795    } else {
796        Receipt::from_value(v).map(AnyReceipt::Value)
797    }
798}
799
800fn withdrawal_structure(v: &Value) -> Result<()> {
801    let m = schema::object(v, "$")?;
802    schema::exact(m, &WITHDRAWAL_MEMBERS, &["source"], "$", ErrorCode::Schema)?;
803    if schema::get(m, "proto").as_str() != Some("datumesh/1") {
804        return err(ErrorCode::Schema, "$.proto", "proto must be 'datumesh/1'");
805    }
806    let publisher = schema::get(m, "publisher").as_str().unwrap_or("");
807    for (k, val) in jcs_sorted(m) {
808        let p = member("$", k);
809        match k.as_str() {
810            "cell" => model::cell_structure(val, &p)?,
811            "source" => source_structure(val, &p, publisher, false)?,
812            "valid" => model::args_structure(val, &p)?,
813            "inputs" => {
814                if !matches!(val, Value::Array(a) if a.is_empty()) {
815                    return err(ErrorCode::Schema, &p, "a withdrawal is a stored cell's: inputs is empty");
816                }
817            }
818            "withdrawn" => {
819                if !matches!(val, Value::String(text) if !text.is_empty()) {
820                    return err(ErrorCode::Schema, &p, "withdrawn is a non-empty string: the reason");
821                }
822            }
823            _ => {
824                if !matches!(val, Value::String(_)) {
825                    return err(ErrorCode::Schema, &p, format!("{k} must be a string"));
826                }
827            }
828        }
829    }
830    Ok(())
831}
832
833fn withdrawal_canonical(v: &Value) -> Result<Withdrawal> {
834    let m = schema::object(v, "$")?;
835    let s = |name: &str| schema::string(m, name, "$");
836    let asof = s("asof")?;
837    lexical::check_instant(asof, "$.asof")?;
838    let cell = model::cell_canonical(schema::get(m, "cell"), "$.cell")?;
839    let computed_by = s("computed_by")?;
840    lexical::check_key_ref(computed_by, "$.computed_by")?;
841    let issued = s("issued")?;
842    lexical::check_instant(issued, "$.issued")?;
843    let licence = s("licence")?;
844    lexical::check_licence(licence, "$.licence")?;
845    let publisher = s("publisher")?;
846    lexical::check_namespace(publisher, "$.publisher")?;
847    let sig = s("sig")?;
848    lexical::check_hex(sig, 128, "$.sig")?;
849    let summary = s("summary")?;
850    lexical::check_text(summary, limits::SUMMARY, false, "$.summary")?;
851    if summary.is_empty() {
852        return err(ErrorCode::CanonString, "$.summary", "summary must not be empty");
853    }
854    let tx = s("tx")?;
855    lexical::check_instant(tx, "$.tx")?;
856    let withdrawn = s("withdrawn")?;
857    lexical::check_text(withdrawn, limits::SUMMARY, false, "$.withdrawn")?;
858    let valid = model::args_canonical(schema::get(m, "valid"), "$.valid")?;
859    let source = match schema::opt(m, "source") {
860        Some(sv) => Some(source_canonical(sv, "$.source")?),
861        None => None,
862    };
863    let without_sig: Vec<(String, Value)> = m.iter().filter(|(k, _)| k != "sig").cloned().collect();
864    let payload = Value::Object(without_sig).to_jcs();
865    let hash = crate::crypto::sha256_hex(&payload);
866    Ok(Withdrawal {
867        asof: asof.into(),
868        cell,
869        computed_by: computed_by.into(),
870        issued: issued.into(),
871        licence: licence.into(),
872        publisher: publisher.into(),
873        sig: sig.into(),
874        summary: summary.into(),
875        tx: tx.into(),
876        valid,
877        withdrawn: withdrawn.into(),
878        source,
879        payload,
880        hash,
881        canonical: Value::Object(m.to_vec()).to_jcs(),
882    })
883}