use rs_merkle::{algorithms::Sha256 as RsSha256, Hasher, MerkleTree};
pub fn calculate_epistemic_root(
ontology_schema_content: Option<&[u8]>,
manifest_version: &str,
capabilities_ledger_content: Option<&[u8]>,
) -> String {
let mut leaves: Vec<[u8; 32]> = Vec::new();
if let Some(content) = ontology_schema_content {
leaves.push(RsSha256::hash(content));
} else {
leaves.push(RsSha256::hash(b""));
}
let env_str = format!(
"coreason-manifest=={}\ncoreason-runtime=={}\n",
manifest_version, manifest_version
);
leaves.push(RsSha256::hash(env_str.as_bytes()));
if let Some(content) = capabilities_ledger_content {
leaves.push(RsSha256::hash(content));
} else {
leaves.push(RsSha256::hash(b"{}"));
}
let merkle_tree = MerkleTree::<RsSha256>::from_leaves(&leaves);
let root = merkle_tree.root().unwrap_or([0u8; 32]);
hex::encode(root)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_calculate_epistemic_root_deterministic() {
let ontology = b"{\"key\":\"value\"}";
let ledger = b"{\"cap1\":\"hash1\"}";
let version = "1.0.0";
let root1 = calculate_epistemic_root(Some(ontology), version, Some(ledger));
let root2 = calculate_epistemic_root(Some(ontology), version, Some(ledger));
assert_eq!(root1, root2);
}
#[test]
fn test_calculate_epistemic_root_empty_inputs() {
let version = "1.0.0";
let root_empty = calculate_epistemic_root(None, version, None);
let root_default = calculate_epistemic_root(Some(b""), version, Some(b"{}"));
assert_eq!(root_empty, root_default);
}
}