Expand description
blake3-servil is a fast BLAKE3 implementation for 64-bit Arm and
x86-64. It produces the same digests as official BLAKE3, with a call
for each way programs hash (the table below).
It is two crates in one: blake3_servil_core, which hashes on the
calling thread (the assembly kernels, each proved against the
specification, and every one-thread call), re-exported here whole; and
this crate’s own part, a pool of threads and the multithreaded form of
each call. A program that wants no thread started depends on the core
alone.
§Examples
// Once per process, before any other call (see Startup self-test).
blake3_servil::initialize();
// Hash an input all at once.
let hash1 = blake3_servil::convenience::hash(b"foobarbaz");
// Hash an input incrementally.
let mut hasher = blake3_servil::convenience::Hasher::new(blake3_servil::Mode::Plain, None);
hasher.update(b"foo");
hasher.update(b"bar");
hasher.update(b"baz");
// finalize leaves the Hasher as it is: more updates may follow it.
let hash2 = hasher.finalize();
assert_eq!(hash1, hash2);
// Extended output. OutputReader also implements Read and Seek.
let mut output = [0; 1000];
let mut hasher = blake3_servil::convenience::Hasher::new(blake3_servil::Mode::Plain, None);
hasher.update(b"foobarbaz");
let mut output_reader = hasher.finalize_xof();
output_reader.fill(&mut output);
assert_eq!(hash1, output[..32]);
// Print a hash as hex.
println!("{}", hash1);
// Many short messages in one call: a Batch lays them out in Blocks.
use blake3_servil::{throughput::{self, Batch}, Mode};
let mut batch = Batch::new(64, 3);
for i in 0..3 {
batch.set(i, &[i as u8; 64]);
}
let mut hashes = [[0u8; 32]; 3];
throughput::hash_many(Mode::Plain, &batch, &mut hashes);
assert_eq!(hashes[2], *blake3_servil::convenience::hash(&[2u8; 64]).as_bytes());§Two kinds of call
convenience: one call per hash, every feature of BLAKE3 (the plain hash, the keyed hash, key derivation, extended output), any slice, the result returned, and theHasherfor a message fed in pieces. Tuned for a hash now and then, amid other work: where it helps, a call fetches its code back into the caches before it starts.throughput, for power users: every way this crate makes hashing fast (other cores, batches, collections), tuned for call after call: an occasional call amid other work may run slower than a convenience call would. The program takes on more of the work: inputs come asBlocks (64 bytes on a 64-byte boundary, so alignment is the type’s), digests go into the program’s places, and every call takes aMode.
The Hasher runs on the calling thread; its
first update is treated as a call now and then (its code fetched first
where that helps), and its later updates as call after call. The
throughput calls that take it, throughput::update_multithreaded
and throughput::update_each, are tuned as throughput calls.
Start with the convenience calls; when a program needs more speed, it moves to the throughput ones.
| Your data | Call |
|---|---|
| One message in memory (now and then) | convenience::hash, or for large inputs across cores throughput::hash_multithreaded |
| One message in memory, repeated call after call | throughput::hash_multithreaded (on aligned Blocks), or on one thread throughput::TreeHasher::hash directly on caller-owned &[u8] slices without copying into aligned blocks (use throughput::update_multithreaded for large unaligned slices across cores) |
| One message arriving in pieces | convenience::Hasher, or for speed throughput::update_multithreaded |
| Many messages of one length, in one buffer | throughput::hash_many_multithreaded over a throughput::Batch |
| Many 16-, 32-, or 48-byte messages (a Merkle layer’s leaves or digests) | throughput::hash_many_multithreaded over throughput::Packed / &[[u8; N]] (compact storage; avoids refill copies in chains; full groups loaded directly on AVX2, AVX-512, NEON, and SME2; short tails and SSE4.1 expand on the stack) or an owned throughput::Batch::new (note Batch::from_blocks requires whole-block lengths) |
| Many messages of different lengths, in memory | throughput::hash_each_multithreaded |
| Many messages arriving at once (a server’s uploads) | throughput::Pipeline (owned for zero-copy caller-owned buffers such as Vec<u8> or bytes::Bytes, room/commit for streaming); on one thread, or holding each message’s running state, throughput::update_each |
Continuous stream of messages or batches (single or mixed Modes) | throughput::Pipeline (message for the pipeline’s default mode, message_with for a per-message Mode) |
Each call returns once its hash is done, and uses other CPU cores
where that is faster (the forms without multithreaded stay on the
calling thread). As a current heuristic (not a frozen contract),
throughput::hash_multithreaded and
throughput::hash_many_multithreaded stay on the calling thread
below 512 KiB of compression-block bytes — raw input length for single
messages, and count × max(64, round_up(message_len, 64)) for both
throughput::Batch and throughput::Packed<N> (so 8,192 messages
of 16, 32, or 64 bytes all equal 8,192 compressions and qualify) —
and at or above 512 KiB are eligible to use available worker threads
(batches also require at least two messages).
Short messages hash fastest together: 1024 messages of 64 bytes in one
throughput::hash_many call take about a fifth of the time of 1024
convenience::hash calls.
Select keyed hashing or key derivation with Mode, supplied to
throughput calls and the Hasher constructor. See Key-dependent
timing for the key-independence contract.
Hashing now and then (rather than nonstop) is slower per byte on every hash function, since its code and data must come back into the CPU’s caches and a resting core runs slower at first: hashing 64 KiB after a pause takes about three times as long as nonstop on an Apple M4 Max.
Apple M4 and later have one matrix unit that this crate uses for inputs of 16 KiB and more; when several threads of a program hash such inputs at the same moment, one runs at full speed and the others at about two thirds of it. The multithreaded calls share the work among the cores themselves, so a program gets the most from one thread making them.
§Key-dependent timing
Hashing code treats secret key bytes, including derived keys, as data: they select neither branches, memory-access addresses, nor kernels. For a fixed public call shape, grouped calls do the same work whether their hashers’ keys are equal or different. Key equality selects neither groups nor temporary storage sizes.
Public call shape includes the mode kind (plain, keyed, or key derivation),
message and output lengths, input layout, update boundaries, hasher indices,
and size hints. Dispatch may also depend on CPU features and available
processing resources. A batch supplied with one Mode shares a key by
construction. Plain mode’s fixed key is public.
This is a software-level key-independence contract. Elapsed time varies with public call shape, scheduling, clock speed, and machine load. Caller callbacks and I/O have their own timing properties. Applications choose which lengths, modes, and operation patterns they expose to observers.
§Memory
- A
Hasheris 26 KiB; box it where that matters. - These single-threaded calls allocate nothing (except on 512-bit SME2
CPUs, where the first flat-walk tree of 32 KiB or more on each thread
lazily allocates one reusable 64 KiB thread-local scratch block; during
thread-local teardown after that block is destroyed, it falls back to
stack scratch):
convenience::hash,throughput::hash,throughput::hash_many,Hasher::updateandHasher::finalize, andOutputReader.Hasher::update_readeruses a 64 KiB stack buffer for the first read (even on immediate EOF), and promotes to a 1 MiB heap buffer once 65,536 bytes or more are read before EOF, freed when it returns.throughput::hash_eachkeeps reusable per-threadVecstorage for messages of 2 to 15 chunks (16 bytes per message and 32 bytes per chunk of payload, plusVeccapacity): its first such collection and a larger one grow that storage, and a repeated collection on a live thread allocates nothing; during thread-local teardown after that storage is destroyed, multi-chunk collections fall back to call-localVecs. - Grouped incremental calls use bounded stack tables and tree buffers.
throughput::update_eachallocates and frees nothing beyond the one-time per-thread SME2 flat-walk scratch noted above if a fresh thread hashes a whole 32 KiB+ piece on a 512-bit SME2 CPU. throughput::Pipelineallocates itsLimitsrooms and message slots at construction, allocates nothing during steady-state message submission, hashing, and reaping on the calling thread or the workers, and frees its per-pipeline storage once thePipelineand any survivingRooms drop (returning only its worker-facing action ring, waker slot, and monotonic completion lines to the process free list).throughput::hash_multithreadedallocates nothing below 512 KiB, where it hashes on the calling thread. Above that length it keeps a list of the pieces it hands out, 56 bytes for each piece (most are of up to 128 KiB). The list is the calling thread’s and stays with it:initialize_multithreadedmakes 56 KiB of it ready on its own thread (1,024 pieces), a call that needs more pieces grows it, and the thread keeps it at that size (after 1 GiB on 16 CPUs without SME2, 578 KiB). A call that needs no more pieces than an earlier one on that thread allocates nothing. The pieces follow the cut and not the length alone: 1 GiB less one byte is cut into more pieces than 1 GiB.- Once per process: the core startup self-test (stack buffers only; see
blake3-servil-core’s memory section for the post-init per-thread 64 KiB SME2 flat-walk scratch, whichinitialize_multithreadedalso allocates on the calling thread — even withSome(1)— and on the dedicated SME2 worker thread on a 512-bit SME2 CPU), and the pool threads started byinitialize_multithreaded:threads - 1ordinary workers (plus one dedicated SME2 thread whenthreads > 1on a 512-bit SME2 CPU), whereNonepicks thestd::thread::available_parallelismestimate capped by permitted CPUs on the chosen node or process (seeinitialize_multithreadedfor the exact count and sandbox caveats), each with the standard library’s stack. - Nothing is wiped: this crate does not clear what it held from
memory, and offers no call that does. A key, the message bytes a
Hasheror a Pipeline holds and the chaining values made from them stay in the value, in the copies the kernels leave on the stacks, and in the pool’s and the Pipelines’ storage, until something else overwrites them. Official BLAKE3 offersZeroizefor its types.
§Panics
A broken precondition of a call panics on the calling thread, and unwinds as usual. This crate itself ends the whole process in the cases below, with a line on standard error where that takes one; a program cannot catch them. (Rust’s own rules end a process too: a panic while another unwinds, as in an owner’s destructor.)
- Two breaches, since worker threads may be reading memory that the
unwinding would free: a
Pipelinedropped while its messages are still being hashed, and aLentguard dropped while its message’s hashing has not finished. A server keeps both from happening when a client goes away: see “Giving up a message” on the Pipeline. In a child forked while such work was in flight, either drop ends the child (initialize_multithreaded). - A worker thread that the system refuses to start, and a panic on a
worker thread, which speaks through the panic hook first
(
initialize_multithreadedtells both). - A
Wakerof the program’s that panics when it is woken, on whichever thread (the Pipeline’s “Panics”). - A startup self-test that fails, and an x86-64 CPU without SSE4.1
(
initialize). - A panic out of this crate’s own hashing on a calling thread while workers hold that call’s job: a fault of the crate’s, which no input is known to cause.
§Startup self-test
Every program calls initialize (or initialize_multithreaded)
once before hashing: any call that loads the detected platform before
initialization completes panics, in every build, saying so (pure
constructors such as TreeHasher::new(Mode::Plain) and const coordinate
helpers do not load the platform). A program that makes multithreaded
calls calls initialize_multithreaded: a multithreaded call
before it panics (one load per call).
initialize runs a minimal “outside-the-box” self-test before the process
first hashes, well under a millisecond: one unified six-case chained pass
(~5.5 KiB total input, shared across x86-64 and AArch64) exercises the
scalar ALU, .rodata IV, active SIMD vector unit (NEON+SHA-3 / SSE4.1 /
AVX2 / AVX-512), and on SME2 hosts the 512-bit streaming matrix unit plus
live rdsvl check, comparing each folded result with reference values from
official BLAKE3 1.8.7 (and checking compiled x86-64 LZCNT/BMI1 features
on the host CPU). Individual unrolled static assembly variants are proved by
Z3 and verified by unit tests rather than exercised on every process start.
A mismatch stops the process, which no caller can catch: it attempts a best-effort diagnostic
directly to file descriptor 2 (bypassing Rust’s stderr lock, arming a
best-effort alarm(1) watchdog around poll(0) and write, skipping
already-full or already-closed pipes, and disarming alarm(0) before
aborting — taking over and clearing any pre-existing process real-time alarm
even when the write to fd 2 is skipped) and calls std::process::abort when
control returns. Other threads that call
initialize meanwhile wait for it (parked via std::sync::Once).
§Build requirements
Both blake3-servil and blake3-servil-core require the standard library
(neither defines a std Cargo feature or no_std mode; callers upgrading
from 0.11.0 should drop features = ["std"], and default-features = false does not opt out of std).
All kernels are assembled directly by rustc via
core::arch::global_asm! (no external C compiler or cc build dependency
is required for the Rust libraries). This crate runs its assembly or not at
all: for no_std, portable Rust, or other targets, use official BLAKE3.
Modules§
- convenience
- The convenience API: one call per hash, every feature of BLAKE3 (the
plain hash, the keyed hash, key derivation, extended output), any
slice, the result returned, and a
Hasherfor a message fed in pieces, on the calling thread. It does without what makes hashing fast: other cores, batches, streams. Those are thethroughputcalls, for power users. - throughput
- The throughput API: the core’s, and the calls that use other cores.
Structs§
- Hash
- An output of the default size, 32 bytes, which provides constant-time equality checking.
- HexError
- The error type for
Hash::from_hex. - HexHash
- The 64 lowercase hexadecimal characters of a
Hash, held inline with no heap allocation. - Output
Reader - An incremental reader for extended output, returned by
Hasher::finalize_xof.
Enums§
- Mode
- Which of BLAKE3’s three functions a call computes: the plain hash
(
hash), the keyed hash, or key derivation. Every call that takes a mode runs each one at the same speed, but forDeriveKey, which first hashes its context string (once per call;DeriveKeyWithtakes it hashed once for many calls).
Constants§
- BLOCK_
LEN - The number of bytes in a block, 64.
- BUILD_
VERSION - This build’s version: the crate’s version, and for any build but a
release’s own commit, the commit built and, from a dirty tree, the Git
tree id of its working tree, e.g.
0.8.0+dev.<commit>.dirty.<tree>(version/build_version.rs).b3sum --versionand the C library’sb3_version()print it. - CHUNK_
LEN - The number of bytes in a chunk, 1024.
- KEY_LEN
- The number of bytes in a key, 32.
- OUT_LEN
- The number of bytes in a
Hash, 32.
Functions§
- initialize
- Run the startup self-test and detect the CPU: every program calls this
once before hashing (any call that loads the detected platform before
initializecompletes panics). Under 0.2 ms, once per process (see the crate’s documentation); later calls return at once. - initialize_
multithreaded initialize, and start the threads that the multithreaded calls use: every program that makes such calls calls this once, before them, in place ofinitialize. It startsthreads - 1workers, and each multithreaded call hashes on its calling thread and the workers (calls made at once share the workers), and on CPUs with SME2 (Apple M4) the SME2 thread too.Noneuses the available logical CPUs, limited on Linux to the allowed CPUs of one memory node (below). With 1, calls hash on their calling thread alone: no workers start, nor the SME2 thread. Otherwise it starts the first worker and returns; the first worker starts the others (each 20-30 us on Linux x86-64), and calls run on the workers started so far. The threads wait asleep whenever no call has work for them (their memory: see Memory). Later calls return at once, and must ask for the same number: anotherSomepanics. A panic on a worker thread (a bug in this crate, or a waker of the program’s that panics when a worker wakes it) ends the process, once the process’s panic hook has returned (the standard one prints the panic’s message, and waits where standard error does not take it), rather than leaving the call that waits for that worker’s piece waiting forever. A worker thread that the system refuses to start ends the process too, for the same reason, with one line on standard error: a limit on the process’s threads (RLIMIT_NPROC, a container’spids.max) or a lack of memory can refuse one. The first worker is started by this call and the others by the first worker, so the end can come shortly after this call has returned, and the program cannot catch it: one that runs under such a limit passes a count of threads that fits.
Type Aliases§
- Context
Key - An alias to distinguish
context_keyoutputs from other keys. It is a plain byte array, and so are its traits: itsDebugprints the key, and its==promises no constant time.