use sha2::{Digest, Sha256};
pub fn extract_raw_pubkey_from_did(did: &str) -> [u8; 32] {
if let Some(b58_str) = did.strip_prefix(crate::layer0::vocabulary_identities::DID_KEY_Z)
&& let Ok(decoded) = bs58::decode(b58_str).into_vec() {
if decoded.len() >= 34 && decoded[0] == 0xed && decoded[1] == 0x01 {
let mut out = [0u8; 32];
out.copy_from_slice(&decoded[2..34]);
return out;
} else if decoded.len() == 32 {
let mut out = [0u8; 32];
out.copy_from_slice(&decoded);
return out;
}
}
let mut hasher = Sha256::new();
hasher.update(did.as_bytes());
let res = hasher.finalize();
let mut out = [0u8; 32];
out.copy_from_slice(&res);
out
}
pub fn derive_destination_hash(
did_or_material: &[u8],
app_name: &str,
aspects: &[&str],
) -> [u8; 16] {
let full_name = if aspects.is_empty() {
app_name.to_string()
} else {
format!("{}.{}", app_name, aspects.join("."))
};
let mut name_hasher = Sha256::new();
name_hasher.update(full_name.as_bytes());
let name_hash_full = name_hasher.finalize();
let name_hash = &name_hash_full[..10];
let raw_key = if let Ok(s) = std::str::from_utf8(did_or_material) {
if s.starts_with("did:") {
extract_raw_pubkey_from_did(s)
} else if did_or_material.len() == 32 {
let mut arr = [0u8; 32];
arr.copy_from_slice(did_or_material);
arr
} else {
let mut hasher = Sha256::new();
hasher.update(did_or_material);
let res = hasher.finalize();
let mut arr = [0u8; 32];
arr.copy_from_slice(&res);
arr
}
} else if did_or_material.len() == 32 {
let mut arr = [0u8; 32];
arr.copy_from_slice(did_or_material);
arr
} else {
let mut hasher = Sha256::new();
hasher.update(did_or_material);
let res = hasher.finalize();
let mut arr = [0u8; 32];
arr.copy_from_slice(&res);
arr
};
let mut id_hasher = Sha256::new();
id_hasher.update(raw_key);
let id_hash_full = id_hasher.finalize();
let id_hash = &id_hash_full[..16];
let mut addr_hasher = Sha256::new();
addr_hasher.update(name_hash);
addr_hasher.update(id_hash);
let final_hash = addr_hasher.finalize();
let mut out = [0u8; 16];
out.copy_from_slice(&final_hash[..16]);
out
}
pub fn derive_destination_hex(
did_or_material: &[u8],
app_name: &str,
aspects: &[&str],
) -> String {
let hash = derive_destination_hash(did_or_material, app_name, aspects);
hex::encode(hash)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_destination_derivation_consistency() {
let did = "did:key:z6Mku7Gk6gY7bV1bXzJ5k6q1Y8K9v0X4";
let h1 = derive_destination_hash(did.as_bytes(), "clm", &["pkc", "node"]);
let h2 = derive_destination_hash(did.as_bytes(), "clm", &["pkc", "node"]);
assert_eq!(h1, h2);
assert_eq!(derive_destination_hex(did.as_bytes(), "clm", &["pkc", "node"]), hex::encode(h1));
}
}