Elffuss BraidHub

utopia-ia/elffuss-braid public

bceec3f3d91e · 10.4 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Object ids: BLAKE3 in key-derivation mode, with one context string per kind.
5//!
6//! Hashing under a per-kind context gives a blob and a tree with the same bytes
7//! different ids, without a type prefix inside the payload, so a payload can be
8//! hashed while it streams in. A blob id is always the hash of the blob's full
9//! content, however the store happens to keep it (whole, delta, or chunked).
10
11use core::fmt;
12use core::str::FromStr;
13
14/// What an object is. The numeric code is part of the on-disk format.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
16#[repr(u8)]
17pub enum Kind {
18 /// File contents.
19 Blob = 1,
20 /// A directory listing: a flat directory, or one node of a large one.
21 Tree = 2,
22 /// One change to the repository: parents, root tree and per-file changes.
23 Changeset = 3,
24 /// The list of chunks a large blob is stored as.
25 ChunkList = 4,
26 /// A value computed from other objects, such as an index or a mapping.
27 Derived = 5,
28}
29
30impl Kind {
31 /// Every kind, in code order.
32 pub const ALL: [Kind; 5] = [
33 Kind::Blob,
34 Kind::Tree,
35 Kind::Changeset,
36 Kind::ChunkList,
37 Kind::Derived,
38 ];
39
40 /// The BLAKE3 key-derivation context for this kind. Changing one of these
41 /// strings changes every id of that kind, so they are frozen with format v1.
42 pub const fn context(self) -> &'static str {
43 match self {
44 Kind::Blob => "elffuss-braid 2026 blob v1",
45 Kind::Tree => "elffuss-braid 2026 tree v1",
46 Kind::Changeset => "elffuss-braid 2026 changeset v1",
47 Kind::ChunkList => "elffuss-braid 2026 chunklist v1",
48 Kind::Derived => "elffuss-braid 2026 derived v1",
49 }
50 }
51
52 /// The one-byte code stored in object records.
53 pub const fn code(self) -> u8 {
54 self as u8
55 }
56
57 /// The kind with this record code, if there is one.
58 pub const fn from_code(code: u8) -> Option<Kind> {
59 match code {
60 1 => Some(Kind::Blob),
61 2 => Some(Kind::Tree),
62 3 => Some(Kind::Changeset),
63 4 => Some(Kind::ChunkList),
64 5 => Some(Kind::Derived),
65 _ => None,
66 }
67 }
68
69 /// The lowercase name used on the command line and in JSON output.
70 pub const fn name(self) -> &'static str {
71 match self {
72 Kind::Blob => "blob",
73 Kind::Tree => "tree",
74 Kind::Changeset => "changeset",
75 Kind::ChunkList => "chunklist",
76 Kind::Derived => "derived",
77 }
78 }
79}
80
81impl fmt::Display for Kind {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 f.write_str(self.name())
84 }
85}
86
87/// A 32-byte object id. Its text form is 64 lowercase hex digits.
88#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
89pub struct ObjectId([u8; 32]);
90
91impl ObjectId {
92 /// Length of an id in bytes.
93 pub const LEN: usize = 32;
94
95 /// Number of hex digits in the short form shown to people.
96 pub const SHORT_HEX: usize = 12;
97
98 /// Wraps raw id bytes.
99 pub const fn from_bytes(bytes: [u8; 32]) -> Self {
100 Self(bytes)
101 }
102
103 /// The raw id bytes.
104 pub const fn as_bytes(&self) -> &[u8; 32] {
105 &self.0
106 }
107
108 /// Hashes a complete payload as an object of `kind`.
109 pub fn hash(kind: Kind, payload: &[u8]) -> Self {
110 Self(blake3::derive_key(kind.context(), payload))
111 }
112
113 /// The full text form: 64 lowercase hex digits.
114 pub fn to_hex(&self) -> String {
115 self.to_string()
116 }
117
118 /// The first [`Self::SHORT_HEX`] hex digits.
119 pub fn short(&self) -> String {
120 let mut text = self.to_hex();
121 text.truncate(Self::SHORT_HEX);
122 text
123 }
124}
125
126const HEX_DIGITS: &[u8; 16] = b"0123456789abcdef";
127
128impl fmt::Display for ObjectId {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 let mut text = [0u8; 64];
131 for (i, byte) in self.0.iter().enumerate() {
132 text[2 * i] = HEX_DIGITS[usize::from(byte >> 4)];
133 text[2 * i + 1] = HEX_DIGITS[usize::from(byte & 0x0f)];
134 }
135 // Every byte written above is an ASCII hex digit.
136 f.write_str(core::str::from_utf8(&text).map_err(|_| fmt::Error)?)
137 }
138}
139
140impl fmt::Debug for ObjectId {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 write!(f, "ObjectId({self})")
143 }
144}
145
146/// Why a string is not an object id.
147#[derive(Clone, Debug, PartialEq, Eq)]
148pub enum ParseIdError {
149 /// The text is not 64 characters long.
150 Length(usize),
151 /// The character at this byte position is not a lowercase hex digit.
152 Digit(usize),
153}
154
155impl fmt::Display for ParseIdError {
156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157 match self {
158 ParseIdError::Length(len) => {
159 write!(
160 f,
161 "an object id has 64 hex digits, this has {len} characters"
162 )
163 }
164 ParseIdError::Digit(pos) => {
165 write!(f, "character {pos} is not a lowercase hex digit")
166 }
167 }
168 }
169}
170
171impl std::error::Error for ParseIdError {}
172
173fn hex_value(digit: u8) -> Option<u8> {
174 match digit {
175 b'0'..=b'9' => Some(digit - b'0'),
176 b'a'..=b'f' => Some(digit - b'a' + 10),
177 _ => None,
178 }
179}
180
181impl FromStr for ObjectId {
182 type Err = ParseIdError;
183
184 /// Parses the full 64-digit form. Only lowercase is accepted, so two equal
185 /// ids always have equal text.
186 fn from_str(text: &str) -> Result<Self, Self::Err> {
187 let digits = text.as_bytes();
188 if digits.len() != 64 {
189 return Err(ParseIdError::Length(digits.len()));
190 }
191 let mut bytes = [0u8; 32];
192 for (i, pair) in digits.chunks_exact(2).enumerate() {
193 let high = hex_value(pair[0]).ok_or(ParseIdError::Digit(2 * i))?;
194 let low = hex_value(pair[1]).ok_or(ParseIdError::Digit(2 * i + 1))?;
195 bytes[i] = (high << 4) | low;
196 }
197 Ok(Self(bytes))
198 }
199}
200
201/// Incremental hashing, for payloads that arrive in pieces.
202#[derive(Clone)]
203pub struct IdHasher {
204 inner: blake3::Hasher,
205}
206
207impl IdHasher {
208 /// Starts hashing an object of `kind`.
209 pub fn new(kind: Kind) -> Self {
210 Self {
211 inner: blake3::Hasher::new_derive_key(kind.context()),
212 }
213 }
214
215 /// Feeds the next piece of the payload.
216 pub fn update(&mut self, bytes: &[u8]) -> &mut Self {
217 self.inner.update(bytes);
218 self
219 }
220
221 /// The id of everything fed so far. The hasher can keep going afterwards.
222 pub fn finalize(&self) -> ObjectId {
223 ObjectId(*self.inner.finalize().as_bytes())
224 }
225}
226
227impl fmt::Debug for IdHasher {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 f.debug_struct("IdHasher").finish_non_exhaustive()
230 }
231}
232
233#[cfg(test)]
234mod tests {
235 use super::*;
236
237 /// Golden vectors. Each one can be checked independently with the `b3sum`
238 /// tool: `printf 'hello\n' | b3sum --derive-key "elffuss-braid 2026 blob v1"`.
239 const GOLDEN: &[(Kind, &[u8], &str)] = &[
240 (
241 Kind::Blob,
242 b"",
243 "ff9c212a7ef64fa38f0c411b3a68d523a20fd197ee3ba03fa4a44b7c5e99c958",
244 ),
245 (
246 Kind::Blob,
247 b"hello\n",
248 "6acd5cdf880a325d2df716699943aae586ad77d54fb2ed0c5a3f53c76fa56f89",
249 ),
250 (
251 Kind::Tree,
252 b"",
253 "46f1ab000b3145d2e28ff69f7570eb88065d76ef86905bb268699adb9c860c08",
254 ),
255 (
256 Kind::Changeset,
257 b"",
258 "1be995db81f244ac5ea57f1ba45d9f9da94ad4edd6dbfa0979c16101a34d04ef",
259 ),
260 (
261 Kind::ChunkList,
262 b"",
263 "f14231be43c0cc73e7c4850ec9d980e6952b56c57f7125d0c39d16874be2ab04",
264 ),
265 (
266 Kind::Derived,
267 b"",
268 "6f101e23c531e6e3959878774beefb475944b2f0200e52eafb37fd80f97df172",
269 ),
270 ];
271
272 #[test]
273 fn golden_vectors() {
274 for (kind, payload, expected) in GOLDEN {
275 assert_eq!(
276 ObjectId::hash(*kind, payload).to_hex(),
277 *expected,
278 "{kind} {payload:?}"
279 );
280 }
281 }
282
283 #[test]
284 fn kinds_never_share_an_id() {
285 for payload in [&b""[..], b"hello\n", &[0u8; 1000]] {
286 let mut ids: Vec<ObjectId> = Kind::ALL
287 .iter()
288 .map(|kind| ObjectId::hash(*kind, payload))
289 .collect();
290 ids.sort();
291 ids.dedup();
292 assert_eq!(ids.len(), Kind::ALL.len());
293 }
294 }
295
296 #[test]
297 fn streaming_matches_one_shot() {
298 // Long enough to cross BLAKE3's 1 KiB chunk and SIMD batch boundaries.
299 let payload: Vec<u8> = (0..300_000u32).map(|i| (i * 31 % 251) as u8).collect();
300 let whole = ObjectId::hash(Kind::Blob, &payload);
301 for piece in [1, 7, 1024, 4096, 65_537] {
302 let mut hasher = IdHasher::new(Kind::Blob);
303 for part in payload.chunks(piece) {
304 hasher.update(part);
305 }
306 assert_eq!(hasher.finalize(), whole, "pieces of {piece}");
307 }
308 }
309
310 #[test]
311 fn text_round_trip() {
312 let id = ObjectId::hash(Kind::Blob, b"round trip");
313 let text = id.to_hex();
314 assert_eq!(text.len(), 64);
315 assert_eq!(text.parse::<ObjectId>(), Ok(id));
316 assert_eq!(id.short(), text[..ObjectId::SHORT_HEX]);
317 assert_eq!(format!("{id:?}"), format!("ObjectId({text})"));
318 }
319
320 #[test]
321 fn rejects_bad_text() {
322 let good = ObjectId::hash(Kind::Blob, b"x").to_hex();
323 assert_eq!("".parse::<ObjectId>(), Err(ParseIdError::Length(0)));
324 assert_eq!(
325 good[..63].parse::<ObjectId>(),
326 Err(ParseIdError::Length(63))
327 );
328 let mut upper = good.clone().into_bytes();
329 upper[0] = b'A';
330 assert_eq!(
331 String::from_utf8(upper).unwrap().parse::<ObjectId>(),
332 Err(ParseIdError::Digit(0))
333 );
334 let mut bad = good.clone().into_bytes();
335 bad[10] = b'g';
336 assert_eq!(
337 String::from_utf8(bad).unwrap().parse::<ObjectId>(),
338 Err(ParseIdError::Digit(10))
339 );
340 }
341
342 #[test]
343 fn kind_codes_round_trip() {
344 for kind in Kind::ALL {
345 assert_eq!(Kind::from_code(kind.code()), Some(kind));
346 }
347 for code in [0u8, 6, 7, 127, 255] {
348 assert_eq!(Kind::from_code(code), None);
349 }
350 }
351}