qualia_core_db/semantic_instruments/
canonical.rs1use sha2::{Digest, Sha256};
4
5use super::errors::InstrumentError;
6use super::manifest::InstrumentManifest;
7
8pub fn sha256_prefixed(bytes: &[u8]) -> String {
10 let digest = Sha256::digest(bytes);
11 let mut hex = String::with_capacity(7 + 64);
12 hex.push_str("sha256:");
13 for b in digest {
14 hex.push_str(&format!("{b:02x}"));
15 }
16 hex
17}
18
19pub fn canonical_manifest_bytes(manifest: &InstrumentManifest) -> Result<Vec<u8>, InstrumentError> {
21 serde_json::to_vec(manifest).map_err(|e| InstrumentError::Canonical(e.to_string()))
22}
23
24pub fn manifest_digest(manifest: &InstrumentManifest) -> Result<String, InstrumentError> {
26 let bytes = canonical_manifest_bytes(manifest)?;
27 Ok(sha256_prefixed(&bytes))
28}
29
30#[cfg(test)]
31mod tests {
32 use super::*;
33 use crate::semantic_instruments::category::ContentCategory;
34 use crate::semantic_instruments::manifest::COLLECTABLE_FORMAT_VERSION;
35
36 fn sample() -> InstrumentManifest {
37 InstrumentManifest {
38 format_version: COLLECTABLE_FORMAT_VERSION.into(),
39 instrument_id: "https://ns.webizen.org/demo/unit-convert".into(),
40 release_id: "https://ns.webizen.org/demo/unit-convert/releases/1.0.0".into(),
41 version: "1.0.0".into(),
42 name: "Unit conversion (demo)".into(),
43 purpose: "demonstration-and-development".into(),
44 content_category: ContentCategory::Demo,
45 prohibited_interpretation: "operational-use".into(),
46 domain: "https://ns.webizen.org/demo/concepts/units".into(),
47 ontology_reference: "https://ns.webizen.org/semantic-instrument/".into(),
48 entry_point: "assess".into(),
49 citation: "https://ns.webizen.org/demo/citations/si-units".into(),
50 honesty_notice: "Demo instrument for demonstration and development. Not operational."
51 .into(),
52 incomplete_input: "held".into(),
53 result_kind: "demo-claim".into(),
54 licence: "https://spdx.org/licenses/CC-BY-4.0.html".into(),
55 authored_by: "did:webizen:agent:demo-seed".into(),
56 accessible_text: "Unit conversion demo instrument".into(),
57 visual_media_type: "application/vnd.qualia.10d".into(),
58 content_digest: String::new(),
59 extra: Default::default(),
60 }
61 }
62
63 #[test]
64 fn digest_is_stable() {
65 let a = manifest_digest(&sample()).unwrap();
66 let b = manifest_digest(&sample()).unwrap();
67 assert_eq!(a, b);
68 assert!(a.starts_with("sha256:"));
69 assert_eq!(a.len(), 7 + 64);
70 }
71
72 #[test]
73 fn extra_fields_round_trip() {
74 let mut m = sample();
75 m.extra
76 .insert("note".into(), serde_json::Value::String("keep".into()));
77 let bytes = canonical_manifest_bytes(&m).unwrap();
78 let back: InstrumentManifest = serde_json::from_slice(&bytes).unwrap();
79 assert_eq!(
80 back.extra.get("note").and_then(|v| v.as_str()),
81 Some("keep")
82 );
83 }
84}