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