| 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 | |
| 11 | use core::fmt; |
| 12 | use 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)] |
| 17 | pub 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 | |
| 30 | impl 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 | |
| 81 | impl 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)] |
| 89 | pub struct ObjectId([u8; 32]); |
| 90 | |
| 91 | impl 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 | |
| 126 | const HEX_DIGITS: &[u8; 16] = b"0123456789abcdef"; |
| 127 | |
| 128 | impl 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 | |
| 140 | impl 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)] |
| 148 | pub 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 | |
| 155 | impl 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 | |
| 171 | impl std::error::Error for ParseIdError {} |
| 172 | |
| 173 | fn 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 | |
| 181 | impl 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 | let (pairs, _) = digits.as_chunks::<2>(); |
| 193 | for (i, [high, low]) in pairs.iter().enumerate() { |
| 194 | let high = hex_value(*high).ok_or(ParseIdError::Digit(2 * i))?; |
| 195 | let low = hex_value(*low).ok_or(ParseIdError::Digit(2 * i + 1))?; |
| 196 | bytes[i] = (high << 4) | low; |
| 197 | } |
| 198 | Ok(Self(bytes)) |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | /// Incremental hashing, for payloads that arrive in pieces. |
| 203 | #[derive(Clone)] |
| 204 | pub struct IdHasher { |
| 205 | inner: blake3::Hasher, |
| 206 | } |
| 207 | |
| 208 | impl IdHasher { |
| 209 | /// Starts hashing an object of `kind`. |
| 210 | pub fn new(kind: Kind) -> Self { |
| 211 | Self { |
| 212 | inner: blake3::Hasher::new_derive_key(kind.context()), |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | /// Feeds the next piece of the payload. |
| 217 | pub fn update(&mut self, bytes: &[u8]) -> &mut Self { |
| 218 | self.inner.update(bytes); |
| 219 | self |
| 220 | } |
| 221 | |
| 222 | /// The id of everything fed so far. The hasher can keep going afterwards. |
| 223 | pub fn finalize(&self) -> ObjectId { |
| 224 | ObjectId(*self.inner.finalize().as_bytes()) |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | impl fmt::Debug for IdHasher { |
| 229 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 230 | f.debug_struct("IdHasher").finish_non_exhaustive() |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | #[cfg(test)] |
| 235 | mod tests { |
| 236 | use super::*; |
| 237 | |
| 238 | /// Golden vectors. Each one can be checked independently with the `b3sum` |
| 239 | /// tool: `printf 'hello\n' | b3sum --derive-key "elffuss-braid 2026 blob v1"`. |
| 240 | const GOLDEN: &[(Kind, &[u8], &str)] = &[ |
| 241 | ( |
| 242 | Kind::Blob, |
| 243 | b"", |
| 244 | "ff9c212a7ef64fa38f0c411b3a68d523a20fd197ee3ba03fa4a44b7c5e99c958", |
| 245 | ), |
| 246 | ( |
| 247 | Kind::Blob, |
| 248 | b"hello\n", |
| 249 | "6acd5cdf880a325d2df716699943aae586ad77d54fb2ed0c5a3f53c76fa56f89", |
| 250 | ), |
| 251 | ( |
| 252 | Kind::Tree, |
| 253 | b"", |
| 254 | "46f1ab000b3145d2e28ff69f7570eb88065d76ef86905bb268699adb9c860c08", |
| 255 | ), |
| 256 | ( |
| 257 | Kind::Changeset, |
| 258 | b"", |
| 259 | "1be995db81f244ac5ea57f1ba45d9f9da94ad4edd6dbfa0979c16101a34d04ef", |
| 260 | ), |
| 261 | ( |
| 262 | Kind::ChunkList, |
| 263 | b"", |
| 264 | "f14231be43c0cc73e7c4850ec9d980e6952b56c57f7125d0c39d16874be2ab04", |
| 265 | ), |
| 266 | ( |
| 267 | Kind::Derived, |
| 268 | b"", |
| 269 | "6f101e23c531e6e3959878774beefb475944b2f0200e52eafb37fd80f97df172", |
| 270 | ), |
| 271 | ]; |
| 272 | |
| 273 | #[test] |
| 274 | fn golden_vectors() { |
| 275 | for (kind, payload, expected) in GOLDEN { |
| 276 | assert_eq!( |
| 277 | ObjectId::hash(*kind, payload).to_hex(), |
| 278 | *expected, |
| 279 | "{kind} {payload:?}" |
| 280 | ); |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | #[test] |
| 285 | fn kinds_never_share_an_id() { |
| 286 | for payload in [&b""[..], b"hello\n", &[0u8; 1000]] { |
| 287 | let mut ids: Vec<ObjectId> = Kind::ALL |
| 288 | .iter() |
| 289 | .map(|kind| ObjectId::hash(*kind, payload)) |
| 290 | .collect(); |
| 291 | ids.sort(); |
| 292 | ids.dedup(); |
| 293 | assert_eq!(ids.len(), Kind::ALL.len()); |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | #[test] |
| 298 | fn streaming_matches_one_shot() { |
| 299 | // Long enough to cross BLAKE3's 1 KiB chunk and SIMD batch boundaries. |
| 300 | let payload: Vec<u8> = (0..300_000u32).map(|i| (i * 31 % 251) as u8).collect(); |
| 301 | let whole = ObjectId::hash(Kind::Blob, &payload); |
| 302 | for piece in [1, 7, 1024, 4096, 65_537] { |
| 303 | let mut hasher = IdHasher::new(Kind::Blob); |
| 304 | for part in payload.chunks(piece) { |
| 305 | hasher.update(part); |
| 306 | } |
| 307 | assert_eq!(hasher.finalize(), whole, "pieces of {piece}"); |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | #[test] |
| 312 | fn text_round_trip() { |
| 313 | let id = ObjectId::hash(Kind::Blob, b"round trip"); |
| 314 | let text = id.to_hex(); |
| 315 | assert_eq!(text.len(), 64); |
| 316 | assert_eq!(text.parse::<ObjectId>(), Ok(id)); |
| 317 | assert_eq!(id.short(), text[..ObjectId::SHORT_HEX]); |
| 318 | assert_eq!(format!("{id:?}"), format!("ObjectId({text})")); |
| 319 | } |
| 320 | |
| 321 | #[test] |
| 322 | fn rejects_bad_text() { |
| 323 | let good = ObjectId::hash(Kind::Blob, b"x").to_hex(); |
| 324 | assert_eq!("".parse::<ObjectId>(), Err(ParseIdError::Length(0))); |
| 325 | assert_eq!( |
| 326 | good[..63].parse::<ObjectId>(), |
| 327 | Err(ParseIdError::Length(63)) |
| 328 | ); |
| 329 | let mut upper = good.clone().into_bytes(); |
| 330 | upper[0] = b'A'; |
| 331 | assert_eq!( |
| 332 | String::from_utf8(upper).unwrap().parse::<ObjectId>(), |
| 333 | Err(ParseIdError::Digit(0)) |
| 334 | ); |
| 335 | let mut bad = good.clone().into_bytes(); |
| 336 | bad[10] = b'g'; |
| 337 | assert_eq!( |
| 338 | String::from_utf8(bad).unwrap().parse::<ObjectId>(), |
| 339 | Err(ParseIdError::Digit(10)) |
| 340 | ); |
| 341 | } |
| 342 | |
| 343 | #[test] |
| 344 | fn kind_codes_round_trip() { |
| 345 | for kind in Kind::ALL { |
| 346 | assert_eq!(Kind::from_code(kind.code()), Some(kind)); |
| 347 | } |
| 348 | for code in [0u8, 6, 7, 127, 255] { |
| 349 | assert_eq!(Kind::from_code(code), None); |
| 350 | } |
| 351 | } |
| 352 | } |