Skip to main content

datumesh_http/
bundle.rs

1//! `bundle 1` (CONTRACT-1.8b H2, `docs/bundle-1.md`): a namespace's function descriptors, name
2//! bindings and signed receipts as one JSON object, with a manifest signed by the namespace's host
3//! (Ed25519, RFC 8032, over the JCS bytes of the names, the namespace and the receipt hashes).
4//! Operator format, not spec: the body of the plan-3.1 write endpoint and of `import-signed`.
5
6use std::collections::{BTreeMap, BTreeSet};
7
8use datumesh_core::json::{self, Value};
9use datumesh_core::{
10    keys_from_response, lexical::to_hex, verify, verify_ed25519, FunctionDescriptor, Keys, Receipt, SigningKey,
11};
12use datumesh_engine::Clock;
13use datumesh_store::Store;
14
15/// After every binding.
16const END: &str = "9999-12-31T23:59:59.999999Z";
17
18/// The members of a bundle, in JCS order. `catalog` is optional (CONTRACT-build2-part2-read R5).
19const MEMBERS: [&str; 6] = ["bundle", "descriptors", "manifest", "names", "namespace", "receipts"];
20
21/// Why a bundle is refused. The first failing check is reported; nothing is written unless all pass.
22#[non_exhaustive]
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub enum BundleError {
25    /// Not JSON, a missing or extra member, `bundle` not 1, a malformed hex, or an order not kept.
26    Format(String),
27    /// The namespace's host is neither the mesh's nor an owned one, or a name is not under the namespace.
28    NotOwned(String),
29    /// The manifest: no key of the namespace's host, the key's window does not hold now, or the
30    /// signature does not verify over the bundle's names and receipt hashes.
31    Manifest(String),
32    /// A descriptor that is not canonical, or a name whose descriptor is neither in the bundle nor stored.
33    Descriptor(String),
34    /// A receipt: computed (with inputs), not verifying against the namespace's key document, or
35    /// not for one of the bundle's names.
36    Receipt(String),
37    /// A receipt whose `tx` is later than the mesh clock.
38    TxInFuture {
39        /// The receipt's hash.
40        receipt: String,
41        /// Its `tx`.
42        tx: String,
43        /// The mesh clock.
44        now: String,
45    },
46    /// A name whose latest binding is at or after the clock.
47    Bind(String),
48    /// The store refused a read or a write (a cell with a later version, say).
49    Store(String),
50    /// A test hook (`import_signed_with`'s `stop_after`): stopped after this many writes.
51    Stopped(usize),
52    /// A name under a path the mesh reserves (`E_NAME_RESERVED`, CONTRACT-0.4.9 H8); the text starts with the code.
53    Reserved(String),
54    /// The public rule (Build 2 Part 3, D8): a computed function of the bundle is not covered by its
55    /// tests (`E_TESTS_MISSING`), or one of its tests fails (`E_TESTS_FAILING`). The text starts with
56    /// the code and lists them.
57    Tests(String),
58}
59
60impl std::fmt::Display for BundleError {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        match self {
63            BundleError::Format(s) => write!(f, "bundle format: {s}"),
64            BundleError::NotOwned(s) => write!(f, "not owned: {s}"),
65            BundleError::Reserved(s) => f.write_str(s),
66            BundleError::Manifest(s) => write!(f, "manifest: {s}"),
67            BundleError::Descriptor(s) => write!(f, "descriptor: {s}"),
68            BundleError::Receipt(s) => write!(f, "receipt: {s}"),
69            BundleError::TxInFuture { receipt, tx, now } => {
70                write!(f, "receipt {receipt}: tx {tx} is later than the mesh clock {now}")
71            }
72            BundleError::Bind(s) => write!(f, "binding: {s}"),
73            BundleError::Store(s) => write!(f, "store: {s}"),
74            BundleError::Stopped(n) => write!(f, "stopped after write {n}"),
75            BundleError::Tests(s) => write!(f, "tests: {s}"),
76        }
77    }
78}
79
80impl std::error::Error for BundleError {}
81
82/// What an import did.
83#[non_exhaustive]
84#[derive(Clone, Debug, PartialEq, Eq)]
85pub struct Imported {
86    /// The bundle's namespace.
87    pub namespace: String,
88    /// Names newly bound (a name already bound to its hash is not counted).
89    pub functions_bound: usize,
90    /// Receipts in the bundle (each is stored; putting one again is idempotent).
91    pub receipts: usize,
92    /// Versions newly added.
93    pub versions: usize,
94    /// The instant the names were bound at: the mesh clock.
95    pub bound_at: String,
96}
97
98impl Imported {
99    /// The result as one JCS object (the CLI prints this).
100    pub fn to_jcs(&self) -> Vec<u8> {
101        Value::Object(vec![
102            ("bound_at".into(), s(&self.bound_at)),
103            ("functions_bound".into(), number(self.functions_bound)),
104            ("namespace".into(), s(&self.namespace)),
105            ("receipts".into(), number(self.receipts)),
106            ("versions".into(), number(self.versions)),
107        ])
108        .to_jcs()
109    }
110}
111
112fn s(v: &str) -> Value {
113    Value::String(v.to_string())
114}
115
116fn number(n: usize) -> Value {
117    json::parse(n.to_string().as_bytes()).unwrap_or(Value::Null)
118}
119
120fn is_hex(text: &str, len: usize) -> bool {
121    text.len() == len && text.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
122}
123
124fn unhex(text: &str) -> Vec<u8> {
125    (0..text.len()).step_by(2).filter_map(|i| u8::from_str_radix(text.get(i..i + 2)?, 16).ok()).collect()
126}
127
128/// The bare-host namespace of the test cases (D20, spec-0.6.1 7.3): a bundle whose namespace is a
129/// host alone is accepted when it has at least one name and every name, and every catalogue entry,
130/// is `<host>/test_case`. Any other bundle of a bare host is a format error, as before.
131pub(crate) fn bare_host_test_cases(doc: &Value, namespace: &str) -> bool {
132    if namespace.is_empty() || namespace.contains('/') {
133        return false;
134    }
135    let want = format!("{namespace}/test_case");
136    let is_want = |v: &Value| v.get("name").and_then(Value::as_str) == Some(want.as_str());
137    let names_ok = match doc.get("names") {
138        Some(Value::Array(a)) => !a.is_empty() && a.iter().all(is_want),
139        _ => false,
140    };
141    let catalog_ok = match doc.get("catalog") {
142        None => true,
143        Some(Value::Array(a)) => a.iter().all(is_want),
144        Some(_) => false,
145    };
146    names_ok && catalog_ok
147}
148
149/// The host of a namespace: its first segment.
150fn host_of(namespace: &str) -> &str {
151    namespace.split('/').next().unwrap_or("")
152}
153
154/// The JSON of a name and its function hash, as the bundle and the manifest write it.
155fn name_value(name: &str, fn_hash: &str) -> Value {
156    Value::Object(vec![("fn_hash".into(), s(fn_hash)), ("name".into(), s(name))])
157}
158
159/// The bytes the manifest signs (CONTRACT-1.8b H2): the JCS object of the names (`(name, fn_hash)`,
160/// ascending by name), the namespace and the receipt hashes (ascending).
161pub fn manifest_bytes(namespace: &str, names: &[(String, String)], receipts: &[String]) -> Vec<u8> {
162    manifest_bytes_with(namespace, names, receipts, None, None, None)
163}
164
165/// As [`manifest_bytes`], and the catalogue member when the bundle has one (R5): the manifest signs
166/// the catalogue too, so a changed entry fails the signature.
167fn manifest_bytes_with(
168    namespace: &str,
169    names: &[(String, String)],
170    receipts: &[String],
171    catalog: Option<&Value>,
172    tests: Option<&Value>,
173    close: Option<&Value>,
174) -> Vec<u8> {
175    let mut members = vec![
176        ("names".into(), Value::Array(names.iter().map(|(n, h)| name_value(n, h)).collect())),
177        ("namespace".into(), s(namespace)),
178        ("receipts".into(), Value::Array(receipts.iter().map(|h| s(h)).collect())),
179    ];
180    if let Some(c) = close {
181        members.push(("close".into(), c.clone()));
182    }
183    if let Some(c) = catalog {
184        members.push(("catalog".into(), c.clone()));
185    }
186    if let Some(t) = tests {
187        members.push(("tests".into(), t.clone()));
188    }
189    Value::Object(members).to_jcs()
190}
191
192/// A bundle's receipt as the import reads it: a valued receipt, or a withdrawal, which has no value (R1).
193struct Item {
194    /// The valued receipt; `None` for a withdrawal.
195    receipt: Option<Receipt>,
196    hash: String,
197    tx: String,
198    cell: datumesh_core::Cell,
199}
200
201impl Item {
202    fn parse(bytes: &[u8]) -> Result<Item, String> {
203        match Receipt::from_json(bytes) {
204            Ok(r) => Ok(Item {
205                hash: r.hash().to_string(),
206                tx: r.tx().to_string(),
207                cell: r.cell().clone(),
208                receipt: Some(r),
209            }),
210            Err(e) => match datumesh_core::Withdrawal::from_json(bytes) {
211                Ok(w) => Ok(Item {
212                    hash: w.hash().to_string(),
213                    tx: w.tx().to_string(),
214                    cell: w.cell().clone(),
215                    receipt: None,
216                }),
217                Err(_) => Err(e.to_string()),
218            },
219        }
220    }
221
222    fn hash(&self) -> &str {
223        &self.hash
224    }
225
226    fn tx(&self) -> &str {
227        &self.tx
228    }
229
230    fn cell(&self) -> &datumesh_core::Cell {
231        &self.cell
232    }
233
234    /// A computed receipt has inputs; a withdrawal never does.
235    fn is_computed(&self) -> bool {
236        self.receipt.as_ref().is_some_and(|r| !r.inputs().is_empty())
237    }
238}
239
240/// Ed25519 (RFC 8032) over `message` with the key of `seed`, by `ed25519-dalek`: the signature
241/// `R || S`. The public key and key id are those of `SigningKey::from_seed(seed)`; the import
242/// verifies with core's `verify_ed25519`, the strict rules of receipt verification.
243fn sign(seed: &[u8; 32], message: &[u8]) -> [u8; 64] {
244    use ed25519_dalek::Signer;
245    ed25519_dalek::SigningKey::from_bytes(seed).sign(message).to_bytes()
246}
247
248/// Builds a bundle 1 (see the module documentation): `descriptors` (each a canonical function
249/// descriptor), `names` (`(name, fn_hash)`), `receipts` (each a receipt's JSON), signed with the
250/// key of `seed` as the manifest of `namespace`. The names and the receipts are put in ascending
251/// order. Errors: `Format` for a receipt or descriptor that does not parse.
252pub fn build(
253    namespace: &str,
254    descriptors: Vec<Vec<u8>>,
255    names: Vec<(String, String)>,
256    receipts: Vec<Vec<u8>>,
257    seed: &[u8; 32],
258) -> Result<Vec<u8>, BundleError> {
259    build_with_catalog(namespace, descriptors, names, receipts, Vec::new(), seed)
260}
261
262/// As [`build_with_catalog`], with the bundle's tests (Build 2 Part 3, E5): `tests` are the test
263/// objects of `test` lines (each `{"test", "call", "asof"?, "inputs"?, "expect"}`), sorted by function
264/// name then by case id into the bundle's `tests` member, which the manifest signs. No tests make a
265/// bundle without the member. Errors: `Format` for a test that is not a test.
266pub fn build_with_tests(
267    namespace: &str,
268    descriptors: Vec<Vec<u8>>,
269    names: Vec<(String, String)>,
270    receipts: Vec<Vec<u8>>,
271    catalog: Vec<Vec<u8>>,
272    tests: Vec<Vec<u8>>,
273    seed: &[u8; 32],
274) -> Result<Vec<u8>, BundleError> {
275    let mut entries: Vec<(String, String, Value)> = Vec::new();
276    for t in tests {
277        let v = json::parse(&t).map_err(|e| BundleError::Format(format!("test: {e}")))?;
278        let spec = crate::testrun::parse_test(&v).map_err(|e| BundleError::Format(format!("test: {e}")))?;
279        entries.push((spec.function.clone(), spec.case.clone(), v));
280    }
281    entries.sort_by(|a, b| (a.0.as_str(), a.1.as_str()).cmp(&(b.0.as_str(), b.1.as_str())));
282    let tests_value = (!entries.is_empty()).then(|| Value::Array(entries.into_iter().map(|(_, _, v)| v).collect()));
283    build_inner(namespace, descriptors, names, receipts, catalog, tests_value, Vec::new(), seed)
284}
285
286/// As [`build`], with the publisher's catalogue (CONTRACT-build2-part2-read R5): `catalog` is a list
287/// of entries `{"name", "kind", "label", "description", "args", "examples", "dictionary"}` (each a
288/// JSON object), checked as a publish's catalogue lines are, and sorted by name into the bundle's
289/// `catalog` member, which the manifest signs. An empty list makes a bundle without the member.
290/// Errors: `Format` for an entry that breaks its bounds.
291pub fn build_with_catalog(
292    namespace: &str,
293    descriptors: Vec<Vec<u8>>,
294    names: Vec<(String, String)>,
295    receipts: Vec<Vec<u8>>,
296    catalog: Vec<Vec<u8>>,
297    seed: &[u8; 32],
298) -> Result<Vec<u8>, BundleError> {
299    build_inner(namespace, descriptors, names, receipts, catalog, None, Vec::new(), seed)
300}
301
302/// As [`build`], with the bundle's closed names (R2, SPEC 9.7): `close` lists full names, sorted into the bundle's
303/// `close` member, which the manifest signs. Each is ended at the importing mesh's clock (`import`); a name that is
304/// not bound there is refused, and nothing is written. An empty list makes a bundle without the member.
305pub fn build_with_close(
306    namespace: &str,
307    descriptors: Vec<Vec<u8>>,
308    names: Vec<(String, String)>,
309    receipts: Vec<Vec<u8>>,
310    close: Vec<String>,
311    seed: &[u8; 32],
312) -> Result<Vec<u8>, BundleError> {
313    build_inner(namespace, descriptors, names, receipts, Vec::new(), None, close, seed)
314}
315
316#[allow(clippy::too_many_arguments)]
317fn build_inner(
318    namespace: &str,
319    descriptors: Vec<Vec<u8>>,
320    names: Vec<(String, String)>,
321    receipts: Vec<Vec<u8>>,
322    catalog: Vec<Vec<u8>>,
323    tests: Option<Value>,
324    mut close: Vec<String>,
325    seed: &[u8; 32],
326) -> Result<Vec<u8>, BundleError> {
327    close.sort();
328    close.dedup();
329    let close_value = (!close.is_empty()).then(|| Value::Array(close.iter().map(|c| s(c)).collect()));
330    let mut catalog_entries: Vec<(String, Value)> = Vec::new();
331    for c in catalog {
332        let v = json::parse(&c).map_err(|e| BundleError::Format(format!("catalog: {e}")))?;
333        let d = crate::catalog::parse(&v, "name").map_err(|e| BundleError::Format(format!("catalog: {e}")))?;
334        catalog_entries.push((d.name.clone(), v));
335    }
336    catalog_entries.sort_by(|a, b| a.0.cmp(&b.0));
337    let catalog_value =
338        (!catalog_entries.is_empty()).then(|| Value::Array(catalog_entries.into_iter().map(|(_, v)| v).collect()));
339    let mut names = names;
340    names.sort();
341    let mut signed: Vec<(String, Value)> = Vec::new();
342    for r in receipts {
343        let hash = Item::parse(&r).map_err(|e| BundleError::Format(format!("receipt: {e}")))?.hash().to_string();
344        let v = json::parse(&r).map_err(|e| BundleError::Format(format!("receipt: {e}")))?;
345        signed.push((hash, v));
346    }
347    signed.sort_by(|a, b| a.0.cmp(&b.0));
348    let hashes: Vec<String> = signed.iter().map(|(h, _)| h.clone()).collect();
349    let sig = sign(
350        seed,
351        &manifest_bytes_with(namespace, &names, &hashes, catalog_value.as_ref(), tests.as_ref(), close_value.as_ref()),
352    );
353    let key = SigningKey::from_seed(seed);
354    let descriptors = descriptors
355        .iter()
356        .map(|d| json::parse(d).map_err(|e| BundleError::Format(format!("descriptor: {e}"))))
357        .collect::<Result<Vec<Value>, _>>()?;
358    let mut members = vec![("bundle".into(), number(1))];
359    if let Some(c) = close_value {
360        members.push(("close".into(), c));
361    }
362    if let Some(c) = catalog_value {
363        members.push(("catalog".into(), c));
364    }
365    if let Some(t) = tests {
366        members.push(("tests".into(), t));
367    }
368    members.extend([
369        ("descriptors".into(), Value::Array(descriptors)),
370        (
371            "manifest".into(),
372            Value::Object(vec![("key_id".into(), s(key.key_id())), ("signature".into(), s(&to_hex(&sig)))]),
373        ),
374        ("names".into(), Value::Array(names.iter().map(|(n, h)| name_value(n, h)).collect())),
375        ("namespace".into(), s(namespace)),
376        ("receipts".into(), Value::Array(signed.into_iter().map(|(_, v)| v).collect())),
377    ]);
378    Ok(Value::Object(members).to_jcs())
379}
380
381/// The keys of an object's members, sorted.
382fn member_names(v: &Value) -> Option<Vec<&str>> {
383    let mut keys: Vec<&str> = v.as_object()?.iter().map(|(k, _)| k.as_str()).collect();
384    keys.sort_unstable();
385    Some(keys)
386}
387
388/// A string member of `v`, or a format error.
389fn text<'a>(v: &'a Value, key: &str) -> Result<&'a str, BundleError> {
390    v.get(key).and_then(Value::as_str).ok_or_else(|| BundleError::Format(format!("{key} is not a string")))
391}
392
393/// Imports the bundle `bytes` for the mesh `host`, whose own namespaces are `owned`, at the clock's
394/// now (CONTRACT-1.8b H2). Checks run in the order of the contract, and nothing is written unless
395/// they all pass. The writes are, in order: the descriptors; the receipts (each `put_receipt`), then
396/// the versions (each `put_version`); the name bindings last, so that a crash part-way leaves no
397/// name answering. A re-run completes a partial import: a version or a binding already there is
398/// skipped.
399pub fn import_signed<S: Store + ?Sized>(
400    store: &S,
401    host: &str,
402    owned: &[String],
403    clock: &dyn Clock,
404    bytes: &[u8],
405) -> Result<Imported, BundleError> {
406    import_signed_with(store, host, owned, clock, bytes, None)
407}
408
409/// As [`import_signed`], with a test hook (`#[doc(hidden)]`): with `stop_after` `Some(n)` the import
410/// stops with [`BundleError::Stopped`]`(n)` after its `n`-th write (each `put_descriptor`,
411/// `put_receipt`, `put_version` and `bind_name` counts as one), to test that a re-run completes it.
412#[doc(hidden)]
413pub fn import_signed_with<S: Store + ?Sized>(
414    store: &S,
415    host: &str,
416    owned: &[String],
417    clock: &dyn Clock,
418    bytes: &[u8],
419    stop_after: Option<usize>,
420) -> Result<Imported, BundleError> {
421    import_with(store, host, owned, clock, bytes, None, stop_after, Stage::All)
422}
423
424/// How far an import goes: the domain proof only (`POST /bundles`'s first two checks), or all of it.
425#[derive(Clone, Copy, Debug, PartialEq, Eq)]
426pub(crate) enum Stage {
427    Proof,
428    All,
429}
430
431/// The domain proof of a bundle (Build 2 Part 4, P1, checks 1 and 2): the bundle parses, every name
432/// and catalogue entry is under its namespace, and its manifest is signed by a key of `keydoc` (the
433/// publisher's key document, as fetched) that holds now. Writes nothing.
434pub(crate) fn prove<S: Store + ?Sized>(
435    store: &S,
436    host: &str,
437    clock: &dyn Clock,
438    bytes: &[u8],
439    keydoc: &[u8],
440) -> Result<(), BundleError> {
441    import_with(store, host, &[], clock, bytes, Some(keydoc), None, Stage::Proof).map(|_| ())
442}
443
444/// The import of a bundle whose publisher's key document is `keydoc` (fetched for the request) or,
445/// when `None`, the store's record of its namespace's host. `owned` are the hosts that may publish
446/// here besides `host`.
447pub(crate) fn import_published<S: Store + ?Sized>(
448    store: &S,
449    host: &str,
450    owned: &[String],
451    clock: &dyn Clock,
452    bytes: &[u8],
453    keydoc: Option<&[u8]>,
454) -> Result<Imported, BundleError> {
455    import_with(store, host, owned, clock, bytes, keydoc, None, Stage::All)
456}
457
458#[allow(clippy::too_many_arguments)]
459fn import_with<S: Store + ?Sized>(
460    store: &S,
461    host: &str,
462    owned: &[String],
463    clock: &dyn Clock,
464    bytes: &[u8],
465    keydoc: Option<&[u8]>,
466    stop_after: Option<usize>,
467    stage: Stage,
468) -> Result<Imported, BundleError> {
469    let now = clock.now();
470    let doc = json::parse(bytes).map_err(|e| BundleError::Format(format!("not JSON: {e}")))?;
471
472    // 1. Format.
473    let mut keys = member_names(&doc).ok_or_else(|| BundleError::Format("not an object".into()))?;
474    keys.sort_unstable();
475    let has_catalog = keys.contains(&"catalog");
476    let has_tests = keys.contains(&"tests");
477    let has_close = keys.contains(&"close");
478    keys.retain(|k| *k != "catalog" && *k != "tests" && *k != "close");
479    let mut want = MEMBERS;
480    want.sort_unstable();
481    if keys != want {
482        return Err(BundleError::Format("the members are not exactly those of a bundle".into()));
483    }
484    if doc.get("bundle").and_then(Value::as_number_text) != Some("1") {
485        return Err(BundleError::Format("bundle is not 1".into()));
486    }
487    let namespace = text(&doc, "namespace")?.to_string();
488    if namespace.split('/').count() < 2 && !bare_host_test_cases(&doc, &namespace) {
489        return Err(BundleError::Format("namespace has no host and name".into()));
490    }
491    let manifest = doc.get("manifest").ok_or_else(|| BundleError::Format("no manifest".into()))?;
492    if member_names(manifest) != Some(vec!["key_id", "signature"]) {
493        return Err(BundleError::Format("the manifest's members are not key_id and signature".into()));
494    }
495    let key_id = text(manifest, "key_id")?.to_string();
496    let signature = text(manifest, "signature")?.to_string();
497    if !is_hex(&key_id, 16) || !is_hex(&signature, 128) {
498        return Err(BundleError::Format("the manifest's key_id or signature is not hex".into()));
499    }
500    let mut names: Vec<(String, String)> = Vec::new();
501    let Some(Value::Array(name_vs)) = doc.get("names") else {
502        return Err(BundleError::Format("names is not an array".into()));
503    };
504    for n in name_vs {
505        if member_names(n) != Some(vec!["fn_hash", "name"]) {
506            return Err(BundleError::Format("a name's members are not fn_hash and name".into()));
507        }
508        let fh = text(n, "fn_hash")?;
509        if !is_hex(fh, 64) {
510            return Err(BundleError::Format(format!("fn_hash {fh} is not 64 hex digits")));
511        }
512        names.push((text(n, "name")?.to_string(), fh.to_string()));
513    }
514    if names.windows(2).any(|w| w[0].0 >= w[1].0) {
515        return Err(BundleError::Format("names are not in ascending order".into()));
516    }
517    let Some(Value::Array(desc_vs)) = doc.get("descriptors") else {
518        return Err(BundleError::Format("descriptors is not an array".into()));
519    };
520    let Some(Value::Array(receipt_vs)) = doc.get("receipts") else {
521        return Err(BundleError::Format("receipts is not an array".into()));
522    };
523    // (the JCS bytes of the receipt, the receipt): a valued receipt, or a withdrawal (SPEC 8.1, R1)
524    let mut receipts: Vec<(Vec<u8>, Item)> = Vec::new();
525    for r in receipt_vs {
526        let rb = r.to_jcs();
527        let parsed = Item::parse(&rb).map_err(|e| BundleError::Receipt(format!("unreadable: {e}")))?;
528        receipts.push((rb, parsed));
529    }
530    if receipts.windows(2).any(|w| w[0].1.hash() >= w[1].1.hash()) {
531        return Err(BundleError::Format("receipts are not in ascending order of their hashes".into()));
532    }
533    let hashes: Vec<String> = receipts.iter().map(|(_, r)| r.hash().to_string()).collect();
534    // The catalogue (R5): each entry checked as a publish's line is; a function's hash is its name's.
535    let mut catalog_entries: Vec<(crate::catalog::Described, Option<String>)> = Vec::new();
536    let catalog_doc = if has_catalog { doc.get("catalog").cloned() } else { None };
537    if let Some(Value::Array(items)) = &catalog_doc {
538        for item in items {
539            let d = crate::catalog::parse(item, "name").map_err(|e| BundleError::Format(format!("catalog: {e}")))?;
540            if d.extends.is_some() {
541                // `extends` is checked by publish (K9); a bundle's catalogue does not take it yet.
542                return Err(BundleError::Format(format!(
543                    "catalog: {} extends a class: not accepted in a bundle",
544                    d.name
545                )));
546            }
547            let hash =
548                match d.kind {
549                    datumesh_store::CatalogKind::Class => None,
550                    _ => {
551                        Some(names.iter().find(|(n, _)| *n == d.name).map(|(_, h)| h.clone()).ok_or_else(|| {
552                            BundleError::Format(format!("catalog: {} is not among the names", d.name))
553                        })?)
554                    }
555                };
556            catalog_entries.push((d, hash));
557        }
558    } else if has_catalog {
559        return Err(BundleError::Format("catalog is not an array".into()));
560    }
561
562    // 2. NotOwned.
563    let ns_host = host_of(&namespace);
564    if stage == Stage::All && ns_host != host && !owned.iter().any(|o| o == ns_host) {
565        return Err(BundleError::NotOwned(format!("{ns_host} is neither this mesh's host nor owned")));
566    }
567    if let Some((n, _)) = names.iter().find(|(n, _)| !n.starts_with(&format!("{namespace}/"))) {
568        return Err(BundleError::NotOwned(format!("{n} is not under {namespace}/")));
569    }
570    if let Some((d, _)) = catalog_entries.iter().find(|(d, _)| !d.name.starts_with(&format!("{namespace}/"))) {
571        return Err(BundleError::NotOwned(format!("catalog: {} is not under {namespace}/", d.name)));
572    }
573    // The reserved paths (H8). The mesh's own import (no key document fetched for the request) takes no key
574    // namespace's name; `POST /bundles` checks its own signer before it gets here.
575    if keydoc.is_none() {
576        for n in names.iter().map(|(n, _)| n).chain(catalog_entries.iter().map(|(d, _)| &d.name)) {
577            crate::reserved::check(host, n, None).map_err(BundleError::Reserved)?;
578        }
579    }
580
581    // 3. Manifest: the key of the namespace's host, valid now, signing the bundle's names and receipts.
582    let keydoc_fetched = keydoc;
583    let keydoc = match keydoc {
584        Some(d) => d.to_vec(),
585        None => {
586            store
587                .namespace(ns_host)
588                .map_err(|e| BundleError::Store(e.to_string()))?
589                .ok_or_else(|| BundleError::Manifest(format!("the store holds no key document of {ns_host}")))?
590                .keydoc
591        }
592    };
593    let kd = keys_from_response(ns_host, 200, Some(&keydoc)).map_err(|e| BundleError::Manifest(e.to_string()))?;
594    let key = kd
595        .key(&key_id)
596        .ok_or_else(|| BundleError::Manifest(format!("key {key_id} is not in the key document of {ns_host}")))?;
597    if !key.usable_at(&now) {
598        return Err(BundleError::Manifest(format!("key {key_id} does not hold at {now}")));
599    }
600    let mut keys_set = Keys::new();
601    keys_set.insert(kd.clone());
602    let sig: [u8; 64] = unhex(&signature).try_into().map_err(|_| BundleError::Format("signature length".into()))?;
603    let tests_doc = if has_tests { doc.get("tests").cloned() } else { None };
604    if tests_doc.as_ref().is_some_and(|t| !matches!(t, Value::Array(_))) {
605        return Err(BundleError::Format("tests is not an array".into()));
606    }
607    // The closed names (R2): strings under the namespace, signed with the manifest like the rest.
608    let close_doc = if has_close { doc.get("close").cloned() } else { None };
609    let closes: Vec<String> = match &close_doc {
610        Some(Value::Array(items)) => items
611            .iter()
612            .map(|c| match c {
613                Value::String(name) if name.starts_with(&format!("{namespace}/")) => Ok(name.clone()),
614                Value::String(name) => Err(BundleError::NotOwned(format!("close: {name} is not under {namespace}/"))),
615                _ => Err(BundleError::Format("close: a name is a string".into())),
616            })
617            .collect::<Result<_, _>>()?,
618        Some(_) => return Err(BundleError::Format("close is not an array".into())),
619        None => Vec::new(),
620    };
621    if !verify_ed25519(
622        &key.public,
623        &manifest_bytes_with(&namespace, &names, &hashes, catalog_doc.as_ref(), tests_doc.as_ref(), close_doc.as_ref()),
624        &sig,
625    ) {
626        return Err(BundleError::Manifest("the signature does not verify".into()));
627    }
628    if stage == Stage::Proof {
629        return Ok(Imported { namespace, functions_bound: 0, receipts: 0, versions: 0, bound_at: now });
630    }
631
632    // 4. Descriptor.
633    let mut descriptors: BTreeMap<String, Vec<u8>> = BTreeMap::new();
634    for d in desc_vs {
635        let db = d.to_jcs();
636        let fd = FunctionDescriptor::from_json(&db).map_err(|e| BundleError::Descriptor(e.to_string()))?;
637        if fd.canonical() != db {
638            return Err(BundleError::Descriptor("a descriptor is not canonical".into()));
639        }
640        descriptors.insert(fd.hash(), db);
641    }
642    for (name, fh) in &names {
643        if !descriptors.contains_key(fh) && store.descriptor(fh).is_none() {
644            return Err(BundleError::Descriptor(format!(
645                "{name}: descriptor {fh} is neither in the bundle nor stored"
646            )));
647        }
648    }
649
650    // 5. Receipt.
651    for (rb, r) in &receipts {
652        if r.is_computed() {
653            return Err(BundleError::Receipt(format!("{}: a computed receipt is not imported", r.hash())));
654        }
655        let fname = r.cell().function_name();
656        let Some((_, fh)) = names.iter().find(|(n, _)| *n == fname) else {
657            return Err(BundleError::Receipt(format!("{}: {fname} is not among the names", r.hash())));
658        };
659        if r.cell().fn_hash != *fh {
660            return Err(BundleError::Receipt(format!("{}: the function hash differs from {fname}'s", r.hash())));
661        }
662        let out = verify(rb, &keys_set, None, None);
663        if !out.ok {
664            let why = out.error().map(|e| e.to_string()).unwrap_or_else(|| "does not verify".into());
665            return Err(BundleError::Receipt(format!("{}: {why}", r.hash())));
666        }
667    }
668
669    // 6. TxInFuture.
670    for (_, r) in &receipts {
671        if r.tx() > now.as_str() {
672            return Err(BundleError::TxInFuture {
673                receipt: r.hash().to_string(),
674                tx: r.tx().to_string(),
675                now: now.clone(),
676            });
677        }
678    }
679
680    // The public rule (D8): every computed function of the bundle is covered by its tests, and they pass.
681    let mut overlay = crate::testrun::Overlay::default();
682    for (name, fh) in &names {
683        overlay.functions.entry(name.clone()).or_default().push((now.clone(), fh.clone()));
684    }
685    for (fh, db) in &descriptors {
686        overlay.descriptors.insert(fh.clone(), db.clone());
687    }
688    for (rb, _) in &receipts {
689        overlay.cell(rb).map_err(BundleError::Receipt)?;
690    }
691    let mut formulas = Vec::new();
692    for (name, fh) in &names {
693        let bytes = match descriptors.get(fh) {
694            Some(b) => Some(b.clone()),
695            None => store.descriptor(fh).map(|b| b.into_owned()),
696        };
697        let Some(bytes) = bytes else { continue };
698        let fd = FunctionDescriptor::from_json(&bytes).map_err(|e| BundleError::Descriptor(e.to_string()))?;
699        if fd.lang != "stored" {
700            formulas.push((0usize, name.clone(), fh.clone()));
701        }
702    }
703    let mut test_specs = Vec::new();
704    for (i, t) in tests_doc
705        .iter()
706        .flat_map(|v| match v {
707            Value::Array(a) => a.iter().collect::<Vec<_>>(),
708            _ => Vec::new(),
709        })
710        .enumerate()
711    {
712        let spec = crate::testrun::parse_test(t).map_err(|e| BundleError::Format(format!("test: {e}")))?;
713        test_specs.push((i + 1, spec));
714    }
715    let test_rows =
716        crate::publish::check_tests(store, &overlay, &test_specs, &formulas, host, &now, true).map_err(|e| {
717            let code = match e.kind {
718                crate::publish::PublishErrorKind::TestsFailing(_) => "E_TESTS_FAILING",
719                crate::publish::PublishErrorKind::TestsMissing(_) => "E_TESTS_MISSING",
720                _ => "E_BUNDLE_TESTS",
721            };
722            BundleError::Tests(format!("{code}: {}", e.detail))
723        })?;
724    // Plan: the binds, and the versions not already there; a conflict is refused before any write.
725    let mut binds: Vec<&(String, String)> = Vec::new();
726    for pair in &names {
727        let (name, fh) = pair;
728        match store.resolve_binding(name, END).map_err(|e| BundleError::Store(e.to_string()))? {
729            Some(b) if b.fn_hash == *fh => {}
730            Some(b) if b.tx.as_str() >= now.as_str() => {
731                return Err(BundleError::Bind(format!("{name} is bound from {} (at or after the clock)", b.tx)));
732            }
733            _ => binds.push(pair),
734        }
735    }
736    let mut new_versions: Vec<(String, String, String)> = Vec::new(); // (cell id, tx, receipt hash)
737    for (_, r) in &receipts {
738        let id = r.cell().id();
739        let tx = r.tx();
740        match store.version_asof(&id, tx).map_err(|e| BundleError::Store(e.to_string()))? {
741            Some(v) if v.tx == tx => {
742                if v.receipt_hash != r.hash() {
743                    return Err(BundleError::Store(format!("{id} has another version at {tx}")));
744                }
745                continue;
746            }
747            _ => {}
748        }
749        if let Some(l) = store.latest(&id).map_err(|e| BundleError::Store(e.to_string()))? {
750            if l.tx.as_str() >= tx {
751                return Err(BundleError::Store(format!("{id} has a version at or after {tx}")));
752            }
753        }
754        new_versions.push((id, tx.to_string(), r.hash().to_string()));
755    }
756
757    // A closed name must be bound (R2): checked before anything is written, so a refused bundle writes nothing.
758    for name in &closes {
759        let bound = store.resolve_name(name, END).map_err(|e| BundleError::Store(e.to_string()))?.is_some()
760            || store.resolve_class(name, END).map_err(|e| BundleError::Store(e.to_string()))?.is_some();
761        if !bound {
762            return Err(BundleError::Format(format!(
763                "E_NAME_UNBOUND: close: {name} is not bound, so it cannot be closed"
764            )));
765        }
766    }
767    // The publisher's key document, as fetched for this request, is the namespace's record before its
768    // receipts are written (the store checks each receipt's signer against it): written after every
769    // check has passed, as the bundle's first write.
770    if let Some(doc) = keydoc_fetched {
771        let stored = store.namespace(ns_host).map_err(|e| BundleError::Store(e.to_string()))?.map(|n| n.keydoc);
772        if stored.as_deref() != Some(doc) {
773            store.put_namespace(ns_host, doc, &now).map_err(|e| BundleError::Store(e.to_string()))?;
774        }
775    }
776    // Writes: descriptors, receipts, versions, then the bindings (a version without its binding is
777    // not answered, so a crash before the bindings leaves nothing answerable).
778    let mut writes = 0usize;
779    let mut step = || -> Result<(), BundleError> {
780        writes += 1;
781        if stop_after == Some(writes) {
782            return Err(BundleError::Stopped(writes));
783        }
784        Ok(())
785    };
786    for db in descriptors.values() {
787        store.put_descriptor(db).map_err(|e| BundleError::Store(e.to_string()))?;
788        step()?;
789    }
790    for (rb, _) in &receipts {
791        store.put_receipt(rb).map_err(|e| BundleError::Store(e.to_string()))?;
792        step()?;
793    }
794    for (id, tx, h) in &new_versions {
795        store.put_version(id, tx, h).map_err(|e| BundleError::Store(e.to_string()))?;
796        step()?;
797    }
798    for (name, fh) in &binds {
799        store.bind_name(name, fh, &now).map_err(|e| BundleError::Bind(format!("{name}: {e}")))?;
800        step()?;
801    }
802    for name in &closes {
803        store.close_binding(name, &now).map_err(|e| BundleError::Store(format!("close {name}: {e}")))?;
804        step()?;
805    }
806    crate::testrun::apply_rows(store, &test_rows, &now).map_err(BundleError::Store)?;
807    let rebound: Vec<String> = binds.iter().map(|(n, _)| (*n).clone()).collect();
808    crate::testrun::rerun_readers(store, &rebound, &now).map_err(BundleError::Store)?;
809    // The stored functions' tests read the cells this bundle writes, and the names it rebinds (F2).
810    let rebound: BTreeSet<String> = rebound.into_iter().collect();
811    let written_cells: Vec<(String, String)> =
812        receipts.iter().map(|(_, r)| (r.cell().function_name(), r.cell().id())).collect();
813    crate::testrun::rerun_stored_tests(store, &rebound, &written_cells, &now).map_err(BundleError::Store)?;
814    // The publisher's catalogue (R5), signed by this bundle's key; then the values of the cells (R3).
815    for (d, hash) in &catalog_entries {
816        let entry = d.entry(hash.clone(), datumesh_store::CatalogSource::Publisher, Some(key_id.clone()));
817        crate::catalog::store_publisher(
818            store,
819            &entry,
820            &d.dictionary,
821            &d.open_keys,
822            None,
823            &d.facets,
824            d.source_name.as_deref(),
825        )
826        .map_err(BundleError::Store)?;
827    }
828    let mut cell_values = BTreeSet::new();
829    for (_, r) in &receipts {
830        if let Some(valued) = &r.receipt {
831            crate::publish::cell_string_values(valued, &mut cell_values);
832        }
833    }
834    crate::publish::store_cell_values(store, cell_values).map_err(BundleError::Store)?;
835    Ok(Imported {
836        namespace,
837        functions_bound: binds.len(),
838        receipts: receipts.len(),
839        versions: new_versions.len(),
840        bound_at: now,
841    })
842}
843
844#[cfg(test)]
845mod tests {
846    use super::*;
847
848    /// RFC 8032 section 7.1, test 1: the empty message.
849    #[test]
850    fn rfc8032_test_1() {
851        let seed: [u8; 32] =
852            unhex("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60").try_into().unwrap();
853        let sig = sign(&seed, b"");
854        assert_eq!(
855            to_hex(&sig),
856            "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"
857        );
858    }
859
860    /// A signature over some bytes verifies with core's strict verification, under the key of the seed.
861    #[test]
862    fn a_signature_verifies_under_the_seed_key() {
863        let seed = [7u8; 32];
864        let message = b"the manifest bytes";
865        let sig = sign(&seed, message);
866        let public = SigningKey::from_seed(&seed).public_key();
867        assert!(verify_ed25519(&public, message, &sig));
868        assert!(!verify_ed25519(&public, b"other bytes", &sig));
869    }
870}