Skip to main content

nibkeep_base/
hash.rs

1//! Content hashes that name their algorithm.
2
3use std::fmt;
4use std::io;
5use std::str::FromStr;
6
7use crate::cbor::{self, FromCbor, ToCbor, Value};
8
9/// The ID of a change: the BLAKE3 hash of its encoding.
10#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
11pub struct ChangeId(Hash);
12
13impl ChangeId {
14	/// The hash.
15	#[must_use]
16	pub const fn hash(&self) -> &Hash {
17		&self.0
18	}
19
20	/// The ID of the change whose hash this is.
21	#[must_use]
22	pub const fn from_hash(hash: Hash) -> Self {
23		Self(hash)
24	}
25}
26
27impl fmt::Display for ChangeId {
28	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29		self.0.fmt(f)
30	}
31}
32
33impl FromStr for ChangeId {
34	type Err = <Hash as std::str::FromStr>::Err;
35
36	fn from_str(text: &str) -> Result<Self, Self::Err> {
37		text.parse().map(Self)
38	}
39}
40
41impl ToCbor for ChangeId {
42	fn to_cbor(&self) -> Value {
43		self.0.to_cbor()
44	}
45}
46
47impl FromCbor for ChangeId {
48	fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
49		Hash::from_cbor(value).map(Self)
50	}
51}
52
53/// The algorithms that produce hashes ([`Hash`](struct@Hash)).
54#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
55#[non_exhaustive]
56pub enum HashAlgorithm {
57	/// BLAKE3 with a 32-byte digest.
58	Blake3,
59}
60
61impl HashAlgorithm {
62	/// The name used in the text form of a hash, such as `blake3`.
63	#[must_use]
64	pub const fn name(self) -> &'static str {
65		match self {
66			Self::Blake3 => "blake3",
67		}
68	}
69
70	/// The algorithm's code in the multihash table.
71	const fn multihash_code(self) -> u64 {
72		match self {
73			Self::Blake3 => 0x1e,
74		}
75	}
76
77	/// The length of the algorithm's digest in bytes.
78	const fn digest_len(self) -> usize {
79		match self {
80			Self::Blake3 => 32,
81		}
82	}
83
84	fn from_name(name: &str) -> Option<Self> {
85		(name == Self::Blake3.name()).then_some(Self::Blake3)
86	}
87
88	fn from_multihash_code(code: u64) -> Option<Self> {
89		(code == Self::Blake3.multihash_code()).then_some(Self::Blake3)
90	}
91}
92
93/// The longest digest of any algorithm, in bytes.
94const MAX_DIGEST_LEN: usize = 64;
95
96/// The hash of some content, together with the algorithm that produced it.
97///
98/// Its text form is the algorithm's name, a colon and the digest in lowercase hexadecimal,
99/// such as `blake3:af1349b9…`. In CBOR, it is a byte string holding a multihash.
100#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
101pub struct Hash {
102	algorithm: HashAlgorithm,
103	/// The digest, followed by zeros up to [`MAX_DIGEST_LEN`]. Keeping the unused bytes
104	/// zero makes the derived comparisons depend on the algorithm and the digest only.
105	digest: [u8; MAX_DIGEST_LEN],
106}
107
108impl Hash {
109	/// Hashes `data` with BLAKE3.
110	#[must_use]
111	pub fn of(data: &[u8]) -> Self {
112		Self::from_blake3(&blake3::hash(data))
113	}
114
115	/// The algorithm that produced the hash.
116	#[must_use]
117	pub fn algorithm(&self) -> HashAlgorithm {
118		self.algorithm
119	}
120
121	/// The digest. Its length depends on the algorithm.
122	#[must_use]
123	pub fn digest(&self) -> &[u8] {
124		&self.digest[..self.algorithm.digest_len()]
125	}
126
127	/// The binary form: a multihash, that is the algorithm's code and the digest's length
128	/// as unsigned varints, followed by the digest.
129	#[must_use]
130	pub fn to_multihash(&self) -> Vec<u8> {
131		let digest = self.digest();
132		let mut out = Vec::with_capacity(2 + digest.len());
133		write_varint(&mut out, self.algorithm.multihash_code());
134		write_varint(&mut out, digest.len() as u64);
135		out.extend_from_slice(digest);
136		out
137	}
138
139	/// Reads the binary form.
140	///
141	/// # Errors
142	///
143	/// Returns an error if `bytes` is not a multihash, if its algorithm is unknown, or if
144	/// the digest does not have the algorithm's length.
145	pub fn from_multihash(bytes: &[u8]) -> Result<Self, ParseHashError> {
146		let mut rest = bytes;
147		let code = read_varint(&mut rest)?;
148		let len = read_varint(&mut rest)?;
149		let algorithm =
150			HashAlgorithm::from_multihash_code(code).ok_or(ParseHashError::UnknownAlgorithm)?;
151		if usize::try_from(len).ok() != Some(algorithm.digest_len()) {
152			return Err(ParseHashError::WrongLength);
153		}
154		if rest.len() != algorithm.digest_len() {
155			return Err(ParseHashError::Malformed);
156		}
157		Ok(Self::new(algorithm, rest))
158	}
159
160	fn from_blake3(hash: &blake3::Hash) -> Self {
161		Self::new(HashAlgorithm::Blake3, hash.as_bytes())
162	}
163
164	/// Builds a hash from a digest that has the algorithm's length.
165	fn new(algorithm: HashAlgorithm, digest: &[u8]) -> Self {
166		debug_assert_eq!(digest.len(), algorithm.digest_len());
167		let mut padded = [0; MAX_DIGEST_LEN];
168		padded[..digest.len()].copy_from_slice(digest);
169		Self {
170			algorithm,
171			digest: padded,
172		}
173	}
174}
175
176impl fmt::Display for Hash {
177	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178		write!(f, "{}:", self.algorithm.name())?;
179		self.digest()
180			.iter()
181			.try_for_each(|byte| write!(f, "{byte:02x}"))
182	}
183}
184
185impl fmt::Debug for Hash {
186	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187		write!(f, "Hash({self})")
188	}
189}
190
191impl FromStr for Hash {
192	type Err = ParseHashError;
193
194	/// Reads the text form. Only lowercase hexadecimal is accepted, so that every hash has
195	/// exactly one text form.
196	fn from_str(text: &str) -> Result<Self, Self::Err> {
197		let (name, hex) = text.split_once(':').ok_or(ParseHashError::Malformed)?;
198		let algorithm = HashAlgorithm::from_name(name).ok_or(ParseHashError::UnknownAlgorithm)?;
199		if hex.len() != 2 * algorithm.digest_len() {
200			return Err(ParseHashError::WrongLength);
201		}
202		let mut digest = [0; MAX_DIGEST_LEN];
203		for (byte, pair) in digest.iter_mut().zip(hex.as_bytes().chunks(2)) {
204			*byte = (hex_digit(pair[0])? << 4) | hex_digit(pair[1])?;
205		}
206		Ok(Self { algorithm, digest })
207	}
208}
209
210impl ToCbor for Hash {
211	fn to_cbor(&self) -> Value {
212		Value::Bytes(self.to_multihash())
213	}
214}
215
216impl FromCbor for Hash {
217	fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
218		match value {
219			Value::Bytes(bytes) => {
220				Self::from_multihash(bytes).map_err(|_| cbor::Error::Expected("a multihash"))
221			}
222			_ => Err(cbor::Error::Expected("a multihash")),
223		}
224	}
225}
226
227/// Why a hash could not be read.
228#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
229#[non_exhaustive]
230pub enum ParseHashError {
231	/// The algorithm is not one that NibKeep knows.
232	#[error("unknown hash algorithm")]
233	UnknownAlgorithm,
234	/// The digest does not have the algorithm's length.
235	#[error("digest has the wrong length for its algorithm")]
236	WrongLength,
237	/// The input is not a hash in the expected form.
238	#[error("not a hash in the expected form")]
239	Malformed,
240}
241
242/// Computes a [`Hash`](struct@Hash) incrementally, for content that arrives in pieces.
243#[derive(Clone, Debug, Default)]
244pub struct Hasher(blake3::Hasher);
245
246impl Hasher {
247	/// Returns a hasher that has seen no content yet.
248	#[must_use]
249	pub fn new() -> Self {
250		Self::default()
251	}
252
253	/// Adds content.
254	pub fn update(&mut self, data: &[u8]) -> &mut Self {
255		self.0.update(data);
256		self
257	}
258
259	/// Returns the hash of all the content added so far.
260	#[must_use]
261	pub fn finalize(&self) -> Hash {
262		Hash::from_blake3(&self.0.finalize())
263	}
264}
265
266impl io::Write for Hasher {
267	fn write(&mut self, data: &[u8]) -> io::Result<usize> {
268		self.update(data);
269		Ok(data.len())
270	}
271
272	fn flush(&mut self) -> io::Result<()> {
273		Ok(())
274	}
275}
276
277fn hex_digit(digit: u8) -> Result<u8, ParseHashError> {
278	match digit {
279		b'0'..=b'9' => Ok(digit - b'0'),
280		b'a'..=b'f' => Ok(digit - b'a' + 10),
281		_ => Err(ParseHashError::Malformed),
282	}
283}
284
285/// Writes an unsigned varint: seven bits per byte, least significant first, with the high
286/// bit set on every byte but the last.
287fn write_varint(out: &mut Vec<u8>, mut value: u64) {
288	loop {
289		let low = u8::try_from(value & 0x7f).expect("seven bits");
290		value >>= 7;
291		if value == 0 {
292			out.push(low);
293			return;
294		}
295		out.push(low | 0x80);
296	}
297}
298
299/// Reads an unsigned varint in its minimal form, as the multiformats specification
300/// requires, and at most nine bytes long.
301fn read_varint(bytes: &mut &[u8]) -> Result<u64, ParseHashError> {
302	let mut value = 0u64;
303	for (index, &byte) in bytes.iter().enumerate().take(9) {
304		value |= u64::from(byte & 0x7f) << (7 * index);
305		if byte & 0x80 == 0 {
306			if byte == 0 && index > 0 {
307				return Err(ParseHashError::Malformed);
308			}
309			*bytes = &bytes[index + 1..];
310			return Ok(value);
311		}
312	}
313	Err(ParseHashError::Malformed)
314}