Skip to main content

fluence_blake3/
lib.rs

1//! The official Rust implementation of the [BLAKE3] cryptographic hash
2//! function.
3//!
4//! # Examples
5//!
6//! ```
7//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
8//! // Hash an input all at once.
9//! let hash1 = blake3::hash(b"foobarbaz");
10//!
11//! // Hash an input incrementally.
12//! let mut hasher = blake3::Hasher::new();
13//! hasher.update(b"foo");
14//! hasher.update(b"bar");
15//! hasher.update(b"baz");
16//! let hash2 = hasher.finalize();
17//! assert_eq!(hash1, hash2);
18//!
19//! // Extended output. OutputReader also implements Read and Seek.
20//! # #[cfg(feature = "std")] {
21//! let mut output = [0; 1000];
22//! let mut output_reader = hasher.finalize_xof();
23//! output_reader.fill(&mut output);
24//! assert_eq!(hash1, output[..32]);
25//! # }
26//!
27//! // Print a hash as hex.
28//! println!("{}", hash1);
29//! # Ok(())
30//! # }
31//! ```
32//!
33//! # Cargo Features
34//!
35//! The `std` feature (the only feature enabled by default) is required for
36//! implementations of the [`Write`] and [`Seek`] traits, the
37//! [`update_reader`](Hasher::update_reader) helper method, and runtime CPU
38//! feature detection on x86. If this feature is disabled, the only way to use
39//! the x86 SIMD implementations is to enable the corresponding instruction sets
40//! globally, with e.g. `RUSTFLAGS="-C target-cpu=native"`. The resulting binary
41//! will not be portable to other machines.
42//!
43//! The `rayon` feature (disabled by default, but enabled for [docs.rs]) adds
44//! the [`update_rayon`](Hasher::update_rayon) and (in combination with `mmap`
45//! below) [`update_mmap_rayon`](Hasher::update_mmap_rayon) methods, for
46//! multithreaded hashing. However, even if this feature is enabled, all other
47//! APIs remain single-threaded.
48//!
49//! The `mmap` feature (disabled by default, but enabled for [docs.rs]) adds the
50//! [`update_mmap`](Hasher::update_mmap) and (in combination with `rayon` above)
51//! [`update_mmap_rayon`](Hasher::update_mmap_rayon) helper methods for
52//! memory-mapped IO.
53//!
54//! The `zeroize` feature (disabled by default, but enabled for [docs.rs])
55//! implements
56//! [`Zeroize`](https://docs.rs/zeroize/latest/zeroize/trait.Zeroize.html) for
57//! this crate's types.
58//!
59//! The `serde` feature (disabled by default, but enabled for [docs.rs]) implements
60//! [`serde::Serialize`](https://docs.rs/serde/latest/serde/trait.Serialize.html) and
61//! [`serde::Deserialize`](https://docs.rs/serde/latest/serde/trait.Deserialize.html)
62//! for [`Hash`](struct@Hash).
63//!
64//! The NEON implementation is enabled by default for AArch64 but requires the
65//! `neon` feature for other ARM targets. Not all ARMv7 CPUs support NEON, and
66//! enabling this feature will produce a binary that's not portable to CPUs
67//! without NEON support.
68//!
69//! The `traits-preview` feature enables implementations of traits from the
70//! RustCrypto [`digest`] crate, and re-exports that crate as `traits::digest`.
71//! However, the traits aren't stable, and they're expected to change in
72//! incompatible ways before that crate reaches 1.0. For that reason, this crate
73//! makes no SemVer guarantees for this feature, and callers who use it should
74//! expect breaking changes between patch versions. (The "-preview" feature name
75//! follows the conventions of the RustCrypto [`signature`] crate.)
76//!
77//! [`Hasher::update_rayon`]: struct.Hasher.html#method.update_rayon
78//! [BLAKE3]: https://blake3.io
79//! [Rayon]: https://github.com/rayon-rs/rayon
80//! [docs.rs]: https://docs.rs/
81//! [`Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
82//! [`Seek`]: https://doc.rust-lang.org/std/io/trait.Seek.html
83//! [`digest`]: https://crates.io/crates/digest
84//! [`signature`]: https://crates.io/crates/signature
85
86#![cfg_attr(not(feature = "std"), no_std)]
87
88#[cfg(test)]
89mod test;
90
91// The guts module is for incremental use cases like the `bao` crate that need
92// to explicitly compute chunk and parent chaining values. It is semi-stable
93// and likely to keep working, but largely undocumented and not intended for
94// widespread use.
95#[doc(hidden)]
96pub mod guts;
97
98/// Undocumented and unstable, for benchmarks only.
99#[doc(hidden)]
100pub mod platform;
101
102// Platform-specific implementations of the compression function. These
103// BLAKE3-specific cfg flags are set in build.rs.
104#[cfg(blake3_avx2_rust)]
105#[path = "rust_avx2.rs"]
106mod avx2;
107#[cfg(blake3_avx2_ffi)]
108#[path = "ffi_avx2.rs"]
109mod avx2;
110#[cfg(blake3_avx512_ffi)]
111#[path = "ffi_avx512.rs"]
112mod avx512;
113#[cfg(blake3_neon)]
114#[path = "ffi_neon.rs"]
115mod neon;
116mod portable;
117#[cfg(blake3_sse2_rust)]
118#[path = "rust_sse2.rs"]
119mod sse2;
120#[cfg(blake3_sse2_ffi)]
121#[path = "ffi_sse2.rs"]
122mod sse2;
123#[cfg(blake3_sse41_rust)]
124#[path = "rust_sse41.rs"]
125mod sse41;
126#[cfg(blake3_sse41_ffi)]
127#[path = "ffi_sse41.rs"]
128mod sse41;
129
130#[cfg(blake3_wasm32_simd)]
131#[path = "wasm32_simd.rs"]
132mod wasm32_simd;
133
134#[cfg(feature = "traits-preview")]
135pub mod traits;
136
137mod io;
138mod join;
139
140use arrayref::{array_mut_ref, array_ref};
141use arrayvec::{ArrayString, ArrayVec};
142use core::cmp;
143use core::fmt;
144use platform::{Platform, MAX_SIMD_DEGREE, MAX_SIMD_DEGREE_OR_2};
145
146/// The number of bytes in a [`Hash`](struct.Hash.html), 32.
147pub const OUT_LEN: usize = 32;
148
149/// The number of bytes in a key, 32.
150pub const KEY_LEN: usize = 32;
151
152const MAX_DEPTH: usize = 54; // 2^54 * CHUNK_LEN = 2^64
153use guts::{BLOCK_LEN, CHUNK_LEN};
154
155// While iterating the compression function within a chunk, the CV is
156// represented as words, to avoid doing two extra endianness conversions for
157// each compression in the portable implementation. But the hash_many interface
158// needs to hash both input bytes and parent nodes, so its better for its
159// output CVs to be represented as bytes.
160type CVWords = [u32; 8];
161type CVBytes = [u8; 32]; // little-endian
162
163const IV: &CVWords = &[
164    0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19,
165];
166
167const MSG_SCHEDULE: [[usize; 16]; 7] = [
168    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
169    [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8],
170    [3, 4, 10, 12, 13, 2, 7, 14, 6, 5, 9, 0, 11, 15, 8, 1],
171    [10, 7, 12, 9, 14, 3, 13, 15, 4, 0, 11, 2, 5, 8, 1, 6],
172    [12, 13, 9, 11, 15, 10, 14, 8, 7, 2, 5, 3, 0, 1, 6, 4],
173    [9, 14, 11, 5, 8, 12, 15, 1, 13, 3, 0, 10, 2, 6, 4, 7],
174    [11, 15, 5, 0, 1, 9, 8, 6, 14, 10, 2, 12, 3, 4, 7, 13],
175];
176
177// These are the internal flags that we use to domain separate root/non-root,
178// chunk/parent, and chunk beginning/middle/end. These get set at the high end
179// of the block flags word in the compression function, so their values start
180// high and go down.
181const CHUNK_START: u8 = 1 << 0;
182const CHUNK_END: u8 = 1 << 1;
183const PARENT: u8 = 1 << 2;
184const ROOT: u8 = 1 << 3;
185const KEYED_HASH: u8 = 1 << 4;
186const DERIVE_KEY_CONTEXT: u8 = 1 << 5;
187const DERIVE_KEY_MATERIAL: u8 = 1 << 6;
188
189#[inline]
190fn counter_low(counter: u64) -> u32 {
191    counter as u32
192}
193
194#[inline]
195fn counter_high(counter: u64) -> u32 {
196    (counter >> 32) as u32
197}
198
199/// An output of the default size, 32 bytes, which provides constant-time
200/// equality checking.
201///
202/// `Hash` implements [`From`] and [`Into`] for `[u8; 32]`, and it provides
203/// [`from_bytes`] and [`as_bytes`] for explicit conversions between itself and
204/// `[u8; 32]`. However, byte arrays and slices don't provide constant-time
205/// equality checking, which is often a security requirement in software that
206/// handles private data. `Hash` doesn't implement [`Deref`] or [`AsRef`], to
207/// avoid situations where a type conversion happens implicitly and the
208/// constant-time property is accidentally lost.
209///
210/// `Hash` provides the [`to_hex`] and [`from_hex`] methods for converting to
211/// and from hexadecimal. It also implements [`Display`] and [`FromStr`].
212///
213/// [`From`]: https://doc.rust-lang.org/std/convert/trait.From.html
214/// [`Into`]: https://doc.rust-lang.org/std/convert/trait.Into.html
215/// [`as_bytes`]: #method.as_bytes
216/// [`from_bytes`]: #method.from_bytes
217/// [`Deref`]: https://doc.rust-lang.org/stable/std/ops/trait.Deref.html
218/// [`AsRef`]: https://doc.rust-lang.org/std/convert/trait.AsRef.html
219/// [`to_hex`]: #method.to_hex
220/// [`from_hex`]: #method.from_hex
221/// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
222/// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
223#[cfg_attr(feature = "zeroize", derive(zeroize::Zeroize))]
224#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
225#[derive(Clone, Copy, Hash)]
226pub struct Hash([u8; OUT_LEN]);
227
228impl Hash {
229    /// The raw bytes of the `Hash`. Note that byte arrays don't provide
230    /// constant-time equality checking, so if  you need to compare hashes,
231    /// prefer the `Hash` type.
232    #[inline]
233    pub const fn as_bytes(&self) -> &[u8; OUT_LEN] {
234        &self.0
235    }
236
237    /// Create a `Hash` from its raw bytes representation.
238    pub const fn from_bytes(bytes: [u8; OUT_LEN]) -> Self {
239        Self(bytes)
240    }
241
242    /// Encode a `Hash` in lowercase hexadecimal.
243    ///
244    /// The returned [`ArrayString`] is a fixed size and doesn't allocate memory
245    /// on the heap. Note that [`ArrayString`] doesn't provide constant-time
246    /// equality checking, so if you need to compare hashes, prefer the `Hash`
247    /// type.
248    ///
249    /// [`ArrayString`]: https://docs.rs/arrayvec/0.5.1/arrayvec/struct.ArrayString.html
250    pub fn to_hex(&self) -> ArrayString<{ 2 * OUT_LEN }> {
251        let mut s = ArrayString::new();
252        let table = b"0123456789abcdef";
253        for &b in self.0.iter() {
254            s.push(table[(b >> 4) as usize] as char);
255            s.push(table[(b & 0xf) as usize] as char);
256        }
257        s
258    }
259
260    /// Decode a `Hash` from hexadecimal. Both uppercase and lowercase ASCII
261    /// bytes are supported.
262    ///
263    /// Any byte outside the ranges `'0'...'9'`, `'a'...'f'`, and `'A'...'F'`
264    /// results in an error. An input length other than 64 also results in an
265    /// error.
266    ///
267    /// Note that `Hash` also implements `FromStr`, so `Hash::from_hex("...")`
268    /// is equivalent to `"...".parse()`.
269    pub fn from_hex(hex: impl AsRef<[u8]>) -> Result<Self, HexError> {
270        fn hex_val(byte: u8) -> Result<u8, HexError> {
271            match byte {
272                b'A'..=b'F' => Ok(byte - b'A' + 10),
273                b'a'..=b'f' => Ok(byte - b'a' + 10),
274                b'0'..=b'9' => Ok(byte - b'0'),
275                _ => Err(HexError(HexErrorInner::InvalidByte(byte))),
276            }
277        }
278        let hex_bytes: &[u8] = hex.as_ref();
279        if hex_bytes.len() != OUT_LEN * 2 {
280            return Err(HexError(HexErrorInner::InvalidLen(hex_bytes.len())));
281        }
282        let mut hash_bytes: [u8; OUT_LEN] = [0; OUT_LEN];
283        for i in 0..OUT_LEN {
284            hash_bytes[i] = 16 * hex_val(hex_bytes[2 * i])? + hex_val(hex_bytes[2 * i + 1])?;
285        }
286        Ok(Hash::from(hash_bytes))
287    }
288}
289
290impl From<[u8; OUT_LEN]> for Hash {
291    #[inline]
292    fn from(bytes: [u8; OUT_LEN]) -> Self {
293        Self::from_bytes(bytes)
294    }
295}
296
297impl From<Hash> for [u8; OUT_LEN] {
298    #[inline]
299    fn from(hash: Hash) -> Self {
300        hash.0
301    }
302}
303
304impl core::str::FromStr for Hash {
305    type Err = HexError;
306
307    fn from_str(s: &str) -> Result<Self, Self::Err> {
308        Hash::from_hex(s)
309    }
310}
311
312/// This implementation is constant-time.
313impl PartialEq for Hash {
314    #[inline]
315    fn eq(&self, other: &Hash) -> bool {
316        constant_time_eq::constant_time_eq_32(&self.0, &other.0)
317    }
318}
319
320/// This implementation is constant-time.
321impl PartialEq<[u8; OUT_LEN]> for Hash {
322    #[inline]
323    fn eq(&self, other: &[u8; OUT_LEN]) -> bool {
324        constant_time_eq::constant_time_eq_32(&self.0, other)
325    }
326}
327
328/// This implementation is constant-time if the target is 32 bytes long.
329impl PartialEq<[u8]> for Hash {
330    #[inline]
331    fn eq(&self, other: &[u8]) -> bool {
332        constant_time_eq::constant_time_eq(&self.0, other)
333    }
334}
335
336impl Eq for Hash {}
337
338impl fmt::Display for Hash {
339    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
340        // Formatting field as `&str` to reduce code size since the `Debug`
341        // dynamic dispatch table for `&str` is likely needed elsewhere already,
342        // but that for `ArrayString<[u8; 64]>` is not.
343        let hex = self.to_hex();
344        let hex: &str = hex.as_str();
345
346        f.write_str(hex)
347    }
348}
349
350impl fmt::Debug for Hash {
351    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
352        // Formatting field as `&str` to reduce code size since the `Debug`
353        // dynamic dispatch table for `&str` is likely needed elsewhere already,
354        // but that for `ArrayString<[u8; 64]>` is not.
355        let hex = self.to_hex();
356        let hex: &str = hex.as_str();
357
358        f.debug_tuple("Hash").field(&hex).finish()
359    }
360}
361
362/// The error type for [`Hash::from_hex`].
363///
364/// The `.to_string()` representation of this error currently distinguishes between bad length
365/// errors and bad character errors. This is to help with logging and debugging, but it isn't a
366/// stable API detail, and it may change at any time.
367#[derive(Clone, Debug)]
368pub struct HexError(HexErrorInner);
369
370#[derive(Clone, Debug)]
371enum HexErrorInner {
372    InvalidByte(u8),
373    InvalidLen(usize),
374}
375
376impl fmt::Display for HexError {
377    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
378        match self.0 {
379            HexErrorInner::InvalidByte(byte) => {
380                if byte < 128 {
381                    write!(f, "invalid hex character: {:?}", byte as char)
382                } else {
383                    write!(f, "invalid hex character: 0x{:x}", byte)
384                }
385            }
386            HexErrorInner::InvalidLen(len) => {
387                write!(f, "expected 64 hex bytes, received {}", len)
388            }
389        }
390    }
391}
392
393#[cfg(feature = "std")]
394impl std::error::Error for HexError {}
395
396// Each chunk or parent node can produce either a 32-byte chaining value or, by
397// setting the ROOT flag, any number of final output bytes. The Output struct
398// captures the state just prior to choosing between those two possibilities.
399#[cfg_attr(feature = "zeroize", derive(zeroize::Zeroize))]
400#[derive(Clone)]
401struct Output {
402    input_chaining_value: CVWords,
403    block: [u8; 64],
404    block_len: u8,
405    counter: u64,
406    flags: u8,
407    #[cfg_attr(feature = "zeroize", zeroize(skip))]
408    platform: Platform,
409}
410
411impl Output {
412    fn chaining_value(&self) -> CVBytes {
413        let mut cv = self.input_chaining_value;
414        self.platform.compress_in_place(
415            &mut cv,
416            &self.block,
417            self.block_len,
418            self.counter,
419            self.flags,
420        );
421        platform::le_bytes_from_words_32(&cv)
422    }
423
424    fn root_hash(&self) -> Hash {
425        debug_assert_eq!(self.counter, 0);
426        let mut cv = self.input_chaining_value;
427        self.platform
428            .compress_in_place(&mut cv, &self.block, self.block_len, 0, self.flags | ROOT);
429        Hash(platform::le_bytes_from_words_32(&cv))
430    }
431
432    fn root_output_block(&self) -> [u8; 2 * OUT_LEN] {
433        self.platform.compress_xof(
434            &self.input_chaining_value,
435            &self.block,
436            self.block_len,
437            self.counter,
438            self.flags | ROOT,
439        )
440    }
441}
442
443#[derive(Clone)]
444#[cfg_attr(feature = "zeroize", derive(zeroize::Zeroize))]
445struct ChunkState {
446    cv: CVWords,
447    chunk_counter: u64,
448    buf: [u8; BLOCK_LEN],
449    buf_len: u8,
450    blocks_compressed: u8,
451    flags: u8,
452    #[cfg_attr(feature = "zeroize", zeroize(skip))]
453    platform: Platform,
454}
455
456impl ChunkState {
457    fn new(key: &CVWords, chunk_counter: u64, flags: u8, platform: Platform) -> Self {
458        Self {
459            cv: *key,
460            chunk_counter,
461            buf: [0; BLOCK_LEN],
462            buf_len: 0,
463            blocks_compressed: 0,
464            flags,
465            platform,
466        }
467    }
468
469    fn len(&self) -> usize {
470        BLOCK_LEN * self.blocks_compressed as usize + self.buf_len as usize
471    }
472
473    fn fill_buf(&mut self, input: &mut &[u8]) {
474        let want = BLOCK_LEN - self.buf_len as usize;
475        let take = cmp::min(want, input.len());
476        self.buf[self.buf_len as usize..][..take].copy_from_slice(&input[..take]);
477        self.buf_len += take as u8;
478        *input = &input[take..];
479    }
480
481    fn start_flag(&self) -> u8 {
482        if self.blocks_compressed == 0 {
483            CHUNK_START
484        } else {
485            0
486        }
487    }
488
489    // Try to avoid buffering as much as possible, by compressing directly from
490    // the input slice when full blocks are available.
491    fn update(&mut self, mut input: &[u8]) -> &mut Self {
492        if self.buf_len > 0 {
493            self.fill_buf(&mut input);
494            if !input.is_empty() {
495                debug_assert_eq!(self.buf_len as usize, BLOCK_LEN);
496                let block_flags = self.flags | self.start_flag(); // borrowck
497                self.platform.compress_in_place(
498                    &mut self.cv,
499                    &self.buf,
500                    BLOCK_LEN as u8,
501                    self.chunk_counter,
502                    block_flags,
503                );
504                self.buf_len = 0;
505                self.buf = [0; BLOCK_LEN];
506                self.blocks_compressed += 1;
507            }
508        }
509
510        while input.len() > BLOCK_LEN {
511            debug_assert_eq!(self.buf_len, 0);
512            let block_flags = self.flags | self.start_flag(); // borrowck
513            self.platform.compress_in_place(
514                &mut self.cv,
515                array_ref!(input, 0, BLOCK_LEN),
516                BLOCK_LEN as u8,
517                self.chunk_counter,
518                block_flags,
519            );
520            self.blocks_compressed += 1;
521            input = &input[BLOCK_LEN..];
522        }
523
524        self.fill_buf(&mut input);
525        debug_assert!(input.is_empty());
526        debug_assert!(self.len() <= CHUNK_LEN);
527        self
528    }
529
530    fn output(&self) -> Output {
531        let block_flags = self.flags | self.start_flag() | CHUNK_END;
532        Output {
533            input_chaining_value: self.cv,
534            block: self.buf,
535            block_len: self.buf_len,
536            counter: self.chunk_counter,
537            flags: block_flags,
538            platform: self.platform,
539        }
540    }
541}
542
543// Don't derive(Debug), because the state may be secret.
544impl fmt::Debug for ChunkState {
545    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
546        f.debug_struct("ChunkState")
547            .field("len", &self.len())
548            .field("chunk_counter", &self.chunk_counter)
549            .field("flags", &self.flags)
550            .field("platform", &self.platform)
551            .finish()
552    }
553}
554
555// IMPLEMENTATION NOTE
556// ===================
557// The recursive function compress_subtree_wide(), implemented below, is the
558// basis of high-performance BLAKE3. We use it both for all-at-once hashing,
559// and for the incremental input with Hasher (though we have to be careful with
560// subtree boundaries in the incremental case). compress_subtree_wide() applies
561// several optimizations at the same time:
562// - Multithreading with Rayon.
563// - Parallel chunk hashing with SIMD.
564// - Parallel parent hashing with SIMD. Note that while SIMD chunk hashing
565//   maxes out at MAX_SIMD_DEGREE*CHUNK_LEN, parallel parent hashing continues
566//   to benefit from larger inputs, because more levels of the tree benefit can
567//   use full-width SIMD vectors for parent hashing. Without parallel parent
568//   hashing, we lose about 10% of overall throughput on AVX2 and AVX-512.
569
570/// Undocumented and unstable, for benchmarks only.
571#[doc(hidden)]
572#[derive(Clone, Copy)]
573pub enum IncrementCounter {
574    Yes,
575    No,
576}
577
578impl IncrementCounter {
579    #[inline]
580    fn yes(&self) -> bool {
581        match self {
582            IncrementCounter::Yes => true,
583            IncrementCounter::No => false,
584        }
585    }
586}
587
588// The largest power of two less than or equal to `n`, used for left_len()
589// immediately below, and also directly in Hasher::update().
590fn largest_power_of_two_leq(n: usize) -> usize {
591    ((n / 2) + 1).next_power_of_two()
592}
593
594// Given some input larger than one chunk, return the number of bytes that
595// should go in the left subtree. This is the largest power-of-2 number of
596// chunks that leaves at least 1 byte for the right subtree.
597fn left_len(content_len: usize) -> usize {
598    debug_assert!(content_len > CHUNK_LEN);
599    // Subtract 1 to reserve at least one byte for the right side.
600    let full_chunks = (content_len - 1) / CHUNK_LEN;
601    largest_power_of_two_leq(full_chunks) * CHUNK_LEN
602}
603
604// Use SIMD parallelism to hash up to MAX_SIMD_DEGREE chunks at the same time
605// on a single thread. Write out the chunk chaining values and return the
606// number of chunks hashed. These chunks are never the root and never empty;
607// those cases use a different codepath.
608fn compress_chunks_parallel(
609    input: &[u8],
610    key: &CVWords,
611    chunk_counter: u64,
612    flags: u8,
613    platform: Platform,
614    out: &mut [u8],
615) -> usize {
616    debug_assert!(!input.is_empty(), "empty chunks below the root");
617    debug_assert!(input.len() <= MAX_SIMD_DEGREE * CHUNK_LEN);
618
619    let mut chunks_exact = input.chunks_exact(CHUNK_LEN);
620    let mut chunks_array = ArrayVec::<&[u8; CHUNK_LEN], MAX_SIMD_DEGREE>::new();
621    for chunk in &mut chunks_exact {
622        chunks_array.push(array_ref!(chunk, 0, CHUNK_LEN));
623    }
624    platform.hash_many(
625        &chunks_array,
626        key,
627        chunk_counter,
628        IncrementCounter::Yes,
629        flags,
630        CHUNK_START,
631        CHUNK_END,
632        out,
633    );
634
635    // Hash the remaining partial chunk, if there is one. Note that the empty
636    // chunk (meaning the empty message) is a different codepath.
637    let chunks_so_far = chunks_array.len();
638    if !chunks_exact.remainder().is_empty() {
639        let counter = chunk_counter + chunks_so_far as u64;
640        let mut chunk_state = ChunkState::new(key, counter, flags, platform);
641        chunk_state.update(chunks_exact.remainder());
642        *array_mut_ref!(out, chunks_so_far * OUT_LEN, OUT_LEN) =
643            chunk_state.output().chaining_value();
644        chunks_so_far + 1
645    } else {
646        chunks_so_far
647    }
648}
649
650// Use SIMD parallelism to hash up to MAX_SIMD_DEGREE parents at the same time
651// on a single thread. Write out the parent chaining values and return the
652// number of parents hashed. (If there's an odd input chaining value left over,
653// return it as an additional output.) These parents are never the root and
654// never empty; those cases use a different codepath.
655fn compress_parents_parallel(
656    child_chaining_values: &[u8],
657    key: &CVWords,
658    flags: u8,
659    platform: Platform,
660    out: &mut [u8],
661) -> usize {
662    debug_assert_eq!(child_chaining_values.len() % OUT_LEN, 0, "wacky hash bytes");
663    let num_children = child_chaining_values.len() / OUT_LEN;
664    debug_assert!(num_children >= 2, "not enough children");
665    debug_assert!(num_children <= 2 * MAX_SIMD_DEGREE_OR_2, "too many");
666
667    let mut parents_exact = child_chaining_values.chunks_exact(BLOCK_LEN);
668    // Use MAX_SIMD_DEGREE_OR_2 rather than MAX_SIMD_DEGREE here, because of
669    // the requirements of compress_subtree_wide().
670    let mut parents_array = ArrayVec::<&[u8; BLOCK_LEN], MAX_SIMD_DEGREE_OR_2>::new();
671    for parent in &mut parents_exact {
672        parents_array.push(array_ref!(parent, 0, BLOCK_LEN));
673    }
674    platform.hash_many(
675        &parents_array,
676        key,
677        0, // Parents always use counter 0.
678        IncrementCounter::No,
679        flags | PARENT,
680        0, // Parents have no start flags.
681        0, // Parents have no end flags.
682        out,
683    );
684
685    // If there's an odd child left over, it becomes an output.
686    let parents_so_far = parents_array.len();
687    if !parents_exact.remainder().is_empty() {
688        out[parents_so_far * OUT_LEN..][..OUT_LEN].copy_from_slice(parents_exact.remainder());
689        parents_so_far + 1
690    } else {
691        parents_so_far
692    }
693}
694
695// The wide helper function returns (writes out) an array of chaining values
696// and returns the length of that array. The number of chaining values returned
697// is the dynamically detected SIMD degree, at most MAX_SIMD_DEGREE. Or fewer,
698// if the input is shorter than that many chunks. The reason for maintaining a
699// wide array of chaining values going back up the tree, is to allow the
700// implementation to hash as many parents in parallel as possible.
701//
702// As a special case when the SIMD degree is 1, this function will still return
703// at least 2 outputs. This guarantees that this function doesn't perform the
704// root compression. (If it did, it would use the wrong flags, and also we
705// wouldn't be able to implement extendable output.) Note that this function is
706// not used when the whole input is only 1 chunk long; that's a different
707// codepath.
708//
709// Why not just have the caller split the input on the first update(), instead
710// of implementing this special rule? Because we don't want to limit SIMD or
711// multithreading parallelism for that update().
712fn compress_subtree_wide<J: join::Join>(
713    input: &[u8],
714    key: &CVWords,
715    chunk_counter: u64,
716    flags: u8,
717    platform: Platform,
718    out: &mut [u8],
719) -> usize {
720    // Note that the single chunk case does *not* bump the SIMD degree up to 2
721    // when it is 1. This allows Rayon the option of multithreading even the
722    // 2-chunk case, which can help performance on smaller platforms.
723    if input.len() <= platform.simd_degree() * CHUNK_LEN {
724        return compress_chunks_parallel(input, key, chunk_counter, flags, platform, out);
725    }
726
727    // With more than simd_degree chunks, we need to recurse. Start by dividing
728    // the input into left and right subtrees. (Note that this is only optimal
729    // as long as the SIMD degree is a power of 2. If we ever get a SIMD degree
730    // of 3 or something, we'll need a more complicated strategy.)
731    debug_assert_eq!(platform.simd_degree().count_ones(), 1, "power of 2");
732    let (left, right) = input.split_at(left_len(input.len()));
733    let right_chunk_counter = chunk_counter + (left.len() / CHUNK_LEN) as u64;
734
735    // Make space for the child outputs. Here we use MAX_SIMD_DEGREE_OR_2 to
736    // account for the special case of returning 2 outputs when the SIMD degree
737    // is 1.
738    let mut cv_array = [0; 2 * MAX_SIMD_DEGREE_OR_2 * OUT_LEN];
739    let degree = if left.len() == CHUNK_LEN {
740        // The "simd_degree=1 and we're at the leaf nodes" case.
741        debug_assert_eq!(platform.simd_degree(), 1);
742        1
743    } else {
744        cmp::max(platform.simd_degree(), 2)
745    };
746    let (left_out, right_out) = cv_array.split_at_mut(degree * OUT_LEN);
747
748    // Recurse! For update_rayon(), this is where we take advantage of RayonJoin and use multiple
749    // threads.
750    let (left_n, right_n) = J::join(
751        || compress_subtree_wide::<J>(left, key, chunk_counter, flags, platform, left_out),
752        || compress_subtree_wide::<J>(right, key, right_chunk_counter, flags, platform, right_out),
753    );
754
755    // The special case again. If simd_degree=1, then we'll have left_n=1 and
756    // right_n=1. Rather than compressing them into a single output, return
757    // them directly, to make sure we always have at least two outputs.
758    debug_assert_eq!(left_n, degree);
759    debug_assert!(right_n >= 1 && right_n <= left_n);
760    if left_n == 1 {
761        out[..2 * OUT_LEN].copy_from_slice(&cv_array[..2 * OUT_LEN]);
762        return 2;
763    }
764
765    // Otherwise, do one layer of parent node compression.
766    let num_children = left_n + right_n;
767    compress_parents_parallel(
768        &cv_array[..num_children * OUT_LEN],
769        key,
770        flags,
771        platform,
772        out,
773    )
774}
775
776// Hash a subtree with compress_subtree_wide(), and then condense the resulting
777// list of chaining values down to a single parent node. Don't compress that
778// last parent node, however. Instead, return its message bytes (the
779// concatenated chaining values of its children). This is necessary when the
780// first call to update() supplies a complete subtree, because the topmost
781// parent node of that subtree could end up being the root. It's also necessary
782// for extended output in the general case.
783//
784// As with compress_subtree_wide(), this function is not used on inputs of 1
785// chunk or less. That's a different codepath.
786fn compress_subtree_to_parent_node<J: join::Join>(
787    input: &[u8],
788    key: &CVWords,
789    chunk_counter: u64,
790    flags: u8,
791    platform: Platform,
792) -> [u8; BLOCK_LEN] {
793    debug_assert!(input.len() > CHUNK_LEN);
794    let mut cv_array = [0; MAX_SIMD_DEGREE_OR_2 * OUT_LEN];
795    let mut num_cvs =
796        compress_subtree_wide::<J>(input, &key, chunk_counter, flags, platform, &mut cv_array);
797    debug_assert!(num_cvs >= 2);
798
799    // If MAX_SIMD_DEGREE is greater than 2 and there's enough input,
800    // compress_subtree_wide() returns more than 2 chaining values. Condense
801    // them into 2 by forming parent nodes repeatedly.
802    let mut out_array = [0; MAX_SIMD_DEGREE_OR_2 * OUT_LEN / 2];
803    while num_cvs > 2 {
804        let cv_slice = &cv_array[..num_cvs * OUT_LEN];
805        num_cvs = compress_parents_parallel(cv_slice, key, flags, platform, &mut out_array);
806        cv_array[..num_cvs * OUT_LEN].copy_from_slice(&out_array[..num_cvs * OUT_LEN]);
807    }
808    *array_ref!(cv_array, 0, 2 * OUT_LEN)
809}
810
811// Hash a complete input all at once. Unlike compress_subtree_wide() and
812// compress_subtree_to_parent_node(), this function handles the 1 chunk case.
813fn hash_all_at_once<J: join::Join>(input: &[u8], key: &CVWords, flags: u8) -> Output {
814    let platform = Platform::detect();
815
816    // If the whole subtree is one chunk, hash it directly with a ChunkState.
817    if input.len() <= CHUNK_LEN {
818        return ChunkState::new(key, 0, flags, platform)
819            .update(input)
820            .output();
821    }
822
823    // Otherwise construct an Output object from the parent node returned by
824    // compress_subtree_to_parent_node().
825    Output {
826        input_chaining_value: *key,
827        block: compress_subtree_to_parent_node::<J>(input, key, 0, flags, platform),
828        block_len: BLOCK_LEN as u8,
829        counter: 0,
830        flags: flags | PARENT,
831        platform,
832    }
833}
834
835/// The default hash function.
836///
837/// For an incremental version that accepts multiple writes, see
838/// [`Hasher::update`].
839///
840/// For output sizes other than 32 bytes, see [`Hasher::finalize_xof`] and
841/// [`OutputReader`].
842///
843/// This function is always single-threaded. For multithreading support, see
844/// [`Hasher::update_rayon`](struct.Hasher.html#method.update_rayon).
845pub fn hash(input: &[u8]) -> Hash {
846    hash_all_at_once::<join::SerialJoin>(input, IV, 0).root_hash()
847}
848
849/// The keyed hash function.
850///
851/// This is suitable for use as a message authentication code, for example to
852/// replace an HMAC instance. In that use case, the constant-time equality
853/// checking provided by [`Hash`](struct.Hash.html) is almost always a security
854/// requirement, and callers need to be careful not to compare MACs as raw
855/// bytes.
856///
857/// For output sizes other than 32 bytes, see [`Hasher::new_keyed`],
858/// [`Hasher::finalize_xof`], and [`OutputReader`].
859///
860/// This function is always single-threaded. For multithreading support, see
861/// [`Hasher::new_keyed`] and
862/// [`Hasher::update_rayon`](struct.Hasher.html#method.update_rayon).
863pub fn keyed_hash(key: &[u8; KEY_LEN], input: &[u8]) -> Hash {
864    let key_words = platform::words_from_le_bytes_32(key);
865    hash_all_at_once::<join::SerialJoin>(input, &key_words, KEYED_HASH).root_hash()
866}
867
868/// The key derivation function.
869///
870/// Given cryptographic key material of any length and a context string of any
871/// length, this function outputs a 32-byte derived subkey. **The context string
872/// should be hardcoded, globally unique, and application-specific.** A good
873/// default format for such strings is `"[application] [commit timestamp]
874/// [purpose]"`, e.g., `"example.com 2019-12-25 16:18:03 session tokens v1"`.
875///
876/// Key derivation is important when you want to use the same key in multiple
877/// algorithms or use cases. Using the same key with different cryptographic
878/// algorithms is generally forbidden, and deriving a separate subkey for each
879/// use case protects you from bad interactions. Derived keys also mitigate the
880/// damage from one part of your application accidentally leaking its key.
881///
882/// As a rare exception to that general rule, however, it is possible to use
883/// `derive_key` itself with key material that you are already using with
884/// another algorithm. You might need to do this if you're adding features to
885/// an existing application, which does not yet use key derivation internally.
886/// However, you still must not share key material with algorithms that forbid
887/// key reuse entirely, like a one-time pad. For more on this, see sections 6.2
888/// and 7.8 of the [BLAKE3 paper](https://github.com/BLAKE3-team/BLAKE3-specs/blob/master/blake3.pdf).
889///
890/// Note that BLAKE3 is not a password hash, and **`derive_key` should never be
891/// used with passwords.** Instead, use a dedicated password hash like
892/// [Argon2]. Password hashes are entirely different from generic hash
893/// functions, with opposite design requirements.
894///
895/// For output sizes other than 32 bytes, see [`Hasher::new_derive_key`],
896/// [`Hasher::finalize_xof`], and [`OutputReader`].
897///
898/// This function is always single-threaded. For multithreading support, see
899/// [`Hasher::new_derive_key`] and
900/// [`Hasher::update_rayon`](struct.Hasher.html#method.update_rayon).
901///
902/// [Argon2]: https://en.wikipedia.org/wiki/Argon2
903pub fn derive_key(context: &str, key_material: &[u8]) -> [u8; OUT_LEN] {
904    let context_key =
905        hash_all_at_once::<join::SerialJoin>(context.as_bytes(), IV, DERIVE_KEY_CONTEXT)
906            .root_hash();
907    let context_key_words = platform::words_from_le_bytes_32(context_key.as_bytes());
908    hash_all_at_once::<join::SerialJoin>(key_material, &context_key_words, DERIVE_KEY_MATERIAL)
909        .root_hash()
910        .0
911}
912
913fn parent_node_output(
914    left_child: &CVBytes,
915    right_child: &CVBytes,
916    key: &CVWords,
917    flags: u8,
918    platform: Platform,
919) -> Output {
920    let mut block = [0; BLOCK_LEN];
921    block[..32].copy_from_slice(left_child);
922    block[32..].copy_from_slice(right_child);
923    Output {
924        input_chaining_value: *key,
925        block,
926        block_len: BLOCK_LEN as u8,
927        counter: 0,
928        flags: flags | PARENT,
929        platform,
930    }
931}
932
933/// An incremental hash state that can accept any number of writes.
934///
935/// The `rayon` and `mmap` Cargo features enable additional methods on this
936/// type related to multithreading and memory-mapped IO.
937///
938/// When the `traits-preview` Cargo feature is enabled, this type implements
939/// several commonly used traits from the
940/// [`digest`](https://crates.io/crates/digest) crate. However, those
941/// traits aren't stable, and they're expected to change in incompatible ways
942/// before that crate reaches 1.0. For that reason, this crate makes no SemVer
943/// guarantees for this feature, and callers who use it should expect breaking
944/// changes between patch versions.
945///
946/// # Examples
947///
948/// ```
949/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
950/// // Hash an input incrementally.
951/// let mut hasher = blake3::Hasher::new();
952/// hasher.update(b"foo");
953/// hasher.update(b"bar");
954/// hasher.update(b"baz");
955/// assert_eq!(hasher.finalize(), blake3::hash(b"foobarbaz"));
956///
957/// // Extended output. OutputReader also implements Read and Seek.
958/// # #[cfg(feature = "std")] {
959/// let mut output = [0; 1000];
960/// let mut output_reader = hasher.finalize_xof();
961/// output_reader.fill(&mut output);
962/// assert_eq!(&output[..32], blake3::hash(b"foobarbaz").as_bytes());
963/// # }
964/// # Ok(())
965/// # }
966/// ```
967#[derive(Clone)]
968#[cfg_attr(feature = "zeroize", derive(zeroize::Zeroize))]
969pub struct Hasher {
970    key: CVWords,
971    chunk_state: ChunkState,
972    // The stack size is MAX_DEPTH + 1 because we do lazy merging. For example,
973    // with 7 chunks, we have 3 entries in the stack. Adding an 8th chunk
974    // requires a 4th entry, rather than merging everything down to 1, because
975    // we don't know whether more input is coming. This is different from how
976    // the reference implementation does things.
977    cv_stack: ArrayVec<CVBytes, { MAX_DEPTH + 1 }>,
978}
979
980impl Hasher {
981    fn new_internal(key: &CVWords, flags: u8) -> Self {
982        Self {
983            key: *key,
984            chunk_state: ChunkState::new(key, 0, flags, Platform::detect()),
985            cv_stack: ArrayVec::new(),
986        }
987    }
988
989    /// Construct a new `Hasher` for the regular hash function.
990    pub fn new() -> Self {
991        Self::new_internal(IV, 0)
992    }
993
994    /// Construct a new `Hasher` for the keyed hash function. See
995    /// [`keyed_hash`].
996    ///
997    /// [`keyed_hash`]: fn.keyed_hash.html
998    pub fn new_keyed(key: &[u8; KEY_LEN]) -> Self {
999        let key_words = platform::words_from_le_bytes_32(key);
1000        Self::new_internal(&key_words, KEYED_HASH)
1001    }
1002
1003    /// Construct a new `Hasher` for the key derivation function. See
1004    /// [`derive_key`]. The context string should be hardcoded, globally
1005    /// unique, and application-specific.
1006    ///
1007    /// [`derive_key`]: fn.derive_key.html
1008    pub fn new_derive_key(context: &str) -> Self {
1009        let context_key =
1010            hash_all_at_once::<join::SerialJoin>(context.as_bytes(), IV, DERIVE_KEY_CONTEXT)
1011                .root_hash();
1012        let context_key_words = platform::words_from_le_bytes_32(context_key.as_bytes());
1013        Self::new_internal(&context_key_words, DERIVE_KEY_MATERIAL)
1014    }
1015
1016    /// Reset the `Hasher` to its initial state.
1017    ///
1018    /// This is functionally the same as overwriting the `Hasher` with a new
1019    /// one, using the same key or context string if any.
1020    pub fn reset(&mut self) -> &mut Self {
1021        self.chunk_state = ChunkState::new(
1022            &self.key,
1023            0,
1024            self.chunk_state.flags,
1025            self.chunk_state.platform,
1026        );
1027        self.cv_stack.clear();
1028        self
1029    }
1030
1031    // As described in push_cv() below, we do "lazy merging", delaying merges
1032    // until right before the next CV is about to be added. This is different
1033    // from the reference implementation. Another difference is that we aren't
1034    // always merging 1 chunk at a time. Instead, each CV might represent any
1035    // power-of-two number of chunks, as long as the smaller-above-larger stack
1036    // order is maintained. Instead of the "count the trailing 0-bits"
1037    // algorithm described in the spec, we use a "count the total number of
1038    // 1-bits" variant that doesn't require us to retain the subtree size of
1039    // the CV on top of the stack. The principle is the same: each CV that
1040    // should remain in the stack is represented by a 1-bit in the total number
1041    // of chunks (or bytes) so far.
1042    fn merge_cv_stack(&mut self, total_len: u64) {
1043        let post_merge_stack_len = total_len.count_ones() as usize;
1044        while self.cv_stack.len() > post_merge_stack_len {
1045            let right_child = self.cv_stack.pop().unwrap();
1046            let left_child = self.cv_stack.pop().unwrap();
1047            let parent_output = parent_node_output(
1048                &left_child,
1049                &right_child,
1050                &self.key,
1051                self.chunk_state.flags,
1052                self.chunk_state.platform,
1053            );
1054            self.cv_stack.push(parent_output.chaining_value());
1055        }
1056    }
1057
1058    // In reference_impl.rs, we merge the new CV with existing CVs from the
1059    // stack before pushing it. We can do that because we know more input is
1060    // coming, so we know none of the merges are root.
1061    //
1062    // This setting is different. We want to feed as much input as possible to
1063    // compress_subtree_wide(), without setting aside anything for the
1064    // chunk_state. If the user gives us 64 KiB, we want to parallelize over
1065    // all 64 KiB at once as a single subtree, if at all possible.
1066    //
1067    // This leads to two problems:
1068    // 1) This 64 KiB input might be the only call that ever gets made to
1069    //    update. In this case, the root node of the 64 KiB subtree would be
1070    //    the root node of the whole tree, and it would need to be ROOT
1071    //    finalized. We can't compress it until we know.
1072    // 2) This 64 KiB input might complete a larger tree, whose root node is
1073    //    similarly going to be the the root of the whole tree. For example,
1074    //    maybe we have 196 KiB (that is, 128 + 64) hashed so far. We can't
1075    //    compress the node at the root of the 256 KiB subtree until we know
1076    //    how to finalize it.
1077    //
1078    // The second problem is solved with "lazy merging". That is, when we're
1079    // about to add a CV to the stack, we don't merge it with anything first,
1080    // as the reference impl does. Instead we do merges using the *previous* CV
1081    // that was added, which is sitting on top of the stack, and we put the new
1082    // CV (unmerged) on top of the stack afterwards. This guarantees that we
1083    // never merge the root node until finalize().
1084    //
1085    // Solving the first problem requires an additional tool,
1086    // compress_subtree_to_parent_node(). That function always returns the top
1087    // *two* chaining values of the subtree it's compressing. We then do lazy
1088    // merging with each of them separately, so that the second CV will always
1089    // remain unmerged. (That also helps us support extendable output when
1090    // we're hashing an input all-at-once.)
1091    fn push_cv(&mut self, new_cv: &CVBytes, chunk_counter: u64) {
1092        self.merge_cv_stack(chunk_counter);
1093        self.cv_stack.push(*new_cv);
1094    }
1095
1096    /// Add input bytes to the hash state. You can call this any number of times.
1097    ///
1098    /// This method is always single-threaded. For multithreading support, see
1099    /// [`update_rayon`](#method.update_rayon) (enabled with the `rayon` Cargo feature).
1100    ///
1101    /// Note that the degree of SIMD parallelism that `update` can use is limited by the size of
1102    /// this input buffer. See [`update_reader`](#method.update_reader).
1103    pub fn update(&mut self, input: &[u8]) -> &mut Self {
1104        self.update_with_join::<join::SerialJoin>(input)
1105    }
1106
1107    fn update_with_join<J: join::Join>(&mut self, mut input: &[u8]) -> &mut Self {
1108        // If we have some partial chunk bytes in the internal chunk_state, we
1109        // need to finish that chunk first.
1110        if self.chunk_state.len() > 0 {
1111            let want = CHUNK_LEN - self.chunk_state.len();
1112            let take = cmp::min(want, input.len());
1113            self.chunk_state.update(&input[..take]);
1114            input = &input[take..];
1115            if !input.is_empty() {
1116                // We've filled the current chunk, and there's more input
1117                // coming, so we know it's not the root and we can finalize it.
1118                // Then we'll proceed to hashing whole chunks below.
1119                debug_assert_eq!(self.chunk_state.len(), CHUNK_LEN);
1120                let chunk_cv = self.chunk_state.output().chaining_value();
1121                self.push_cv(&chunk_cv, self.chunk_state.chunk_counter);
1122                self.chunk_state = ChunkState::new(
1123                    &self.key,
1124                    self.chunk_state.chunk_counter + 1,
1125                    self.chunk_state.flags,
1126                    self.chunk_state.platform,
1127                );
1128            } else {
1129                return self;
1130            }
1131        }
1132
1133        // Now the chunk_state is clear, and we have more input. If there's
1134        // more than a single chunk (so, definitely not the root chunk), hash
1135        // the largest whole subtree we can, with the full benefits of SIMD and
1136        // multithreading parallelism. Two restrictions:
1137        // - The subtree has to be a power-of-2 number of chunks. Only subtrees
1138        //   along the right edge can be incomplete, and we don't know where
1139        //   the right edge is going to be until we get to finalize().
1140        // - The subtree must evenly divide the total number of chunks up until
1141        //   this point (if total is not 0). If the current incomplete subtree
1142        //   is only waiting for 1 more chunk, we can't hash a subtree of 4
1143        //   chunks. We have to complete the current subtree first.
1144        // Because we might need to break up the input to form powers of 2, or
1145        // to evenly divide what we already have, this part runs in a loop.
1146        while input.len() > CHUNK_LEN {
1147            debug_assert_eq!(self.chunk_state.len(), 0, "no partial chunk data");
1148            debug_assert_eq!(CHUNK_LEN.count_ones(), 1, "power of 2 chunk len");
1149            let mut subtree_len = largest_power_of_two_leq(input.len());
1150            let count_so_far = self.chunk_state.chunk_counter * CHUNK_LEN as u64;
1151            // Shrink the subtree_len until it evenly divides the count so far.
1152            // We know that subtree_len itself is a power of 2, so we can use a
1153            // bitmasking trick instead of an actual remainder operation. (Note
1154            // that if the caller consistently passes power-of-2 inputs of the
1155            // same size, as is hopefully typical, this loop condition will
1156            // always fail, and subtree_len will always be the full length of
1157            // the input.)
1158            //
1159            // An aside: We don't have to shrink subtree_len quite this much.
1160            // For example, if count_so_far is 1, we could pass 2 chunks to
1161            // compress_subtree_to_parent_node. Since we'll get 2 CVs back,
1162            // we'll still get the right answer in the end, and we might get to
1163            // use 2-way SIMD parallelism. The problem with this optimization,
1164            // is that it gets us stuck always hashing 2 chunks. The total
1165            // number of chunks will remain odd, and we'll never graduate to
1166            // higher degrees of parallelism. See
1167            // https://github.com/BLAKE3-team/BLAKE3/issues/69.
1168            while (subtree_len - 1) as u64 & count_so_far != 0 {
1169                subtree_len /= 2;
1170            }
1171            // The shrunken subtree_len might now be 1 chunk long. If so, hash
1172            // that one chunk by itself. Otherwise, compress the subtree into a
1173            // pair of CVs.
1174            let subtree_chunks = (subtree_len / CHUNK_LEN) as u64;
1175            if subtree_len <= CHUNK_LEN {
1176                debug_assert_eq!(subtree_len, CHUNK_LEN);
1177                self.push_cv(
1178                    &ChunkState::new(
1179                        &self.key,
1180                        self.chunk_state.chunk_counter,
1181                        self.chunk_state.flags,
1182                        self.chunk_state.platform,
1183                    )
1184                    .update(&input[..subtree_len])
1185                    .output()
1186                    .chaining_value(),
1187                    self.chunk_state.chunk_counter,
1188                );
1189            } else {
1190                // This is the high-performance happy path, though getting here
1191                // depends on the caller giving us a long enough input.
1192                let cv_pair = compress_subtree_to_parent_node::<J>(
1193                    &input[..subtree_len],
1194                    &self.key,
1195                    self.chunk_state.chunk_counter,
1196                    self.chunk_state.flags,
1197                    self.chunk_state.platform,
1198                );
1199                let left_cv = array_ref!(cv_pair, 0, 32);
1200                let right_cv = array_ref!(cv_pair, 32, 32);
1201                // Push the two CVs we received into the CV stack in order. Because
1202                // the stack merges lazily, this guarantees we aren't merging the
1203                // root.
1204                self.push_cv(left_cv, self.chunk_state.chunk_counter);
1205                self.push_cv(
1206                    right_cv,
1207                    self.chunk_state.chunk_counter + (subtree_chunks / 2),
1208                );
1209            }
1210            self.chunk_state.chunk_counter += subtree_chunks;
1211            input = &input[subtree_len..];
1212        }
1213
1214        // What remains is 1 chunk or less. Add it to the chunk state.
1215        debug_assert!(input.len() <= CHUNK_LEN);
1216        if !input.is_empty() {
1217            self.chunk_state.update(input);
1218            // Having added some input to the chunk_state, we know what's in
1219            // the CV stack won't become the root node, and we can do an extra
1220            // merge. This simplifies finalize().
1221            self.merge_cv_stack(self.chunk_state.chunk_counter);
1222        }
1223
1224        self
1225    }
1226
1227    fn final_output(&self) -> Output {
1228        // If the current chunk is the only chunk, that makes it the root node
1229        // also. Convert it directly into an Output. Otherwise, we need to
1230        // merge subtrees below.
1231        if self.cv_stack.is_empty() {
1232            debug_assert_eq!(self.chunk_state.chunk_counter, 0);
1233            return self.chunk_state.output();
1234        }
1235
1236        // If there are any bytes in the ChunkState, finalize that chunk and
1237        // merge its CV with everything in the CV stack. In that case, the work
1238        // we did at the end of update() above guarantees that the stack
1239        // doesn't contain any unmerged subtrees that need to be merged first.
1240        // (This is important, because if there were two chunk hashes sitting
1241        // on top of the stack, they would need to merge with each other, and
1242        // merging a new chunk hash into them would be incorrect.)
1243        //
1244        // If there are no bytes in the ChunkState, we'll merge what's already
1245        // in the stack. In this case it's fine if there are unmerged chunks on
1246        // top, because we'll merge them with each other. Note that the case of
1247        // the empty chunk is taken care of above.
1248        let mut output: Output;
1249        let mut num_cvs_remaining = self.cv_stack.len();
1250        if self.chunk_state.len() > 0 {
1251            debug_assert_eq!(
1252                self.cv_stack.len(),
1253                self.chunk_state.chunk_counter.count_ones() as usize,
1254                "cv stack does not need a merge"
1255            );
1256            output = self.chunk_state.output();
1257        } else {
1258            debug_assert!(self.cv_stack.len() >= 2);
1259            output = parent_node_output(
1260                &self.cv_stack[num_cvs_remaining - 2],
1261                &self.cv_stack[num_cvs_remaining - 1],
1262                &self.key,
1263                self.chunk_state.flags,
1264                self.chunk_state.platform,
1265            );
1266            num_cvs_remaining -= 2;
1267        }
1268        while num_cvs_remaining > 0 {
1269            output = parent_node_output(
1270                &self.cv_stack[num_cvs_remaining - 1],
1271                &output.chaining_value(),
1272                &self.key,
1273                self.chunk_state.flags,
1274                self.chunk_state.platform,
1275            );
1276            num_cvs_remaining -= 1;
1277        }
1278        output
1279    }
1280
1281    /// Finalize the hash state and return the [`Hash`](struct.Hash.html) of
1282    /// the input.
1283    ///
1284    /// This method is idempotent. Calling it twice will give the same result.
1285    /// You can also add more input and finalize again.
1286    pub fn finalize(&self) -> Hash {
1287        self.final_output().root_hash()
1288    }
1289
1290    /// Finalize the hash state and return an [`OutputReader`], which can
1291    /// supply any number of output bytes.
1292    ///
1293    /// This method is idempotent. Calling it twice will give the same result.
1294    /// You can also add more input and finalize again.
1295    ///
1296    /// [`OutputReader`]: struct.OutputReader.html
1297    pub fn finalize_xof(&self) -> OutputReader {
1298        OutputReader::new(self.final_output())
1299    }
1300
1301    /// Return the total number of bytes hashed so far.
1302    pub fn count(&self) -> u64 {
1303        self.chunk_state.chunk_counter * CHUNK_LEN as u64 + self.chunk_state.len() as u64
1304    }
1305
1306    /// As [`update`](Hasher::update), but reading from a
1307    /// [`std::io::Read`](https://doc.rust-lang.org/std/io/trait.Read.html) implementation.
1308    ///
1309    /// [`Hasher`] implements
1310    /// [`std::io::Write`](https://doc.rust-lang.org/std/io/trait.Write.html), so it's possible to
1311    /// use [`std::io::copy`](https://doc.rust-lang.org/std/io/fn.copy.html) to update a [`Hasher`]
1312    /// from any reader. Unfortunately, this standard approach can limit performance, because
1313    /// `copy` currently uses an internal 8 KiB buffer that isn't big enough to take advantage of
1314    /// all SIMD instruction sets. (In particular, [AVX-512](https://en.wikipedia.org/wiki/AVX-512)
1315    /// needs a 16 KiB buffer.) `update_reader` avoids this performance problem and is slightly
1316    /// more convenient.
1317    ///
1318    /// The internal buffer size this method uses may change at any time, and it may be different
1319    /// for different targets. The only guarantee is that it will be large enough for all of this
1320    /// crate's SIMD implementations on the current platform.
1321    ///
1322    /// The most common implementer of
1323    /// [`std::io::Read`](https://doc.rust-lang.org/std/io/trait.Read.html) might be
1324    /// [`std::fs::File`](https://doc.rust-lang.org/std/fs/struct.File.html), but note that memory
1325    /// mapping can be faster than this method for hashing large files. See
1326    /// [`update_mmap`](Hasher::update_mmap) and [`update_mmap_rayon`](Hasher::update_mmap_rayon),
1327    /// which require the `mmap` and (for the latter) `rayon` Cargo features.
1328    ///
1329    /// This method requires the `std` Cargo feature, which is enabled by default.
1330    ///
1331    /// # Example
1332    ///
1333    /// ```no_run
1334    /// # use std::fs::File;
1335    /// # use std::io;
1336    /// # fn main() -> io::Result<()> {
1337    /// // Hash standard input.
1338    /// let mut hasher = blake3::Hasher::new();
1339    /// hasher.update_reader(std::io::stdin().lock())?;
1340    /// println!("{}", hasher.finalize());
1341    /// # Ok(())
1342    /// # }
1343    /// ```
1344    #[cfg(feature = "std")]
1345    pub fn update_reader(&mut self, reader: impl std::io::Read) -> std::io::Result<&mut Self> {
1346        io::copy_wide(reader, self)?;
1347        Ok(self)
1348    }
1349
1350    /// As [`update`](Hasher::update), but using Rayon-based multithreading
1351    /// internally.
1352    ///
1353    /// This method is gated by the `rayon` Cargo feature, which is disabled by
1354    /// default but enabled on [docs.rs](https://docs.rs).
1355    ///
1356    /// To get any performance benefit from multithreading, the input buffer
1357    /// needs to be large. As a rule of thumb on x86_64, `update_rayon` is
1358    /// _slower_ than `update` for inputs under 128 KiB. That threshold varies
1359    /// quite a lot across different processors, and it's important to benchmark
1360    /// your specific use case. See also the performance warning associated with
1361    /// [`update_mmap_rayon`](Hasher::update_mmap_rayon).
1362    ///
1363    /// If you already have a large buffer in memory, and you want to hash it
1364    /// with multiple threads, this method is a good option. However, reading a
1365    /// file into memory just to call this method can be a performance mistake,
1366    /// both because it requires lots of memory and because single-threaded
1367    /// reads can be slow. For hashing whole files, see
1368    /// [`update_mmap_rayon`](Hasher::update_mmap_rayon), which is gated by both
1369    /// the `rayon` and `mmap` Cargo features.
1370    #[cfg(feature = "rayon")]
1371    pub fn update_rayon(&mut self, input: &[u8]) -> &mut Self {
1372        self.update_with_join::<join::RayonJoin>(input)
1373    }
1374
1375    /// As [`update`](Hasher::update), but reading the contents of a file using memory mapping.
1376    ///
1377    /// Not all files can be memory mapped, and memory mapping small files can be slower than
1378    /// reading them the usual way. In those cases, this method will fall back to standard file IO.
1379    /// The heuristic for whether to use memory mapping is currently very simple (file size >=
1380    /// 16 KiB), and it might change at any time.
1381    ///
1382    /// Like [`update`](Hasher::update), this method is single-threaded. In this author's
1383    /// experience, memory mapping improves single-threaded performance by ~10% for large files
1384    /// that are already in cache. This probably varies between platforms, and as always it's a
1385    /// good idea to benchmark your own use case. In comparison, the multithreaded
1386    /// [`update_mmap_rayon`](Hasher::update_mmap_rayon) method can have a much larger impact on
1387    /// performance.
1388    ///
1389    /// There's a correctness reason that this method takes
1390    /// [`Path`](https://doc.rust-lang.org/stable/std/path/struct.Path.html) instead of
1391    /// [`File`](https://doc.rust-lang.org/std/fs/struct.File.html): reading from a memory-mapped
1392    /// file ignores the seek position of the original file handle (it neither respects the current
1393    /// position nor updates the position). This difference in behavior would've caused
1394    /// `update_mmap` and [`update_reader`](Hasher::update_reader) to give different answers and
1395    /// have different side effects in some cases. Taking a
1396    /// [`Path`](https://doc.rust-lang.org/stable/std/path/struct.Path.html) avoids this problem by
1397    /// making it clear that a new [`File`](https://doc.rust-lang.org/std/fs/struct.File.html) is
1398    /// opened internally.
1399    ///
1400    /// This method requires the `mmap` Cargo feature, which is disabled by default but enabled on
1401    /// [docs.rs](https://docs.rs).
1402    ///
1403    /// # Example
1404    ///
1405    /// ```no_run
1406    /// # use std::io;
1407    /// # use std::path::Path;
1408    /// # fn main() -> io::Result<()> {
1409    /// let path = Path::new("file.dat");
1410    /// let mut hasher = blake3::Hasher::new();
1411    /// hasher.update_mmap(path)?;
1412    /// println!("{}", hasher.finalize());
1413    /// # Ok(())
1414    /// # }
1415    /// ```
1416    #[cfg(feature = "mmap")]
1417    pub fn update_mmap(&mut self, path: impl AsRef<std::path::Path>) -> std::io::Result<&mut Self> {
1418        let file = std::fs::File::open(path.as_ref())?;
1419        if let Some(mmap) = io::maybe_mmap_file(&file)? {
1420            self.update(&mmap);
1421        } else {
1422            io::copy_wide(&file, self)?;
1423        }
1424        Ok(self)
1425    }
1426
1427    /// As [`update_rayon`](Hasher::update_rayon), but reading the contents of a file using
1428    /// memory mapping. This is the default behavior of `b3sum`.
1429    ///
1430    /// For large files that are likely to be in cache, this can be much faster than
1431    /// single-threaded hashing. When benchmarks report that BLAKE3 is 10x or 20x faster than other
1432    /// cryptographic hashes, this is usually what they're measuring. However...
1433    ///
1434    /// **Performance Warning:** There are cases where multithreading hurts performance. The worst
1435    /// case is [a large file on a spinning disk](https://github.com/BLAKE3-team/BLAKE3/issues/31),
1436    /// where simultaneous reads from multiple threads can cause "thrashing" (i.e. the disk spends
1437    /// more time seeking around than reading data). Windows tends to be somewhat worse about this,
1438    /// in part because it's less likely than Linux to keep very large files in cache. More
1439    /// generally, if your CPU cores are already busy, then multithreading will add overhead
1440    /// without improving performance. If your code runs in different environments that you don't
1441    /// control and can't measure, then unfortunately there's no one-size-fits-all answer for
1442    /// whether multithreading is a good idea.
1443    ///
1444    /// The memory mapping behavior of this function is the same as
1445    /// [`update_mmap`](Hasher::update_mmap), and the heuristic for when to fall back to standard
1446    /// file IO might change at any time.
1447    ///
1448    /// This method requires both the `mmap` and `rayon` Cargo features, which are disabled by
1449    /// default but enabled on [docs.rs](https://docs.rs).
1450    ///
1451    /// # Example
1452    ///
1453    /// ```no_run
1454    /// # use std::io;
1455    /// # use std::path::Path;
1456    /// # fn main() -> io::Result<()> {
1457    /// # #[cfg(feature = "rayon")]
1458    /// # {
1459    /// let path = Path::new("big_file.dat");
1460    /// let mut hasher = blake3::Hasher::new();
1461    /// hasher.update_mmap_rayon(path)?;
1462    /// println!("{}", hasher.finalize());
1463    /// # }
1464    /// # Ok(())
1465    /// # }
1466    /// ```
1467    #[cfg(feature = "mmap")]
1468    #[cfg(feature = "rayon")]
1469    pub fn update_mmap_rayon(
1470        &mut self,
1471        path: impl AsRef<std::path::Path>,
1472    ) -> std::io::Result<&mut Self> {
1473        let file = std::fs::File::open(path.as_ref())?;
1474        if let Some(mmap) = io::maybe_mmap_file(&file)? {
1475            self.update_rayon(&mmap);
1476        } else {
1477            io::copy_wide(&file, self)?;
1478        }
1479        Ok(self)
1480    }
1481}
1482
1483// Don't derive(Debug), because the state may be secret.
1484impl fmt::Debug for Hasher {
1485    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1486        f.debug_struct("Hasher")
1487            .field("flags", &self.chunk_state.flags)
1488            .field("platform", &self.chunk_state.platform)
1489            .finish()
1490    }
1491}
1492
1493impl Default for Hasher {
1494    #[inline]
1495    fn default() -> Self {
1496        Self::new()
1497    }
1498}
1499
1500#[cfg(feature = "std")]
1501impl std::io::Write for Hasher {
1502    /// This is equivalent to [`update`](#method.update).
1503    #[inline]
1504    fn write(&mut self, input: &[u8]) -> std::io::Result<usize> {
1505        self.update(input);
1506        Ok(input.len())
1507    }
1508
1509    #[inline]
1510    fn flush(&mut self) -> std::io::Result<()> {
1511        Ok(())
1512    }
1513}
1514
1515/// An incremental reader for extended output, returned by
1516/// [`Hasher::finalize_xof`](struct.Hasher.html#method.finalize_xof).
1517///
1518/// Shorter BLAKE3 outputs are prefixes of longer ones, and explicitly requesting a short output is
1519/// equivalent to truncating the default-length output. Note that this is a difference between
1520/// BLAKE2 and BLAKE3.
1521///
1522/// # Security notes
1523///
1524/// Outputs shorter than the default length of 32 bytes (256 bits) provide less security. An N-bit
1525/// BLAKE3 output is intended to provide N bits of first and second preimage resistance and N/2
1526/// bits of collision resistance, for any N up to 256. Longer outputs don't provide any additional
1527/// security.
1528///
1529/// Avoid relying on the secrecy of the output offset, that is, the number of output bytes read or
1530/// the arguments to [`seek`](struct.OutputReader.html#method.seek) or
1531/// [`set_position`](struct.OutputReader.html#method.set_position). [_Block-Cipher-Based Tree
1532/// Hashing_ by Aldo Gunsing](https://eprint.iacr.org/2022/283) shows that an attacker who knows
1533/// both the message and the key (if any) can easily determine the offset of an extended output.
1534/// For comparison, AES-CTR has a similar property: if you know the key, you can decrypt a block
1535/// from an unknown position in the output stream to recover its block index. Callers with strong
1536/// secret keys aren't affected in practice, but secret offsets are a [design
1537/// smell](https://en.wikipedia.org/wiki/Design_smell) in any case.
1538#[cfg_attr(feature = "zeroize", derive(zeroize::Zeroize))]
1539#[derive(Clone)]
1540pub struct OutputReader {
1541    inner: Output,
1542    position_within_block: u8,
1543}
1544
1545impl OutputReader {
1546    fn new(inner: Output) -> Self {
1547        Self {
1548            inner,
1549            position_within_block: 0,
1550        }
1551    }
1552
1553    /// Fill a buffer with output bytes and advance the position of the
1554    /// `OutputReader`. This is equivalent to [`Read::read`], except that it
1555    /// doesn't return a `Result`. Both methods always fill the entire buffer.
1556    ///
1557    /// Note that `OutputReader` doesn't buffer output bytes internally, so
1558    /// calling `fill` repeatedly with a short-length or odd-length slice will
1559    /// end up performing the same compression multiple times. If you're
1560    /// reading output in a loop, prefer a slice length that's a multiple of
1561    /// 64.
1562    ///
1563    /// The maximum output size of BLAKE3 is 2<sup>64</sup>-1 bytes. If you try
1564    /// to extract more than that, for example by seeking near the end and
1565    /// reading further, the behavior is unspecified.
1566    ///
1567    /// [`Read::read`]: #method.read
1568    pub fn fill(&mut self, mut buf: &mut [u8]) {
1569        while !buf.is_empty() {
1570            let block: [u8; BLOCK_LEN] = self.inner.root_output_block();
1571            let output_bytes = &block[self.position_within_block as usize..];
1572            let take = cmp::min(buf.len(), output_bytes.len());
1573            buf[..take].copy_from_slice(&output_bytes[..take]);
1574            buf = &mut buf[take..];
1575            self.position_within_block += take as u8;
1576            if self.position_within_block == BLOCK_LEN as u8 {
1577                self.inner.counter += 1;
1578                self.position_within_block = 0;
1579            }
1580        }
1581    }
1582
1583    /// Return the current read position in the output stream. This is
1584    /// equivalent to [`Seek::stream_position`], except that it doesn't return
1585    /// a `Result`. The position of a new `OutputReader` starts at 0, and each
1586    /// call to [`fill`] or [`Read::read`] moves the position forward by the
1587    /// number of bytes read.
1588    ///
1589    /// [`Seek::stream_position`]: #method.stream_position
1590    /// [`fill`]: #method.fill
1591    /// [`Read::read`]: #method.read
1592    pub fn position(&self) -> u64 {
1593        self.inner.counter * BLOCK_LEN as u64 + self.position_within_block as u64
1594    }
1595
1596    /// Seek to a new read position in the output stream. This is equivalent to
1597    /// calling [`Seek::seek`] with [`SeekFrom::Start`], except that it doesn't
1598    /// return a `Result`.
1599    ///
1600    /// [`Seek::seek`]: #method.seek
1601    /// [`SeekFrom::Start`]: https://doc.rust-lang.org/std/io/enum.SeekFrom.html
1602    pub fn set_position(&mut self, position: u64) {
1603        self.position_within_block = (position % BLOCK_LEN as u64) as u8;
1604        self.inner.counter = position / BLOCK_LEN as u64;
1605    }
1606}
1607
1608// Don't derive(Debug), because the state may be secret.
1609impl fmt::Debug for OutputReader {
1610    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1611        f.debug_struct("OutputReader")
1612            .field("position", &self.position())
1613            .finish()
1614    }
1615}
1616
1617#[cfg(feature = "std")]
1618impl std::io::Read for OutputReader {
1619    #[inline]
1620    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
1621        self.fill(buf);
1622        Ok(buf.len())
1623    }
1624}
1625
1626#[cfg(feature = "std")]
1627impl std::io::Seek for OutputReader {
1628    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
1629        let max_position = u64::max_value() as i128;
1630        let target_position: i128 = match pos {
1631            std::io::SeekFrom::Start(x) => x as i128,
1632            std::io::SeekFrom::Current(x) => self.position() as i128 + x as i128,
1633            std::io::SeekFrom::End(_) => {
1634                return Err(std::io::Error::new(
1635                    std::io::ErrorKind::InvalidInput,
1636                    "seek from end not supported",
1637                ));
1638            }
1639        };
1640        if target_position < 0 {
1641            return Err(std::io::Error::new(
1642                std::io::ErrorKind::InvalidInput,
1643                "seek before start",
1644            ));
1645        }
1646        self.set_position(cmp::min(target_position, max_position) as u64);
1647        Ok(self.position())
1648    }
1649}