Skip to main content

hashiverse_lib/tools/
hashing.rs

1//! # Blake3 hashing helpers
2//!
3//! Thin wrappers over `blake3::Hasher` that return a strongly-typed
4//! [`crate::tools::types::Hash`] (32 bytes) instead of raw bytes. Blake3 is used as the
5//! canonical *fast* hash throughout the protocol — for [`crate::tools::types::Id`]
6//! derivation, content addressing, bucket location hashing, and as the last step of
7//! any multi-input hash that needs a single output.
8//!
9//! The four functions are minor ergonomic variants:
10//! - [`hash`] — one slice.
11//! - [`hash_two`] — two slices, concatenated without copying.
12//! - [`hash_multiple`] — arbitrary slice of slices.
13//! - [`hash_multiple_plus_one`] — the common case of "hash this list, plus one more tail
14//!   value" without allocating a combined slice.
15//!
16//! For the deliberately *slow* multi-algorithm chain used in proof-of-work, see
17//! [`crate::tools::pow`].
18
19use crate::tools::types::Hash;
20
21pub fn hash(data: &[u8]) -> Hash {
22
23    let mut hasher = blake3::Hasher::new();
24    hasher.update(data);
25    let hash = hasher.finalize();
26
27    Hash(hash.into())
28}
29
30pub fn hash_two(data_1: &[u8], data_2: &[u8]) -> Hash {
31
32    let mut hasher = blake3::Hasher::new();
33    hasher.update(data_1);
34    hasher.update(data_2);
35    let hash = hasher.finalize();
36
37    Hash(hash.into())
38}
39
40pub fn hash_multiple(datas: &[&[u8]]) -> Hash {
41
42    let mut hasher = blake3::Hasher::new();
43    for &data in datas {
44        hasher.update(data);
45    }
46    let hash = hasher.finalize();
47
48    Hash(hash.into())
49}
50
51pub fn hash_multiple_plus_one(datas: &[&[u8]], data_plus_one: &[u8]) -> Hash {
52
53    let mut hasher = blake3::Hasher::new();
54    for &data in datas {
55        hasher.update(data);
56    }
57    hasher.update(data_plus_one);
58    let hash = hasher.finalize();
59
60    Hash(hash.into())
61}