Skip to main content

TreeHasher

Struct TreeHasher 

Source
pub struct TreeHasher { /* private fields */ }
Expand description

A Mode prepared for a program that builds or verifies a BLAKE3 tree itself (verified streaming, an outboard, a tree hashed in parts on other machines): the subtrees’ chaining values, their parents, and the root. The mode’s key is derived once, here; each call then costs its hashing alone.

A message of more than one chunk (1024 bytes) is a binary tree: its left subtree holds the largest power of two of chunks below its count (left_len), its right subtree the rest, and so on down. A message of one chunk or less is its root alone: hash or convenience::hash_with.

A tree that is not BLAKE3’s has no way through these calls. Every left child is a whole subtree: a power of two of chunks, starting at a multiple of its own size. Its right sibling begins where it ends and is no longer. The message’s last subtree, the right child at every level down the tree’s right edge, is the only one that may be shorter.

Part of the ruleKept byWhen
A whole subtree’s size is a power of two of chunksits name, level: no other size can be said. For a size in bytes, level_of in a constthe build stops
A whole subtree starts at a multiple of its sizeits name, index, counted in subtrees of its sizecannot be written
A left child is wholetwo types: Cv is whole, LastCv is the last. A left child is a Cvthe build stops
A root’s right child ends the messageroot_hash takes a LastCv on the rightthe build stops
The bytes handed over are the subtree namedsubtree_cv takes exactly 1024 << level bytespanics, in every build
The last subtree is no longer than its left siblinglast_cv takes from 1 byte to the whole subtree aligned at its first chunkpanics, in every build
Two children are siblings, in ordereach value carries its place, and every call that joins two compares the placespanics, in every build
The tree holds the whole messageroot_hash takes the message’s length and compares it with what the two children holdpanics, in every build

What no call can check: that the bytes handed over are the message’s bytes at the place named. Wrong bytes give a wrong hash, as they do in any hash call. Nor that a value was made in this mode and under this key: a Cv carries its place and not its mode, so one kept from a TreeHasher of another mode or key joins at the same place without a panic, and the root is then not promised to be the message’s hash under either. A program that keeps values (a cache of subtrees) keeps them by mode and key as well as by place.

A message hashed in parts of 4 KiB (the part size is checked when this compiles; parts of 5 MiB would stop the build):

use blake3_servil_core::{Mode, convenience, throughput::{TreeHasher, level_of}};
const PART: usize = 4096;
const LEVEL: u32 = level_of(PART as u64);
let message = [7u8; 3 * PART + 100];
let tree = TreeHasher::new(Mode::Plain);
let part = |i: usize| &message[i * PART..message.len().min((i + 1) * PART)];
let (p0, p1, p2) = (tree.subtree_cv(LEVEL, 0, part(0)), tree.subtree_cv(LEVEL, 1, part(1)), tree.subtree_cv(LEVEL, 2, part(2)));
let end = tree.last_cv((3 * PART / 1024) as u64, part(3));
let left = tree.parent_cv(&p0, &p1);
let right = tree.last_parent_cv(&p2, &end);
assert_eq!(tree.root_hash(&left, &right, message.len() as u64), convenience::hash(&message));

A root’s right child is one that ends the message, so two whole subtrees are no root’s children until the program says the second is the last (right.into()):

ⓘ
use blake3_servil_core::{Mode, throughput::TreeHasher};
let tree = TreeHasher::new(Mode::Plain);
let (left, right) = (tree.subtree_cv(0, 0, &[7u8; 1024]), tree.subtree_cv(0, 1, &[7u8; 1024]));
let _ = tree.root_hash(&left, &right, 2048);
use blake3_servil_core::{Mode, convenience, throughput::TreeHasher};
let tree = TreeHasher::new(Mode::Plain);
let (left, right) = (tree.subtree_cv(0, 0, &[7u8; 1024]), tree.subtree_cv(0, 1, &[7u8; 1024]));
assert_eq!(tree.root_hash(&left, &right.into(), 2048), convenience::hash(&[7u8; 2048]));

§Key-dependent timing

A keyed TreeHasher’s work depends on the lengths it is given and on the kind of its mode, never on the key’s value. See the key-independence contract.

§Trait implementations

  • Clone prepares an independent tree hasher with the same key, mode and core selection.

Implementations§

Source§

impl TreeHasher

Source

pub fn new(mode: Mode<'_>) -> TreeHasher

The tree of messages hashed in mode.

Source

pub fn on_this_core(self) -> TreeHasher

This TreeHasher, its calls kept to the calling core’s own kernels.

On systems where this build selects SME2 (such as Apple M4 and later, or 64-bit Arm Linux CPUs with 512-bit SME2), calls hashing 16 KiB or more (or SME2-sized batches, e.g. 11 or more nonempty one-block messages in hash_many) take a process-local, best-effort turn on SME2; this option routes this TreeHasher’s calls to the core’s own NEON kernels instead. That helps in two situations:

  • Several threads hashing at once: avoiding contention on the shared matrix hardware.
  • Single-threaded workloads interleaving short batches with scalar hashes: entering and leaving SME2 streaming mode (and any resulting core clock transitions) can cost more than hashing the batch on NEON directly. On Apple M4/M6 this crossover sits around ~135–155 one-block messages when calls alternate with scalar work (e.g. a 12-to-64-message batch interleaved with scalar hashes runs faster with .on_this_core(), while steady cold-cache batches from ONE_BLOCK_PAD_MIN = 11 upward still benefit from SME2 by default).

On builds or CPUs that do not select SME2, this changes nothing.

Source

pub fn hash(&self, input: &[u8]) -> Hash

The hash of the whole message input: what convenience::hash_with returns for this TreeHasher’s mode, the mode’s key not derived again.

Unlike convenience::hash_with, this runs the hot throughput path (no cold-call code prefetch), and unlike hash, it takes any &[u8] slice directly without the caller copying it into aligned Blocks (partial trailing blocks are still padded on the stack internally) — making it the direct single-threaded call for repeated back-to-back hashing of caller-owned &[u8] slices (and for deriving many hashes under one key-derivation context, paid once in new).

use blake3_servil_core::{Mode, convenience, throughput::TreeHasher};
let tree = TreeHasher::new(Mode::DeriveKey("example.com 2026-11-16 session keys"));
assert_eq!(tree.hash(b"material"), convenience::hash_with(Mode::DeriveKey("example.com 2026-11-16 session keys"), b"material"));
Source

pub fn hash_many<P>(&self, batch: &P, out: &mut [[u8; 32]])
where P: Prepared + ?Sized,

The hashes of a batch’s messages, as hash_many gives them, in this TreeHasher’s mode: out[i] becomes the hash of message i.

Requires one output a message.

Source

pub fn hash_counter_range( &self, template: &[u8], counter_word: usize, start: u32, out: &mut [[u8; 32]], )

Hash out.len() single-block messages derived from template (4..=64 bytes) in this TreeHasher’s mode, replacing the 4-byte little-endian word at byte offset counter_word * 4 with start.wrapping_add(i) (modulo 2^32) for i in 0..out.len().

Respects Self::on_this_core on Apple/AArch64 SME2 hosts. Panics if template.len() > BLOCK_LEN, counter_word >= 16, or counter_word * 4 + 4 > template.len() (checked in every build, even when out is empty).

Source

pub fn hash_counter_range_trunc16( &self, template: &[u8], counter_word: usize, start: u32, out: &mut [[u8; 16]], )

Hash out.len() single-block messages derived from template (4..=64 bytes) in this TreeHasher’s mode, writing the first 16 bytes of each digest. See hash_counter_range_trunc16.

Respects Self::on_this_core on Apple/AArch64 SME2 hosts.

Source

pub fn find_counter_range( &self, template: &[u8], counter_word: usize, start: u32, count: u64, mask: u32, target: u32, matches: &mut [(u32, [u8; 32])], ) -> usize

Search count consecutive single-block messages derived from template (4..=64 bytes) in this TreeHasher’s mode for digests whose first little-endian 32-bit word satisfies (word0 & mask) == target, writing up to matches.len() pairs in ascending offset order and returning the number found. See find_counter_range.

Respects Self::on_this_core on Apple/AArch64 SME2 hosts.

Source

pub fn hash_chains_32_trunc16( &self, init: &[[u8; 32]], steps: u32, out: &mut [[u8; 16]], )

Evaluate init.len() independent 32-byte iterated hash chains in this TreeHasher’s mode, advancing each chain by steps iterations and writing its final 16-byte state to out[i] (#584).

See hash_chains_32_trunc16 for the 32-byte [prefix12 || step_u32_le || state16] layout. Respects Self::on_this_core on Apple/AArch64 SME2 hosts. Panics if init.len() != out.len() (checked in every build).

Source

pub fn hash_chains_varlen_32_trunc16( &self, init: &[[u8; 32]], steps: &[u32], out: &mut [[u8; 16]], )

Variable-step counterpart to Self::hash_chains_32_trunc16: advances chain i by steps[i] iterations in this TreeHasher’s mode and writes its final 16-byte state to out[i] (#584).

Uses an LPT continuous lane-refilling scheduler over fused multi-step SIMD bursts; respects Self::on_this_core. Panics if init.len() != steps.len() or init.len() != out.len().

Source

pub fn hash_each(&self, items: &[(&[Block], usize)], out: &mut [[u8; 32]])

The hash of each message, of any lengths, as hash_each gives them, in this TreeHasher’s mode: out[i] becomes the hash of the message of items[i].1 bytes that starts items[i].0.

Requires out.len() == items.len().

Source

pub fn subtree_cv(&self, level: u32, index: u64, input: &[u8]) -> Cv

The chaining value of a whole subtree: the index-th of 2^level chunks.

Requires input.len() == 1024 << level, checked in every build.

Source

pub fn subtree_halves(&self, level: u32, index: u64, input: &[u8]) -> [Cv; 2]

The chaining values of a whole subtree’s left and right halves, in that order. Keep the halves when the subtree might turn out to be the whole message: its root needs both children.

Requires a positive level and the same whole subtree as subtree_cv, checked in every build.

Source

pub fn last_cv(&self, first_chunk: u64, input: &[u8]) -> LastCv

The chaining value of the message’s last subtree: input is the message from its chunk first_chunk to its end.

Requires from one byte to the whole subtree aligned at first_chunk (as many chunks as the largest power of two that divides it), checked in every build. That is what makes it no longer than the left sibling it will be given.

Source

pub fn parent_cv(&self, left: &Cv, right: &Cv) -> Cv

The parent of two whole subtrees: whole, a level up.

Requires siblings in order (left at an even index, right the next of its size), checked in every build.

Source

pub fn last_parent_cv(&self, left: &Cv, right: &LastCv) -> LastCv

The parent of a whole subtree and the message’s last subtree: the last subtree a level up.

Requires left at an even index and right beginning where it ends, checked in every build. (A last subtree that begins there is no longer than left: last_cv saw to it.)

Source

pub fn parent_cvs(&self, children: &[Cv], out: &mut [Cv])

A layer of parents: out[i] becomes the parent of children[2 * i] and children[2 * i + 1], side by side in the CPU’s lanes.

The places cost 3 to 5 ns a parent over its hashing (the values are gathered for the kernels and labelled after): 2% of b3sum --outboard on a 1 GiB file in memory (Ryzen 9700X), which makes a parent for every 16 KiB.

Requires an even number of children, half as many outputs, and the children consecutive whole subtrees of one size from an even index, checked in every build.

Source

pub fn root_hash(&self, left: &Cv, right: &LastCv, len: u64) -> Hash

The hash of the message of len bytes whose root has these two children: the tree’s top, where the chaining values end.

Requires left at the message’s start, right beginning where it ends, and the two holding len bytes, checked in every build: a tree that leaves out the message’s end is refused, where it would give the hash of the bytes before it.

Source

pub fn root_output(&self, left: &Cv, right: &LastCv, len: u64) -> OutputReader ⓘ

The extended output of the message of len bytes whose root has these two children: its first 32 bytes are root_hash’s.

Requires what root_hash does.

Trait Implementations§

Source§

impl Clone for TreeHasher

Source§

fn clone(&self) -> TreeHasher

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.