Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
blake3s.cpp
Go to the documentation of this file.
1/*
2 BLAKE3 reference source code package - C implementations
3
4 Intellectual property:
5
6 The Rust code is copyright Jack O'Connor, 2019-2020.
7 The C code is copyright Samuel Neves and Jack O'Connor, 2019-2020.
8 The assembly code is copyright Samuel Neves, 2019-2020.
9
10 This work is released into the public domain with CC0 1.0. Alternatively, it is licensed under the Apache
11 License 2.0.
12
13 - CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0
14 - Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0
15
16 More information about the BLAKE3 hash function can be found at
17 https://github.com/BLAKE3-team/BLAKE3.
18*/
19
20#include <assert.h>
21#include <iostream>
22#include <stdbool.h>
23#include <string.h>
24
25#include "blake3-impl.hpp"
26
27namespace blake3_full {
28
29const char* blake3_version(void)
30{
32}
33
34INLINE void chunk_state_init(blake3_chunk_state* self, const uint32_t key[8], uint8_t flags)
35{
36 for (size_t i = 0; i < 8; ++i) {
37 self->cv[i] = key[i];
38 }
39 self->chunk_counter = 0;
40 for (size_t i = 0; i < BLAKE3_BLOCK_LEN; ++i) {
41 self->buf[i] = 0;
42 }
43 self->buf_len = 0;
44 self->blocks_compressed = 0;
45 self->flags = flags;
46}
47
48INLINE void chunk_state_reset(blake3_chunk_state* self, const uint32_t key[8], uint64_t chunk_counter)
49{
50 for (size_t i = 0; i < 8; ++i) {
51 self->cv[i] = key[i];
52 }
53 self->chunk_counter = chunk_counter;
54 self->blocks_compressed = 0;
55 for (size_t i = 0; i < BLAKE3_BLOCK_LEN; ++i) {
56 self->buf[i] = 0;
57 }
58 self->buf_len = 0;
59}
60
62{
63 return (BLAKE3_BLOCK_LEN * (size_t)self->blocks_compressed) + ((size_t)self->buf_len);
64}
65
66INLINE size_t chunk_state_fill_buf(blake3_chunk_state* self, const uint8_t* input, size_t input_len)
67{
68 size_t take = BLAKE3_BLOCK_LEN - ((size_t)self->buf_len);
69 if (take > input_len) {
70 take = input_len;
71 }
72 uint8_t* dest = self->buf + ((size_t)self->buf_len);
73 for (size_t i = 0; i < take; ++i) {
74 dest[i] = input[i];
75 }
76 self->buf_len = static_cast<uint8_t>(self->buf_len + static_cast<uint8_t>(take));
77 return take;
78}
79
81{
82 if (self->blocks_compressed == 0) {
83 return CHUNK_START;
84 } else {
85 return 0;
86 }
87}
88
89typedef struct output_t__ {
90 uint32_t input_cv[8];
91 uint64_t counter;
93 uint8_t block_len;
94 uint8_t flags;
96
97INLINE output_t make_output(const uint32_t input_cv[8],
98 const uint8_t block[BLAKE3_BLOCK_LEN],
99 uint8_t block_len,
100 uint64_t counter,
101 uint8_t flags)
102{
103 output_t ret;
104 for (size_t i = 0; i < 8; ++i) {
105 ret.input_cv[i] = input_cv[i];
106 }
107 for (size_t i = 0; i < BLAKE3_BLOCK_LEN; ++i) {
108 ret.block[i] = block[i];
109 }
110 ret.block_len = block_len;
111 ret.counter = counter;
112 ret.flags = flags;
113 return ret;
114}
115
116// Chaining values within a given chunk (specifically the compress_in_place
117// interface) are represented as words. This avoids unnecessary bytes<->words
118// conversion overhead in the portable implementation. However, the hash_many
119// interface handles both user input and parent node blocks, so it accepts
120// bytes. For that reason, chaining values in the CV stack are represented as
121// bytes.
122INLINE void output_chaining_value(const output_t* self, uint8_t cv[32])
123{
124 uint32_t cv_words[8];
125 for (size_t i = 0; i < 8; ++i) {
126 cv_words[i] = self->input_cv[i];
127 }
128 blake3_compress_in_place(cv_words, self->block, self->block_len, self->counter, self->flags);
129 store_cv_words(cv, cv_words);
130}
131
132INLINE void output_root_bytes(const output_t* self, uint64_t seek, uint8_t* out, size_t out_len)
133{
134 uint64_t output_block_counter = seek / 64;
135 size_t offset_within_block = seek % 64;
136 uint8_t wide_buf[64];
137 while (out_len > 0) {
139 self->input_cv, self->block, self->block_len, output_block_counter, self->flags | ROOT, wide_buf);
140 size_t available_bytes = 64 - offset_within_block;
141 size_t memcpy_len;
142 if (out_len > available_bytes) {
143 memcpy_len = available_bytes;
144 } else {
145 memcpy_len = out_len;
146 }
147 for (size_t i = 0; i < memcpy_len; ++i) {
148 out[i] = wide_buf[i + offset_within_block];
149 }
150
151 out += memcpy_len;
152 out_len -= memcpy_len;
153 output_block_counter += 1;
154 offset_within_block = 0;
155 }
156}
157
158INLINE void chunk_state_update(blake3_chunk_state* self, const uint8_t* input, size_t input_len)
159{
160 if (self->buf_len > 0) {
161 size_t take = chunk_state_fill_buf(self, input, input_len);
162 input += take;
163 input_len -= take;
164 if (input_len > 0) {
166 self->buf,
168 self->chunk_counter,
169 self->flags | chunk_state_maybe_start_flag(self));
170 self->blocks_compressed = static_cast<uint8_t>(self->blocks_compressed + 1);
171 self->buf_len = 0;
172 for (size_t i = 0; i < BLAKE3_BLOCK_LEN; i++) {
173 self->buf[i] = 0;
174 }
175 }
176 }
177
178 while (input_len > BLAKE3_BLOCK_LEN) {
180 self->cv, input, BLAKE3_BLOCK_LEN, self->chunk_counter, self->flags | chunk_state_maybe_start_flag(self));
181 self->blocks_compressed = static_cast<uint8_t>(self->blocks_compressed + 1);
182 input += BLAKE3_BLOCK_LEN;
183 input_len -= BLAKE3_BLOCK_LEN;
184 }
185
186 size_t take = chunk_state_fill_buf(self, input, input_len);
187 input += take;
188 input_len -= take;
189}
190
192{
193 uint8_t block_flags = self->flags | chunk_state_maybe_start_flag(self) | CHUNK_END;
194 return make_output(self->cv, self->buf, self->buf_len, self->chunk_counter, block_flags);
195}
196
197INLINE output_t parent_output(const uint8_t block[BLAKE3_BLOCK_LEN], const uint32_t key[8], uint8_t flags)
198{
199 return make_output(key, block, BLAKE3_BLOCK_LEN, 0, flags | PARENT);
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.
205INLINE size_t left_len(size_t content_len)
206{
207 // Subtract 1 to reserve at least one byte for the right side. content_len
208 // should always be greater than BLAKE3_CHUNK_LEN.
209 size_t full_chunks = (content_len - 1) / BLAKE3_CHUNK_LEN;
210 return round_down_to_power_of_2(full_chunks) * BLAKE3_CHUNK_LEN;
211}
212
213// Use SIMD parallelism to hash up to MAX_SIMD_DEGREE chunks at the same time
214// on a single thread. Write out the chunk chaining values and return the
215// number of chunks hashed. These chunks are never the root and never empty;
216// those cases use a different codepath.
218 const uint8_t* input, size_t input_len, const uint32_t key[8], uint64_t chunk_counter, uint8_t flags, uint8_t* out)
219{
220#if defined(BLAKE3_TESTING)
221 assert(0 < input_len);
222 assert(input_len <= MAX_SIMD_DEGREE * BLAKE3_CHUNK_LEN);
223#endif
224
225 const uint8_t* chunks_array[MAX_SIMD_DEGREE];
226 size_t input_position = 0;
227 size_t chunks_array_len = 0;
228 while (input_len - input_position >= BLAKE3_CHUNK_LEN) {
229 chunks_array[chunks_array_len] = &input[input_position];
230 input_position += BLAKE3_CHUNK_LEN;
231 chunks_array_len += 1;
232 }
233
234 blake3_hash_many(chunks_array,
235 chunks_array_len,
237 key,
238 chunk_counter,
239 true,
240 flags,
242 CHUNK_END,
243 out);
244
245 // Hash the remaining partial chunk, if there is one. Note that the empty
246 // chunk (meaning the empty message) is a different codepath.
247 if (input_len > input_position) {
248 uint64_t counter = chunk_counter + (uint64_t)chunks_array_len;
249 blake3_chunk_state chunk_state;
250 chunk_state_init(&chunk_state, key, flags);
251 chunk_state.chunk_counter = counter;
252 chunk_state_update(&chunk_state, &input[input_position], input_len - input_position);
253 output_t output = chunk_state_output(&chunk_state);
254 output_chaining_value(&output, &out[chunks_array_len * BLAKE3_OUT_LEN]);
255 return chunks_array_len + 1;
256 } else {
257 return chunks_array_len;
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.
266INLINE size_t compress_parents_parallel(const uint8_t* child_chaining_values,
267 size_t num_chaining_values,
268 const uint32_t key[8],
269 uint8_t flags,
270 uint8_t* out)
271{
272#if defined(BLAKE3_TESTING)
273 assert(2 <= num_chaining_values);
274 assert(num_chaining_values <= 2 * MAX_SIMD_DEGREE_OR_2);
275#endif
276
277 const uint8_t* parents_array[MAX_SIMD_DEGREE_OR_2];
278 size_t parents_array_len = 0;
279 while (num_chaining_values - (2 * parents_array_len) >= 2) {
280 parents_array[parents_array_len] = &child_chaining_values[2 * parents_array_len * BLAKE3_OUT_LEN];
281 parents_array_len += 1;
282 }
283
284 blake3_hash_many(parents_array,
285 parents_array_len,
286 1,
287 key,
288 0, // Parents always use counter 0.
289 false,
290 flags | PARENT,
291 0, // Parents have no start flags.
292 0, // Parents have no end flags.
293 out);
294
295 // If there's an odd child left over, it becomes an output.
296 if (num_chaining_values > 2 * parents_array_len) {
297 for (size_t i = 0; i < BLAKE3_OUT_LEN; i++) {
298 out[parents_array_len * BLAKE3_OUT_LEN + i] =
299 child_chaining_values[2 * parents_array_len * BLAKE3_OUT_LEN + i];
300 }
301
302 return parents_array_len + 1;
303 } else {
304 return parents_array_len;
305 }
306}
307
308// The wide helper function returns (writes out) an array of chaining values
309// and returns the length of that array. The number of chaining values returned
310// is the dyanmically detected SIMD degree, at most MAX_SIMD_DEGREE. Or fewer,
311// if the input is shorter than that many chunks. The reason for maintaining a
312// wide array of chaining values going back up the tree, is to allow the
313// implementation to hash as many parents in parallel as possible.
314//
315// As a special case when the SIMD degree is 1, this function will still return
316// at least 2 outputs. This guarantees that this function doesn't perform the
317// root compression. (If it did, it would use the wrong flags, and also we
318// wouldn't be able to implement exendable ouput.) Note that this function is
319// not used when the whole input is only 1 chunk long; that's a different
320// codepath.
321//
322// Why not just have the caller split the input on the first update(), instead
323// of implementing this special rule? Because we don't want to limit SIMD o
324// multi-threading parallelism for that update().
325static size_t blake3_compress_subtree_wide(
326 const uint8_t* input, size_t input_len, const uint32_t key[8], uint64_t chunk_counter, uint8_t flags, uint8_t* out)
327{
328 // Note that the single chunk case does *not* bump the SIMD degree up to 2
329 // when it is 1. If this implementation adds multi-threading in the future,
330 // this gives us the option of multi-threading even the 2-chunk case, which
331 // can help performance on smaller platforms.
332 if (input_len <= blake3_simd_degree() * BLAKE3_CHUNK_LEN) {
333 return compress_chunks_parallel(input, input_len, key, chunk_counter, flags, out);
334 }
335
336 // With more than simd_degree chunks, we need to recurse. Start by dividing
337 // the input into left and right subtrees. (Note that this is only optimal
338 // as long as the SIMD degree is a power of 2. If we ever get a SIMD degree
339 // of 3 or something, we'll need a more complicated strategy.)
340 size_t left_input_len = left_len(input_len);
341 size_t right_input_len = input_len - left_input_len;
342 const uint8_t* right_input = &input[left_input_len];
343 uint64_t right_chunk_counter = chunk_counter + (uint64_t)(left_input_len / BLAKE3_CHUNK_LEN);
344
345 // Make space for the child outputs. Here we use MAX_SIMD_DEGREE_OR_2 to
346 // account for the special case of returning 2 outputs when the SIMD degree
347 // is 1.
348 uint8_t cv_array[2 * MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN];
349 size_t degree = blake3_simd_degree();
350 if (left_input_len > BLAKE3_CHUNK_LEN && degree == 1) {
351 // The special case: We always use a degree of at least two, to make
352 // sure there are two outputs. Except, as noted above, at the chunk
353 // level, where we allow degree=1. (Note that the 1-chunk-input case is
354 // a different codepath.)
355 degree = 2;
356 }
357 uint8_t* right_cvs = &cv_array[degree * BLAKE3_OUT_LEN];
358
359 // Recurse! If this implementation adds multi-threading support in the
360 // future, this is where it will go.
361 size_t left_n = blake3_compress_subtree_wide(input, left_input_len, key, chunk_counter, flags, cv_array);
362 size_t right_n =
363 blake3_compress_subtree_wide(right_input, right_input_len, key, right_chunk_counter, flags, right_cvs);
364
365 // The special case again. If simd_degree=1, then we'll have left_n=1 and
366 // right_n=1. Rather than compressing them into a single output, return
367 // them directly, to make sure we always have at least two outputs.
368 if (left_n == 1) {
369 for (size_t i = 0; i < 2 * BLAKE3_OUT_LEN; i++) {
370 out[i] = cv_array[i];
371 }
372
373 return 2;
374 }
375
376 // Otherwise, do one layer of parent node compression.
377 size_t num_chaining_values = left_n + right_n;
378 return compress_parents_parallel(cv_array, num_chaining_values, key, flags, out);
379}
380
381// Hash a subtree with compress_subtree_wide(), and then condense the resulting
382// list of chaining values down to a single parent node. Don't compress that
383// last parent node, however. Instead, return its message bytes (the
384// concatenated chaining values of its children). This is necessary when the
385// first call to update() supplies a complete subtree, because the topmost
386// parent node of that subtree could end up being the root. It's also necessary
387// for extended output in the general case.
388//
389// As with compress_subtree_wide(), this function is not used on inputs of 1
390// chunk or less. That's a different codepath.
391INLINE void compress_subtree_to_parent_node(const uint8_t* input,
392 size_t input_len,
393 const uint32_t key[8],
394 uint64_t chunk_counter,
395 uint8_t flags,
396 uint8_t out[2 * BLAKE3_OUT_LEN])
397{
398#if defined(BLAKE3_TESTING)
399 assert(input_len > BLAKE3_CHUNK_LEN);
400#endif
401
402 // We need the size of cv_array to be atleast 4 * 32
403 uint8_t cv_array[MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN * 2];
404 size_t num_cvs = blake3_compress_subtree_wide(input, input_len, key, chunk_counter, flags, cv_array);
405
406 // If MAX_SIMD_DEGREE is greater than 2 and there's enough input,
407 // compress_subtree_wide() returns more than 2 chaining values. Condense
408 // them into 2 by forming parent nodes repeatedly.
409 uint8_t out_array[MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN];
410 while (num_cvs > 2) {
411 num_cvs = compress_parents_parallel(cv_array, num_cvs, key, flags, out_array);
412 for (size_t i = 0; i < num_cvs * BLAKE3_OUT_LEN; i++) {
413 cv_array[i] = out_array[i];
414 }
415 }
416 for (size_t i = 0; i < 2 * BLAKE3_OUT_LEN; i++) {
417 out[i] = cv_array[i];
418 }
419}
420
421INLINE void hasher_init_base(blake3_hasher* self, const uint32_t key[8], uint8_t flags)
422{
423 for (size_t i = 0; i < 8; i++) {
424 self->key[i] = key[i];
425 }
426
427 chunk_state_init(&self->chunk, key, flags);
428 self->cv_stack_len = 0;
429}
430
432{
433 hasher_init_base(self, IV, 0);
434}
435
437{
438 uint32_t key_words[8];
439 load_key_words(key, key_words);
440 hasher_init_base(self, key_words, KEYED_HASH);
441}
442
443void blake3_hasher_init_derive_key_raw(blake3_hasher* self, const void* context, size_t context_len)
444{
445 blake3_hasher context_hasher;
446 hasher_init_base(&context_hasher, IV, DERIVE_KEY_CONTEXT);
447 blake3_hasher_update(&context_hasher, context, context_len);
448 uint8_t context_key[BLAKE3_KEY_LEN];
449 blake3_hasher_finalize(&context_hasher, context_key, BLAKE3_KEY_LEN);
450 uint32_t context_key_words[8];
451 load_key_words(context_key, context_key_words);
452 hasher_init_base(self, context_key_words, DERIVE_KEY_MATERIAL);
453}
454
459
460// As described in hasher_push_cv() below, we do "lazy merging", delaying
461// merges until right before the next CV is about to be added. This is
462// different from the reference implementation. Another difference is that we
463// aren't always merging 1 chunk at a time. Instead, each CV might represent
464// any power-of-two number of chunks, as long as the smaller-above-larger stack
465// order is maintained. Instead of the "count the trailing 0-bits" algorithm
466// described in the spec, we use a "count the total number of 1-bits" variant
467// that doesn't require us to retain the subtree size of the CV on top of the
468// stack. The principle is the same: each CV that should remain in the stack is
469// represented by a 1-bit in the total number of chunks (or bytes) so far.
470INLINE void hasher_merge_cv_stack(blake3_hasher* self, uint64_t total_len)
471{
472 size_t post_merge_stack_len = (size_t)popcnt(total_len);
473 while (self->cv_stack_len > post_merge_stack_len) {
474 uint8_t* parent_node = &self->cv_stack[(self->cv_stack_len - 2) * BLAKE3_OUT_LEN];
475 output_t output = parent_output(parent_node, self->key, self->chunk.flags);
476 output_chaining_value(&output, parent_node);
477 self->cv_stack_len = static_cast<uint8_t>(self->cv_stack_len - 1);
478 }
479}
480
481// In reference_impl.rs, we merge the new CV with existing CVs from the stack
482// before pushing it. We can do that because we know more input is coming, so
483// we know none of the merges are root.
484//
485// This setting is different. We want to feed as much input as possible to
486// compress_subtree_wide(), without setting aside anything for the chunk_state.
487// If the user gives us 64 KiB, we want to parallelize over all 64 KiB at once
488// as a single subtree, if at all possible.
489//
490// This leads to two problems:
491// 1) This 64 KiB input might be the only call that ever gets made to update.
492// In this case, the root node of the 64 KiB subtree would be the root node
493// of the whole tree, and it would need to be ROOT finalized. We can't
494// compress it until we know.
495// 2) This 64 KiB input might complete a larger tree, whose root node is
496// similarly going to be the root of the whole tree. For example, maybe
497// we have 196 KiB (that is, 128 + 64) hashed so far. We can't compress the
498// node at the root of the 256 KiB subtree until we know how to finalize it.
499//
500// The second problem is solved with "lazy merging". That is, when we're about
501// to add a CV to the stack, we don't merge it with anything first, as the
502// reference impl does. Instead we do merges using the *previous* CV that was
503// added, which is sitting on top of the stack, and we put the new CV
504// (unmerged) on top of the stack afterwards. This guarantees that we neve
505// merge the root node until finalize().
506//
507// Solving the first problem requires an additional tool,
508// compress_subtree_to_parent_node(). That function always returns the top
509// *two* chaining values of the subtree it's compressing. We then do lazy
510// merging with each of them separately, so that the second CV will always
511// remain unmerged. (That also helps us support extendable output when we're
512// hashing an input all-at-once.)
513INLINE void hasher_push_cv(blake3_hasher* self, uint8_t new_cv[BLAKE3_OUT_LEN], uint64_t chunk_counter)
514{
515 hasher_merge_cv_stack(self, chunk_counter);
516 for (int i = 0; i < BLAKE3_OUT_LEN; i++) {
517 self->cv_stack[self->cv_stack_len * BLAKE3_OUT_LEN + i] = new_cv[i];
518 }
519
520 self->cv_stack_len = static_cast<uint8_t>(self->cv_stack_len + 1);
521}
522
523void blake3_hasher_update(blake3_hasher* self, const void* input, size_t input_len)
524{
525 // Explicitly checking for zero avoids causing UB by passing a null pointe
526 // to memcpy. This comes up in practice with things like:
527 // std::vector<uint8_t> v;
528 // blake3_hasher_update(&hasher, v.data(), v.size());
529 if (input_len == 0) {
530 return;
531 }
532
533 const uint8_t* input_bytes = (const uint8_t*)input;
534
535 // If we have some partial chunk bytes in the internal chunk_state, we need
536 // to finish that chunk first.
537 if (chunk_state_len(&self->chunk) > 0) {
538 size_t take = BLAKE3_CHUNK_LEN - chunk_state_len(&self->chunk);
539 if (take > input_len) {
540 take = input_len;
541 }
542 chunk_state_update(&self->chunk, input_bytes, take);
543 input_bytes += take;
544 input_len -= take;
545 // If we've filled the current chunk and there's more coming, finalize this
546 // chunk and proceed. In this case we know it's not the root.
547 if (input_len > 0) {
548 output_t output = chunk_state_output(&self->chunk);
549 uint8_t chunk_cv[32];
550 output_chaining_value(&output, chunk_cv);
551 hasher_push_cv(self, chunk_cv, self->chunk.chunk_counter);
552 chunk_state_reset(&self->chunk, self->key, self->chunk.chunk_counter + 1);
553 } else {
554 return;
555 }
556 }
557
558 // Now the chunk_state is clear, and we have more input. If there's more than
559 // a single chunk (so, definitely not the root chunk), hash the largest whole
560 // subtree we can, with the full benefits of SIMD (and maybe in the future,
561 // multi-threading) parallelism. Two restrictions:
562 // - The subtree has to be a power-of-2 number of chunks. Only subtrees along
563 // the right edge can be incomplete, and we don't know where the right edge
564 // is going to be until we get to finalize().
565 // - The subtree must evenly divide the total number of chunks up until this
566 // point (if total is not 0). If the current incomplete subtree is only
567 // waiting for 1 more chunk, we can't hash a subtree of 4 chunks. We have
568 // to complete the current subtree first.
569 // Because we might need to break up the input to form powers of 2, or to
570 // evenly divide what we already have, this part runs in a loop.
571 while (input_len > BLAKE3_CHUNK_LEN) {
572 size_t subtree_len = round_down_to_power_of_2(input_len);
573 uint64_t count_so_far = self->chunk.chunk_counter * BLAKE3_CHUNK_LEN;
574 // Shrink the subtree_len until it evenly divides the count so far. We know
575 // that subtree_len itself is a power of 2, so we can use a bitmasking
576 // trick instead of an actual remainder operation. (Note that if the calle
577 // consistently passes power-of-2 inputs of the same size, as is hopefully
578 // typical, this loop condition will always fail, and subtree_len will
579 // always be the full length of the input.)
580 //
581 // An aside: We don't have to shrink subtree_len quite this much. Fo
582 // example, if count_so_far is 1, we could pass 2 chunks to
583 // compress_subtree_to_parent_node. Since we'll get 2 CVs back, we'll still
584 // get the right answer in the end, and we might get to use 2-way SIMD
585 // parallelism. The problem with this optimization, is that it gets us
586 // stuck always hashing 2 chunks. The total number of chunks will remain
587 // odd, and we'll never graduate to higher degrees of parallelism. See
588 // https://github.com/BLAKE3-team/BLAKE3/issues/69.
589 while ((((uint64_t)(subtree_len - 1)) & count_so_far) != 0) {
590 subtree_len /= 2;
591 }
592 // The shrunken subtree_len might now be 1 chunk long. If so, hash that one
593 // chunk by itself. Otherwise, compress the subtree into a pair of CVs.
594 uint64_t subtree_chunks = subtree_len / BLAKE3_CHUNK_LEN;
595 if (subtree_len <= BLAKE3_CHUNK_LEN) {
596 blake3_chunk_state chunk_state;
597 chunk_state_init(&chunk_state, self->key, self->chunk.flags);
598 chunk_state.chunk_counter = self->chunk.chunk_counter;
599 chunk_state_update(&chunk_state, input_bytes, subtree_len);
600 output_t output = chunk_state_output(&chunk_state);
601 uint8_t cv[BLAKE3_OUT_LEN];
602 output_chaining_value(&output, cv);
603 hasher_push_cv(self, cv, chunk_state.chunk_counter);
604 } else {
605 // This is the high-performance happy path, though getting here depends
606 // on the caller giving us a long enough input.
607 uint8_t cv_pair[2 * BLAKE3_OUT_LEN];
609 input_bytes, subtree_len, self->key, self->chunk.chunk_counter, self->chunk.flags, cv_pair);
610 hasher_push_cv(self, cv_pair, self->chunk.chunk_counter);
611 hasher_push_cv(self, &cv_pair[BLAKE3_OUT_LEN], self->chunk.chunk_counter + (subtree_chunks / 2));
612 }
613 self->chunk.chunk_counter += subtree_chunks;
614 input_bytes += subtree_len;
615 input_len -= subtree_len;
616 }
617
618 // If there's any remaining input less than a full chunk, add it to the chunk
619 // state. In that case, also do a final merge loop to make sure the subtree
620 // stack doesn't contain any unmerged pairs. The remaining input means we
621 // know these merges are non-root. This merge loop isn't strictly necessary
622 // here, because hasher_push_chunk_cv already does its own merge loop, but it
623 // simplifies blake3_hasher_finalize below.
624 if (input_len > 0) {
625 chunk_state_update(&self->chunk, input_bytes, input_len);
627 }
628}
629
630void blake3_hasher_finalize(const blake3_hasher* self, uint8_t* out, size_t out_len)
631{
632 blake3_hasher_finalize_seek(self, 0, out, out_len);
633}
634
635void blake3_hasher_finalize_seek(const blake3_hasher* self, uint64_t seek, uint8_t* out, size_t out_len)
636{
637 // Explicitly checking for zero avoids causing UB by passing a null pointe
638 // to memcpy. This comes up in practice with things like:
639 // std::vector<uint8_t> v;
640 // blake3_hasher_finalize(&hasher, v.data(), v.size());
641 if (out_len == 0) {
642 return;
643 }
644
645 // If the subtree stack is empty, then the current chunk is the root.
646 if (self->cv_stack_len == 0) {
647 output_t output = chunk_state_output(&self->chunk);
648 output_root_bytes(&output, seek, out, out_len);
649 return;
650 }
651 // If there are any bytes in the chunk state, finalize that chunk and do a
652 // roll-up merge between that chunk hash and every subtree in the stack. In
653 // this case, the extra merge loop at the end of blake3_hasher_update
654 // guarantees that none of the subtrees in the stack need to be merged with
655 // each other first. Otherwise, if there are no bytes in the chunk state,
656 // then the top of the stack is a chunk hash, and we start the merge from
657 // that.
658 output_t output;
659 size_t cvs_remaining;
660 if (chunk_state_len(&self->chunk) > 0) {
661 cvs_remaining = self->cv_stack_len;
662 output = chunk_state_output(&self->chunk);
663 } else {
664 // There are always at least 2 CVs in the stack in this case.
665 cvs_remaining = static_cast<size_t>(self->cv_stack_len - 2);
666 output = parent_output(&self->cv_stack[cvs_remaining * 32], self->key, self->chunk.flags);
667 }
668 while (cvs_remaining > 0) {
669 cvs_remaining -= 1;
670 uint8_t parent_block[BLAKE3_BLOCK_LEN];
671 for (size_t i = 0; i < 32; i++) {
672 parent_block[i] = self->cv_stack[cvs_remaining * 32 + i];
673 }
674
675 output_chaining_value(&output, &parent_block[32]);
676 output = parent_output(parent_block, self->key, self->chunk.flags);
677 }
678 output_root_bytes(&output, seek, out, out_len);
679}
680
681void g(uint32_t* state, size_t a, size_t b, size_t c, size_t d, uint32_t x, uint32_t y)
682{
683 state[a] = state[a] + state[b] + x;
684 state[d] = rotr32(state[d] ^ state[a], 16);
685 state[c] = state[c] + state[d];
686 state[b] = rotr32(state[b] ^ state[c], 12);
687 state[a] = state[a] + state[b] + y;
688 state[d] = rotr32(state[d] ^ state[a], 8);
689 state[c] = state[c] + state[d];
690 state[b] = rotr32(state[b] ^ state[c], 7);
691}
692
693void round_fn(uint32_t state[16], const uint32_t* msg, size_t round)
694{
695 // Select the message schedule based on the round.
696 const uint8_t* schedule = MSG_SCHEDULE[round];
697
698 // Mix the columns.
699 g(state, 0, 4, 8, 12, msg[schedule[0]], msg[schedule[1]]);
700 g(state, 1, 5, 9, 13, msg[schedule[2]], msg[schedule[3]]);
701 g(state, 2, 6, 10, 14, msg[schedule[4]], msg[schedule[5]]);
702 g(state, 3, 7, 11, 15, msg[schedule[6]], msg[schedule[7]]);
703
704 // Mix the rows.
705 g(state, 0, 5, 10, 15, msg[schedule[8]], msg[schedule[9]]);
706 g(state, 1, 6, 11, 12, msg[schedule[10]], msg[schedule[11]]);
707 g(state, 2, 7, 8, 13, msg[schedule[12]], msg[schedule[13]]);
708 g(state, 3, 4, 9, 14, msg[schedule[14]], msg[schedule[15]]);
709}
710
711void compress_pre(uint32_t state[16],
712 const uint32_t cv[8],
713 const uint8_t block[BLAKE3_BLOCK_LEN],
714 uint8_t block_len,
715 uint64_t counter,
716 uint8_t flags)
717{
718 uint32_t block_words[16];
719 block_words[0] = load32(block + 4 * 0);
720 block_words[1] = load32(block + 4 * 1);
721 block_words[2] = load32(block + 4 * 2);
722 block_words[3] = load32(block + 4 * 3);
723 block_words[4] = load32(block + 4 * 4);
724 block_words[5] = load32(block + 4 * 5);
725 block_words[6] = load32(block + 4 * 6);
726 block_words[7] = load32(block + 4 * 7);
727 block_words[8] = load32(block + 4 * 8);
728 block_words[9] = load32(block + 4 * 9);
729 block_words[10] = load32(block + 4 * 10);
730 block_words[11] = load32(block + 4 * 11);
731 block_words[12] = load32(block + 4 * 12);
732 block_words[13] = load32(block + 4 * 13);
733 block_words[14] = load32(block + 4 * 14);
734 block_words[15] = load32(block + 4 * 15);
735
736 state[0] = cv[0];
737 state[1] = cv[1];
738 state[2] = cv[2];
739 state[3] = cv[3];
740 state[4] = cv[4];
741 state[5] = cv[5];
742 state[6] = cv[6];
743 state[7] = cv[7];
744 state[8] = IV[0];
745 state[9] = IV[1];
746 state[10] = IV[2];
747 state[11] = IV[3];
748 state[12] = counter_low(counter);
749 state[13] = counter_high(counter);
750 state[14] = (uint32_t)block_len;
751 state[15] = (uint32_t)flags;
752
753 round_fn(state, &block_words[0], 0);
754 round_fn(state, &block_words[0], 1);
755 round_fn(state, &block_words[0], 2);
756 round_fn(state, &block_words[0], 3);
757 round_fn(state, &block_words[0], 4);
758 round_fn(state, &block_words[0], 5);
759 round_fn(state, &block_words[0], 6);
760}
761
763 uint32_t cv[8], const uint8_t block[BLAKE3_BLOCK_LEN], uint8_t block_len, uint64_t counter, uint8_t flags)
764{
765 uint32_t state[16];
766 compress_pre(state, cv, block, block_len, counter, flags);
767 cv[0] = state[0] ^ state[8];
768 cv[1] = state[1] ^ state[9];
769 cv[2] = state[2] ^ state[10];
770 cv[3] = state[3] ^ state[11];
771 cv[4] = state[4] ^ state[12];
772 cv[5] = state[5] ^ state[13];
773 cv[6] = state[6] ^ state[14];
774 cv[7] = state[7] ^ state[15];
775}
776
777void blake3_compress_xof(const uint32_t cv[8],
778 const uint8_t block[BLAKE3_BLOCK_LEN],
779 uint8_t block_len,
780 uint64_t counter,
781 uint8_t flags,
782 uint8_t out[64])
783{
784 uint32_t state[16];
785 compress_pre(state, cv, block, block_len, counter, flags);
786
787 store32(&out[0 * 4], state[0] ^ state[8]);
788 store32(&out[1 * 4], state[1] ^ state[9]);
789 store32(&out[2 * 4], state[2] ^ state[10]);
790 store32(&out[3 * 4], state[3] ^ state[11]);
791 store32(&out[4 * 4], state[4] ^ state[12]);
792 store32(&out[5 * 4], state[5] ^ state[13]);
793 store32(&out[6 * 4], state[6] ^ state[14]);
794 store32(&out[7 * 4], state[7] ^ state[15]);
795 store32(&out[8 * 4], state[8] ^ cv[0]);
796 store32(&out[9 * 4], state[9] ^ cv[1]);
797 store32(&out[10 * 4], state[10] ^ cv[2]);
798 store32(&out[11 * 4], state[11] ^ cv[3]);
799 store32(&out[12 * 4], state[12] ^ cv[4]);
800 store32(&out[13 * 4], state[13] ^ cv[5]);
801 store32(&out[14 * 4], state[14] ^ cv[6]);
802 store32(&out[15 * 4], state[15] ^ cv[7]);
803}
804
805void blake3s_hash_one(const uint8_t* input,
806 size_t blocks,
807 const uint32_t key[8],
808 uint64_t counter,
809 uint8_t flags,
810 uint8_t flags_start,
811 uint8_t flags_end,
812 uint8_t out[BLAKE3_OUT_LEN])
813{
814 uint32_t cv[8];
815 for (size_t i = 0; i < 8; i++) {
816 cv[i] = key[i];
817 }
818
819 uint8_t block_flags = flags | flags_start;
820 while (blocks > 0) {
821 if (blocks == 1) {
822 block_flags |= flags_end;
823 }
824 blake3_compress_in_place(cv, input, BLAKE3_BLOCK_LEN, counter, block_flags);
825 input = &input[BLAKE3_BLOCK_LEN];
826 blocks -= 1;
827 block_flags = flags;
828 }
829 store_cv_words(out, cv);
830}
831
832void blake3_hash_many(const uint8_t* const* inputs,
833 size_t num_inputs,
834 size_t blocks,
835 const uint32_t key[8],
836 uint64_t counter,
837 bool increment_counter,
838 uint8_t flags,
839 uint8_t flags_start,
840 uint8_t flags_end,
841 uint8_t* out)
842{
843 while (num_inputs > 0) {
844 blake3s_hash_one(inputs[0], blocks, key, counter, flags, flags_start, flags_end, out);
845 if (increment_counter) {
846 counter += 1;
847 }
848 inputs += 1;
849 num_inputs -= 1;
850 out = &out[BLAKE3_OUT_LEN];
851 }
852}
853
854std::vector<uint8_t> blake3s(std::vector<uint8_t> const& input,
855 const mode mode_id,
856 const uint8_t key[BLAKE3_KEY_LEN],
857 const char* context)
858{
859 // Initialize the hasher.
860 blake3_hasher hasher;
861 blake3_hasher_init(&hasher);
862 switch (mode_id) {
863 case HASH_MODE:
864 blake3_hasher_init(&hasher);
865 break;
866 case KEYED_HASH_MODE:
868 break;
869 case DERIVE_KEY_MODE:
871 break;
872 default:
873 abort();
874 }
875
876 blake3_hasher_update(&hasher, (const uint8_t*)input.data(), input.size());
877
878 std::vector<uint8_t> output(BLAKE3_OUT_LEN);
879 blake3_hasher_finalize(&hasher, &output[0], BLAKE3_OUT_LEN);
880 return output;
881}
882
883} // namespace blake3_full
#define INLINE
#define MAX_SIMD_DEGREE
#define MAX_SIMD_DEGREE_OR_2
StrictMock< MockContext > context
FF a
FF b
#define BLAKE3_VERSION_STRING
Definition blake3s.hpp:27
AvmProvingInputs inputs
INLINE void chunk_state_reset(blake3_chunk_state *self, const uint32_t key[8], uint64_t chunk_counter)
Definition blake3s.cpp:48
void blake3_hasher_init_derive_key_raw(blake3_hasher *self, const void *context, size_t context_len)
Definition blake3s.cpp:443
@ DERIVE_KEY_MATERIAL
Definition blake3s.hpp:37
@ DERIVE_KEY_CONTEXT
Definition blake3s.hpp:36
struct blake3_full::output_t__ output_t
INLINE void store32(void *dst, uint32_t w)
INLINE output_t parent_output(const uint8_t block[BLAKE3_BLOCK_LEN], const uint32_t key[8], uint8_t flags)
Definition blake3s.cpp:197
void blake3_hasher_init_keyed(blake3_hasher *self, const uint8_t key[BLAKE3_KEY_LEN])
Definition blake3s.cpp:436
INLINE unsigned int popcnt(uint64_t x)
@ DERIVE_KEY_MODE
Definition blake3s.hpp:50
@ KEYED_HASH_MODE
Definition blake3s.hpp:50
void blake3_hasher_finalize_seek(const blake3_hasher *self, uint64_t seek, uint8_t *out, size_t out_len)
Definition blake3s.cpp:635
size_t blake3_simd_degree(void)
const char * blake3_version(void)
Definition blake3s.cpp:29
void blake3_hasher_init_derive_key(blake3_hasher *self, const char *context)
Definition blake3s.cpp:455
void blake3_hasher_update(blake3_hasher *self, const void *input, size_t input_len)
Definition blake3s.cpp:523
INLINE output_t chunk_state_output(const blake3_chunk_state *self)
Definition blake3s.cpp:191
INLINE size_t chunk_state_fill_buf(blake3_chunk_state *self, const uint8_t *input, size_t input_len)
Definition blake3s.cpp:66
INLINE void hasher_merge_cv_stack(blake3_hasher *self, uint64_t total_len)
Definition blake3s.cpp:470
@ BLAKE3_CHUNK_LEN
Definition blake3s.hpp:45
@ BLAKE3_BLOCK_LEN
Definition blake3s.hpp:44
INLINE void hasher_push_cv(blake3_hasher *self, uint8_t new_cv[BLAKE3_OUT_LEN], uint64_t chunk_counter)
Definition blake3s.cpp:513
std::vector< uint8_t > blake3s(std::vector< uint8_t > const &input, const mode mode_id, const uint8_t key[BLAKE3_KEY_LEN], const char *context)
Definition blake3s.cpp:854
INLINE uint64_t round_down_to_power_of_2(uint64_t x)
INLINE size_t left_len(size_t content_len)
Definition blake3s.cpp:205
void round_fn(uint32_t state[16], const uint32_t *msg, size_t round)
Definition blake3s.cpp:693
void blake3_compress_xof(const uint32_t cv[8], const uint8_t block[BLAKE3_BLOCK_LEN], uint8_t block_len, uint64_t counter, uint8_t flags, uint8_t out[64])
Definition blake3s.cpp:777
INLINE uint32_t load32(const void *src)
INLINE output_t make_output(const uint32_t input_cv[8], const uint8_t block[BLAKE3_BLOCK_LEN], uint8_t block_len, uint64_t counter, uint8_t flags)
Definition blake3s.cpp:97
INLINE void output_root_bytes(const output_t *self, uint64_t seek, uint8_t *out, size_t out_len)
Definition blake3s.cpp:132
INLINE uint8_t chunk_state_maybe_start_flag(const blake3_chunk_state *self)
Definition blake3s.cpp:80
INLINE void store_cv_words(uint8_t bytes_out[32], uint32_t cv_words[8])
INLINE size_t compress_chunks_parallel(const uint8_t *input, size_t input_len, const uint32_t key[8], uint64_t chunk_counter, uint8_t flags, uint8_t *out)
Definition blake3s.cpp:217
INLINE uint32_t counter_high(uint64_t counter)
INLINE void chunk_state_update(blake3_chunk_state *self, const uint8_t *input, size_t input_len)
Definition blake3s.cpp:158
INLINE size_t compress_parents_parallel(const uint8_t *child_chaining_values, size_t num_chaining_values, const uint32_t key[8], uint8_t flags, uint8_t *out)
Definition blake3s.cpp:266
INLINE void output_chaining_value(const output_t *self, uint8_t cv[32])
Definition blake3s.cpp:122
INLINE void compress_subtree_to_parent_node(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])
Definition blake3s.cpp:391
void g(uint32_t *state, size_t a, size_t b, size_t c, size_t d, uint32_t x, uint32_t y)
Definition blake3s.cpp:681
INLINE void hasher_init_base(blake3_hasher *self, const uint32_t key[8], uint8_t flags)
Definition blake3s.cpp:421
void blake3_hasher_finalize(const blake3_hasher *self, uint8_t *out, size_t out_len)
Definition blake3s.cpp:630
void blake3_hasher_init(blake3_hasher *self)
Definition blake3s.cpp:431
INLINE uint32_t counter_low(uint64_t counter)
void blake3s_hash_one(const uint8_t *input, size_t blocks, const uint32_t key[8], uint64_t counter, uint8_t flags, uint8_t flags_start, uint8_t flags_end, uint8_t out[BLAKE3_OUT_LEN])
Definition blake3s.cpp:805
INLINE uint32_t rotr32(uint32_t w, uint32_t c)
INLINE void chunk_state_init(blake3_chunk_state *self, const uint32_t key[8], uint8_t flags)
Definition blake3s.cpp:34
INLINE void load_key_words(const uint8_t key[BLAKE3_KEY_LEN], uint32_t key_words[8])
void blake3_hash_many(const uint8_t *const *inputs, size_t num_inputs, size_t blocks, const uint32_t key[8], uint64_t counter, bool increment_counter, uint8_t flags, uint8_t flags_start, uint8_t flags_end, uint8_t *out)
Definition blake3s.cpp:832
void blake3_compress_in_place(uint32_t cv[8], const uint8_t block[BLAKE3_BLOCK_LEN], uint8_t block_len, uint64_t counter, uint8_t flags)
Definition blake3s.cpp:762
INLINE size_t chunk_state_len(const blake3_chunk_state *self)
Definition blake3s.cpp:61
void compress_pre(uint32_t state[16], const uint32_t cv[8], const uint8_t block[BLAKE3_BLOCK_LEN], uint8_t block_len, uint64_t counter, uint8_t flags)
Definition blake3s.cpp:711
uint8_t buf[BLAKE3_BLOCK_LEN]
Definition blake3s.hpp:67
blake3_chunk_state chunk
Definition blake3s.hpp:75
uint8_t cv_stack[(BLAKE3_MAX_DEPTH+1) *BLAKE3_OUT_LEN]
Definition blake3s.hpp:82
uint8_t block[BLAKE3_BLOCK_LEN]
Definition blake3s.cpp:92