Skip to main content

ab_blake3/
single_block.rs

1//! BLAKE3 functions that process at most a single block.
2//!
3//! This module and submodules are copied with modifications from the official [`blake3`] crate, but
4//! are unlikely to be upstreamed.
5
6#[cfg(test)]
7mod tests;
8
9use crate::platform::{le_bytes_from_words_32, words_from_le_bytes_32};
10use crate::{
11    BLOCK_LEN, BlockBytes, BlockWords, CHUNK_END, CHUNK_START, CVWords, DERIVE_KEY_CONTEXT,
12    DERIVE_KEY_MATERIAL, IV, KEY_LEN, KEYED_HASH, OUT_LEN, ROOT, portable,
13};
14use blake3::IncrementCounter;
15use blake3::platform::Platform;
16
17/// Hash single block worth of values
18#[inline(always)]
19fn hash_block(input: &[u8], key: CVWords, flags: u8) -> Option<[u8; OUT_LEN]> {
20    // If the whole subtree is one block, hash it directly with a ChunkState.
21    if input.len() > BLOCK_LEN {
22        return None;
23    }
24
25    let mut cv = key;
26
27    let mut block = [0; BLOCK_LEN];
28    block[..input.len()].copy_from_slice(input);
29    Platform::detect().compress_in_place(
30        &mut cv,
31        &block,
32        input.len() as u8,
33        0,
34        flags | CHUNK_START | CHUNK_END | ROOT,
35    );
36
37    Some(*le_bytes_from_words_32(&cv))
38}
39
40/// Hash multiple single block-sized inputs
41#[inline(always)]
42fn hash_block_many_exact<const NUM_BLOCKS: usize>(
43    inputs: &[BlockBytes; NUM_BLOCKS],
44    // TODO: `&mut [MaybeUninit<[u8; OUT_LEN]>; N]` would make more sense, but doesn't match
45    //  `blake3` API
46    outputs: &mut [[u8; OUT_LEN]; NUM_BLOCKS],
47    key: CVWords,
48    flags: u8,
49) {
50    let platform = Platform::detect();
51
52    // Inputs are hashed in chunks to limit the size of the array of references to them
53    let (input_chunks, remaining_inputs) = inputs.as_chunks::<16>();
54    let (output_chunks, remaining_outputs) = outputs.as_chunks_mut::<16>();
55
56    for (inputs, outputs) in input_chunks.iter().zip(output_chunks) {
57        // TODO: This is a very awkward API, ideally we wouldn't have this array allocated inline
58        //  for no good reason
59        platform.hash_many(
60            &inputs.each_ref(),
61            &key,
62            0,
63            IncrementCounter::No,
64            flags | CHUNK_START | CHUNK_END | ROOT,
65            0,
66            0,
67            outputs.as_flattened_mut(),
68        );
69    }
70
71    // A single input is hashed faster without `blake3::platform::Platform::hash_many()`
72    if remaining_inputs.len() < 2 {
73        for (input, output) in remaining_inputs.iter().zip(remaining_outputs) {
74            let mut cv = key;
75
76            platform.compress_in_place(
77                &mut cv,
78                input,
79                BLOCK_LEN as u8,
80                0,
81                flags | CHUNK_START | CHUNK_END | ROOT,
82            );
83
84            output.copy_from_slice(le_bytes_from_words_32(&cv));
85        }
86        return;
87    }
88
89    let mut input_refs = [&[0; BLOCK_LEN]; 16];
90    for (input_ref, input) in input_refs.iter_mut().zip(remaining_inputs) {
91        *input_ref = input;
92    }
93
94    cfg_select! {
95        // A varying number of inputs prevents the compiler from proving that `blake3` doesn't
96        // panic, so inputs are padded to 16 instead
97        feature = "no-panic" => {
98            let mut padded_outputs = [[0; OUT_LEN]; 16];
99            platform.hash_many(
100                &input_refs,
101                &key,
102                0,
103                IncrementCounter::No,
104                flags | CHUNK_START | CHUNK_END | ROOT,
105                0,
106                0,
107                padded_outputs.as_flattened_mut(),
108            );
109            for (output, padded_output) in remaining_outputs.iter_mut().zip(&padded_outputs) {
110                *output = *padded_output;
111            }
112        }
113        // `blake3` hashes inputs that don't fill the widest SIMD with narrower SIMD
114        _ => {
115            platform.hash_many(
116                &input_refs[..remaining_inputs.len()],
117                &key,
118                0,
119                IncrementCounter::No,
120                flags | CHUNK_START | CHUNK_END | ROOT,
121                0,
122                0,
123                remaining_outputs.as_flattened_mut(),
124            );
125        }
126    }
127}
128
129/// Hashing function for at most single block worth of bytes.
130///
131/// Returns `None` if the input length exceeds one block.
132#[inline]
133#[cfg_attr(feature = "no-panic", no_panic::no_panic)]
134pub fn single_block_hash(input: &[u8]) -> Option<[u8; OUT_LEN]> {
135    hash_block(input, *IV, 0)
136}
137
138/// Hashing function for many single-block inputs
139#[inline]
140#[cfg_attr(feature = "no-panic", no_panic::no_panic)]
141pub fn single_block_hash_many_exact<const NUM_BLOCKS: usize>(
142    inputs: &[BlockBytes; NUM_BLOCKS],
143    // TODO: `&mut [MaybeUninit<[u8; OUT_LEN]>; N]` would make more sense, but doesn't match
144    //  `blake3` API
145    outputs: &mut [[u8; OUT_LEN]; NUM_BLOCKS],
146) {
147    hash_block_many_exact(inputs, outputs, *IV, 0);
148}
149
150/// The keyed hash function for at most single block worth of bytes.
151///
152/// Returns `None` if the input length exceeds one block.
153#[inline]
154#[cfg_attr(feature = "no-panic", no_panic::no_panic)]
155pub fn single_block_keyed_hash(key: &[u8; KEY_LEN], input: &[u8]) -> Option<[u8; OUT_LEN]> {
156    let key_words = words_from_le_bytes_32(key);
157    hash_block(input, key_words, KEYED_HASH)
158}
159
160/// Keyed hash function for many single-block inputs
161#[inline]
162#[cfg_attr(feature = "no-panic", no_panic::no_panic)]
163pub fn single_block_keyed_hash_many_exact<const NUM_BLOCKS: usize>(
164    key: &[u8; KEY_LEN],
165    inputs: &[BlockBytes; NUM_BLOCKS],
166    // TODO: `&mut [MaybeUninit<[u8; OUT_LEN]>; N]` would make more sense, but doesn't match
167    //  `blake3` API
168    outputs: &mut [[u8; OUT_LEN]; NUM_BLOCKS],
169) {
170    let key_words = words_from_le_bytes_32(key);
171    hash_block_many_exact(inputs, outputs, key_words, KEYED_HASH);
172}
173
174/// The key derivation function for at most a single block worth of bytes.
175///
176/// Returns `None` if either context or key material length exceed one block.
177#[inline]
178#[cfg_attr(feature = "no-panic", no_panic::no_panic)]
179pub fn single_block_derive_key(context: &str, key_material: &[u8]) -> Option<[u8; OUT_LEN]> {
180    let context_key = hash_block(context.as_bytes(), *IV, DERIVE_KEY_CONTEXT)?;
181    let context_key_words = words_from_le_bytes_32(&context_key);
182    hash_block(key_material, context_key_words, DERIVE_KEY_MATERIAL)
183}
184
185/// Hashing function for at most single block worth of words using portable implementation.
186///
187/// This API operates on words and is GPU-friendly.
188///
189/// `num_bytes` specifies how many actual bytes are occupied by useful value in `input`. Bytes
190/// outside that must be set to `0`.
191///
192/// NOTE: If unused bytes are not set to `0` or an invalid number of bytes is specified, it'll
193/// simply result in an invalid hash.
194///
195/// [`words_from_le_bytes_32()`], [`words_from_le_bytes_64()`] and [`le_bytes_from_words_32()`] can
196/// be used to convert bytes to words and back if necessary.
197///
198/// [`words_from_le_bytes_64()`]: crate::words_from_le_bytes_64
199#[inline]
200#[cfg_attr(feature = "no-panic", no_panic::no_panic)]
201pub fn single_block_hash_portable_words(input: &BlockWords, num_bytes: u32) -> CVWords {
202    let mut cv = *IV;
203
204    portable::compress_in_place_u32(
205        &mut cv,
206        input,
207        num_bytes,
208        0,
209        u32::from(CHUNK_START | CHUNK_END | ROOT),
210    );
211
212    cv
213}