digest-blake3 0.0.1

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