use core::fmt;
use serde::{Serialize, Serializer};
use crate::address::Address;
const LEAF_DOMAIN: u8 = 0x00;
const NODE_DOMAIN: u8 = 0x01;
const LABEL_PROGRAM: &str = "tear.genesis.program.v1";
const LABEL_INTENT: &str = "tear.genesis.intent.v1";
const LABEL_CONTEXT: &str = "tear.genesis.context.v1";
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Guid([u8; 32]);
impl Guid {
#[must_use]
pub fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
#[must_use]
pub fn to_hex(&self) -> String {
let mut out = String::with_capacity(64);
for b in self.0 {
out.push_str(&format!("{b:02x}"));
}
out
}
#[must_use]
pub fn short(&self) -> String {
self.to_hex()[..16].to_string()
}
}
impl fmt::Display for Guid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_hex())
}
}
impl fmt::Debug for Guid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Guid({})", self.to_hex())
}
}
impl Serialize for Guid {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.to_hex())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Genesis {
pub program: String,
pub requested_address: Address,
pub args: Vec<String>,
pub cwd: String,
pub parent: Option<Guid>,
}
impl Genesis {
#[must_use]
pub fn new(program: impl Into<String>, requested_address: Address, cwd: impl Into<String>) -> Self {
Self {
program: program.into(),
requested_address,
args: Vec::new(),
cwd: cwd.into(),
parent: None,
}
}
#[must_use]
pub fn with_args<I, S>(mut self, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.args = args.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub fn with_parent(mut self, parent: Guid) -> Self {
self.parent = Some(parent);
self
}
#[must_use]
pub fn guid(&self) -> Guid {
let [program, intent, context] = self.leaves();
Guid(node(&node(&program, &intent), &context))
}
fn leaves(&self) -> [[u8; 32]; 3] {
let program = leaf(LABEL_PROGRAM, |h| {
frame(h, self.program.as_bytes());
});
let intent = leaf(LABEL_INTENT, |h| {
frame(h, self.requested_address.to_string().as_bytes());
frame_len(h, self.args.len());
for arg in &self.args {
frame(h, arg.as_bytes());
}
});
let context = leaf(LABEL_CONTEXT, |h| {
frame(h, self.cwd.as_bytes());
match &self.parent {
None => {
h.update(&[0u8]);
}
Some(parent) => {
h.update(&[1u8]);
h.update(parent.as_bytes());
}
}
});
[program, intent, context]
}
}
fn frame(h: &mut blake3::Hasher, bytes: &[u8]) {
frame_len(h, bytes.len());
h.update(bytes);
}
fn frame_len(h: &mut blake3::Hasher, len: usize) {
h.update(&(len as u64).to_le_bytes());
}
fn leaf(label: &str, body: impl FnOnce(&mut blake3::Hasher)) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(&[LEAF_DOMAIN]);
frame(&mut h, label.as_bytes());
body(&mut h);
*h.finalize().as_bytes()
}
fn node(left: &[u8; 32], right: &[u8; 32]) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(&[NODE_DOMAIN]);
h.update(left);
h.update(right);
*h.finalize().as_bytes()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::address::Address;
fn addr(s: &str) -> Address {
Address::parse(s).expect("test fixture must be a legal address")
}
fn sample() -> Genesis {
Genesis {
program: "/bin/zsh".into(),
requested_address: addr("work.akeyless.helm-charts.build"),
args: vec!["-l".into()],
cwd: "/code/akeylesslabs/helm-charts".into(),
parent: None,
}
}
#[test]
fn the_same_genesis_always_derives_the_same_guid() {
assert_eq!(sample().guid(), sample().guid());
let g = sample();
assert_eq!(g.guid(), g.guid());
}
#[test]
fn the_guid_is_a_full_256_bit_root_not_a_truncation() {
let guid = sample().guid();
assert_eq!(guid.as_bytes().len(), 32);
assert_eq!(guid.to_hex().len(), 64);
assert!(
guid.as_bytes()[8..].iter().any(|b| *b != 0),
"bytes past the first 8 must not be dropped"
);
assert_eq!(guid.short(), &guid.to_hex()[..16]);
}
#[test]
fn a_different_program_derives_a_different_guid() {
let mut other = sample();
other.program = "/bin/bash".into();
assert_ne!(sample().guid(), other.guid());
}
#[test]
fn a_different_requested_address_derives_a_different_guid() {
let mut other = sample();
other.requested_address = addr("work.akeyless.helm-charts.test");
assert_ne!(sample().guid(), other.guid());
}
#[test]
fn different_args_derive_a_different_guid() {
let mut other = sample();
other.args = vec!["-i".into()];
assert_ne!(sample().guid(), other.guid());
let mut none = sample();
none.args = Vec::new();
assert_ne!(sample().guid(), none.guid());
assert_ne!(other.guid(), none.guid());
}
#[test]
fn a_different_cwd_derives_a_different_guid() {
let mut other = sample();
other.cwd = "/code/akeylesslabs/cli".into();
assert_ne!(sample().guid(), other.guid());
}
#[test]
fn a_different_parent_derives_a_different_guid() {
let parent_a = sample().guid();
let parent_b = Genesis::new("/bin/bash", addr("work.other"), "/tmp").guid();
assert_ne!(parent_a, parent_b);
let orphan = sample();
let under_a = sample().with_parent(parent_a);
let under_b = sample().with_parent(parent_b);
assert_ne!(orphan.guid(), under_a.guid());
assert_ne!(orphan.guid(), under_b.guid());
assert_ne!(under_a.guid(), under_b.guid());
}
#[test]
fn every_leaf_is_load_bearing() {
let base = sample();
let mut variants = vec![base.guid()];
let mut v = base.clone();
v.program = "/bin/bash".into();
variants.push(v.guid());
let mut v = base.clone();
v.requested_address = addr("work.other");
variants.push(v.guid());
let mut v = base.clone();
v.args = vec!["-l".into(), "-i".into()];
variants.push(v.guid());
let mut v = base.clone();
v.cwd = "/elsewhere".into();
variants.push(v.guid());
let v = base.clone().with_parent(base.guid());
variants.push(v.guid());
let mut seen = std::collections::BTreeSet::new();
for g in &variants {
assert!(seen.insert(g.to_hex()), "leaf perturbation collided: {g:?}");
}
assert_eq!(seen.len(), 6);
}
#[test]
fn args_are_length_framed_not_concatenated() {
let split = sample().with_args(["a", "b"]);
let joined = sample().with_args(["ab"]);
let dotted = sample().with_args(["a.b"]);
assert_ne!(split.guid(), joined.guid());
assert_ne!(split.guid(), dotted.guid());
assert_ne!(joined.guid(), dotted.guid());
let trailing_empty = sample().with_args(["a", ""]);
let bare = sample().with_args(["a"]);
assert_ne!(trailing_empty.guid(), bare.guid());
}
#[test]
fn leaf_and_interior_domains_cannot_collide() {
let l = leaf("x", |h| frame(h, b"left"));
let r = leaf("x", |h| frame(h, b"right"));
let interior = node(&l, &r);
let leafish = {
let mut h = blake3::Hasher::new();
h.update(&[LEAF_DOMAIN]);
h.update(&l);
h.update(&r);
*h.finalize().as_bytes()
};
assert_ne!(interior, leafish, "domain prefixes must separate");
assert_ne!(LEAF_DOMAIN, NODE_DOMAIN);
let raw = *blake3::hash(b"left").as_bytes();
assert_ne!(l, raw);
}
#[test]
fn the_root_is_the_documented_tree_shape() {
let g = sample();
let [l0, l1, l2] = g.leaves();
let expected = node(&node(&l0, &l1), &l2);
assert_eq!(g.guid().as_bytes(), &expected);
assert_ne!(l0, l1);
assert_ne!(l1, l2);
assert_ne!(l0, l2);
}
#[test]
fn a_parent_link_can_only_be_a_derived_guid() {
let parent = Genesis::new("/bin/zsh", addr("work"), "/code");
let child = Genesis::new("/bin/zsh", addr("work.build"), "/code")
.with_parent(parent.guid());
assert_eq!(child.parent, Some(parent.guid()));
assert_ne!(child.guid(), parent.guid());
}
#[test]
fn renaming_is_structurally_outside_the_hash() {
let genesis = sample();
let identity = genesis.guid();
let mut live_alias = genesis.requested_address.clone();
assert_eq!(live_alias.to_string(), "work.akeyless.helm-charts.build");
live_alias = addr("archive.2026.helm-charts.build");
assert_eq!(genesis.guid(), identity);
assert_ne!(live_alias, genesis.requested_address);
}
#[test]
fn guid_serializes_outward_as_lowercase_hex() {
let guid = sample().guid();
let json = serde_json::to_string(&guid).unwrap();
assert_eq!(json, format!("\"{}\"", guid.to_hex()));
assert_eq!(json.len(), 66);
assert!(guid.to_hex().chars().all(|c| c.is_ascii_hexdigit()));
assert!(!guid.to_hex().chars().any(|c| c.is_ascii_uppercase()));
}
#[test]
fn genesis_serializes_with_its_address_as_a_plain_string() {
let json = serde_json::to_value(sample()).unwrap();
assert_eq!(
json["requested_address"],
serde_json::json!("work.akeyless.helm-charts.build")
);
assert_eq!(json["parent"], serde_json::Value::Null);
}
#[test]
fn guid_display_and_debug_agree_on_the_hex() {
let guid = sample().guid();
assert_eq!(guid.to_string(), guid.to_hex());
assert_eq!(format!("{guid:?}"), format!("Guid({})", guid.to_hex()));
}
#[test]
fn genesis_commits_to_exactly_program_intent_and_context() {
let Genesis {
program,
requested_address,
args,
cwd,
parent,
} = sample();
assert_eq!(program, "/bin/zsh");
assert_eq!(requested_address.to_string(), "work.akeyless.helm-charts.build");
assert_eq!(args, vec!["-l".to_string()]);
assert_eq!(cwd, "/code/akeylesslabs/helm-charts");
assert!(parent.is_none());
}
#[test]
fn guid_never_gains_a_constructor_other_than_genesis() {
let src = include_str!("genesis.rs");
let code: String = src
.lines()
.map(str::trim_start)
.filter(|l| !l.starts_with("//"))
.collect::<Vec<_>>()
.join("\n");
let code = code.split("mod tests").next().unwrap_or(&code);
assert!(
!code.contains("Deserialize"),
"`Deserialize` appeared in genesis.rs. A peer could then SEND an \
identity instead of deriving one, which is the whole thing this \
type prevents."
);
assert!(
!code.contains("FromStr"),
"`FromStr` would let any string become a Guid"
);
assert!(
!code.contains("impl From<"),
"a `From` impl would be a second way to mint a Guid"
);
assert!(
code.contains("pub struct Guid([u8; 32]);"),
"Guid's bytes must stay private — a `pub` field is a constructor"
);
assert_eq!(
code.matches("-> Guid").count(),
1,
"exactly one function may return a Guid, and it is Genesis::guid"
);
assert!(code.contains("pub fn guid(&self) -> Guid"));
assert!(
code.contains("impl Serialize for Guid"),
"a Guid must still report OUTWARD (audit, list, MCP reads)"
);
}
}