Skip to main content

hash_many

Function hash_many 

Source
pub fn hash_many<P>(mode: Mode<'_>, batch: &P, out: &mut [[u8; 32]])
where P: Prepared + ?Sized,
Expand description

The hashes of a Batch’s messages, in mode, on the calling thread: out[i] becomes the hash of message i, one digest a message. This is the shape of a Merkle tree’s layer: leaves of one size, or nodes of two 32-byte children, which the layer below writes straight into the next layer’s batch (Batch::digests_mut).

Such a tree is one of your own design, not BLAKE3’s own tree: each node here is the hash of a whole 64-byte message, where BLAKE3’s parents are TreeHasher::parent_cvs’. In your design, hash the leaves and the nodes apart, with two modes (two Mode::DeriveKey contexts, say) or leaves that are never 64 bytes. Hashed alike, a 64-byte leaf made of two digests passes for a node, and a proof for one tree’s leaf proves another tree’s node.

use blake3_servil_core::{Mode, convenience, throughput::{self, Batch}};
let mut leaves = Batch::new(256, 1000);
for i in 0..1000 {
    leaves.set(i, &[7u8; 256]);
}
let mut hashes = vec![[0u8; 32]; 1000];
throughput::hash_many(Mode::Plain, &leaves, &mut hashes);
assert_eq!(hashes[3], *convenience::hash(&[7u8; 256]).as_bytes());

Speed: short messages hash several at a time, so a batch beats a loop of hash: on an Apple M4 Max, 64-byte messages take about 10 to 20 ns each in batches of 16 or more, against about 50 for one hash each. Messages longer than 15 KiB cost what hash costs. For the same hashes over several cores, the crate blake3-servil has hash_many_multithreaded.

A Packed of 16-, 32-, or 48-byte messages (or a borrowed &[[u8; N]] slice) is a batch too, hashed directly from contiguous caller memory on full SIMD groups with no copy into Blocks:

use blake3_servil_core::{Mode, convenience, throughput::{self, Packed}};
let mut leaves = Packed::<32>::new(1000);
for (i, leaf) in leaves.iter_mut().enumerate() {
    leaf[0] = i as u8;
}
let mut digests = Packed::<32>::new(1000); // the next layer's input
throughput::hash_many(Mode::Plain, &leaves, &mut digests);
assert_eq!(digests[3], *convenience::hash(&leaves[3]).as_bytes());