1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3 * This file and its contents are supplied under the terms of the
4 * Common Development and Distribution License ("CDDL"), version 1.0.
5 * You may only use this file in accordance with the terms of version
6 * 1.0 of the CDDL.
7 *
8 * A full copy of the text of the CDDL should have accompanied this
9 * source. A copy of the CDDL is also available via the Internet at
10 * https://opensource.org/license/CDDL-1.0.
11 */
12
13 /*
14 * Based on BLAKE3 v1.3.1, https://github.com/BLAKE3-team/BLAKE3
15 * Copyright (c) 2019-2020 Samuel Neves and Jack O'Connor
16 * Copyright (c) 2021-2022 Tino Reichardt <milky-zfs@mcmilk.de>
17 */
18
19 #include <sys/simd.h>
20 #include <sys/zfs_context.h>
21 #include <sys/blake3.h>
22
23 #include "blake3_impl.h"
24
25 /*
26 * We need 1056 byte stack for blake3_compress_subtree_wide()
27 * - we define this pragma to make gcc happy
28 */
29 #if defined(__GNUC__)
30 #pragma GCC diagnostic ignored "-Wframe-larger-than="
31 #endif
32
33 /* internal used */
34 typedef struct {
35 uint32_t input_cv[8];
36 uint64_t counter;
37 uint8_t block[BLAKE3_BLOCK_LEN];
38 uint8_t block_len;
39 uint8_t flags;
40 } output_t;
41
42 /* internal flags */
43 enum blake3_flags {
44 CHUNK_START = 1 << 0,
45 CHUNK_END = 1 << 1,
46 PARENT = 1 << 2,
47 ROOT = 1 << 3,
48 KEYED_HASH = 1 << 4,
49 DERIVE_KEY_CONTEXT = 1 << 5,
50 DERIVE_KEY_MATERIAL = 1 << 6,
51 };
52
53 /* internal start */
chunk_state_init(blake3_chunk_state_t * ctx,const uint32_t key[8],uint8_t flags)54 static void chunk_state_init(blake3_chunk_state_t *ctx,
55 const uint32_t key[8], uint8_t flags)
56 {
57 memcpy(ctx->cv, key, BLAKE3_KEY_LEN);
58 ctx->chunk_counter = 0;
59 memset(ctx->buf, 0, BLAKE3_BLOCK_LEN);
60 ctx->buf_len = 0;
61 ctx->blocks_compressed = 0;
62 ctx->flags = flags;
63 }
64
chunk_state_reset(blake3_chunk_state_t * ctx,const uint32_t key[8],uint64_t chunk_counter)65 static void chunk_state_reset(blake3_chunk_state_t *ctx,
66 const uint32_t key[8], uint64_t chunk_counter)
67 {
68 memcpy(ctx->cv, key, BLAKE3_KEY_LEN);
69 ctx->chunk_counter = chunk_counter;
70 ctx->blocks_compressed = 0;
71 memset(ctx->buf, 0, BLAKE3_BLOCK_LEN);
72 ctx->buf_len = 0;
73 }
74
chunk_state_len(const blake3_chunk_state_t * ctx)75 static size_t chunk_state_len(const blake3_chunk_state_t *ctx)
76 {
77 return (BLAKE3_BLOCK_LEN * (size_t)ctx->blocks_compressed) +
78 ((size_t)ctx->buf_len);
79 }
80
chunk_state_fill_buf(blake3_chunk_state_t * ctx,const uint8_t * input,size_t input_len)81 static size_t chunk_state_fill_buf(blake3_chunk_state_t *ctx,
82 const uint8_t *input, size_t input_len)
83 {
84 size_t take = BLAKE3_BLOCK_LEN - ((size_t)ctx->buf_len);
85 if (take > input_len) {
86 take = input_len;
87 }
88 uint8_t *dest = ctx->buf + ((size_t)ctx->buf_len);
89 memcpy(dest, input, take);
90 ctx->buf_len += (uint8_t)take;
91 return (take);
92 }
93
chunk_state_maybe_start_flag(const blake3_chunk_state_t * ctx)94 static uint8_t chunk_state_maybe_start_flag(const blake3_chunk_state_t *ctx)
95 {
96 if (ctx->blocks_compressed == 0) {
97 return (CHUNK_START);
98 } else {
99 return (0);
100 }
101 }
102
make_output(const uint32_t input_cv[8],const uint8_t * block,uint8_t block_len,uint64_t counter,uint8_t flags)103 static output_t make_output(const uint32_t input_cv[8],
104 const uint8_t *block, uint8_t block_len,
105 uint64_t counter, uint8_t flags)
106 {
107 output_t ret;
108 memcpy(ret.input_cv, input_cv, 32);
109 memcpy(ret.block, block, BLAKE3_BLOCK_LEN);
110 ret.block_len = block_len;
111 ret.counter = counter;
112 ret.flags = flags;
113 return (ret);
114 }
115
116 /*
117 * Chaining values within a given chunk (specifically the compress_in_place
118 * interface) are represented as words. This avoids unnecessary bytes<->words
119 * conversion overhead in the portable implementation. However, the hash_many
120 * interface handles both user input and parent node blocks, so it accepts
121 * bytes. For that reason, chaining values in the CV stack are represented as
122 * bytes.
123 */
output_chaining_value(const blake3_ops_t * ops,const output_t * ctx,uint8_t cv[32])124 static void output_chaining_value(const blake3_ops_t *ops,
125 const output_t *ctx, uint8_t cv[32])
126 {
127 uint32_t cv_words[8];
128 memcpy(cv_words, ctx->input_cv, 32);
129 ops->compress_in_place(cv_words, ctx->block, ctx->block_len,
130 ctx->counter, ctx->flags);
131 store_cv_words(cv, cv_words);
132 }
133
output_root_bytes(const blake3_ops_t * ops,const output_t * ctx,uint64_t seek,uint8_t * out,size_t out_len)134 static void output_root_bytes(const blake3_ops_t *ops, const output_t *ctx,
135 uint64_t seek, uint8_t *out, size_t out_len)
136 {
137 uint64_t output_block_counter = seek / 64;
138 size_t offset_within_block = seek % 64;
139 uint8_t wide_buf[64];
140 while (out_len > 0) {
141 ops->compress_xof(ctx->input_cv, ctx->block, ctx->block_len,
142 output_block_counter, ctx->flags | ROOT, wide_buf);
143 size_t available_bytes = 64 - offset_within_block;
144 size_t memcpy_len;
145 if (out_len > available_bytes) {
146 memcpy_len = available_bytes;
147 } else {
148 memcpy_len = out_len;
149 }
150 memcpy(out, wide_buf + offset_within_block, memcpy_len);
151 out += memcpy_len;
152 out_len -= memcpy_len;
153 output_block_counter += 1;
154 offset_within_block = 0;
155 }
156 }
157
chunk_state_update(const blake3_ops_t * ops,blake3_chunk_state_t * ctx,const uint8_t * input,size_t input_len)158 static void chunk_state_update(const blake3_ops_t *ops,
159 blake3_chunk_state_t *ctx, const uint8_t *input, size_t input_len)
160 {
161 if (ctx->buf_len > 0) {
162 size_t take = chunk_state_fill_buf(ctx, input, input_len);
163 input += take;
164 input_len -= take;
165 if (input_len > 0) {
166 ops->compress_in_place(ctx->cv, ctx->buf,
167 BLAKE3_BLOCK_LEN, ctx->chunk_counter,
168 ctx->flags|chunk_state_maybe_start_flag(ctx));
169 ctx->blocks_compressed += 1;
170 ctx->buf_len = 0;
171 memset(ctx->buf, 0, BLAKE3_BLOCK_LEN);
172 }
173 }
174
175 while (input_len > BLAKE3_BLOCK_LEN) {
176 ops->compress_in_place(ctx->cv, input, BLAKE3_BLOCK_LEN,
177 ctx->chunk_counter,
178 ctx->flags|chunk_state_maybe_start_flag(ctx));
179 ctx->blocks_compressed += 1;
180 input += BLAKE3_BLOCK_LEN;
181 input_len -= BLAKE3_BLOCK_LEN;
182 }
183
184 chunk_state_fill_buf(ctx, input, input_len);
185 }
186
chunk_state_output(const blake3_chunk_state_t * ctx)187 static output_t chunk_state_output(const blake3_chunk_state_t *ctx)
188 {
189 uint8_t block_flags =
190 ctx->flags | chunk_state_maybe_start_flag(ctx) | CHUNK_END;
191 return (make_output(ctx->cv, ctx->buf, ctx->buf_len, ctx->chunk_counter,
192 block_flags));
193 }
194
parent_output(const uint8_t block[BLAKE3_BLOCK_LEN],const uint32_t key[8],uint8_t flags)195 static output_t parent_output(const uint8_t block[BLAKE3_BLOCK_LEN],
196 const uint32_t key[8], uint8_t flags)
197 {
198 return (make_output(key, block, BLAKE3_BLOCK_LEN, 0, flags | PARENT));
199 }
200
201 /*
202 * Given some input larger than one chunk, return the number of bytes that
203 * should go in the left subtree. This is the largest power-of-2 number of
204 * chunks that leaves at least 1 byte for the right subtree.
205 */
left_len(size_t content_len)206 static size_t left_len(size_t content_len)
207 {
208 /*
209 * Subtract 1 to reserve at least one byte for the right side.
210 * content_len
211 * should always be greater than BLAKE3_CHUNK_LEN.
212 */
213 size_t full_chunks = (content_len - 1) / BLAKE3_CHUNK_LEN;
214 return (round_down_to_power_of_2(full_chunks) * BLAKE3_CHUNK_LEN);
215 }
216
217 /*
218 * Use SIMD parallelism to hash up to MAX_SIMD_DEGREE chunks at the same time
219 * on a single thread. Write out the chunk chaining values and return the
220 * number of chunks hashed. These chunks are never the root and never empty;
221 * those cases use a different codepath.
222 */
compress_chunks_parallel(const blake3_ops_t * ops,const uint8_t * input,size_t input_len,const uint32_t key[8],uint64_t chunk_counter,uint8_t flags,uint8_t * out)223 static size_t compress_chunks_parallel(const blake3_ops_t *ops,
224 const uint8_t *input, size_t input_len, const uint32_t key[8],
225 uint64_t chunk_counter, uint8_t flags, uint8_t *out)
226 {
227 const uint8_t *chunks_array[MAX_SIMD_DEGREE];
228 size_t input_position = 0;
229 size_t chunks_array_len = 0;
230 while (input_len - input_position >= BLAKE3_CHUNK_LEN) {
231 chunks_array[chunks_array_len] = &input[input_position];
232 input_position += BLAKE3_CHUNK_LEN;
233 chunks_array_len += 1;
234 }
235
236 ops->hash_many(chunks_array, chunks_array_len, BLAKE3_CHUNK_LEN /
237 BLAKE3_BLOCK_LEN, key, chunk_counter, B_TRUE, flags, CHUNK_START,
238 CHUNK_END, out);
239
240 /*
241 * Hash the remaining partial chunk, if there is one. Note that the
242 * empty chunk (meaning the empty message) is a different codepath.
243 */
244 if (input_len > input_position) {
245 uint64_t counter = chunk_counter + (uint64_t)chunks_array_len;
246 blake3_chunk_state_t chunk_state;
247 chunk_state_init(&chunk_state, key, flags);
248 chunk_state.chunk_counter = counter;
249 chunk_state_update(ops, &chunk_state, &input[input_position],
250 input_len - input_position);
251 output_t output = chunk_state_output(&chunk_state);
252 output_chaining_value(ops, &output, &out[chunks_array_len *
253 BLAKE3_OUT_LEN]);
254 return (chunks_array_len + 1);
255 } else {
256 return (chunks_array_len);
257 }
258 }
259
260 /*
261 * Use SIMD parallelism to hash up to MAX_SIMD_DEGREE parents at the same time
262 * on a single thread. Write out the parent chaining values and return the
263 * number of parents hashed. (If there's an odd input chaining value left over,
264 * return it as an additional output.) These parents are never the root and
265 * never empty; those cases use a different codepath.
266 */
compress_parents_parallel(const blake3_ops_t * ops,const uint8_t * child_chaining_values,size_t num_chaining_values,const uint32_t key[8],uint8_t flags,uint8_t * out)267 static size_t compress_parents_parallel(const blake3_ops_t *ops,
268 const uint8_t *child_chaining_values, size_t num_chaining_values,
269 const uint32_t key[8], uint8_t flags, uint8_t *out)
270 {
271 const uint8_t *parents_array[MAX_SIMD_DEGREE_OR_2] = {0};
272 size_t parents_array_len = 0;
273
274 while (num_chaining_values - (2 * parents_array_len) >= 2) {
275 parents_array[parents_array_len] = &child_chaining_values[2 *
276 parents_array_len * BLAKE3_OUT_LEN];
277 parents_array_len += 1;
278 }
279
280 ops->hash_many(parents_array, parents_array_len, 1, key, 0, B_FALSE,
281 flags | PARENT, 0, 0, out);
282
283 /* If there's an odd child left over, it becomes an output. */
284 if (num_chaining_values > 2 * parents_array_len) {
285 memcpy(&out[parents_array_len * BLAKE3_OUT_LEN],
286 &child_chaining_values[2 * parents_array_len *
287 BLAKE3_OUT_LEN], BLAKE3_OUT_LEN);
288 return (parents_array_len + 1);
289 } else {
290 return (parents_array_len);
291 }
292 }
293
294 /*
295 * The wide helper function returns (writes out) an array of chaining values
296 * and returns the length of that array. The number of chaining values returned
297 * is the dyanmically detected SIMD degree, at most MAX_SIMD_DEGREE. Or fewer,
298 * if the input is shorter than that many chunks. The reason for maintaining a
299 * wide array of chaining values going back up the tree, is to allow the
300 * implementation to hash as many parents in parallel as possible.
301 *
302 * As a special case when the SIMD degree is 1, this function will still return
303 * at least 2 outputs. This guarantees that this function doesn't perform the
304 * root compression. (If it did, it would use the wrong flags, and also we
305 * wouldn't be able to implement exendable ouput.) Note that this function is
306 * not used when the whole input is only 1 chunk long; that's a different
307 * codepath.
308 *
309 * Why not just have the caller split the input on the first update(), instead
310 * of implementing this special rule? Because we don't want to limit SIMD or
311 * multi-threading parallelism for that update().
312 */
blake3_compress_subtree_wide(const blake3_ops_t * ops,const uint8_t * input,size_t input_len,const uint32_t key[8],uint64_t chunk_counter,uint8_t flags,uint8_t * out)313 static size_t blake3_compress_subtree_wide(const blake3_ops_t *ops,
314 const uint8_t *input, size_t input_len, const uint32_t key[8],
315 uint64_t chunk_counter, uint8_t flags, uint8_t *out)
316 {
317 /*
318 * Note that the single chunk case does *not* bump the SIMD degree up
319 * to 2 when it is 1. If this implementation adds multi-threading in
320 * the future, this gives us the option of multi-threading even the
321 * 2-chunk case, which can help performance on smaller platforms.
322 */
323 if (input_len <= (size_t)(ops->degree * BLAKE3_CHUNK_LEN)) {
324 return (compress_chunks_parallel(ops, input, input_len, key,
325 chunk_counter, flags, out));
326 }
327
328
329 /*
330 * With more than simd_degree chunks, we need to recurse. Start by
331 * dividing the input into left and right subtrees. (Note that this is
332 * only optimal as long as the SIMD degree is a power of 2. If we ever
333 * get a SIMD degree of 3 or something, we'll need a more complicated
334 * strategy.)
335 */
336 size_t left_input_len = left_len(input_len);
337 size_t right_input_len = input_len - left_input_len;
338 const uint8_t *right_input = &input[left_input_len];
339 uint64_t right_chunk_counter = chunk_counter +
340 (uint64_t)(left_input_len / BLAKE3_CHUNK_LEN);
341
342 /*
343 * Make space for the child outputs. Here we use MAX_SIMD_DEGREE_OR_2
344 * to account for the special case of returning 2 outputs when the
345 * SIMD degree is 1.
346 */
347 uint8_t cv_array[2 * MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN];
348 size_t degree = ops->degree;
349 if (left_input_len > BLAKE3_CHUNK_LEN && degree == 1) {
350
351 /*
352 * The special case: We always use a degree of at least two,
353 * to make sure there are two outputs. Except, as noted above,
354 * at the chunk level, where we allow degree=1. (Note that the
355 * 1-chunk-input case is a different codepath.)
356 */
357 degree = 2;
358 }
359 uint8_t *right_cvs = &cv_array[degree * BLAKE3_OUT_LEN];
360
361 /*
362 * Recurse! If this implementation adds multi-threading support in the
363 * future, this is where it will go.
364 */
365 size_t left_n = blake3_compress_subtree_wide(ops, input, left_input_len,
366 key, chunk_counter, flags, cv_array);
367 size_t right_n = blake3_compress_subtree_wide(ops, right_input,
368 right_input_len, key, right_chunk_counter, flags, right_cvs);
369
370 /*
371 * The special case again. If simd_degree=1, then we'll have left_n=1
372 * and right_n=1. Rather than compressing them into a single output,
373 * return them directly, to make sure we always have at least two
374 * outputs.
375 */
376 if (left_n == 1) {
377 memcpy(out, cv_array, 2 * BLAKE3_OUT_LEN);
378 return (2);
379 }
380
381 /* Otherwise, do one layer of parent node compression. */
382 size_t num_chaining_values = left_n + right_n;
383 return compress_parents_parallel(ops, cv_array,
384 num_chaining_values, key, flags, out);
385 }
386
387 /*
388 * Hash a subtree with compress_subtree_wide(), and then condense the resulting
389 * list of chaining values down to a single parent node. Don't compress that
390 * last parent node, however. Instead, return its message bytes (the
391 * concatenated chaining values of its children). This is necessary when the
392 * first call to update() supplies a complete subtree, because the topmost
393 * parent node of that subtree could end up being the root. It's also necessary
394 * for extended output in the general case.
395 *
396 * As with compress_subtree_wide(), this function is not used on inputs of 1
397 * chunk or less. That's a different codepath.
398 */
compress_subtree_to_parent_node(const blake3_ops_t * ops,const uint8_t * input,size_t input_len,const uint32_t key[8],uint64_t chunk_counter,uint8_t flags,uint8_t out[2* BLAKE3_OUT_LEN])399 static void compress_subtree_to_parent_node(const blake3_ops_t *ops,
400 const uint8_t *input, size_t input_len, const uint32_t key[8],
401 uint64_t chunk_counter, uint8_t flags, uint8_t out[2 * BLAKE3_OUT_LEN])
402 {
403 uint8_t cv_array[MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN];
404 size_t num_cvs = blake3_compress_subtree_wide(ops, input, input_len,
405 key, chunk_counter, flags, cv_array);
406
407 /*
408 * If MAX_SIMD_DEGREE is greater than 2 and there's enough input,
409 * compress_subtree_wide() returns more than 2 chaining values. Condense
410 * them into 2 by forming parent nodes repeatedly.
411 */
412 uint8_t out_array[MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN / 2];
413 while (num_cvs > 2) {
414 num_cvs = compress_parents_parallel(ops, cv_array, num_cvs, key,
415 flags, out_array);
416 memcpy(cv_array, out_array, num_cvs * BLAKE3_OUT_LEN);
417 }
418 memcpy(out, cv_array, 2 * BLAKE3_OUT_LEN);
419 }
420
hasher_init_base(BLAKE3_CTX * ctx,const uint32_t key[8],uint8_t flags)421 static void hasher_init_base(BLAKE3_CTX *ctx, const uint32_t key[8],
422 uint8_t flags)
423 {
424 memcpy(ctx->key, key, BLAKE3_KEY_LEN);
425 chunk_state_init(&ctx->chunk, key, flags);
426 ctx->cv_stack_len = 0;
427 ctx->ops = blake3_get_ops();
428 }
429
430 /*
431 * As described in hasher_push_cv() below, we do "lazy merging", delaying
432 * merges until right before the next CV is about to be added. This is
433 * different from the reference implementation. Another difference is that we
434 * aren't always merging 1 chunk at a time. Instead, each CV might represent
435 * any power-of-two number of chunks, as long as the smaller-above-larger
436 * stack order is maintained. Instead of the "count the trailing 0-bits"
437 * algorithm described in the spec, we use a "count the total number of
438 * 1-bits" variant that doesn't require us to retain the subtree size of the
439 * CV on top of the stack. The principle is the same: each CV that should
440 * remain in the stack is represented by a 1-bit in the total number of chunks
441 * (or bytes) so far.
442 */
hasher_merge_cv_stack(BLAKE3_CTX * ctx,uint64_t total_len)443 static void hasher_merge_cv_stack(BLAKE3_CTX *ctx, uint64_t total_len)
444 {
445 size_t post_merge_stack_len = (size_t)popcnt(total_len);
446 while (ctx->cv_stack_len > post_merge_stack_len) {
447 uint8_t *parent_node =
448 &ctx->cv_stack[(ctx->cv_stack_len - 2) * BLAKE3_OUT_LEN];
449 output_t output =
450 parent_output(parent_node, ctx->key, ctx->chunk.flags);
451 output_chaining_value(ctx->ops, &output, parent_node);
452 ctx->cv_stack_len -= 1;
453 }
454 }
455
456 /*
457 * In reference_impl.rs, we merge the new CV with existing CVs from the stack
458 * before pushing it. We can do that because we know more input is coming, so
459 * we know none of the merges are root.
460 *
461 * This setting is different. We want to feed as much input as possible to
462 * compress_subtree_wide(), without setting aside anything for the chunk_state.
463 * If the user gives us 64 KiB, we want to parallelize over all 64 KiB at once
464 * as a single subtree, if at all possible.
465 *
466 * This leads to two problems:
467 * 1) This 64 KiB input might be the only call that ever gets made to update.
468 * In this case, the root node of the 64 KiB subtree would be the root node
469 * of the whole tree, and it would need to be ROOT finalized. We can't
470 * compress it until we know.
471 * 2) This 64 KiB input might complete a larger tree, whose root node is
472 * similarly going to be the the root of the whole tree. For example, maybe
473 * we have 196 KiB (that is, 128 + 64) hashed so far. We can't compress the
474 * node at the root of the 256 KiB subtree until we know how to finalize it.
475 *
476 * The second problem is solved with "lazy merging". That is, when we're about
477 * to add a CV to the stack, we don't merge it with anything first, as the
478 * reference impl does. Instead we do merges using the *previous* CV that was
479 * added, which is sitting on top of the stack, and we put the new CV
480 * (unmerged) on top of the stack afterwards. This guarantees that we never
481 * merge the root node until finalize().
482 *
483 * Solving the first problem requires an additional tool,
484 * compress_subtree_to_parent_node(). That function always returns the top
485 * *two* chaining values of the subtree it's compressing. We then do lazy
486 * merging with each of them separately, so that the second CV will always
487 * remain unmerged. (That also helps us support extendable output when we're
488 * hashing an input all-at-once.)
489 */
hasher_push_cv(BLAKE3_CTX * ctx,uint8_t new_cv[BLAKE3_OUT_LEN],uint64_t chunk_counter)490 static void hasher_push_cv(BLAKE3_CTX *ctx, uint8_t new_cv[BLAKE3_OUT_LEN],
491 uint64_t chunk_counter)
492 {
493 hasher_merge_cv_stack(ctx, chunk_counter);
494 memcpy(&ctx->cv_stack[ctx->cv_stack_len * BLAKE3_OUT_LEN], new_cv,
495 BLAKE3_OUT_LEN);
496 ctx->cv_stack_len += 1;
497 }
498
499 void
Blake3_Init(BLAKE3_CTX * ctx)500 Blake3_Init(BLAKE3_CTX *ctx)
501 {
502 hasher_init_base(ctx, BLAKE3_IV, 0);
503 }
504
505 void
Blake3_InitKeyed(BLAKE3_CTX * ctx,const uint8_t key[BLAKE3_KEY_LEN])506 Blake3_InitKeyed(BLAKE3_CTX *ctx, const uint8_t key[BLAKE3_KEY_LEN])
507 {
508 uint32_t key_words[8];
509 load_key_words(key, key_words);
510 hasher_init_base(ctx, key_words, KEYED_HASH);
511 }
512
513 static void
Blake3_Update2(BLAKE3_CTX * ctx,const void * input,size_t input_len)514 Blake3_Update2(BLAKE3_CTX *ctx, const void *input, size_t input_len)
515 {
516 /*
517 * Explicitly checking for zero avoids causing UB by passing a null
518 * pointer to memcpy. This comes up in practice with things like:
519 * std::vector<uint8_t> v;
520 * blake3_hasher_update(&hasher, v.data(), v.size());
521 */
522 if (input_len == 0) {
523 return;
524 }
525
526 const uint8_t *input_bytes = (const uint8_t *)input;
527
528 /*
529 * If we have some partial chunk bytes in the internal chunk_state, we
530 * need to finish that chunk first.
531 */
532 if (chunk_state_len(&ctx->chunk) > 0) {
533 size_t take = BLAKE3_CHUNK_LEN - chunk_state_len(&ctx->chunk);
534 if (take > input_len) {
535 take = input_len;
536 }
537 chunk_state_update(ctx->ops, &ctx->chunk, input_bytes, take);
538 input_bytes += take;
539 input_len -= take;
540 /*
541 * If we've filled the current chunk and there's more coming,
542 * finalize this chunk and proceed. In this case we know it's
543 * not the root.
544 */
545 if (input_len > 0) {
546 output_t output = chunk_state_output(&ctx->chunk);
547 uint8_t chunk_cv[32];
548 output_chaining_value(ctx->ops, &output, chunk_cv);
549 hasher_push_cv(ctx, chunk_cv, ctx->chunk.chunk_counter);
550 chunk_state_reset(&ctx->chunk, ctx->key,
551 ctx->chunk.chunk_counter + 1);
552 } else {
553 return;
554 }
555 }
556
557 /*
558 * Now the chunk_state is clear, and we have more input. If there's
559 * more than a single chunk (so, definitely not the root chunk), hash
560 * the largest whole subtree we can, with the full benefits of SIMD
561 * (and maybe in the future, multi-threading) parallelism. Two
562 * restrictions:
563 * - The subtree has to be a power-of-2 number of chunks. Only
564 * subtrees along the right edge can be incomplete, and we don't know
565 * where the right edge is going to be until we get to finalize().
566 * - The subtree must evenly divide the total number of chunks up
567 * until this point (if total is not 0). If the current incomplete
568 * subtree is only waiting for 1 more chunk, we can't hash a subtree
569 * of 4 chunks. We have to complete the current subtree first.
570 * Because we might need to break up the input to form powers of 2, or
571 * to evenly divide what we already have, this part runs in a loop.
572 */
573 while (input_len > BLAKE3_CHUNK_LEN) {
574 size_t subtree_len = round_down_to_power_of_2(input_len);
575 uint64_t count_so_far =
576 ctx->chunk.chunk_counter * BLAKE3_CHUNK_LEN;
577 /*
578 * Shrink the subtree_len until it evenly divides the count so
579 * far. We know that subtree_len itself is a power of 2, so we
580 * can use a bitmasking trick instead of an actual remainder
581 * operation. (Note that if the caller consistently passes
582 * power-of-2 inputs of the same size, as is hopefully
583 * typical, this loop condition will always fail, and
584 * subtree_len will always be the full length of the input.)
585 *
586 * An aside: We don't have to shrink subtree_len quite this
587 * much. For example, if count_so_far is 1, we could pass 2
588 * chunks to compress_subtree_to_parent_node. Since we'll get
589 * 2 CVs back, we'll still get the right answer in the end,
590 * and we might get to use 2-way SIMD parallelism. The problem
591 * with this optimization, is that it gets us stuck always
592 * hashing 2 chunks. The total number of chunks will remain
593 * odd, and we'll never graduate to higher degrees of
594 * parallelism. See
595 * https://github.com/BLAKE3-team/BLAKE3/issues/69.
596 */
597 while ((((uint64_t)(subtree_len - 1)) & count_so_far) != 0) {
598 subtree_len /= 2;
599 }
600 /*
601 * The shrunken subtree_len might now be 1 chunk long. If so,
602 * hash that one chunk by itself. Otherwise, compress the
603 * subtree into a pair of CVs.
604 */
605 uint64_t subtree_chunks = subtree_len / BLAKE3_CHUNK_LEN;
606 if (subtree_len <= BLAKE3_CHUNK_LEN) {
607 blake3_chunk_state_t chunk_state;
608 chunk_state_init(&chunk_state, ctx->key,
609 ctx->chunk.flags);
610 chunk_state.chunk_counter = ctx->chunk.chunk_counter;
611 chunk_state_update(ctx->ops, &chunk_state, input_bytes,
612 subtree_len);
613 output_t output = chunk_state_output(&chunk_state);
614 uint8_t cv[BLAKE3_OUT_LEN];
615 output_chaining_value(ctx->ops, &output, cv);
616 hasher_push_cv(ctx, cv, chunk_state.chunk_counter);
617 } else {
618 /*
619 * This is the high-performance happy path, though
620 * getting here depends on the caller giving us a long
621 * enough input.
622 */
623 uint8_t cv_pair[2 * BLAKE3_OUT_LEN];
624 compress_subtree_to_parent_node(ctx->ops, input_bytes,
625 subtree_len, ctx->key, ctx-> chunk.chunk_counter,
626 ctx->chunk.flags, cv_pair);
627 hasher_push_cv(ctx, cv_pair, ctx->chunk.chunk_counter);
628 hasher_push_cv(ctx, &cv_pair[BLAKE3_OUT_LEN],
629 ctx->chunk.chunk_counter + (subtree_chunks / 2));
630 }
631 ctx->chunk.chunk_counter += subtree_chunks;
632 input_bytes += subtree_len;
633 input_len -= subtree_len;
634 }
635
636 /*
637 * If there's any remaining input less than a full chunk, add it to
638 * the chunk state. In that case, also do a final merge loop to make
639 * sure the subtree stack doesn't contain any unmerged pairs. The
640 * remaining input means we know these merges are non-root. This merge
641 * loop isn't strictly necessary here, because hasher_push_chunk_cv
642 * already does its own merge loop, but it simplifies
643 * blake3_hasher_finalize below.
644 */
645 if (input_len > 0) {
646 chunk_state_update(ctx->ops, &ctx->chunk, input_bytes,
647 input_len);
648 hasher_merge_cv_stack(ctx, ctx->chunk.chunk_counter);
649 }
650 }
651
652 void
Blake3_Update(BLAKE3_CTX * ctx,const void * input,size_t todo)653 Blake3_Update(BLAKE3_CTX *ctx, const void *input, size_t todo)
654 {
655 size_t done = 0;
656 const uint8_t *data = input;
657 const size_t block_max = 1024 * 64;
658
659 /* max feed buffer to leave the stack size small */
660 while (todo != 0) {
661 size_t block = (todo >= block_max) ? block_max : todo;
662 Blake3_Update2(ctx, data + done, block);
663 done += block;
664 todo -= block;
665 }
666 }
667
668 void
Blake3_Final(const BLAKE3_CTX * ctx,uint8_t * out)669 Blake3_Final(const BLAKE3_CTX *ctx, uint8_t *out)
670 {
671 Blake3_FinalSeek(ctx, 0, out, BLAKE3_OUT_LEN);
672 }
673
674 void
Blake3_FinalSeek(const BLAKE3_CTX * ctx,uint64_t seek,uint8_t * out,size_t out_len)675 Blake3_FinalSeek(const BLAKE3_CTX *ctx, uint64_t seek, uint8_t *out,
676 size_t out_len)
677 {
678 /*
679 * Explicitly checking for zero avoids causing UB by passing a null
680 * pointer to memcpy. This comes up in practice with things like:
681 * std::vector<uint8_t> v;
682 * blake3_hasher_finalize(&hasher, v.data(), v.size());
683 */
684 if (out_len == 0) {
685 return;
686 }
687 /* If the subtree stack is empty, then the current chunk is the root. */
688 if (ctx->cv_stack_len == 0) {
689 output_t output = chunk_state_output(&ctx->chunk);
690 output_root_bytes(ctx->ops, &output, seek, out, out_len);
691 return;
692 }
693 /*
694 * If there are any bytes in the chunk state, finalize that chunk and
695 * do a roll-up merge between that chunk hash and every subtree in the
696 * stack. In this case, the extra merge loop at the end of
697 * blake3_hasher_update guarantees that none of the subtrees in the
698 * stack need to be merged with each other first. Otherwise, if there
699 * are no bytes in the chunk state, then the top of the stack is a
700 * chunk hash, and we start the merge from that.
701 */
702 output_t output;
703 size_t cvs_remaining;
704 if (chunk_state_len(&ctx->chunk) > 0) {
705 cvs_remaining = ctx->cv_stack_len;
706 output = chunk_state_output(&ctx->chunk);
707 } else {
708 /* There are always at least 2 CVs in the stack in this case. */
709 cvs_remaining = ctx->cv_stack_len - 2;
710 output = parent_output(&ctx->cv_stack[cvs_remaining * 32],
711 ctx->key, ctx->chunk.flags);
712 }
713 while (cvs_remaining > 0) {
714 cvs_remaining -= 1;
715 uint8_t parent_block[BLAKE3_BLOCK_LEN];
716 memcpy(parent_block, &ctx->cv_stack[cvs_remaining * 32], 32);
717 output_chaining_value(ctx->ops, &output, &parent_block[32]);
718 output = parent_output(parent_block, ctx->key,
719 ctx->chunk.flags);
720 }
721 output_root_bytes(ctx->ops, &output, seek, out, out_len);
722 }
723