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 Tests(String),
56}
57
58impl std::fmt::Display for BundleError {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 match self {
61 BundleError::Format(s) => write!(f, "bundle format: {s}"),
62 BundleError::NotOwned(s) => write!(f, "not owned: {s}"),
63 BundleError::Manifest(s) => write!(f, "manifest: {s}"),
64 BundleError::Descriptor(s) => write!(f, "descriptor: {s}"),
65 BundleError::Receipt(s) => write!(f, "receipt: {s}"),
66 BundleError::TxInFuture { receipt, tx, now } => {
67 write!(f, "receipt {receipt}: tx {tx} is later than the mesh clock {now}")
68 }
69 BundleError::Bind(s) => write!(f, "binding: {s}"),
70 BundleError::Store(s) => write!(f, "store: {s}"),
71 BundleError::Stopped(n) => write!(f, "stopped after write {n}"),
72 BundleError::Tests(s) => write!(f, "tests: {s}"),
73 }
74 }
75}
76
77impl std::error::Error for BundleError {}
78
79#[non_exhaustive]
81#[derive(Clone, Debug, PartialEq, Eq)]
82pub struct Imported {
83 pub namespace: String,
85 pub functions_bound: usize,
87 pub receipts: usize,
89 pub versions: usize,
91 pub bound_at: String,
93}
94
95impl Imported {
96 pub fn to_jcs(&self) -> Vec<u8> {
98 Value::Object(vec![
99 ("bound_at".into(), s(&self.bound_at)),
100 ("functions_bound".into(), number(self.functions_bound)),
101 ("namespace".into(), s(&self.namespace)),
102 ("receipts".into(), number(self.receipts)),
103 ("versions".into(), number(self.versions)),
104 ])
105 .to_jcs()
106 }
107}
108
109fn s(v: &str) -> Value {
110 Value::String(v.to_string())
111}
112
113fn number(n: usize) -> Value {
114 json::parse(n.to_string().as_bytes()).unwrap_or(Value::Null)
115}
116
117fn is_hex(text: &str, len: usize) -> bool {
118 text.len() == len && text.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
119}
120
121fn unhex(text: &str) -> Vec<u8> {
122 (0..text.len()).step_by(2).filter_map(|i| u8::from_str_radix(text.get(i..i + 2)?, 16).ok()).collect()
123}
124
125pub(crate) fn bare_host_test_cases(doc: &Value, namespace: &str) -> bool {
129 if namespace.is_empty() || namespace.contains('/') {
130 return false;
131 }
132 let want = format!("{namespace}/test_case");
133 let is_want = |v: &Value| v.get("name").and_then(Value::as_str) == Some(want.as_str());
134 let names_ok = match doc.get("names") {
135 Some(Value::Array(a)) => !a.is_empty() && a.iter().all(is_want),
136 _ => false,
137 };
138 let catalog_ok = match doc.get("catalog") {
139 None => true,
140 Some(Value::Array(a)) => a.iter().all(is_want),
141 Some(_) => false,
142 };
143 names_ok && catalog_ok
144}
145
146fn host_of(namespace: &str) -> &str {
148 namespace.split('/').next().unwrap_or("")
149}
150
151fn name_value(name: &str, fn_hash: &str) -> Value {
153 Value::Object(vec![("fn_hash".into(), s(fn_hash)), ("name".into(), s(name))])
154}
155
156pub fn manifest_bytes(namespace: &str, names: &[(String, String)], receipts: &[String]) -> Vec<u8> {
159 manifest_bytes_with(namespace, names, receipts, None, None)
160}
161
162fn manifest_bytes_with(
165 namespace: &str,
166 names: &[(String, String)],
167 receipts: &[String],
168 catalog: Option<&Value>,
169 tests: Option<&Value>,
170) -> Vec<u8> {
171 let mut members = vec![
172 ("names".into(), Value::Array(names.iter().map(|(n, h)| name_value(n, h)).collect())),
173 ("namespace".into(), s(namespace)),
174 ("receipts".into(), Value::Array(receipts.iter().map(|h| s(h)).collect())),
175 ];
176 if let Some(c) = catalog {
177 members.push(("catalog".into(), c.clone()));
178 }
179 if let Some(t) = tests {
180 members.push(("tests".into(), t.clone()));
181 }
182 Value::Object(members).to_jcs()
183}
184
185fn sign(seed: &[u8; 32], message: &[u8]) -> [u8; 64] {
189 use ed25519_dalek::Signer;
190 ed25519_dalek::SigningKey::from_bytes(seed).sign(message).to_bytes()
191}
192
193pub fn build(
198 namespace: &str,
199 descriptors: Vec<Vec<u8>>,
200 names: Vec<(String, String)>,
201 receipts: Vec<Vec<u8>>,
202 seed: &[u8; 32],
203) -> Result<Vec<u8>, BundleError> {
204 build_with_catalog(namespace, descriptors, names, receipts, Vec::new(), seed)
205}
206
207pub fn build_with_tests(
212 namespace: &str,
213 descriptors: Vec<Vec<u8>>,
214 names: Vec<(String, String)>,
215 receipts: Vec<Vec<u8>>,
216 catalog: Vec<Vec<u8>>,
217 tests: Vec<Vec<u8>>,
218 seed: &[u8; 32],
219) -> Result<Vec<u8>, BundleError> {
220 let mut entries: Vec<(String, String, Value)> = Vec::new();
221 for t in tests {
222 let v = json::parse(&t).map_err(|e| BundleError::Format(format!("test: {e}")))?;
223 let spec = crate::testrun::parse_test(&v).map_err(|e| BundleError::Format(format!("test: {e}")))?;
224 entries.push((spec.function.clone(), spec.case.clone(), v));
225 }
226 entries.sort_by(|a, b| (a.0.as_str(), a.1.as_str()).cmp(&(b.0.as_str(), b.1.as_str())));
227 let tests_value = (!entries.is_empty()).then(|| Value::Array(entries.into_iter().map(|(_, _, v)| v).collect()));
228 build_inner(namespace, descriptors, names, receipts, catalog, tests_value, seed)
229}
230
231pub fn build_with_catalog(
237 namespace: &str,
238 descriptors: Vec<Vec<u8>>,
239 names: Vec<(String, String)>,
240 receipts: Vec<Vec<u8>>,
241 catalog: Vec<Vec<u8>>,
242 seed: &[u8; 32],
243) -> Result<Vec<u8>, BundleError> {
244 build_inner(namespace, descriptors, names, receipts, catalog, None, seed)
245}
246
247fn build_inner(
248 namespace: &str,
249 descriptors: Vec<Vec<u8>>,
250 names: Vec<(String, String)>,
251 receipts: Vec<Vec<u8>>,
252 catalog: Vec<Vec<u8>>,
253 tests: Option<Value>,
254 seed: &[u8; 32],
255) -> Result<Vec<u8>, BundleError> {
256 let mut catalog_entries: Vec<(String, Value)> = Vec::new();
257 for c in catalog {
258 let v = json::parse(&c).map_err(|e| BundleError::Format(format!("catalog: {e}")))?;
259 let d = crate::catalog::parse(&v, "name").map_err(|e| BundleError::Format(format!("catalog: {e}")))?;
260 catalog_entries.push((d.name.clone(), v));
261 }
262 catalog_entries.sort_by(|a, b| a.0.cmp(&b.0));
263 let catalog_value =
264 (!catalog_entries.is_empty()).then(|| Value::Array(catalog_entries.into_iter().map(|(_, v)| v).collect()));
265 let mut names = names;
266 names.sort();
267 let mut signed: Vec<(String, Value)> = Vec::new();
268 for r in receipts {
269 let hash = Receipt::from_json(&r).map_err(|e| BundleError::Format(format!("receipt: {e}")))?.hash().to_string();
270 let v = json::parse(&r).map_err(|e| BundleError::Format(format!("receipt: {e}")))?;
271 signed.push((hash, v));
272 }
273 signed.sort_by(|a, b| a.0.cmp(&b.0));
274 let hashes: Vec<String> = signed.iter().map(|(h, _)| h.clone()).collect();
275 let sig = sign(seed, &manifest_bytes_with(namespace, &names, &hashes, catalog_value.as_ref(), tests.as_ref()));
276 let key = SigningKey::from_seed(seed);
277 let descriptors = descriptors
278 .iter()
279 .map(|d| json::parse(d).map_err(|e| BundleError::Format(format!("descriptor: {e}"))))
280 .collect::<Result<Vec<Value>, _>>()?;
281 let mut members = vec![("bundle".into(), number(1))];
282 if let Some(c) = catalog_value {
283 members.push(("catalog".into(), c));
284 }
285 if let Some(t) = tests {
286 members.push(("tests".into(), t));
287 }
288 members.extend([
289 ("descriptors".into(), Value::Array(descriptors)),
290 (
291 "manifest".into(),
292 Value::Object(vec![("key_id".into(), s(key.key_id())), ("signature".into(), s(&to_hex(&sig)))]),
293 ),
294 ("names".into(), Value::Array(names.iter().map(|(n, h)| name_value(n, h)).collect())),
295 ("namespace".into(), s(namespace)),
296 ("receipts".into(), Value::Array(signed.into_iter().map(|(_, v)| v).collect())),
297 ]);
298 Ok(Value::Object(members).to_jcs())
299}
300
301fn member_names(v: &Value) -> Option<Vec<&str>> {
303 let mut keys: Vec<&str> = v.as_object()?.iter().map(|(k, _)| k.as_str()).collect();
304 keys.sort_unstable();
305 Some(keys)
306}
307
308fn text<'a>(v: &'a Value, key: &str) -> Result<&'a str, BundleError> {
310 v.get(key).and_then(Value::as_str).ok_or_else(|| BundleError::Format(format!("{key} is not a string")))
311}
312
313pub fn import_signed<S: Store + ?Sized>(
320 store: &S,
321 host: &str,
322 owned: &[String],
323 clock: &dyn Clock,
324 bytes: &[u8],
325) -> Result<Imported, BundleError> {
326 import_signed_with(store, host, owned, clock, bytes, None)
327}
328
329#[doc(hidden)]
333pub fn import_signed_with<S: Store + ?Sized>(
334 store: &S,
335 host: &str,
336 owned: &[String],
337 clock: &dyn Clock,
338 bytes: &[u8],
339 stop_after: Option<usize>,
340) -> Result<Imported, BundleError> {
341 import_with(store, host, owned, clock, bytes, None, stop_after, Stage::All)
342}
343
344#[derive(Clone, Copy, Debug, PartialEq, Eq)]
346pub(crate) enum Stage {
347 Proof,
348 All,
349}
350
351pub(crate) fn prove<S: Store + ?Sized>(
355 store: &S,
356 host: &str,
357 clock: &dyn Clock,
358 bytes: &[u8],
359 keydoc: &[u8],
360) -> Result<(), BundleError> {
361 import_with(store, host, &[], clock, bytes, Some(keydoc), None, Stage::Proof).map(|_| ())
362}
363
364pub(crate) fn import_published<S: Store + ?Sized>(
368 store: &S,
369 host: &str,
370 owned: &[String],
371 clock: &dyn Clock,
372 bytes: &[u8],
373 keydoc: Option<&[u8]>,
374) -> Result<Imported, BundleError> {
375 import_with(store, host, owned, clock, bytes, keydoc, None, Stage::All)
376}
377
378#[allow(clippy::too_many_arguments)]
379fn import_with<S: Store + ?Sized>(
380 store: &S,
381 host: &str,
382 owned: &[String],
383 clock: &dyn Clock,
384 bytes: &[u8],
385 keydoc: Option<&[u8]>,
386 stop_after: Option<usize>,
387 stage: Stage,
388) -> Result<Imported, BundleError> {
389 let now = clock.now();
390 let doc = json::parse(bytes).map_err(|e| BundleError::Format(format!("not JSON: {e}")))?;
391
392 let mut keys = member_names(&doc).ok_or_else(|| BundleError::Format("not an object".into()))?;
394 keys.sort_unstable();
395 let has_catalog = keys.contains(&"catalog");
396 let has_tests = keys.contains(&"tests");
397 keys.retain(|k| *k != "catalog" && *k != "tests");
398 let mut want = MEMBERS;
399 want.sort_unstable();
400 if keys != want {
401 return Err(BundleError::Format("the members are not exactly those of a bundle".into()));
402 }
403 if doc.get("bundle").and_then(Value::as_number_text) != Some("1") {
404 return Err(BundleError::Format("bundle is not 1".into()));
405 }
406 let namespace = text(&doc, "namespace")?.to_string();
407 if namespace.split('/').count() < 2 && !bare_host_test_cases(&doc, &namespace) {
408 return Err(BundleError::Format("namespace has no host and name".into()));
409 }
410 let manifest = doc.get("manifest").ok_or_else(|| BundleError::Format("no manifest".into()))?;
411 if member_names(manifest) != Some(vec!["key_id", "signature"]) {
412 return Err(BundleError::Format("the manifest's members are not key_id and signature".into()));
413 }
414 let key_id = text(manifest, "key_id")?.to_string();
415 let signature = text(manifest, "signature")?.to_string();
416 if !is_hex(&key_id, 16) || !is_hex(&signature, 128) {
417 return Err(BundleError::Format("the manifest's key_id or signature is not hex".into()));
418 }
419 let mut names: Vec<(String, String)> = Vec::new();
420 let Some(Value::Array(name_vs)) = doc.get("names") else {
421 return Err(BundleError::Format("names is not an array".into()));
422 };
423 for n in name_vs {
424 if member_names(n) != Some(vec!["fn_hash", "name"]) {
425 return Err(BundleError::Format("a name's members are not fn_hash and name".into()));
426 }
427 let fh = text(n, "fn_hash")?;
428 if !is_hex(fh, 64) {
429 return Err(BundleError::Format(format!("fn_hash {fh} is not 64 hex digits")));
430 }
431 names.push((text(n, "name")?.to_string(), fh.to_string()));
432 }
433 if names.windows(2).any(|w| w[0].0 >= w[1].0) {
434 return Err(BundleError::Format("names are not in ascending order".into()));
435 }
436 let Some(Value::Array(desc_vs)) = doc.get("descriptors") else {
437 return Err(BundleError::Format("descriptors is not an array".into()));
438 };
439 let Some(Value::Array(receipt_vs)) = doc.get("receipts") else {
440 return Err(BundleError::Format("receipts is not an array".into()));
441 };
442 let mut receipts: Vec<(Vec<u8>, Receipt)> = Vec::new();
444 for r in receipt_vs {
445 let rb = r.to_jcs();
446 let parsed = Receipt::from_json(&rb).map_err(|e| BundleError::Receipt(format!("unreadable: {e}")))?;
447 receipts.push((rb, parsed));
448 }
449 if receipts.windows(2).any(|w| w[0].1.hash() >= w[1].1.hash()) {
450 return Err(BundleError::Format("receipts are not in ascending order of their hashes".into()));
451 }
452 let hashes: Vec<String> = receipts.iter().map(|(_, r)| r.hash().to_string()).collect();
453 let mut catalog_entries: Vec<(crate::catalog::Described, Option<String>)> = Vec::new();
455 let catalog_doc = if has_catalog { doc.get("catalog").cloned() } else { None };
456 if let Some(Value::Array(items)) = &catalog_doc {
457 for item in items {
458 let d = crate::catalog::parse(item, "name").map_err(|e| BundleError::Format(format!("catalog: {e}")))?;
459 let hash =
460 match d.kind {
461 datumesh_store::CatalogKind::Class => None,
462 _ => {
463 Some(names.iter().find(|(n, _)| *n == d.name).map(|(_, h)| h.clone()).ok_or_else(|| {
464 BundleError::Format(format!("catalog: {} is not among the names", d.name))
465 })?)
466 }
467 };
468 catalog_entries.push((d, hash));
469 }
470 } else if has_catalog {
471 return Err(BundleError::Format("catalog is not an array".into()));
472 }
473
474 let ns_host = host_of(&namespace);
476 if stage == Stage::All && ns_host != host && !owned.iter().any(|o| o == ns_host) {
477 return Err(BundleError::NotOwned(format!("{ns_host} is neither this mesh's host nor owned")));
478 }
479 if let Some((n, _)) = names.iter().find(|(n, _)| !n.starts_with(&format!("{namespace}/"))) {
480 return Err(BundleError::NotOwned(format!("{n} is not under {namespace}/")));
481 }
482 if let Some((d, _)) = catalog_entries.iter().find(|(d, _)| !d.name.starts_with(&format!("{namespace}/"))) {
483 return Err(BundleError::NotOwned(format!("catalog: {} is not under {namespace}/", d.name)));
484 }
485
486 let keydoc_fetched = keydoc;
488 let keydoc = match keydoc {
489 Some(d) => d.to_vec(),
490 None => {
491 store
492 .namespace(ns_host)
493 .map_err(|e| BundleError::Store(e.to_string()))?
494 .ok_or_else(|| BundleError::Manifest(format!("the store holds no key document of {ns_host}")))?
495 .keydoc
496 }
497 };
498 let kd = keys_from_response(ns_host, 200, Some(&keydoc)).map_err(|e| BundleError::Manifest(e.to_string()))?;
499 let key = kd
500 .key(&key_id)
501 .ok_or_else(|| BundleError::Manifest(format!("key {key_id} is not in the key document of {ns_host}")))?;
502 if !key.usable_at(&now) {
503 return Err(BundleError::Manifest(format!("key {key_id} does not hold at {now}")));
504 }
505 let mut keys_set = Keys::new();
506 keys_set.insert(kd.clone());
507 let sig: [u8; 64] = unhex(&signature).try_into().map_err(|_| BundleError::Format("signature length".into()))?;
508 let tests_doc = if has_tests { doc.get("tests").cloned() } else { None };
509 if tests_doc.as_ref().is_some_and(|t| !matches!(t, Value::Array(_))) {
510 return Err(BundleError::Format("tests is not an array".into()));
511 }
512 if !verify_ed25519(
513 &key.public,
514 &manifest_bytes_with(&namespace, &names, &hashes, catalog_doc.as_ref(), tests_doc.as_ref()),
515 &sig,
516 ) {
517 return Err(BundleError::Manifest("the signature does not verify".into()));
518 }
519 if stage == Stage::Proof {
520 return Ok(Imported { namespace, functions_bound: 0, receipts: 0, versions: 0, bound_at: now });
521 }
522
523 let mut descriptors: BTreeMap<String, Vec<u8>> = BTreeMap::new();
525 for d in desc_vs {
526 let db = d.to_jcs();
527 let fd = FunctionDescriptor::from_json(&db).map_err(|e| BundleError::Descriptor(e.to_string()))?;
528 if fd.canonical() != db {
529 return Err(BundleError::Descriptor("a descriptor is not canonical".into()));
530 }
531 descriptors.insert(fd.hash(), db);
532 }
533 for (name, fh) in &names {
534 if !descriptors.contains_key(fh) && store.descriptor(fh).is_none() {
535 return Err(BundleError::Descriptor(format!(
536 "{name}: descriptor {fh} is neither in the bundle nor stored"
537 )));
538 }
539 }
540
541 for (rb, r) in &receipts {
543 if !r.inputs().is_empty() {
544 return Err(BundleError::Receipt(format!("{}: a computed receipt is not imported", r.hash())));
545 }
546 let fname = r.cell().function_name();
547 let Some((_, fh)) = names.iter().find(|(n, _)| *n == fname) else {
548 return Err(BundleError::Receipt(format!("{}: {fname} is not among the names", r.hash())));
549 };
550 if r.cell().fn_hash != *fh {
551 return Err(BundleError::Receipt(format!("{}: the function hash differs from {fname}'s", r.hash())));
552 }
553 let out = verify(rb, &keys_set, None, None);
554 if !out.ok {
555 let why = out.error().map(|e| e.to_string()).unwrap_or_else(|| "does not verify".into());
556 return Err(BundleError::Receipt(format!("{}: {why}", r.hash())));
557 }
558 }
559
560 for (_, r) in &receipts {
562 if r.tx() > now.as_str() {
563 return Err(BundleError::TxInFuture {
564 receipt: r.hash().to_string(),
565 tx: r.tx().to_string(),
566 now: now.clone(),
567 });
568 }
569 }
570
571 let mut overlay = crate::testrun::Overlay::default();
573 for (name, fh) in &names {
574 overlay.functions.entry(name.clone()).or_default().push((now.clone(), fh.clone()));
575 }
576 for (fh, db) in &descriptors {
577 overlay.descriptors.insert(fh.clone(), db.clone());
578 }
579 for (rb, _) in &receipts {
580 overlay.cell(rb).map_err(BundleError::Receipt)?;
581 }
582 let mut formulas = Vec::new();
583 for (name, fh) in &names {
584 let bytes = match descriptors.get(fh) {
585 Some(b) => Some(b.clone()),
586 None => store.descriptor(fh).map(|b| b.into_owned()),
587 };
588 let Some(bytes) = bytes else { continue };
589 let fd = FunctionDescriptor::from_json(&bytes).map_err(|e| BundleError::Descriptor(e.to_string()))?;
590 if fd.lang != "stored" {
591 formulas.push((0usize, name.clone(), fh.clone()));
592 }
593 }
594 let mut test_specs = Vec::new();
595 for (i, t) in tests_doc
596 .iter()
597 .flat_map(|v| match v {
598 Value::Array(a) => a.iter().collect::<Vec<_>>(),
599 _ => Vec::new(),
600 })
601 .enumerate()
602 {
603 let spec = crate::testrun::parse_test(t).map_err(|e| BundleError::Format(format!("test: {e}")))?;
604 test_specs.push((i + 1, spec));
605 }
606 let test_rows =
607 crate::publish::check_tests(store, &overlay, &test_specs, &formulas, host, &now, true).map_err(|e| {
608 let code = match e.kind {
609 crate::publish::PublishErrorKind::TestsFailing(_) => "E_TESTS_FAILING",
610 crate::publish::PublishErrorKind::TestsMissing(_) => "E_TESTS_MISSING",
611 _ => "E_BUNDLE_TESTS",
612 };
613 BundleError::Tests(format!("{code}: {}", e.detail))
614 })?;
615 let mut binds: Vec<&(String, String)> = Vec::new();
617 for pair in &names {
618 let (name, fh) = pair;
619 match store.resolve_binding(name, END).map_err(|e| BundleError::Store(e.to_string()))? {
620 Some(b) if b.fn_hash == *fh => {}
621 Some(b) if b.tx.as_str() >= now.as_str() => {
622 return Err(BundleError::Bind(format!("{name} is bound from {} (at or after the clock)", b.tx)));
623 }
624 _ => binds.push(pair),
625 }
626 }
627 let mut new_versions: Vec<(String, String, String)> = Vec::new(); for (_, r) in &receipts {
629 let id = r.cell().id();
630 let tx = r.tx();
631 match store.version_asof(&id, tx).map_err(|e| BundleError::Store(e.to_string()))? {
632 Some(v) if v.tx == tx => {
633 if v.receipt_hash != r.hash() {
634 return Err(BundleError::Store(format!("{id} has another version at {tx}")));
635 }
636 continue;
637 }
638 _ => {}
639 }
640 if let Some(l) = store.latest(&id).map_err(|e| BundleError::Store(e.to_string()))? {
641 if l.tx.as_str() >= tx {
642 return Err(BundleError::Store(format!("{id} has a version at or after {tx}")));
643 }
644 }
645 new_versions.push((id, tx.to_string(), r.hash().to_string()));
646 }
647
648 if let Some(doc) = keydoc_fetched {
652 let stored = store.namespace(ns_host).map_err(|e| BundleError::Store(e.to_string()))?.map(|n| n.keydoc);
653 if stored.as_deref() != Some(doc) {
654 store.put_namespace(ns_host, doc, &now).map_err(|e| BundleError::Store(e.to_string()))?;
655 }
656 }
657 let mut writes = 0usize;
660 let mut step = || -> Result<(), BundleError> {
661 writes += 1;
662 if stop_after == Some(writes) {
663 return Err(BundleError::Stopped(writes));
664 }
665 Ok(())
666 };
667 for db in descriptors.values() {
668 store.put_descriptor(db).map_err(|e| BundleError::Store(e.to_string()))?;
669 step()?;
670 }
671 for (rb, _) in &receipts {
672 store.put_receipt(rb).map_err(|e| BundleError::Store(e.to_string()))?;
673 step()?;
674 }
675 for (id, tx, h) in &new_versions {
676 store.put_version(id, tx, h).map_err(|e| BundleError::Store(e.to_string()))?;
677 step()?;
678 }
679 for (name, fh) in &binds {
680 store.bind_name(name, fh, &now).map_err(|e| BundleError::Bind(format!("{name}: {e}")))?;
681 step()?;
682 }
683 crate::testrun::apply_rows(store, &test_rows, &now).map_err(BundleError::Store)?;
684 let rebound: Vec<String> = binds.iter().map(|(n, _)| (*n).clone()).collect();
685 crate::testrun::rerun_readers(store, &rebound, &now).map_err(BundleError::Store)?;
686 for (d, hash) in &catalog_entries {
688 let entry = d.entry(hash.clone(), datumesh_store::CatalogSource::Publisher, Some(key_id.clone()));
689 crate::catalog::store_publisher(store, &entry, &d.dictionary).map_err(BundleError::Store)?;
690 }
691 let mut cell_values = BTreeSet::new();
692 for (_, r) in &receipts {
693 crate::publish::cell_string_values(r, &mut cell_values);
694 }
695 crate::publish::store_cell_values(store, cell_values).map_err(BundleError::Store)?;
696 Ok(Imported {
697 namespace,
698 functions_bound: binds.len(),
699 receipts: receipts.len(),
700 versions: new_versions.len(),
701 bound_at: now,
702 })
703}
704
705#[cfg(test)]
706mod tests {
707 use super::*;
708
709 #[test]
711 fn rfc8032_test_1() {
712 let seed: [u8; 32] =
713 unhex("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60").try_into().unwrap();
714 let sig = sign(&seed, b"");
715 assert_eq!(
716 to_hex(&sig),
717 "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"
718 );
719 }
720
721 #[test]
723 fn a_signature_verifies_under_the_seed_key() {
724 let seed = [7u8; 32];
725 let message = b"the manifest bytes";
726 let sig = sign(&seed, message);
727 let public = SigningKey::from_seed(&seed).public_key();
728 assert!(verify_ed25519(&public, message, &sig));
729 assert!(!verify_ed25519(&public, b"other bytes", &sig));
730 }
731}