datumesh-core 0.3.6

Datumesh protocol core: strict JSON and JCS, canonical forms, cell URIs, receipts, keys, envelopes and offline verification.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//! Typed scalars (3, 4.1), argument maps (4.2), cell references (4.3) and cells (4.4).

use std::collections::BTreeMap;

use crate::error::{err, member, ErrorCode, Result};
use crate::json::{self, jcs_sorted, Value};
use crate::lexical::{self, limits};
use crate::schema;

/// One of the six scalar types (3).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Type {
    /// An exact decimal written as a string (3.1).
    Number,
    /// An NFC string of Unicode 15.1 code points (3.5).
    String,
    /// `true` or `false`.
    Boolean,
    /// `YYYY-MM-DD` (3.2).
    Date,
    /// `YYYY-MM-DDTHH:MM:SS.ffffffZ` (3.3).
    Instant,
    /// `<sha256>:<length>:<media type>` (3.7).
    Blob,
}

impl Type {
    /// The type name as written in JSON.
    pub const fn as_str(self) -> &'static str {
        match self {
            Type::Number => "number",
            Type::String => "string",
            Type::Boolean => "boolean",
            Type::Date => "date",
            Type::Instant => "instant",
            Type::Blob => "blob",
        }
    }

    /// The type of a type name; `None` outside the six.
    pub fn from_name(name: &str) -> Option<Type> {
        Some(match name {
            "number" => Type::Number,
            "string" => Type::String,
            "boolean" => Type::Boolean,
            "date" => Type::Date,
            "instant" => Type::Instant,
            "blob" => Type::Blob,
            _ => return None,
        })
    }

    pub(crate) fn parse(name: &str, path: &str) -> Result<Type> {
        match Type::from_name(name) {
            Some(t) => Ok(t),
            None => err(ErrorCode::CanonType, path, format!("unknown type {name:?}")),
        }
    }

    /// Whether a valid-time argument may have this type (date, instant or string).
    pub fn may_be_valid_time(self) -> bool {
        matches!(self, Type::Date | Type::Instant | Type::String)
    }
}

/// A typed scalar value in its one canonical lexical form.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Scalar {
    /// A canonical decimal string.
    Number(String),
    /// A valid string value.
    String(String),
    /// A boolean.
    Boolean(bool),
    /// A calendar date.
    Date(String),
    /// A UTC instant with microseconds.
    Instant(String),
    /// A blob reference.
    Blob(String),
}

impl Scalar {
    /// Builds a scalar of type `ty` from its lexical form, checking it (3). For a boolean,
    /// `text` must be `true` or `false` (`E_CANON_TYPE` otherwise).
    pub fn from_lexical(ty: Type, text: &str) -> Result<Scalar> {
        check_lexical(ty, text, "$")?;
        Ok(unchecked(ty, text))
    }

    /// Parses a typed scalar from JSON text (4.1): strict JSON, structure, canonical form.
    pub fn from_json(bytes: &[u8]) -> Result<Scalar> {
        let v = json::parse(bytes)?;
        scalar_structure(&v, "$")?;
        scalar_canonical(&v, "$")
    }

    /// The scalar's type.
    pub fn ty(&self) -> Type {
        match self {
            Scalar::Number(_) => Type::Number,
            Scalar::String(_) => Type::String,
            Scalar::Boolean(_) => Type::Boolean,
            Scalar::Date(_) => Type::Date,
            Scalar::Instant(_) => Type::Instant,
            Scalar::Blob(_) => Type::Blob,
        }
    }

    /// The lexical form (`true`/`false` for booleans).
    pub fn lexical(&self) -> &str {
        match self {
            Scalar::Number(s) | Scalar::String(s) | Scalar::Date(s) | Scalar::Instant(s) | Scalar::Blob(s) => s,
            Scalar::Boolean(true) => "true",
            Scalar::Boolean(false) => "false",
        }
    }

    /// The JSON form `{"type": …, "value": …}`.
    pub fn to_value(&self) -> Value {
        let value = match self {
            Scalar::Boolean(b) => Value::Bool(*b),
            other => Value::String(other.lexical().into()),
        };
        Value::Object(vec![("type".into(), Value::String(self.ty().as_str().into())), ("value".into(), value)])
    }

    /// The canonical bytes (6.2) of the typed scalar.
    pub fn canonical(&self) -> Vec<u8> {
        self.to_value().to_jcs()
    }
}

/// A scalar from a lexical form already checked against `ty`.
pub(crate) fn unchecked(ty: Type, text: &str) -> Scalar {
    match ty {
        Type::Number => Scalar::Number(text.into()),
        Type::String => Scalar::String(text.into()),
        Type::Date => Scalar::Date(text.into()),
        Type::Instant => Scalar::Instant(text.into()),
        Type::Blob => Scalar::Blob(text.into()),
        Type::Boolean => Scalar::Boolean(text == "true"),
    }
}

/// Checks a lexical form against its type.
pub(crate) fn check_lexical(ty: Type, text: &str, path: &str) -> Result<()> {
    match ty {
        Type::Number => lexical::check_number(text, path),
        Type::String => lexical::check_string(text, path),
        Type::Date => lexical::check_date(text, path),
        Type::Instant => lexical::check_instant(text, path),
        Type::Blob => lexical::check_blob(text, path),
        Type::Boolean => {
            if text == "true" || text == "false" {
                Ok(())
            } else {
                err(ErrorCode::CanonType, path, format!("a boolean is true or false, not {text:?}"))
            }
        }
    }
}

pub(crate) fn scalar_structure(v: &Value, path: &str) -> Result<()> {
    let m = schema::object(v, path)?;
    schema::exact(m, &["type", "value"], &[], path, ErrorCode::Schema)?;
    schema::string(m, "type", path)?;
    match schema::get(m, "value") {
        Value::String(_) | Value::Bool(_) => Ok(()),
        _ => err(ErrorCode::Schema, &member(path, "value"), "value must be a string or a boolean"),
    }
}

/// Canonical check of a structurally valid typed scalar.
pub(crate) fn scalar_canonical(v: &Value, path: &str) -> Result<Scalar> {
    let m = schema::object(v, path)?;
    let ty = Type::parse(schema::string(m, "type", path)?, &member(path, "type"))?;
    let vp = member(path, "value");
    match (ty, schema::get(m, "value")) {
        (Type::Boolean, Value::Bool(b)) => Ok(Scalar::Boolean(*b)),
        (Type::Boolean, _) => err(ErrorCode::CanonType, &vp, "boolean value must be JSON true or false"),
        (t, Value::String(s)) => {
            check_lexical(t, s, &vp)?;
            Ok(unchecked(t, s))
        }
        (t, _) => err(ErrorCode::CanonType, &vp, format!("{} value must be a JSON string", t.as_str())),
    }
}

/// An argument: a typed scalar, or the slice marker `"*"` (4.2).
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Arg {
    /// A bound value.
    Value(Scalar),
    /// The slice marker: the argument is open.
    Slice,
}

impl Arg {
    /// The JSON form: a typed scalar or `"*"`.
    pub fn to_value(&self) -> Value {
        match self {
            Arg::Value(s) => s.to_value(),
            Arg::Slice => Value::String("*".into()),
        }
    }

    /// The scalar, if bound.
    pub fn scalar(&self) -> Option<&Scalar> {
        match self {
            Arg::Value(s) => Some(s),
            Arg::Slice => None,
        }
    }
}

/// An argument map, keyed by argument name (byte order equals JCS order for names).
pub type Args = BTreeMap<String, Arg>;

pub(crate) fn args_to_value(args: &Args) -> Value {
    Value::Object(args.iter().map(|(k, a)| (k.clone(), a.to_value())).collect())
}

pub(crate) fn args_structure(v: &Value, path: &str) -> Result<()> {
    let m = schema::object(v, path)?;
    for (k, a) in jcs_sorted(m) {
        let p = member(path, k);
        match a {
            Value::String(s) if s == "*" => {}
            Value::String(_) => return err(ErrorCode::Schema, &p, "an argument is a typed scalar or \"*\""),
            other => scalar_structure(other, &p)?,
        }
    }
    Ok(())
}

pub(crate) fn args_canonical(v: &Value, path: &str) -> Result<Args> {
    let m = schema::object(v, path)?;
    if m.len() > limits::ARGS {
        return err(ErrorCode::CanonLimit, path, "more than 32 arguments");
    }
    let mut out = Args::new();
    for (k, a) in jcs_sorted(m) {
        let p = member(path, k);
        lexical::check_arg_name(k, &p)?;
        let arg = match a {
            Value::String(s) if s == "*" => Arg::Slice,
            other => Arg::Value(scalar_canonical(other, &p)?),
        };
        out.insert(k.clone(), arg);
    }
    Ok(out)
}

fn check_fn_length(ns: &str, f: &str) -> Result<()> {
    if ns.len() + 1 + f.len() > limits::FUNCTION_NAME {
        return err(ErrorCode::CanonLimit, "$", "function name longer than 512 characters");
    }
    Ok(())
}

/// A cell (4.4): a function, pinned by hash, applied to arguments. May denote a slice.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Cell {
    /// The namespace, e.g. `rates.example.org`.
    pub ns: String,
    /// The function name within the namespace.
    pub fn_name: String,
    /// The function hash, 64 lowercase hex digits.
    pub fn_hash: String,
    /// The arguments.
    pub args: Args,
}

impl Cell {
    /// Parses a cell from JSON text: strict JSON, structure, canonical form. Slices allowed.
    pub fn from_json(bytes: &[u8]) -> Result<Cell> {
        let v = json::parse(bytes)?;
        Cell::from_value(&v)
    }

    /// Checks a parsed JSON value as a cell.
    pub fn from_value(v: &Value) -> Result<Cell> {
        json::check_value_depth(v)?;
        cell_structure(v, "$")?;
        cell_canonical(v, "$")
    }

    /// The JSON form.
    pub fn to_value(&self) -> Value {
        Value::Object(vec![
            ("args".into(), args_to_value(&self.args)),
            ("fn".into(), Value::String(self.fn_name.clone())),
            ("fn_hash".into(), Value::String(self.fn_hash.clone())),
            ("ns".into(), Value::String(self.ns.clone())),
        ])
    }

    /// The canonical bytes (6.2).
    pub fn canonical(&self) -> Vec<u8> {
        self.to_value().to_jcs()
    }

    /// The cell id: SHA-256 of the canonical bytes, lowercase hex.
    pub fn id(&self) -> String {
        crate::crypto::sha256_hex(&self.canonical())
    }

    /// Whether any argument is the slice marker.
    pub fn is_slice(&self) -> bool {
        self.args.values().any(|a| *a == Arg::Slice)
    }

    /// The fully qualified function name `<ns>/<fn>`.
    pub fn function_name(&self) -> String {
        format!("{}/{}", self.ns, self.fn_name)
    }
}

pub(crate) fn cell_structure(v: &Value, path: &str) -> Result<()> {
    let m = schema::object(v, path)?;
    schema::exact(m, &["args", "fn", "fn_hash", "ns"], &[], path, ErrorCode::Schema)?;
    args_structure(schema::get(m, "args"), &member(path, "args"))?;
    schema::string(m, "fn", path)?;
    schema::string(m, "fn_hash", path)?;
    schema::string(m, "ns", path)?;
    Ok(())
}

pub(crate) fn cell_canonical(v: &Value, path: &str) -> Result<Cell> {
    let m = schema::object(v, path)?;
    let args = args_canonical(schema::get(m, "args"), &member(path, "args"))?;
    let f = schema::string(m, "fn", path)?;
    lexical::check_name(f, &member(path, "fn"))?;
    let h = schema::string(m, "fn_hash", path)?;
    lexical::check_hex(h, 64, &member(path, "fn_hash"))?;
    let ns = schema::string(m, "ns", path)?;
    lexical::check_namespace(ns, &member(path, "ns"))?;
    check_fn_length(ns, f).map_err(|e| crate::error::Error::new(e.code(), path, e.detail()))?;
    Ok(Cell { ns: ns.into(), fn_name: f.into(), fn_hash: h.into(), args })
}

/// A cell reference (4.3): what a cell URI denotes before the function name is resolved.
///
/// It has no place for the pin of `spec-0.4.2` (`fn_hash`): [`CellRef::from_json`] refuses a
/// reference with one (`E_SCHEMA`, as in 0.3.5) and [`crate::parse_uri`] a pinned URI. Use
/// [`Reference`], which has it.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct CellRef {
    /// The namespace.
    pub ns: String,
    /// The function name within the namespace.
    pub fn_name: String,
    /// The arguments, typed by the function's signature.
    pub args: Args,
    /// The transaction time asked for; `None` means now.
    pub asof: Option<String>,
}

impl CellRef {
    /// Parses a cell reference from JSON text: strict JSON, structure, canonical form.
    pub fn from_json(bytes: &[u8]) -> Result<CellRef> {
        let v = json::parse(bytes)?;
        let m = schema::object(&v, "$")?;
        schema::exact(m, &["args", "fn", "ns"], &["asof"], "$", ErrorCode::Schema)?;
        args_structure(schema::get(m, "args"), "$.args")?;
        schema::string(m, "fn", "$")?;
        schema::string(m, "ns", "$")?;
        if schema::opt(m, "asof").is_some() {
            schema::string(m, "asof", "$")?;
        }
        let args = args_canonical(schema::get(m, "args"), "$.args")?;
        let asof = match schema::opt(m, "asof") {
            Some(Value::String(s)) => {
                lexical::check_instant(s, "$.asof")?;
                Some(s.clone())
            }
            _ => None,
        };
        let f = schema::string(m, "fn", "$")?;
        lexical::check_name(f, "$.fn")?;
        let ns = schema::string(m, "ns", "$")?;
        lexical::check_namespace(ns, "$.ns")?;
        check_fn_length(ns, f)?;
        Ok(CellRef { ns: ns.into(), fn_name: f.into(), args, asof })
    }

    /// The JSON form.
    pub fn to_value(&self) -> Value {
        let mut m = vec![("args".to_string(), args_to_value(&self.args))];
        if let Some(a) = &self.asof {
            m.push(("asof".into(), Value::String(a.clone())));
        }
        m.push(("fn".into(), Value::String(self.fn_name.clone())));
        m.push(("ns".into(), Value::String(self.ns.clone())));
        Value::Object(m)
    }

    /// The canonical bytes (6.2).
    pub fn canonical(&self) -> Vec<u8> {
        self.to_value().to_jcs()
    }

    /// The cell this reference denotes once its function name has resolved to `fn_hash`.
    pub fn resolve(&self, fn_hash: &str) -> Result<Cell> {
        lexical::check_hex(fn_hash, 64, "$.fn_hash")?;
        Ok(Cell {
            ns: self.ns.clone(),
            fn_name: self.fn_name.clone(),
            fn_hash: fn_hash.into(),
            args: self.args.clone(),
        })
    }
}

/// A cell reference (4.3) with the optional pin of `spec-0.4.2`: `fn_hash`, the function the
/// reference is pinned to, whatever its name is bound to (5.1, 5.8). Unpinned, it is the
/// [`CellRef`] of `spec-0.4.1` ([`From<CellRef>`], [`Reference::to_cell_ref`]).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Reference {
    /// The namespace.
    pub ns: String,
    /// The function name within the namespace.
    pub fn_name: String,
    /// The arguments, typed by the function's signature.
    pub args: Args,
    /// The pin: the function hash the reference is pinned to, or `None`.
    pub fn_hash: Option<String>,
    /// The transaction time asked for; `None` means now.
    pub asof: Option<String>,
}

impl Reference {
    /// Parses a reference from JSON text: strict JSON, structure (`fn_hash` a string,
    /// `E_SCHEMA`), canonical form in JCS order (`args`, `asof`, `fn`, `fn_hash` as 64
    /// lowercase hex digits (`E_CANON_HEX`), `ns`), then the 512-character function name.
    pub fn from_json(bytes: &[u8]) -> Result<Reference> {
        let v = json::parse(bytes)?;
        json::check_value_depth(&v)?;
        let m = schema::object(&v, "$")?;
        schema::exact(m, &["args", "fn", "ns"], &["asof", "fn_hash"], "$", ErrorCode::Schema)?;
        args_structure(schema::get(m, "args"), "$.args")?;
        schema::string(m, "fn", "$")?;
        schema::string(m, "ns", "$")?;
        for o in ["asof", "fn_hash"] {
            if schema::opt(m, o).is_some() {
                schema::string(m, o, "$")?;
            }
        }
        let args = args_canonical(schema::get(m, "args"), "$.args")?;
        let asof = match schema::opt(m, "asof") {
            Some(Value::String(s)) => {
                lexical::check_instant(s, "$.asof")?;
                Some(s.clone())
            }
            _ => None,
        };
        let f = schema::string(m, "fn", "$")?;
        lexical::check_name(f, "$.fn")?;
        let fn_hash = match schema::opt(m, "fn_hash") {
            Some(Value::String(h)) => {
                lexical::check_hex(h, 64, "$.fn_hash")?;
                Some(h.clone())
            }
            _ => None,
        };
        let ns = schema::string(m, "ns", "$")?;
        lexical::check_namespace(ns, "$.ns")?;
        check_fn_length(ns, f)?;
        Ok(Reference { ns: ns.into(), fn_name: f.into(), args, fn_hash, asof })
    }

    /// A reference to `ns/fn_name` with these arguments, unpinned and as of now; set
    /// [`fn_hash`](Self::fn_hash) and [`asof`](Self::asof) to pin it or ask as of a time. Not
    /// checked: [`crate::format_reference`] writes what it is given.
    pub fn new(ns: impl Into<String>, fn_name: impl Into<String>, args: Args) -> Reference {
        Reference { ns: ns.into(), fn_name: fn_name.into(), args, fn_hash: None, asof: None }
    }

    /// The JSON form.
    pub fn to_value(&self) -> Value {
        let mut m = vec![("args".to_string(), args_to_value(&self.args))];
        if let Some(a) = &self.asof {
            m.push(("asof".into(), Value::String(a.clone())));
        }
        m.push(("fn".into(), Value::String(self.fn_name.clone())));
        if let Some(h) = &self.fn_hash {
            m.push(("fn_hash".into(), Value::String(h.clone())));
        }
        m.push(("ns".into(), Value::String(self.ns.clone())));
        Value::Object(m)
    }

    /// The canonical bytes (6.2). A pinned reference without `asof` has the canonical bytes,
    /// and so the id, of the cell it denotes.
    pub fn canonical(&self) -> Vec<u8> {
        self.to_value().to_jcs()
    }

    /// The cell a pinned reference denotes; `None` when it is not pinned (resolve its name
    /// with [`Reference::resolve`]).
    pub fn cell(&self) -> Option<Cell> {
        let h = self.fn_hash.as_ref()?;
        Some(Cell { ns: self.ns.clone(), fn_name: self.fn_name.clone(), fn_hash: h.clone(), args: self.args.clone() })
    }

    /// The cell this reference denotes once its name has resolved to `fn_hash`. A pinned
    /// reference denotes its pin's cell only: another hash is `E_FN_HASH_MISMATCH`.
    pub fn resolve(&self, fn_hash: &str) -> Result<Cell> {
        lexical::check_hex(fn_hash, 64, "$.fn_hash")?;
        if self.fn_hash.as_deref().is_some_and(|p| p != fn_hash) {
            return err(ErrorCode::FnHashMismatch, "$.fn_hash", "the reference is pinned to another function");
        }
        Ok(Cell {
            ns: self.ns.clone(),
            fn_name: self.fn_name.clone(),
            fn_hash: fn_hash.into(),
            args: self.args.clone(),
        })
    }

    /// The `spec-0.4.1` form, when the reference is not pinned.
    pub fn to_cell_ref(&self) -> Option<CellRef> {
        self.fn_hash.is_none().then(|| CellRef {
            ns: self.ns.clone(),
            fn_name: self.fn_name.clone(),
            args: self.args.clone(),
            asof: self.asof.clone(),
        })
    }
}

impl From<CellRef> for Reference {
    fn from(r: CellRef) -> Reference {
        Reference { ns: r.ns, fn_name: r.fn_name, args: r.args, fn_hash: None, asof: r.asof }
    }
}