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)
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) -> Vec<u8> {
174 let mut members = vec![
175 ("names".into(), Value::Array(names.iter().map(|(n, h)| name_value(n, h)).collect())),
176 ("namespace".into(), s(namespace)),
177 ("receipts".into(), Value::Array(receipts.iter().map(|h| s(h)).collect())),
178 ];
179 if let Some(c) = catalog {
180 members.push(("catalog".into(), c.clone()));
181 }
182 if let Some(t) = tests {
183 members.push(("tests".into(), t.clone()));
184 }
185 Value::Object(members).to_jcs()
186}
187
188fn sign(seed: &[u8; 32], message: &[u8]) -> [u8; 64] {
192 use ed25519_dalek::Signer;
193 ed25519_dalek::SigningKey::from_bytes(seed).sign(message).to_bytes()
194}
195
196pub fn build(
201 namespace: &str,
202 descriptors: Vec<Vec<u8>>,
203 names: Vec<(String, String)>,
204 receipts: Vec<Vec<u8>>,
205 seed: &[u8; 32],
206) -> Result<Vec<u8>, BundleError> {
207 build_with_catalog(namespace, descriptors, names, receipts, Vec::new(), seed)
208}
209
210pub fn build_with_tests(
215 namespace: &str,
216 descriptors: Vec<Vec<u8>>,
217 names: Vec<(String, String)>,
218 receipts: Vec<Vec<u8>>,
219 catalog: Vec<Vec<u8>>,
220 tests: Vec<Vec<u8>>,
221 seed: &[u8; 32],
222) -> Result<Vec<u8>, BundleError> {
223 let mut entries: Vec<(String, String, Value)> = Vec::new();
224 for t in tests {
225 let v = json::parse(&t).map_err(|e| BundleError::Format(format!("test: {e}")))?;
226 let spec = crate::testrun::parse_test(&v).map_err(|e| BundleError::Format(format!("test: {e}")))?;
227 entries.push((spec.function.clone(), spec.case.clone(), v));
228 }
229 entries.sort_by(|a, b| (a.0.as_str(), a.1.as_str()).cmp(&(b.0.as_str(), b.1.as_str())));
230 let tests_value = (!entries.is_empty()).then(|| Value::Array(entries.into_iter().map(|(_, _, v)| v).collect()));
231 build_inner(namespace, descriptors, names, receipts, catalog, tests_value, seed)
232}
233
234pub fn build_with_catalog(
240 namespace: &str,
241 descriptors: Vec<Vec<u8>>,
242 names: Vec<(String, String)>,
243 receipts: Vec<Vec<u8>>,
244 catalog: Vec<Vec<u8>>,
245 seed: &[u8; 32],
246) -> Result<Vec<u8>, BundleError> {
247 build_inner(namespace, descriptors, names, receipts, catalog, None, seed)
248}
249
250fn build_inner(
251 namespace: &str,
252 descriptors: Vec<Vec<u8>>,
253 names: Vec<(String, String)>,
254 receipts: Vec<Vec<u8>>,
255 catalog: Vec<Vec<u8>>,
256 tests: Option<Value>,
257 seed: &[u8; 32],
258) -> Result<Vec<u8>, BundleError> {
259 let mut catalog_entries: Vec<(String, Value)> = Vec::new();
260 for c in catalog {
261 let v = json::parse(&c).map_err(|e| BundleError::Format(format!("catalog: {e}")))?;
262 let d = crate::catalog::parse(&v, "name").map_err(|e| BundleError::Format(format!("catalog: {e}")))?;
263 catalog_entries.push((d.name.clone(), v));
264 }
265 catalog_entries.sort_by(|a, b| a.0.cmp(&b.0));
266 let catalog_value =
267 (!catalog_entries.is_empty()).then(|| Value::Array(catalog_entries.into_iter().map(|(_, v)| v).collect()));
268 let mut names = names;
269 names.sort();
270 let mut signed: Vec<(String, Value)> = Vec::new();
271 for r in receipts {
272 let hash = Receipt::from_json(&r).map_err(|e| BundleError::Format(format!("receipt: {e}")))?.hash().to_string();
273 let v = json::parse(&r).map_err(|e| BundleError::Format(format!("receipt: {e}")))?;
274 signed.push((hash, v));
275 }
276 signed.sort_by(|a, b| a.0.cmp(&b.0));
277 let hashes: Vec<String> = signed.iter().map(|(h, _)| h.clone()).collect();
278 let sig = sign(seed, &manifest_bytes_with(namespace, &names, &hashes, catalog_value.as_ref(), tests.as_ref()));
279 let key = SigningKey::from_seed(seed);
280 let descriptors = descriptors
281 .iter()
282 .map(|d| json::parse(d).map_err(|e| BundleError::Format(format!("descriptor: {e}"))))
283 .collect::<Result<Vec<Value>, _>>()?;
284 let mut members = vec![("bundle".into(), number(1))];
285 if let Some(c) = catalog_value {
286 members.push(("catalog".into(), c));
287 }
288 if let Some(t) = tests {
289 members.push(("tests".into(), t));
290 }
291 members.extend([
292 ("descriptors".into(), Value::Array(descriptors)),
293 (
294 "manifest".into(),
295 Value::Object(vec![("key_id".into(), s(key.key_id())), ("signature".into(), s(&to_hex(&sig)))]),
296 ),
297 ("names".into(), Value::Array(names.iter().map(|(n, h)| name_value(n, h)).collect())),
298 ("namespace".into(), s(namespace)),
299 ("receipts".into(), Value::Array(signed.into_iter().map(|(_, v)| v).collect())),
300 ]);
301 Ok(Value::Object(members).to_jcs())
302}
303
304fn member_names(v: &Value) -> Option<Vec<&str>> {
306 let mut keys: Vec<&str> = v.as_object()?.iter().map(|(k, _)| k.as_str()).collect();
307 keys.sort_unstable();
308 Some(keys)
309}
310
311fn text<'a>(v: &'a Value, key: &str) -> Result<&'a str, BundleError> {
313 v.get(key).and_then(Value::as_str).ok_or_else(|| BundleError::Format(format!("{key} is not a string")))
314}
315
316pub fn import_signed<S: Store + ?Sized>(
323 store: &S,
324 host: &str,
325 owned: &[String],
326 clock: &dyn Clock,
327 bytes: &[u8],
328) -> Result<Imported, BundleError> {
329 import_signed_with(store, host, owned, clock, bytes, None)
330}
331
332#[doc(hidden)]
336pub fn import_signed_with<S: Store + ?Sized>(
337 store: &S,
338 host: &str,
339 owned: &[String],
340 clock: &dyn Clock,
341 bytes: &[u8],
342 stop_after: Option<usize>,
343) -> Result<Imported, BundleError> {
344 import_with(store, host, owned, clock, bytes, None, stop_after, Stage::All)
345}
346
347#[derive(Clone, Copy, Debug, PartialEq, Eq)]
349pub(crate) enum Stage {
350 Proof,
351 All,
352}
353
354pub(crate) fn prove<S: Store + ?Sized>(
358 store: &S,
359 host: &str,
360 clock: &dyn Clock,
361 bytes: &[u8],
362 keydoc: &[u8],
363) -> Result<(), BundleError> {
364 import_with(store, host, &[], clock, bytes, Some(keydoc), None, Stage::Proof).map(|_| ())
365}
366
367pub(crate) fn import_published<S: Store + ?Sized>(
371 store: &S,
372 host: &str,
373 owned: &[String],
374 clock: &dyn Clock,
375 bytes: &[u8],
376 keydoc: Option<&[u8]>,
377) -> Result<Imported, BundleError> {
378 import_with(store, host, owned, clock, bytes, keydoc, None, Stage::All)
379}
380
381#[allow(clippy::too_many_arguments)]
382fn import_with<S: Store + ?Sized>(
383 store: &S,
384 host: &str,
385 owned: &[String],
386 clock: &dyn Clock,
387 bytes: &[u8],
388 keydoc: Option<&[u8]>,
389 stop_after: Option<usize>,
390 stage: Stage,
391) -> Result<Imported, BundleError> {
392 let now = clock.now();
393 let doc = json::parse(bytes).map_err(|e| BundleError::Format(format!("not JSON: {e}")))?;
394
395 let mut keys = member_names(&doc).ok_or_else(|| BundleError::Format("not an object".into()))?;
397 keys.sort_unstable();
398 let has_catalog = keys.contains(&"catalog");
399 let has_tests = keys.contains(&"tests");
400 keys.retain(|k| *k != "catalog" && *k != "tests");
401 let mut want = MEMBERS;
402 want.sort_unstable();
403 if keys != want {
404 return Err(BundleError::Format("the members are not exactly those of a bundle".into()));
405 }
406 if doc.get("bundle").and_then(Value::as_number_text) != Some("1") {
407 return Err(BundleError::Format("bundle is not 1".into()));
408 }
409 let namespace = text(&doc, "namespace")?.to_string();
410 if namespace.split('/').count() < 2 && !bare_host_test_cases(&doc, &namespace) {
411 return Err(BundleError::Format("namespace has no host and name".into()));
412 }
413 let manifest = doc.get("manifest").ok_or_else(|| BundleError::Format("no manifest".into()))?;
414 if member_names(manifest) != Some(vec!["key_id", "signature"]) {
415 return Err(BundleError::Format("the manifest's members are not key_id and signature".into()));
416 }
417 let key_id = text(manifest, "key_id")?.to_string();
418 let signature = text(manifest, "signature")?.to_string();
419 if !is_hex(&key_id, 16) || !is_hex(&signature, 128) {
420 return Err(BundleError::Format("the manifest's key_id or signature is not hex".into()));
421 }
422 let mut names: Vec<(String, String)> = Vec::new();
423 let Some(Value::Array(name_vs)) = doc.get("names") else {
424 return Err(BundleError::Format("names is not an array".into()));
425 };
426 for n in name_vs {
427 if member_names(n) != Some(vec!["fn_hash", "name"]) {
428 return Err(BundleError::Format("a name's members are not fn_hash and name".into()));
429 }
430 let fh = text(n, "fn_hash")?;
431 if !is_hex(fh, 64) {
432 return Err(BundleError::Format(format!("fn_hash {fh} is not 64 hex digits")));
433 }
434 names.push((text(n, "name")?.to_string(), fh.to_string()));
435 }
436 if names.windows(2).any(|w| w[0].0 >= w[1].0) {
437 return Err(BundleError::Format("names are not in ascending order".into()));
438 }
439 let Some(Value::Array(desc_vs)) = doc.get("descriptors") else {
440 return Err(BundleError::Format("descriptors is not an array".into()));
441 };
442 let Some(Value::Array(receipt_vs)) = doc.get("receipts") else {
443 return Err(BundleError::Format("receipts is not an array".into()));
444 };
445 let mut receipts: Vec<(Vec<u8>, Receipt)> = Vec::new();
447 for r in receipt_vs {
448 let rb = r.to_jcs();
449 let parsed = Receipt::from_json(&rb).map_err(|e| BundleError::Receipt(format!("unreadable: {e}")))?;
450 receipts.push((rb, parsed));
451 }
452 if receipts.windows(2).any(|w| w[0].1.hash() >= w[1].1.hash()) {
453 return Err(BundleError::Format("receipts are not in ascending order of their hashes".into()));
454 }
455 let hashes: Vec<String> = receipts.iter().map(|(_, r)| r.hash().to_string()).collect();
456 let mut catalog_entries: Vec<(crate::catalog::Described, Option<String>)> = Vec::new();
458 let catalog_doc = if has_catalog { doc.get("catalog").cloned() } else { None };
459 if let Some(Value::Array(items)) = &catalog_doc {
460 for item in items {
461 let d = crate::catalog::parse(item, "name").map_err(|e| BundleError::Format(format!("catalog: {e}")))?;
462 let hash =
463 match d.kind {
464 datumesh_store::CatalogKind::Class => None,
465 _ => {
466 Some(names.iter().find(|(n, _)| *n == d.name).map(|(_, h)| h.clone()).ok_or_else(|| {
467 BundleError::Format(format!("catalog: {} is not among the names", d.name))
468 })?)
469 }
470 };
471 catalog_entries.push((d, hash));
472 }
473 } else if has_catalog {
474 return Err(BundleError::Format("catalog is not an array".into()));
475 }
476
477 let ns_host = host_of(&namespace);
479 if stage == Stage::All && ns_host != host && !owned.iter().any(|o| o == ns_host) {
480 return Err(BundleError::NotOwned(format!("{ns_host} is neither this mesh's host nor owned")));
481 }
482 if let Some((n, _)) = names.iter().find(|(n, _)| !n.starts_with(&format!("{namespace}/"))) {
483 return Err(BundleError::NotOwned(format!("{n} is not under {namespace}/")));
484 }
485 if let Some((d, _)) = catalog_entries.iter().find(|(d, _)| !d.name.starts_with(&format!("{namespace}/"))) {
486 return Err(BundleError::NotOwned(format!("catalog: {} is not under {namespace}/", d.name)));
487 }
488 if keydoc.is_none() {
491 for n in names.iter().map(|(n, _)| n).chain(catalog_entries.iter().map(|(d, _)| &d.name)) {
492 crate::reserved::check(host, n, None).map_err(BundleError::Reserved)?;
493 }
494 }
495
496 let keydoc_fetched = keydoc;
498 let keydoc = match keydoc {
499 Some(d) => d.to_vec(),
500 None => {
501 store
502 .namespace(ns_host)
503 .map_err(|e| BundleError::Store(e.to_string()))?
504 .ok_or_else(|| BundleError::Manifest(format!("the store holds no key document of {ns_host}")))?
505 .keydoc
506 }
507 };
508 let kd = keys_from_response(ns_host, 200, Some(&keydoc)).map_err(|e| BundleError::Manifest(e.to_string()))?;
509 let key = kd
510 .key(&key_id)
511 .ok_or_else(|| BundleError::Manifest(format!("key {key_id} is not in the key document of {ns_host}")))?;
512 if !key.usable_at(&now) {
513 return Err(BundleError::Manifest(format!("key {key_id} does not hold at {now}")));
514 }
515 let mut keys_set = Keys::new();
516 keys_set.insert(kd.clone());
517 let sig: [u8; 64] = unhex(&signature).try_into().map_err(|_| BundleError::Format("signature length".into()))?;
518 let tests_doc = if has_tests { doc.get("tests").cloned() } else { None };
519 if tests_doc.as_ref().is_some_and(|t| !matches!(t, Value::Array(_))) {
520 return Err(BundleError::Format("tests is not an array".into()));
521 }
522 if !verify_ed25519(
523 &key.public,
524 &manifest_bytes_with(&namespace, &names, &hashes, catalog_doc.as_ref(), tests_doc.as_ref()),
525 &sig,
526 ) {
527 return Err(BundleError::Manifest("the signature does not verify".into()));
528 }
529 if stage == Stage::Proof {
530 return Ok(Imported { namespace, functions_bound: 0, receipts: 0, versions: 0, bound_at: now });
531 }
532
533 let mut descriptors: BTreeMap<String, Vec<u8>> = BTreeMap::new();
535 for d in desc_vs {
536 let db = d.to_jcs();
537 let fd = FunctionDescriptor::from_json(&db).map_err(|e| BundleError::Descriptor(e.to_string()))?;
538 if fd.canonical() != db {
539 return Err(BundleError::Descriptor("a descriptor is not canonical".into()));
540 }
541 descriptors.insert(fd.hash(), db);
542 }
543 for (name, fh) in &names {
544 if !descriptors.contains_key(fh) && store.descriptor(fh).is_none() {
545 return Err(BundleError::Descriptor(format!(
546 "{name}: descriptor {fh} is neither in the bundle nor stored"
547 )));
548 }
549 }
550
551 for (rb, r) in &receipts {
553 if !r.inputs().is_empty() {
554 return Err(BundleError::Receipt(format!("{}: a computed receipt is not imported", r.hash())));
555 }
556 let fname = r.cell().function_name();
557 let Some((_, fh)) = names.iter().find(|(n, _)| *n == fname) else {
558 return Err(BundleError::Receipt(format!("{}: {fname} is not among the names", r.hash())));
559 };
560 if r.cell().fn_hash != *fh {
561 return Err(BundleError::Receipt(format!("{}: the function hash differs from {fname}'s", r.hash())));
562 }
563 let out = verify(rb, &keys_set, None, None);
564 if !out.ok {
565 let why = out.error().map(|e| e.to_string()).unwrap_or_else(|| "does not verify".into());
566 return Err(BundleError::Receipt(format!("{}: {why}", r.hash())));
567 }
568 }
569
570 for (_, r) in &receipts {
572 if r.tx() > now.as_str() {
573 return Err(BundleError::TxInFuture {
574 receipt: r.hash().to_string(),
575 tx: r.tx().to_string(),
576 now: now.clone(),
577 });
578 }
579 }
580
581 let mut overlay = crate::testrun::Overlay::default();
583 for (name, fh) in &names {
584 overlay.functions.entry(name.clone()).or_default().push((now.clone(), fh.clone()));
585 }
586 for (fh, db) in &descriptors {
587 overlay.descriptors.insert(fh.clone(), db.clone());
588 }
589 for (rb, _) in &receipts {
590 overlay.cell(rb).map_err(BundleError::Receipt)?;
591 }
592 let mut formulas = Vec::new();
593 for (name, fh) in &names {
594 let bytes = match descriptors.get(fh) {
595 Some(b) => Some(b.clone()),
596 None => store.descriptor(fh).map(|b| b.into_owned()),
597 };
598 let Some(bytes) = bytes else { continue };
599 let fd = FunctionDescriptor::from_json(&bytes).map_err(|e| BundleError::Descriptor(e.to_string()))?;
600 if fd.lang != "stored" {
601 formulas.push((0usize, name.clone(), fh.clone()));
602 }
603 }
604 let mut test_specs = Vec::new();
605 for (i, t) in tests_doc
606 .iter()
607 .flat_map(|v| match v {
608 Value::Array(a) => a.iter().collect::<Vec<_>>(),
609 _ => Vec::new(),
610 })
611 .enumerate()
612 {
613 let spec = crate::testrun::parse_test(t).map_err(|e| BundleError::Format(format!("test: {e}")))?;
614 test_specs.push((i + 1, spec));
615 }
616 let test_rows =
617 crate::publish::check_tests(store, &overlay, &test_specs, &formulas, host, &now, true).map_err(|e| {
618 let code = match e.kind {
619 crate::publish::PublishErrorKind::TestsFailing(_) => "E_TESTS_FAILING",
620 crate::publish::PublishErrorKind::TestsMissing(_) => "E_TESTS_MISSING",
621 _ => "E_BUNDLE_TESTS",
622 };
623 BundleError::Tests(format!("{code}: {}", e.detail))
624 })?;
625 let mut binds: Vec<&(String, String)> = Vec::new();
627 for pair in &names {
628 let (name, fh) = pair;
629 match store.resolve_binding(name, END).map_err(|e| BundleError::Store(e.to_string()))? {
630 Some(b) if b.fn_hash == *fh => {}
631 Some(b) if b.tx.as_str() >= now.as_str() => {
632 return Err(BundleError::Bind(format!("{name} is bound from {} (at or after the clock)", b.tx)));
633 }
634 _ => binds.push(pair),
635 }
636 }
637 let mut new_versions: Vec<(String, String, String)> = Vec::new(); for (_, r) in &receipts {
639 let id = r.cell().id();
640 let tx = r.tx();
641 match store.version_asof(&id, tx).map_err(|e| BundleError::Store(e.to_string()))? {
642 Some(v) if v.tx == tx => {
643 if v.receipt_hash != r.hash() {
644 return Err(BundleError::Store(format!("{id} has another version at {tx}")));
645 }
646 continue;
647 }
648 _ => {}
649 }
650 if let Some(l) = store.latest(&id).map_err(|e| BundleError::Store(e.to_string()))? {
651 if l.tx.as_str() >= tx {
652 return Err(BundleError::Store(format!("{id} has a version at or after {tx}")));
653 }
654 }
655 new_versions.push((id, tx.to_string(), r.hash().to_string()));
656 }
657
658 if let Some(doc) = keydoc_fetched {
662 let stored = store.namespace(ns_host).map_err(|e| BundleError::Store(e.to_string()))?.map(|n| n.keydoc);
663 if stored.as_deref() != Some(doc) {
664 store.put_namespace(ns_host, doc, &now).map_err(|e| BundleError::Store(e.to_string()))?;
665 }
666 }
667 let mut writes = 0usize;
670 let mut step = || -> Result<(), BundleError> {
671 writes += 1;
672 if stop_after == Some(writes) {
673 return Err(BundleError::Stopped(writes));
674 }
675 Ok(())
676 };
677 for db in descriptors.values() {
678 store.put_descriptor(db).map_err(|e| BundleError::Store(e.to_string()))?;
679 step()?;
680 }
681 for (rb, _) in &receipts {
682 store.put_receipt(rb).map_err(|e| BundleError::Store(e.to_string()))?;
683 step()?;
684 }
685 for (id, tx, h) in &new_versions {
686 store.put_version(id, tx, h).map_err(|e| BundleError::Store(e.to_string()))?;
687 step()?;
688 }
689 for (name, fh) in &binds {
690 store.bind_name(name, fh, &now).map_err(|e| BundleError::Bind(format!("{name}: {e}")))?;
691 step()?;
692 }
693 crate::testrun::apply_rows(store, &test_rows, &now).map_err(BundleError::Store)?;
694 let rebound: Vec<String> = binds.iter().map(|(n, _)| (*n).clone()).collect();
695 crate::testrun::rerun_readers(store, &rebound, &now).map_err(BundleError::Store)?;
696 let rebound: BTreeSet<String> = rebound.into_iter().collect();
698 let written_cells: Vec<(String, String)> =
699 receipts.iter().map(|(_, r)| (r.cell().function_name(), r.cell().id())).collect();
700 crate::testrun::rerun_stored_tests(store, &rebound, &written_cells, &now).map_err(BundleError::Store)?;
701 for (d, hash) in &catalog_entries {
703 let entry = d.entry(hash.clone(), datumesh_store::CatalogSource::Publisher, Some(key_id.clone()));
704 crate::catalog::store_publisher(store, &entry, &d.dictionary, &d.open_keys).map_err(BundleError::Store)?;
705 }
706 let mut cell_values = BTreeSet::new();
707 for (_, r) in &receipts {
708 crate::publish::cell_string_values(r, &mut cell_values);
709 }
710 crate::publish::store_cell_values(store, cell_values).map_err(BundleError::Store)?;
711 Ok(Imported {
712 namespace,
713 functions_bound: binds.len(),
714 receipts: receipts.len(),
715 versions: new_versions.len(),
716 bound_at: now,
717 })
718}
719
720#[cfg(test)]
721mod tests {
722 use super::*;
723
724 #[test]
726 fn rfc8032_test_1() {
727 let seed: [u8; 32] =
728 unhex("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60").try_into().unwrap();
729 let sig = sign(&seed, b"");
730 assert_eq!(
731 to_hex(&sig),
732 "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"
733 );
734 }
735
736 #[test]
738 fn a_signature_verifies_under_the_seed_key() {
739 let seed = [7u8; 32];
740 let message = b"the manifest bytes";
741 let sig = sign(&seed, message);
742 let public = SigningKey::from_seed(&seed).public_key();
743 assert!(verify_ed25519(&public, message, &sig));
744 assert!(!verify_ed25519(&public, b"other bytes", &sig));
745 }
746}