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