1use 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
15const END: &str = "9999-12-31T23:59:59.999999Z";
17
18const MEMBERS: [&str; 6] = ["bundle", "descriptors", "manifest", "names", "namespace", "receipts"];
20
21#[non_exhaustive]
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub enum BundleError {
25 Format(String),
27 NotOwned(String),
29 Manifest(String),
32 Descriptor(String),
34 Receipt(String),
37 TxInFuture {
39 receipt: String,
41 tx: String,
43 now: String,
45 },
46 Bind(String),
48 Store(String),
50 Stopped(usize),
52 Reserved(String),
54 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#[non_exhaustive]
84#[derive(Clone, Debug, PartialEq, Eq)]
85pub struct Imported {
86 pub namespace: String,
88 pub functions_bound: usize,
90 pub receipts: usize,
92 pub versions: usize,
94 pub bound_at: String,
96}
97
98impl Imported {
99 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
128pub(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
149fn host_of(namespace: &str) -> &str {
151 namespace.split('/').next().unwrap_or("")
152}
153
154fn name_value(name: &str, fn_hash: &str) -> Value {
156 Value::Object(vec![("fn_hash".into(), s(fn_hash)), ("name".into(), s(name))])
157}
158
159pub fn manifest_bytes(namespace: &str, names: &[(String, String)], receipts: &[String]) -> Vec<u8> {
162 manifest_bytes_with(namespace, names, receipts, None, None, None)
163}
164
165fn 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
192struct Item {
194 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 fn is_computed(&self) -> bool {
236 self.receipt.as_ref().is_some_and(|r| !r.inputs().is_empty())
237 }
238}
239
240fn 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
248pub 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
262pub 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
286pub 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
302pub 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
381fn 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
388fn 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
393pub 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#[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
426pub(crate) enum Stage {
427 Proof,
428 All,
429}
430
431pub(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
444pub(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 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 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 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 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 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 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 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 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 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 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 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 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 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(); for (_, r) in &receipts {
738 let id = r.cell().id();
739 let tx = r.tx();
740 if let Some(v) = store.versions(&id, tx, tx).map_err(|e| BundleError::Store(e.to_string()))?.first() {
742 if v.receipt_hash != r.hash() {
743 return Err(BundleError::Store(format!("{id} has another version at {tx}")));
744 }
745 continue;
746 }
747 if let Some(l) = store.latest(&id).map_err(|e| BundleError::Store(e.to_string()))? {
748 if l.tx.as_str() >= tx {
749 return Err(BundleError::Store(format!("{id} has a version at or after {tx}")));
750 }
751 }
752 new_versions.push((id, tx.to_string(), r.hash().to_string()));
753 }
754
755 for name in &closes {
757 let bound = store.resolve_name(name, END).map_err(|e| BundleError::Store(e.to_string()))?.is_some()
758 || store.resolve_class(name, END).map_err(|e| BundleError::Store(e.to_string()))?.is_some();
759 if !bound {
760 return Err(BundleError::Format(format!(
761 "E_NAME_UNBOUND: close: {name} is not bound, so it cannot be closed"
762 )));
763 }
764 }
765 if let Some(doc) = keydoc_fetched {
769 let stored = store.namespace(ns_host).map_err(|e| BundleError::Store(e.to_string()))?.map(|n| n.keydoc);
770 if stored.as_deref() != Some(doc) {
771 store.put_namespace(ns_host, doc, &now).map_err(|e| BundleError::Store(e.to_string()))?;
772 }
773 }
774 let mut writes = 0usize;
777 let mut step = || -> Result<(), BundleError> {
778 writes += 1;
779 if stop_after == Some(writes) {
780 return Err(BundleError::Stopped(writes));
781 }
782 Ok(())
783 };
784 for db in descriptors.values() {
785 store.put_descriptor(db).map_err(|e| BundleError::Store(e.to_string()))?;
786 step()?;
787 }
788 for (rb, _) in &receipts {
789 store.put_receipt(rb).map_err(|e| BundleError::Store(e.to_string()))?;
790 step()?;
791 }
792 for (id, tx, h) in &new_versions {
793 store.put_version(id, tx, h).map_err(|e| BundleError::Store(e.to_string()))?;
794 step()?;
795 }
796 for (name, fh) in &binds {
797 store.bind_name(name, fh, &now).map_err(|e| BundleError::Bind(format!("{name}: {e}")))?;
798 step()?;
799 }
800 for name in &closes {
801 store.close_binding(name, &now).map_err(|e| BundleError::Store(format!("close {name}: {e}")))?;
802 step()?;
803 }
804 crate::testrun::apply_rows(store, &test_rows, &now).map_err(BundleError::Store)?;
805 let rebound: Vec<String> = binds.iter().map(|(n, _)| (*n).clone()).collect();
806 crate::testrun::rerun_readers(store, &rebound, &now).map_err(BundleError::Store)?;
807 let rebound: BTreeSet<String> = rebound.into_iter().collect();
809 let written_cells: Vec<(String, String)> =
810 receipts.iter().map(|(_, r)| (r.cell().function_name(), r.cell().id())).collect();
811 crate::testrun::rerun_stored_tests(store, &rebound, &written_cells, &now).map_err(BundleError::Store)?;
812 for (d, hash) in &catalog_entries {
814 let entry = d.entry(hash.clone(), datumesh_store::CatalogSource::Publisher, Some(key_id.clone()));
815 crate::catalog::store_publisher(
816 store,
817 &entry,
818 &d.dictionary,
819 &d.open_keys,
820 None,
821 &d.facets,
822 d.source_name.as_deref(),
823 )
824 .map_err(BundleError::Store)?;
825 }
826 let mut cell_values = BTreeSet::new();
827 for (_, r) in &receipts {
828 if let Some(valued) = &r.receipt {
829 crate::publish::cell_string_values(valued, &mut cell_values);
830 }
831 }
832 crate::publish::store_cell_values(store, cell_values).map_err(BundleError::Store)?;
833 Ok(Imported {
834 namespace,
835 functions_bound: binds.len(),
836 receipts: receipts.len(),
837 versions: new_versions.len(),
838 bound_at: now,
839 })
840}
841
842#[cfg(test)]
843mod tests {
844 use super::*;
845
846 #[test]
848 fn rfc8032_test_1() {
849 let seed: [u8; 32] =
850 unhex("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60").try_into().unwrap();
851 let sig = sign(&seed, b"");
852 assert_eq!(
853 to_hex(&sig),
854 "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"
855 );
856 }
857
858 #[test]
860 fn a_signature_verifies_under_the_seed_key() {
861 let seed = [7u8; 32];
862 let message = b"the manifest bytes";
863 let sig = sign(&seed, message);
864 let public = SigningKey::from_seed(&seed).public_key();
865 assert!(verify_ed25519(&public, message, &sig));
866 assert!(!verify_ed25519(&public, b"other bytes", &sig));
867 }
868}