sergio/takana
> Una distribución Linux construida con un laboratorio funcional y hermético en el > sótano, y una terminal mutable, clásica y anárquica en el piso de arriba — diseñada > desde el suelo para que una IA programadora entienda, modifique y co…
⎇ 8b2ff3cfd4747f0496f77f392a3e40dd5e49d714
crates/hammer-core/src/hash.rs
Ñawpa willay
Pi imata llamkarqan
ch'uya
digest: blake3 pelado, no length-prefijado — el mismo archivo tenía dos hex
1//! Direccionamiento por contenido (CAS). Ver `docs/02-build-lab.md` §2.
2//!
3//! El `ArtifactHash` identifica un artefacto por TODO lo que influye en su salida:
4//! commit fuente + parches + flags/compilador/target + hashes de dependencias.
5
6use std::os::unix::ffi::OsStrExt;
7use std::os::unix::fs::PermissionsExt;
8use std::path::{Path, PathBuf};
9
10use serde::{Deserialize, Serialize};
11
12/// Hash BLAKE3 de un artefacto, con prefijo legible `b3:`.
13#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
14pub struct ArtifactHash(String);
15
16impl ArtifactHash {
17 /// Construye desde bytes ya hasheados (representación hex).
18 pub fn from_hex(hex: impl Into<String>) -> Self {
19 ArtifactHash(format!("b3:{}", hex.into()))
20 }
21
22 /// Hashea un conjunto ordenado de entradas. El llamador es responsable de pasar las
23 /// entradas en orden canónico y estable (ver `docs/02-build-lab.md` §2).
24 pub fn of_inputs(inputs: &[&[u8]]) -> Self {
25 let mut hasher = blake3::Hasher::new();
26 for chunk in inputs {
27 // length-prefijado para evitar colisiones por concatenación ambigua.
28 hasher.update(&(chunk.len() as u64).to_le_bytes());
29 hasher.update(chunk);
30 }
31 ArtifactHash(format!("b3:{}", hasher.finalize().to_hex()))
32 }
33
34 /// Forma corta para directorios del store: `<hash-sin-prefijo>-<name>`.
35 pub fn store_dir_name(&self, name: &str) -> String {
36 let bare = self.0.strip_prefix("b3:").unwrap_or(&self.0);
37 format!("{bare}-{name}")
38 }
39
40 pub fn as_str(&self) -> &str {
41 &self.0
42 }
43
44 /// Hash de **contenido** de un árbol de archivos: BLAKE3 determinista sobre los bytes reales
45 /// (rutas relativas ordenadas + tipo + bit de ejecución + contenido / target de symlink).
46 ///
47 /// A diferencia de [`of_inputs`](Self::of_inputs) (input-addressed: identifica por *qué*
48 /// produjo el artefacto — fuente, flags, deps), esto identifica por *qué bytes son*. Es lo que
49 /// **Stage 2** ([SDD 11](../../docs/11-bootstrap.md)) necesita para verificar
50 /// bit-reproducibilidad: `of_tree(stage1) == of_tree(stage1')` ⇒ el sistema se reconstruye
51 /// idéntico. No sigue symlinks (hashea su target literal); el orden del filesystem no afecta
52 /// (se ordena por ruta). El modo se reduce al bit de ejecución (lo único semánticamente
53 /// relevante; el resto lo fija `seal` de forma consistente).
54 pub fn of_tree(root: &Path) -> std::io::Result<ArtifactHash> {
55 let mut rels: Vec<PathBuf> = Vec::new();
56 collect_rel(root, Path::new(""), &mut rels)?;
57 rels.sort();
58
59 let mut hasher = blake3::Hasher::new();
60 hasher.update(b"hammer-tree-v1");
61 for rel in &rels {
62 let abs = root.join(rel);
63 let meta = std::fs::symlink_metadata(&abs)?;
64 let relb = rel.as_os_str().as_bytes();
65 hasher.update(&(relb.len() as u64).to_le_bytes());
66 hasher.update(relb);
67
68 let ft = meta.file_type();
69 if ft.is_symlink() {
70 let tgt = std::fs::read_link(&abs)?;
71 let t = tgt.as_os_str().as_bytes();
72 hasher.update(b"L");
73 hasher.update(&(t.len() as u64).to_le_bytes());
74 hasher.update(t);
75 } else if ft.is_dir() {
76 hasher.update(b"D");
77 } else {
78 // Archivo regular: bit de ejecución + contenido.
79 let exec = meta.permissions().mode() & 0o111 != 0;
80 hasher.update(if exec { b"Fx" } else { b"F0" });
81 let bytes = std::fs::read(&abs)?;
82 hasher.update(&(bytes.len() as u64).to_le_bytes());
83 hasher.update(&bytes);
84 }
85 }
86 Ok(ArtifactHash(format!("b3:{}", hasher.finalize().to_hex())))
87 }
88
89 /// BLAKE3 **crudo** del contenido de un fichero (sin framing): exactamente `blake3(bytes)`. Es lo
90 /// que computa el `blake3_of` de `arje-cas` y el `expected_hash` de un `.swm`, así que sirve para
91 /// la atestación de integridad al arranque (el gate que arje aplica antes de incarnar). A diferencia
92 /// de [`of_inputs`](Self::of_inputs) (length-prefijado) y [`of_tree`](Self::of_tree) (árbol con
93 /// rutas/modo), aquí el hash es del binario tal cual ⇒ casa con quien recompute `blake3` del fichero.
94 pub fn of_file(path: &Path) -> std::io::Result<ArtifactHash> {
95 let mut f = std::fs::File::open(path)?;
96 let mut hasher = blake3::Hasher::new();
97 std::io::copy(&mut f, &mut hasher)?;
98 Ok(ArtifactHash(format!("b3:{}", hasher.finalize().to_hex())))
99 }
100
101 /// BLAKE3 crudo de un buffer en memoria — exactamente `blake3(bytes)`, la misma convención que
102 /// [`of_file`](Self::of_file). Lo usa el checker de evidencia (H1b) para anclar el stdout de un
103 /// check contra su `expected_output`: quien recompute `blake3` de la salida obtiene el mismo `b3:…`.
104 ///
105 /// **Ésta, y no [`of_inputs`](Self::of_inputs), es la que direcciona un blob por su contenido**
106 /// (ADR 0014): con una sola entrada el length-prefijado no desambigua nada y cuesta que el
107 /// nombre deje de ser verificable por un tercero con `b3sum` en la mano. Vale también fuera del
108 /// repo: churay (tawasuyu) direcciona sus blobs con esta misma función bajo el mismo prefijo
109 /// `b3:`, así que un CAS compartido sólo cierra si los dos lados usan ésta — con `of_inputs` el
110 /// mismo archivo tendría dos hex distintos y la discrepancia no fallaría ruidosamente.
111 pub fn of_bytes(bytes: &[u8]) -> ArtifactHash {
112 ArtifactHash(format!("b3:{}", blake3::hash(bytes).to_hex()))
113 }
114}
115
116/// Recorre `root` recursivamente acumulando rutas **relativas a `root`** en `out`. No sigue
117/// symlinks (los registra como entrada, sin descender).
118fn collect_rel(root: &Path, rel: &Path, out: &mut Vec<PathBuf>) -> std::io::Result<()> {
119 for entry in std::fs::read_dir(root.join(rel))? {
120 let entry = entry?;
121 let child = rel.join(entry.file_name());
122 let is_dir = entry.file_type()?.is_dir();
123 out.push(child.clone());
124 if is_dir {
125 collect_rel(root, &child, out)?;
126 }
127 }
128 Ok(())
129}
130
131impl std::fmt::Display for ArtifactHash {
132 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133 f.write_str(&self.0)
134 }
135}
136
137#[cfg(test)]
138mod tests {
139 use super::*;
140
141 #[test]
142 fn deterministic_and_order_sensitive() {
143 let a = ArtifactHash::of_inputs(&[b"grep", b"abc123", b"--static"]);
144 let b = ArtifactHash::of_inputs(&[b"grep", b"abc123", b"--static"]);
145 assert_eq!(a, b, "misma entrada ⇒ mismo hash");
146
147 let c = ArtifactHash::of_inputs(&[b"abc123", b"grep", b"--static"]);
148 assert_ne!(a, c, "orden distinto ⇒ hash distinto");
149 }
150
151 #[test]
152 fn store_dir_name_strips_prefix() {
153 let h = ArtifactHash::from_hex("deadbeef");
154 assert_eq!(h.store_dir_name("grep"), "deadbeef-grep");
155 }
156
157 // --- of_tree: content-hash determinista (pre-Stage 2) ---
158
159 fn populate(d: &std::path::Path) {
160 use std::os::unix::fs::{symlink, PermissionsExt};
161 std::fs::create_dir_all(d.join("usr/bin")).unwrap();
162 std::fs::write(d.join("usr/bin/hello"), b"#!/bin/sh\necho hi\n").unwrap();
163 std::fs::set_permissions(d.join("usr/bin/hello"), std::fs::Permissions::from_mode(0o755)).unwrap();
164 std::fs::write(d.join("README"), b"docs").unwrap();
165 symlink("usr/bin/hello", d.join("link")).unwrap();
166 }
167
168 #[test]
169 fn of_tree_is_deterministic_across_two_identical_trees() {
170 let a = tempfile::tempdir().unwrap();
171 let b = tempfile::tempdir().unwrap();
172 populate(a.path());
173 populate(b.path());
174 // Mismo contenido en dos dirs distintos ⇒ mismo hash (independiente de la ruta raíz).
175 assert_eq!(ArtifactHash::of_tree(a.path()).unwrap(), ArtifactHash::of_tree(b.path()).unwrap());
176 assert!(ArtifactHash::of_tree(a.path()).unwrap().as_str().starts_with("b3:"));
177 }
178
179 #[test]
180 fn of_tree_detects_content_exec_and_symlink_changes() {
181 let base = tempfile::tempdir().unwrap();
182 populate(base.path());
183 let h0 = ArtifactHash::of_tree(base.path()).unwrap();
184
185 // (1) contenido distinto.
186 let c = tempfile::tempdir().unwrap();
187 populate(c.path());
188 std::fs::write(c.path().join("README"), b"otra cosa").unwrap();
189 assert_ne!(h0, ArtifactHash::of_tree(c.path()).unwrap(), "el contenido entra al hash");
190
191 // (2) bit de ejecución distinto.
192 let e = tempfile::tempdir().unwrap();
193 populate(e.path());
194 std::fs::set_permissions(e.path().join("usr/bin/hello"), std::fs::Permissions::from_mode(0o644)).unwrap();
195 assert_ne!(h0, ArtifactHash::of_tree(e.path()).unwrap(), "el bit de ejecución entra al hash");
196
197 // (3) target de symlink distinto.
198 let s = tempfile::tempdir().unwrap();
199 populate(s.path());
200 std::fs::remove_file(s.path().join("link")).unwrap();
201 std::os::unix::fs::symlink("README", s.path().join("link")).unwrap();
202 assert_ne!(h0, ArtifactHash::of_tree(s.path()).unwrap(), "el target del symlink entra al hash");
203 }
204}