Expand description
blake3-servil-core is BLAKE3-Servil on one thread: a fast BLAKE3
implementation for 64-bit Arm and x86-64, its assembly kernels (each
proved against the specification) and every call that hashes on the
thread that makes it. It produces the same digests as official BLAKE3.
It starts no thread and uses no other core: the crate blake3-servil
is this one, whole, with the calls that do.
§Examples
// Once per process, before any other call (see Startup self-test).
blake3_servil_core::initialize();
// Hash an input all at once.
let hash1 = blake3_servil_core::convenience::hash(b"foobarbaz");
// Hash an input incrementally.
let mut hasher = blake3_servil_core::convenience::Hasher::new(blake3_servil_core::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_core::convenience::Hasher::new(blake3_servil_core::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_core::{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_core::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 (batches, collections, many hashers fed in turns), 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 call that takes it, throughput::update_each, is tuned as
a throughput call.
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 convenience::hash_with) |
| One message in memory, repeated call after call | throughput::hash (on aligned Blocks), or throughput::TreeHasher::hash directly on caller-owned &[u8] slices without copying into aligned blocks |
| One message arriving in pieces | convenience::Hasher |
| Many messages of one length, in one buffer | throughput::hash_many over a throughput::Batch |
| Many 16-, 32-, or 48-byte messages (a Merkle layer’s leaves or digests) | throughput::hash_many 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 |
| Many messages arriving at once (a server’s uploads) | throughput::update_each, then throughput::finalize_each |
Each call returns once its hash is done, on the calling thread. For
long inputs and large batches on several cores, the crate
blake3-servil adds a multithreaded form of each, and for messages
that keep arriving its Pipeline
(throughput::update_each says when each is the one to use).
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.
§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, a bounded stack
scratch is used instead — 8 KiB up to 64 KiB inputs, 64 KiB above):
convenience::hash,throughput::hash,throughput::hash_many,throughput::hash_counter_range,throughput::hash_chains_32_trunc16,Hasher::updateandHasher::finalize, andOutputReader.throughput::hash_chains_varlen_32_trunc16uses stack storage when at most 128 chains have nonzero step counts, and allocates a call-localVec<usize>(freed on return) when more than 128 chains have nonzero steps.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, a collection with multi-chunk items falls 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. - Once per process: the startup self-test uses stack buffers on the
calling thread while it runs (it does not touch the thread-local SME2
flat-walk scratch, which is initialized on a thread’s first post-init
whole 32 KiB+ walk — or when
blake3-servil’sinitialize_multithreadedprepares the calling thread, even withSome(1), or starts the SME2 worker — on a 512-bit SME2 CPU). - 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
Hasherholds and the chaining values made from them stay in the value, in the copies the kernels leave on the stack, and in the storage a thread keeps (hash_each’s, above; on CPUs with SME2, a 64 KiB block for the chaining values of the inputs the thread hashes, keyed ones included), 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.
§Startup self-test
Every program calls initialize once, before hashing: any call
that loads the detected platform (including convenience::hash,
Hasher::new, Mode::DeriveKey context
hashing, and hashing methods on TreeHasher)
panics before initialize completes, in every build, saying so. Pure
constructors and const coordinate helpers that need no runtime platform
(such as TreeHasher::new for Plain,
Keyed, or DeriveKeyWith, an empty parent_cvs call, and
throughput::left_len) do not load the platform. The check costs
nothing: it is part of the platform load made when selecting kernels.
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) and calls
std::process::abort when control returns. Arming and disarming alarm
takes over (and clears) any pre-existing process real-time alarm even when
the write to fd 2 is skipped. Other threads that call initialize meanwhile wait
for it (parked via std::sync::Once; programs that fork should finish
initialize before forking).
§Build requirements
This crate requires std (it has no std Cargo feature and no no_std
mode; callers upgrading from 0.11.0 should drop features = ["std"] or
blake3-servil-core/std, and default-features = false does not opt out
of std). It runs on 64-bit little-endian x86-64 Linux and AArch64
Linux/macOS. 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, for power users: every way this crate makes hashing fast (batches, collections, many hashers fed in turns). The program takes on more of the work, so the calls can be fast and simple:
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>. The C library’sb3_version()prints it (the standaloneservil-software-factory/b3sumtool prints its own 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.
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.