Debian Codegraph @

debian/rust-vendor/blake3/src/hazmat.rs

raw
1 //! Low-level tree manipulations and other sharp tools
2 //!
3 //! The target audience for this module is projects like [Bao](https://github.com/oconnor663/bao),
4 //! which work directly with the interior hashes ("chaining values") of BLAKE3 chunks and subtrees.
5 //! For example, you could use these functions to implement a BitTorrent-like protocol using the
6 //! BLAKE3 tree structure, or to hash an input that's distributed across different machines. These
7 //! use cases are advanced, and most applications don't need this module. Also:
8 //!
9 //! <div class="warning">
10 //!
11 //! **Warning:** This module is *hazardous material*. If you've heard folks say *don't roll your
12 //! own crypto,* this is the sort of thing they're talking about. These functions have complicated
13 //! requirements, and any mistakes will give you garbage output and/or break the security
14 //! properties that BLAKE3 is supposed to have. Read section 2.1 of [the BLAKE3
15 //! paper](https://github.com/BLAKE3-team/BLAKE3-specs/blob/master/blake3.pdf) to understand the
16 //! tree structure you need to maintain. Test your code against [`blake3::hash`](../fn.hash.html)
17 //! and make sure you can get the same outputs for [lots of different
18 //! inputs](https://github.com/BLAKE3-team/BLAKE3/blob/master/test_vectors/test_vectors.json).
19 //!
20 //! </div>
21 //!
22 //! On the other hand:
23 //!
24 //! <div class="warning">
25 //!
26 //! **Encouragement:** Playing with these functions is a great way to learn how BLAKE3 works on the
27 //! inside. Have fun!
28 //!
29 //! </div>
30 //!
31 //! The main entrypoint for this module is the [`HasherExt`] trait, particularly the
32 //! [`set_input_offset`](HasherExt::set_input_offset) and
33 //! [`finalize_non_root`](HasherExt::finalize_non_root) methods. These let you compute the chaining
34 //! values of individual chunks or subtrees. You then combine these chaining values into larger
35 //! subtrees using [`merge_subtrees_non_root`] and finally (once at the very top)
36 //! [`merge_subtrees_root`] or [`merge_subtrees_root_xof`].
37 //!
38 //! # Examples
39 //!
40 //! Here's an example of computing all the interior hashes in a 3-chunk tree:
41 //!
42 //! ```text
43 //! root
44 //! / \
45 //! parent \
46 //! / \ \
47 //! chunk0 chunk1 chunk2
48 //! ```
49 //!
50 //! ```
51 //! # fn main() {
52 //! use blake3::{Hasher, CHUNK_LEN};
53 //! use blake3::hazmat::{merge_subtrees_non_root, merge_subtrees_root, Mode};
54 //! use blake3::hazmat::HasherExt; // an extension trait for Hasher
55 //!
56 //! let chunk0 = [b'a'; CHUNK_LEN];
57 //! let chunk1 = [b'b'; CHUNK_LEN];
58 //! let chunk2 = [b'c'; 42]; // The final chunk can be short.
59 //!
60 //! // Compute the non-root hashes ("chaining values") of all three chunks. Chunks or subtrees
61 //! // that don't begin at the start of the input use `set_input_offset` to say where they begin.
62 //! let chunk0_cv = Hasher::new()
63 //! // .set_input_offset(0) is the default.
64 //! .update(&chunk0)
65 //! .finalize_non_root();
66 //! let chunk1_cv = Hasher::new()
67 //! .set_input_offset(CHUNK_LEN as u64)
68 //! .update(&chunk1)
69 //! .finalize_non_root();
70 //! let chunk2_cv = Hasher::new()
71 //! .set_input_offset(2 * CHUNK_LEN as u64)
72 //! .update(&chunk2)
73 //! .finalize_non_root();
74 //!
75 //! // Join the first two chunks with a non-root parent node and compute its chaining value.
76 //! let parent_cv = merge_subtrees_non_root(&chunk0_cv, &chunk1_cv, Mode::Hash);
77 //!
78 //! // Join that parent node and the third chunk with a root parent node and compute the hash.
79 //! let root_hash = merge_subtrees_root(&parent_cv, &chunk2_cv, Mode::Hash);
80 //!
81 //! // Double check that we got the right answer.
82 //! let mut combined_input = Vec::new();
83 //! combined_input.extend_from_slice(&chunk0);
84 //! combined_input.extend_from_slice(&chunk1);
85 //! combined_input.extend_from_slice(&chunk2);
86 //! assert_eq!(root_hash, blake3::hash(&combined_input));
87 //! # }
88 //! ```
89 //!
90 //! Hashing many chunks together is important for performance, because it allows the implementation
91 //! to use SIMD parallelism internally. ([AVX-512](https://en.wikipedia.org/wiki/AVX-512) for
92 //! example needs 16 chunks to really get going.) We can reproduce `parent_cv` by hashing `chunk0`
93 //! and `chunk1` at the same time:
94 //!
95 //! ```
96 //! # fn main() {
97 //! # use blake3::{Hasher, CHUNK_LEN};
98 //! # use blake3::hazmat::{Mode, HasherExt, merge_subtrees_non_root, merge_subtrees_root};
99 //! # let chunk0 = [b'a'; CHUNK_LEN];
100 //! # let chunk1 = [b'b'; CHUNK_LEN];
101 //! # let chunk0_cv = Hasher::new().update(&chunk0).finalize_non_root();
102 //! # let chunk1_cv = Hasher::new().set_input_offset(CHUNK_LEN as u64).update(&chunk1).finalize_non_root();
103 //! # let parent_cv = merge_subtrees_non_root(&chunk0_cv, &chunk1_cv, Mode::Hash);
104 //! # let mut combined_input = Vec::new();
105 //! # combined_input.extend_from_slice(&chunk0);
106 //! # combined_input.extend_from_slice(&chunk1);
107 //! let left_subtree_cv = Hasher::new()
108 //! // .set_input_offset(0) is the default.
109 //! .update(&combined_input[..2 * CHUNK_LEN])
110 //! .finalize_non_root();
111 //! assert_eq!(left_subtree_cv, parent_cv);
112 //!
113 //! // Using multiple updates gives the same answer, though it's not as efficient.
114 //! let mut subtree_hasher = Hasher::new();
115 //! // Again, .set_input_offset(0) is the default.
116 //! subtree_hasher.update(&chunk0);
117 //! subtree_hasher.update(&chunk1);
118 //! assert_eq!(left_subtree_cv, subtree_hasher.finalize_non_root());
119 //! # }
120 //! ```
121 //!
122 //! However, hashing multiple chunks together **must** respect the overall tree structure. Hashing
123 //! `chunk0` and `chunk1` together is valid, but hashing `chunk1` and `chunk2` together is
124 //! incorrect and gives a garbage result that will never match a standard BLAKE3 hash. The
125 //! implementation includes a few best-effort asserts to catch some of these mistakes, but these
126 //! checks aren't guaranteed. For example, this second call to `update` currently panics:
127 //!
128 //! ```should_panic
129 //! # fn main() {
130 //! # use blake3::{Hasher, CHUNK_LEN};
131 //! # use blake3::hazmat::HasherExt;
132 //! # let chunk0 = [b'a'; CHUNK_LEN];
133 //! # let chunk1 = [b'b'; CHUNK_LEN];
134 //! # let chunk2 = [b'c'; 42];
135 //! let oops = Hasher::new()
136 //! .set_input_offset(CHUNK_LEN as u64)
137 //! .update(&chunk1)
138 //! // PANIC: "the subtree starting at 1024 contains at most 1024 bytes"
139 //! .update(&chunk2)
140 //! .finalize_non_root();
141 //! # }
142 //! ```
143 //!
144 //! For more on valid tree structures, see the docs for and [`left_subtree_len`] and
145 //! [`max_subtree_len`], and see section 2.1 of [the BLAKE3
146 //! paper](https://github.com/BLAKE3-team/BLAKE3-specs/blob/master/blake3.pdf). Note that the
147 //! merging functions ([`merge_subtrees_root`] and friends) don't know the shape of the left and
148 //! right subtrees you're giving them, and they can't help you catch mistakes. The best way to
149 //! catch mistakes with these is to compare your root output to the [`blake3::hash`](crate::hash)
150 //! of the same input.
151
152 use crate::platform::Platform;
153 use crate::{CHUNK_LEN, CVWords, Hasher, IV, KEY_LEN, OUT_LEN};
154
155 /// Extension methods for [`Hasher`]. This is the main entrypoint to the `hazmat` module.
156 pub trait HasherExt {
157 /// Similar to [`Hasher::new_derive_key`] but using a pre-hashed [`ContextKey`] from
158 /// [`hash_derive_key_context`].
159 ///
160 /// The [`hash_derive_key_context`] function is the _only_ valid source of the [`ContextKey`].
161 /// Any other source ([`hash`](crate::hash), [`keyed_hash`](crate::keyed_hash), arbitrary bytes
162 /// from the caller) violates the security requirements.
163 ///
164 /// Calling [`derive_key`](crate::derive_key) or [`Hasher::new_derive_key`] in a loop will
165 /// re-hash the context string every time. This constructor function is a performance
166 /// optimization to avoid that repeated work. If you hardcode the [`ContextKey`], the
167 /// derive-key mode becomes zero-overhead, like the keyed mode.
168 ///
169 /// # Example
170 ///
171 /// ```
172 /// use blake3::Hasher;
173 /// use blake3::hazmat::HasherExt;
174 ///
175 /// let context_key = blake3::hazmat::hash_derive_key_context("foo");
176 /// let mut hasher = Hasher::new_from_context_key(&context_key);
177 /// hasher.update(b"bar");
178 /// let derived_key = *hasher.finalize().as_bytes();
179 ///
180 /// assert_eq!(derived_key, blake3::derive_key("foo", b"bar"));
181 /// ```
182 fn new_from_context_key(context_key: &ContextKey) -> Self;
183
184 /// Configure the `Hasher` to process a chunk or subtree starting at `offset` bytes into the
185 /// whole input.
186 ///
187 /// You must call this function before processing any input with [`update`](Hasher::update) or
188 /// similar. This step isn't required for the first chunk, or for a subtree that includes the
189 /// first chunk (i.e. when the `offset` is zero), but it's required for all other chunks and
190 /// subtrees.
191 ///
192 /// The starting input offset of a subtree implies a maximum possible length for that subtree.
193 /// See [`max_subtree_len`] and section 2.1 of [the BLAKE3
194 /// paper](https://github.com/BLAKE3-team/BLAKE3-specs/blob/master/blake3.pdf). Note that only
195 /// subtrees along the right edge of the whole tree can have a length less than their maximum
196 /// possible length.
197 ///
198 /// See the [module level examples](index.html#examples).
199 ///
200 /// # Panics
201 ///
202 /// This function panics if the `Hasher` has already accepted any input with
203 /// [`update`](Hasher::update) or similar.
204 ///
205 /// This should always be paired with [`finalize_non_root`](HasherExt::finalize_non_root). It's
206 /// never correct to use a non-zero input offset with [`finalize`](Hasher::finalize) or
207 /// [`finalize_xof`](Hasher::finalize_xof). The `offset` must also be a multiple of
208 /// `CHUNK_LEN`. Violating either of these rules will currently fail an assertion and panic,
209 /// but this is not guaranteed.
210 fn set_input_offset(&mut self, offset: u64) -> &mut Self;
211
212 /// Finalize the non-root hash ("chaining value") of the current chunk or subtree.
213 ///
214 /// Afterwards you can merge subtree chaining values into parent nodes using
215 /// [`merge_subtrees_non_root`] and ultimately into the root node with either
216 /// [`merge_subtrees_root`] (similar to [`Hasher::finalize`]) or [`merge_subtrees_root_xof`]
217 /// (similar to [`Hasher::finalize_xof`]).
218 ///
219 /// See the [module level examples](index.html#examples), particularly the discussion of valid
220 /// tree structures.
221 fn finalize_non_root(&self) -> ChainingValue;
222 }
223
224 impl HasherExt for Hasher {
225 fn new_from_context_key(context_key: &[u8; KEY_LEN]) -> Hasher {
226 let context_key_words = crate::platform::words_from_le_bytes_32(context_key);
227 Hasher::new_internal(&context_key_words, crate::DERIVE_KEY_MATERIAL)
228 }
229
230 fn set_input_offset(&mut self, offset: u64) -> &mut Hasher {
231 assert_eq!(self.count(), 0, "hasher has already accepted input");
232 assert_eq!(
233 offset % CHUNK_LEN as u64,
234 0,
235 "offset ({offset}) must be a chunk boundary (divisible by {CHUNK_LEN})",
236 );
237 let counter = offset / CHUNK_LEN as u64;
238 self.chunk_state.chunk_counter = counter;
239 self.initial_chunk_counter = counter;
240 self
241 }
242
243 fn finalize_non_root(&self) -> ChainingValue {
244 assert_ne!(self.count(), 0, "empty subtrees are never valid");
245 self.final_output().chaining_value()
246 }
247 }
248
249 /// The maximum length of a subtree in bytes, given its starting offset in bytes
250 ///
251 /// If you try to hash more than this many bytes as one subtree, you'll end up merging parent nodes
252 /// that shouldn't be merged, and your output will be garbage. [`Hasher::update`] will currently
253 /// panic in this case, but this is not guaranteed.
254 ///
255 /// For input offset zero (the default), there is no maximum length, and this function returns
256 /// `None`. For all other offsets it returns `Some`. Note that valid offsets must be a multiple of
257 /// [`CHUNK_LEN`] (1024); it's not possible to start hashing a chunk in the middle.
258 ///
259 /// In the example tree below, chunks are numbered by their _0-based index_. The subtree that
260 /// _starts_ with chunk 3, i.e. `input_offset = 3 * CHUNK_LEN`, includes only that one chunk, so
261 /// its max length is `Some(CHUNK_LEN)`. The subtree that starts with chunk 6 includes chunk 7 but
262 /// not chunk 8, so its max length is `Some(2 * CHUNK_LEN)`. The subtree that starts with chunk 12
263 /// includes chunks 13, 14, and 15, but if the tree were bigger it would not include chunk 16, so
264 /// its max length is `Some(4 * CHUNK_LEN)`. One way to think about the rule here is that, if you
265 /// go beyond the max subtree length from a given starting offset, you start dealing with subtrees
266 /// that include chunks _to the left_ of where you started.
267 ///
268 /// ```text
269 /// root
270 /// / \
271 /// . .
272 /// / \ / \
273 /// . . . .
274 /// / \ / \ / \ / \
275 /// . . . . . . . .
276 /// / \ / \ / \ / \ / \ / \ / \ / \
277 /// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
278 /// ```
279 ///
280 /// The general rule turns out to be that for a subtree starting at a 0-based chunk index N greater
281 /// than zero, the maximum number of chunks in that subtree is the largest power-of-two that
282 /// divides N, which is given by `1 << N.trailing_zeros()`.
283 ///
284 /// This function can be useful for writing tests or debug assertions, but it's actually rare to
285 /// use this for real control flow. Callers who split their input recursively using
286 /// [`left_subtree_len`] will automatically satisfy the `max_subtree_len` bound and don't
287 /// necessarily need to check. It's also common to choose some fixed power-of-two subtree size, say
288 /// 64 chunks, and divide your input up into slices of that fixed length (with the final slice
289 /// possibly short). This approach also automatically satisfies the `max_subtree_len` bound and
290 /// doesn't need to check. Proving that this is true can be an interesting exercise. Note that
291 /// chunks 0, 4, 8, and 12 all begin subtrees of at least 4 chunks in the example tree above.
292 ///
293 /// # Panics
294 ///
295 /// This function currently panics if `input_offset` is not a multiple of `CHUNK_LEN`. This is not
296 /// guaranteed.
297 #[inline(always)]
298 pub fn max_subtree_len(input_offset: u64) -> Option<u64> {
299 if input_offset == 0 {
300 return None;
301 }
302 assert_eq!(input_offset % CHUNK_LEN as u64, 0);
303 let counter = input_offset / CHUNK_LEN as u64;
304 let max_chunks = 1 << counter.trailing_zeros();
305 Some(max_chunks * CHUNK_LEN as u64)
306 }
307
308 #[test]
309 fn test_max_subtree_len() {
310 assert_eq!(max_subtree_len(0), None);
311 // (chunk index, max chunks)
312 let cases = [
313 (1, 1),
314 (2, 2),
315 (3, 1),
316 (4, 4),
317 (5, 1),
318 (6, 2),
319 (7, 1),
320 (8, 8),
321 ];
322 for (chunk_index, max_chunks) in cases {
323 let input_offset = chunk_index * CHUNK_LEN as u64;
324 assert_eq!(
325 max_subtree_len(input_offset),
326 Some(max_chunks * CHUNK_LEN as u64),
327 );
328 }
329 }
330
331 /// Given the length in bytes of either a complete input or a subtree input, return the number of
332 /// bytes that belong to its left child subtree. The rest belong to its right child subtree.
333 ///
334 /// Concretely, this function returns the largest power-of-two number of bytes that's strictly less
335 /// than `input_len`. This leads to a tree where all left subtrees are "complete" and at least as
336 /// large as their sibling right subtrees, as specified in section 2.1 of [the BLAKE3
337 /// paper](https://github.com/BLAKE3-team/BLAKE3-specs/blob/master/blake3.pdf). For example, if an
338 /// input is exactly two chunks, the left subtree gets the first chunk and the right subtree gets
339 /// the second chunk. But if an input is two chunks plus one more byte, then its left subtree gets
340 /// two chunks, and its right subtree only gets one byte.
341 ///
342 /// This function isn't meaningful for one chunk of input, because chunks don't have children. It
343 /// currently panics in debug mode if `input_len <= CHUNK_LEN`.
344 ///
345 /// # Example
346 ///
347 /// Hash a input of random length as two subtrees:
348 ///
349 /// ```
350 /// # #[cfg(feature = "std")] {
351 /// use blake3::hazmat::{left_subtree_len, merge_subtrees_root, HasherExt, Mode};
352 /// use blake3::{Hasher, CHUNK_LEN};
353 ///
354 /// // Generate a random-length input. Note that to be split into two subtrees, the input length
355 /// // must be greater than CHUNK_LEN.
356 /// let input_len = rand::random_range(CHUNK_LEN + 1..1_000_000);
357 /// let mut input = vec![0; input_len];
358 /// rand::fill(&mut input[..]);
359 ///
360 /// // Compute the left and right subtree hashes and then the root hash. left_subtree_len() tells
361 /// // us exactly where to split the input. Any other split would either panic (if we're lucky) or
362 /// // lead to an incorrect root hash.
363 /// let left_len = left_subtree_len(input_len as u64) as usize;
364 /// let left_subtree_cv = Hasher::new()
365 /// .update(&input[..left_len])
366 /// .finalize_non_root();
367 /// let right_subtree_cv = Hasher::new()
368 /// .set_input_offset(left_len as u64)
369 /// .update(&input[left_len..])
370 /// .finalize_non_root();
371 /// let root_hash = merge_subtrees_root(&left_subtree_cv, &right_subtree_cv, Mode::Hash);
372 ///
373 /// // Double check the answer.
374 /// assert_eq!(root_hash, blake3::hash(&input));
375 /// # }
376 /// ```
377 #[inline(always)]
378 pub fn left_subtree_len(input_len: u64) -> u64 {
379 debug_assert!(input_len > CHUNK_LEN as u64);
380 // Note that .next_power_of_two() is greater than *or equal*.
381 ((input_len + 1) / 2).next_power_of_two()
382 }
383
384 #[test]
385 fn test_left_subtree_len() {
386 assert_eq!(left_subtree_len(1025), 1024);
387 for boundary_case in [2, 4, 8, 16, 32, 64] {
388 let input_len = boundary_case * CHUNK_LEN as u64;
389 assert_eq!(left_subtree_len(input_len - 1), input_len / 2);
390 assert_eq!(left_subtree_len(input_len), input_len / 2);
391 assert_eq!(left_subtree_len(input_len + 1), input_len);
392 }
393 }
394
395 /// The `mode` argument to [`merge_subtrees_root`] and friends
396 ///
397 /// See the [module level examples](index.html#examples).
398 #[derive(Copy, Clone, Debug)]
399 pub enum Mode<'a> {
400 /// The default [`hash`][crate::hash] mode. Subtrees must be hashed with [`Hasher::new`].
401 Hash,
402
403 /// The [`keyed_hash`][crate::keyed_hash] mode. Subtrees must be hashed with
404 /// [`Hasher::new_keyed`].
405 KeyedHash(&'a [u8; KEY_LEN]),
406
407 /// The [`derive_key`][crate::derive_key] mode. Subtrees must be hashed with either
408 /// [`Hasher::new_derive_key`] or [`Hasher::new_from_context_key`]. The [`ContextKey`] comes
409 /// from [`hash_derive_key_context`].
410 DeriveKeyMaterial(&'a ContextKey),
411 }
412
413 impl<'a> Mode<'a> {
414 fn key_words(&self) -> CVWords {
415 match self {
416 Mode::Hash => *IV,
417 Mode::KeyedHash(key) => crate::platform::words_from_le_bytes_32(key),
418 Mode::DeriveKeyMaterial(cx_key) => crate::platform::words_from_le_bytes_32(cx_key),
419 }
420 }
421
422 fn flags_byte(&self) -> u8 {
423 match self {
424 Mode::Hash => 0,
425 Mode::KeyedHash(_) => crate::KEYED_HASH,
426 Mode::DeriveKeyMaterial(_) => crate::DERIVE_KEY_MATERIAL,
427 }
428 }
429 }
430
431 /// "Chaining value" is the academic term for a non-root or non-final hash.
432 ///
433 /// Besides just sounding fancy, it turns out there are [security
434 /// reasons](https://jacko.io/tree_hashing.html) to be careful about the difference between
435 /// (root/final) hashes and (non-root/non-final) chaining values.
436 pub type ChainingValue = [u8; OUT_LEN];
437
438 fn merge_subtrees_inner(
439 left_child: &ChainingValue,
440 right_child: &ChainingValue,
441 mode: Mode,
442 ) -> crate::Output {
443 crate::parent_node_output(
444 &left_child,
445 &right_child,
446 &mode.key_words(),
447 mode.flags_byte(),
448 Platform::detect(),
449 )
450 }
451
452 /// Compute a non-root parent node chaining value from two child chaining values.
453 ///
454 /// See the [module level examples](index.html#examples), particularly the discussion of valid tree
455 /// structures. The left and right child chaining values can come from either
456 /// [`Hasher::finalize_non_root`](HasherExt::finalize_non_root) or other calls to
457 /// `merge_subtrees_non_root`. "Chaining value" is the academic term for a non-root or non-final
458 /// hash.
459 pub fn merge_subtrees_non_root(
460 left_child: &ChainingValue,
461 right_child: &ChainingValue,
462 mode: Mode,
463 ) -> ChainingValue {
464 merge_subtrees_inner(left_child, right_child, mode).chaining_value()
465 }
466
467 /// Compute a root hash from two child chaining values.
468 ///
469 /// See the [module level examples](index.html#examples), particularly the discussion of valid tree
470 /// structures. The left and right child chaining values can come from either
471 /// [`Hasher::finalize_non_root`](HasherExt::finalize_non_root) or [`merge_subtrees_non_root`].
472 /// "Chaining value" is the academic term for a non-root or non-final hash.
473 ///
474 /// Note that inputs of [`CHUNK_LEN`] or less don't produce any parent nodes and can't be hashed
475 /// using this function. In that case you must get the root hash from [`Hasher::finalize`] (or just
476 /// [`blake3::hash`](crate::hash)).
477 pub fn merge_subtrees_root(
478 left_child: &ChainingValue,
479 right_child: &ChainingValue,
480 mode: Mode,
481 ) -> crate::Hash {
482 merge_subtrees_inner(left_child, right_child, mode).root_hash()
483 }
484
485 /// Build a root [`OutputReader`](crate::OutputReader) from two child chaining values.
486 ///
487 /// See also the [module level examples](index.html#examples), particularly the discussion of valid
488 /// tree structures. The left and right child chaining values can come from either
489 /// [`Hasher::finalize_non_root`](HasherExt::finalize_non_root) or [`merge_subtrees_non_root`].
490 /// "Chaining value" is the academic term for a non-root or non-final hash.
491 ///
492 /// Note that inputs of [`CHUNK_LEN`] or less don't produce any parent nodes and can't be hashed
493 /// using this function. In that case you must get the `OutputReader` from
494 /// [`Hasher::finalize_xof`].
495 ///
496 /// # Example
497 ///
498 /// ```
499 /// use blake3::hazmat::{merge_subtrees_root_xof, HasherExt, Mode};
500 /// use blake3::{Hasher, CHUNK_LEN};
501 ///
502 /// // Hash a 2-chunk subtree in steps. Note that only
503 /// // the final chunk can be shorter than CHUNK_LEN.
504 /// let chunk0 = &[42; CHUNK_LEN];
505 /// let chunk1 = b"hello world";
506 /// let chunk0_cv = Hasher::new()
507 /// .update(chunk0)
508 /// .finalize_non_root();
509 /// let chunk1_cv = Hasher::new()
510 /// .set_input_offset(CHUNK_LEN as u64)
511 /// .update(chunk1)
512 /// .finalize_non_root();
513 ///
514 /// // Obtain a blake3::OutputReader at the root and extract 1000 bytes.
515 /// let mut output_reader = merge_subtrees_root_xof(&chunk0_cv, &chunk1_cv, Mode::Hash);
516 /// let mut output_bytes = [0; 1_000];
517 /// output_reader.fill(&mut output_bytes);
518 ///
519 /// // Double check the answer.
520 /// let mut hasher = Hasher::new();
521 /// hasher.update(chunk0);
522 /// hasher.update(chunk1);
523 /// let mut expected = [0; 1_000];
524 /// hasher.finalize_xof().fill(&mut expected);
525 /// assert_eq!(output_bytes, expected);
526 /// ```
527 pub fn merge_subtrees_root_xof(
528 left_child: &ChainingValue,
529 right_child: &ChainingValue,
530 mode: Mode,
531 ) -> crate::OutputReader {
532 crate::OutputReader::new(merge_subtrees_inner(left_child, right_child, mode))
533 }
534
535 /// An alias to distinguish [`hash_derive_key_context`] outputs from other keys.
536 pub type ContextKey = [u8; KEY_LEN];
537
538 /// Hash a [`derive_key`](crate::derive_key) context string and return a [`ContextKey`].
539 ///
540 /// This has the same security requirement as [`derive_key`](crate::derive_key). **The context
541 /// string should be hardcoded, globally unique, and application-specific.**
542 ///
543 /// The _only_ valid uses for the returned [`ContextKey`] are
544 /// [`new_from_context_key`](HasherExt::new_from_context_key) and [`Mode::DeriveKeyMaterial`]
545 /// (together with the merge subtree functions).
546 ///
547 /// # Example
548 ///
549 /// ```
550 /// use blake3::Hasher;
551 /// use blake3::hazmat::HasherExt;
552 ///
553 /// let context_key = blake3::hazmat::hash_derive_key_context("foo");
554 /// let mut hasher = Hasher::new_from_context_key(&context_key);
555 /// hasher.update(b"bar");
556 /// let derived_key = *hasher.finalize().as_bytes();
557 ///
558 /// assert_eq!(derived_key, blake3::derive_key("foo", b"bar"));
559 /// ```
560 pub fn hash_derive_key_context(context: &str) -> ContextKey {
561 crate::hash_all_at_once::<crate::join::SerialJoin>(
562 context.as_bytes(),
563 IV,
564 crate::DERIVE_KEY_CONTEXT,
565 )
566 .root_hash()
567 .0
568 }
569
570 #[cfg(test)]
571 mod test {
572 use super::*;
573
574 #[test]
575 #[should_panic]
576 fn test_empty_subtree_should_panic() {
577 Hasher::new().finalize_non_root();
578 }
579
580 #[test]
581 #[should_panic]
582 fn test_unaligned_offset_should_panic() {
583 Hasher::new().set_input_offset(1);
584 }
585
586 #[test]
587 #[should_panic]
588 fn test_hasher_already_accepted_input_should_panic() {
589 Hasher::new().update(b"x").set_input_offset(0);
590 }
591
592 #[test]
593 #[should_panic]
594 fn test_too_much_input_should_panic() {
595 Hasher::new()
596 .set_input_offset(CHUNK_LEN as u64)
597 .update(&[0; CHUNK_LEN + 1]);
598 }
599
600 #[test]
601 #[should_panic]
602 fn test_set_input_offset_cant_finalize() {
603 Hasher::new().set_input_offset(CHUNK_LEN as u64).finalize();
604 }
605
606 #[test]
607 #[should_panic]
608 fn test_set_input_offset_cant_finalize_xof() {
609 Hasher::new()
610 .set_input_offset(CHUNK_LEN as u64)
611 .finalize_xof();
612 }
613
614 #[test]
615 fn test_grouped_hash() {
616 const MAX_CHUNKS: usize = (crate::test::TEST_CASES_MAX + 1) / CHUNK_LEN;
617 let mut input_buf = [0; crate::test::TEST_CASES_MAX];
618 crate::test::paint_test_input(&mut input_buf);
619 for subtree_chunks in [1, 2, 4, 8, 16, 32] {
620 #[cfg(feature = "std")]
621 dbg!(subtree_chunks);
622 let subtree_len = subtree_chunks * CHUNK_LEN;
623 for &case in crate::test::TEST_CASES {
624 if case <= subtree_len {
625 continue;
626 }
627 #[cfg(feature = "std")]
628 dbg!(case);
629 let input = &input_buf[..case];
630 let expected_hash = crate::hash(input);
631
632 // Collect all the group chaining values.
633 let mut chaining_values = arrayvec::ArrayVec::<ChainingValue, MAX_CHUNKS>::new();
634 let mut subtree_offset = 0;
635 while subtree_offset < input.len() {
636 let take = core::cmp::min(subtree_len, input.len() - subtree_offset);
637 let subtree_input = &input[subtree_offset..][..take];
638 let subtree_cv = Hasher::new()
639 .set_input_offset(subtree_offset as u64)
640 .update(subtree_input)
641 .finalize_non_root();
642 chaining_values.push(subtree_cv);
643 subtree_offset += take;
644 }
645
646 // Compress all the chaining_values together, layer by layer.
647 assert!(chaining_values.len() >= 2);
648 while chaining_values.len() > 2 {
649 let n = chaining_values.len();
650 // Merge each side-by-side pair in place, overwriting the front half of the
651 // array with the merged results. This moves us "up one level" in the tree.
652 for i in 0..(n / 2) {
653 chaining_values[i] = merge_subtrees_non_root(
654 &chaining_values[2 * i],
655 &chaining_values[2 * i + 1],
656 Mode::Hash,
657 );
658 }
659 // If there's an odd CV out, it moves up.
660 if n % 2 == 1 {
661 chaining_values[n / 2] = chaining_values[n - 1];
662 }
663 chaining_values.truncate(n / 2 + n % 2);
664 }
665 assert_eq!(chaining_values.len(), 2);
666 let root_hash =
667 merge_subtrees_root(&chaining_values[0], &chaining_values[1], Mode::Hash);
668 assert_eq!(expected_hash, root_hash);
669 }
670 }
671 }
672
673 #[test]
674 fn test_keyed_hash_xof() {
675 let group0 = &[42; 4096];
676 let group1 = &[43; 4095];
677 let mut input = [0; 8191];
678 input[..4096].copy_from_slice(group0);
679 input[4096..].copy_from_slice(group1);
680 let key = &[44; 32];
681
682 let mut expected_output = [0; 100];
683 Hasher::new_keyed(&key)
684 .update(&input)
685 .finalize_xof()
686 .fill(&mut expected_output);
687
688 let mut hazmat_output = [0; 100];
689 let left = Hasher::new_keyed(key).update(group0).finalize_non_root();
690 let right = Hasher::new_keyed(key)
691 .set_input_offset(group0.len() as u64)
692 .update(group1)
693 .finalize_non_root();
694 merge_subtrees_root_xof(&left, &right, Mode::KeyedHash(&key)).fill(&mut hazmat_output);
695 assert_eq!(expected_output, hazmat_output);
696 }
697
698 #[test]
699 fn test_derive_key() {
700 let context = "foo";
701 let mut input = [0; 1025];
702 crate::test::paint_test_input(&mut input);
703 let expected = crate::derive_key(context, &input);
704
705 let cx_key = hash_derive_key_context(context);
706 let left = Hasher::new_from_context_key(&cx_key)
707 .update(&input[..1024])
708 .finalize_non_root();
709 let right = Hasher::new_from_context_key(&cx_key)
710 .set_input_offset(1024)
711 .update(&input[1024..])
712 .finalize_non_root();
713 let derived_key = merge_subtrees_root(&left, &right, Mode::DeriveKeyMaterial(&cx_key)).0;
714 assert_eq!(expected, derived_key);
715 }
716 }