use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::fmt;
pub const UNIT_ID_PREFIX: &str = "ku_";
pub const UNIT_ID_HEX_LEN: usize = 12;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct UnitId(String);
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("not a knowledge-unit id (expected `ku_` and {UNIT_ID_HEX_LEN} lowercase hex chars): {0}")]
pub struct UnitIdError(pub String);
impl UnitId {
pub fn mint(
proposer: &str,
domain: &[impl AsRef<str>],
summary: &str,
detail: &str,
action: &str,
) -> Self {
let mut tags: Vec<&str> = domain.iter().map(AsRef::as_ref).collect();
tags.sort_unstable();
tags.dedup();
let mut h = Sha256::new();
h.update(proposer.as_bytes());
for t in tags {
h.update([0x1f]);
h.update(t.as_bytes());
}
for field in [summary, detail, action] {
h.update([0x1e]); h.update(field.as_bytes());
}
let digest = hex::encode(h.finalize());
Self(format!("{UNIT_ID_PREFIX}{}", &digest[..UNIT_ID_HEX_LEN]))
}
pub fn parse(s: &str) -> Result<Self, UnitIdError> {
let err = || UnitIdError(s.to_string());
let hexpart = s.strip_prefix(UNIT_ID_PREFIX).ok_or_else(err)?;
if hexpart.len() != UNIT_ID_HEX_LEN
|| !hexpart
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
{
return Err(err());
}
Ok(Self(s.to_string()))
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn hex(&self) -> &str {
&self.0[UNIT_ID_PREFIX.len()..]
}
}
impl fmt::Display for UnitId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn minting_is_deterministic_and_shape_correct() {
let id = UnitId::mint("did:nostr:a", &["api"], "s", "d", "a");
assert_eq!(id, UnitId::mint("did:nostr:a", &["api"], "s", "d", "a"));
assert_eq!(id.as_str().len(), UNIT_ID_PREFIX.len() + UNIT_ID_HEX_LEN);
assert_eq!(UnitId::parse(id.as_str()).unwrap(), id);
assert_eq!(id.hex().len(), UNIT_ID_HEX_LEN);
}
#[test]
fn domain_order_and_duplicates_do_not_change_identity() {
let a = UnitId::mint("p", &["b", "a", "b"], "s", "d", "x");
let b = UnitId::mint("p", &["a", "b"], "s", "d", "x");
assert_eq!(a, b);
}
#[test]
fn independent_proposers_of_the_same_insight_get_distinct_ids() {
let a = UnitId::mint("did:nostr:a", &["api"], "s", "d", "x");
let b = UnitId::mint("did:nostr:b", &["api"], "s", "d", "x");
assert_ne!(a, b);
}
#[test]
fn field_boundaries_cannot_be_forged_by_concatenation() {
let a = UnitId::mint("p", &["d"], "ab", "", "x");
let b = UnitId::mint("p", &["d"], "a", "b", "x");
assert_ne!(a, b);
}
#[test]
fn malformed_ids_are_refused() {
for bad in [
"a1b2c3d4e5f6",
"ku_",
"ku_TOOSHORT",
"ku_a1b2c3d4e5f",
"ku_a1b2c3d4e5f66",
"ku_A1B2C3D4E5F6",
"ku_a1b2c3d4e5fg",
] {
assert!(UnitId::parse(bad).is_err(), "{bad} should be refused");
}
}
}