Debian Codegraph @

components/kascrypt/Hashes/dcblake3.pp

raw
1 {
2 BLAKE3 - cryptographic hash function.
3
4 The C code is copyright Samuel Neves and Jack O'Connor, 2019-2020.
5 The assembly code is copyright Samuel Neves, 2019-2020.
6 The Pascal translation by Alexander Koblov, 2020.
7
8 This work is released into the public domain with CC0 1.0.
9 Alternatively, it is licensed under the Apache License 2.0.
10 }
11
12 unit DCblake3;
13
14 {$mode objfpc}{$H+}
15 {$inline on}{$Q-}
16 {$macro on}{$R-}
17
18 interface
19
20 uses
21 Classes, SysUtils, CTypes;
22
23 const
24 BLAKE3_KEY_LEN = 32;
25 BLAKE3_OUT_LEN = 32;
26 BLAKE3_BLOCK_LEN = 64;
27 BLAKE3_CHUNK_LEN = 1024;
28 BLAKE3_MAX_DEPTH = 54;
29 BLAKE3_MAX_SIMD_DEGREE = 16;
30
31 {$if defined(CPUX86_64)}
32 MAX_SIMD_DEGREE = 16;
33 {$else}
34 MAX_SIMD_DEGREE = 1;
35 {$endif}
36
37 {$if (MAX_SIMD_DEGREE > 2)}
38 MAX_SIMD_DEGREE_OR_2 = MAX_SIMD_DEGREE;
39 {$else}
40 MAX_SIMD_DEGREE_OR_2 = 2;
41 {$endif}
42
43 const BLAKE3_IV: array[0..7] of cuint32 = (
44 $6A09E667, $BB67AE85, $3C6EF372, $A54FF53A,
45 $510E527F, $9B05688C, $1F83D9AB, $5BE0CD19
46 );
47
48 const MSG_SCHEDULE: array[0..6] of array[0..15] of cuint8 = (
49 (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15),
50 (2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8),
51 (3, 4, 10, 12, 13, 2, 7, 14, 6, 5, 9, 0, 11, 15, 8, 1),
52 (10, 7, 12, 9, 14, 3, 13, 15, 4, 0, 11, 2, 5, 8, 1, 6),
53 (12, 13, 9, 11, 15, 10, 14, 8, 7, 2, 5, 3, 0, 1, 6, 4),
54 (9, 14, 11, 5, 8, 12, 15, 1, 13, 3, 0, 10, 2, 6, 4, 7),
55 (11, 15, 5, 0, 1, 9, 8, 6, 14, 10, 2, 12, 3, 4, 7, 13)
56 );
57
58 type
59 ppcuint8 = ^pcuint8;
60
61 Tblake_cv = array[0..7] of cuint32;
62
63 Pblake3_chunk_state = ^blake3_chunk_state;
64 blake3_chunk_state = record
65 cv: array[0..7] of cuint32;
66 chunk_counter: cuint64;
67 buf: array[0..Pred(BLAKE3_BLOCK_LEN)] of cuint8;
68 buf_len: cuint8;
69 blocks_compressed: cuint8;
70 flags: cuint8;
71 end;
72
73 Pblake3_hasher = ^blake3_hasher;
74 blake3_hasher = record
75 key: array[0..7] of cuint32;
76 chunk: blake3_chunk_state;
77 cv_stack_len: cuint8;
78 cv_stack: array[0..Pred((BLAKE3_MAX_DEPTH + 1) * BLAKE3_OUT_LEN)] of cuint8;
79 end;
80
81 procedure blake3_hasher_init(self: Pblake3_hasher);
82 procedure blake3_hasher_update(self: Pblake3_hasher; const input: Pointer; input_len: csize_t);
83 procedure blake3_hasher_finalize(const self: Pblake3_hasher; out_: pcuint8; out_len: csize_t);
84
85 implementation
86
87 {$IF DEFINED(CPUX86_64)}
88 uses
89 CPU;
90 {$ENDIF}
91
92 type
93 blake3_flags = (
94 CHUNK_START = 1 shl 0,
95 CHUNK_END = 1 shl 1,
96 PARENT = 1 shl 2,
97 ROOT = 1 shl 3,
98 KEYED_HASH = 1 shl 4,
99 DERIVE_KEY_CONTEXT = 1 shl 5,
100 DERIVE_KEY_MATERIAL = 1 shl 6
101 );
102
103 Poutput_t = ^output_t;
104 output_t = record
105 input_cv: array[0..7] of cuint32;
106 counter: cuint64;
107 block: array[0..Pred(BLAKE3_BLOCK_LEN)] of cuint8;
108 block_len: cuint8;
109 flags: cuint8;
110 end;
111
112 function load32( const src: Pointer ): cuint32; inline;
113 begin
114 Result := NtoLE(pcuint32(src)^);
115 end;
116
117 procedure store32( dst: pointer; w: cuint32 ); inline;
118 begin
119 pcuint32(dst)^ := LEtoN(w);
120 end;
121
122 procedure store_cv_words(bytes_out: pcuint8; cv_words: pcuint32); inline;
123 begin
124 store32(@bytes_out[0 * 4], cv_words[0]);
125 store32(@bytes_out[1 * 4], cv_words[1]);
126 store32(@bytes_out[2 * 4], cv_words[2]);
127 store32(@bytes_out[3 * 4], cv_words[3]);
128 store32(@bytes_out[4 * 4], cv_words[4]);
129 store32(@bytes_out[5 * 4], cv_words[5]);
130 store32(@bytes_out[6 * 4], cv_words[6]);
131 store32(@bytes_out[7 * 4], cv_words[7]);
132 end;
133
134 function round_down_to_power_of_2(x: cuint64): cuint64; inline;
135 begin
136 Result := cuint64(1) shl BsrQWord(x or 1);
137 end;
138
139 procedure chunk_state_init(self: Pblake3_chunk_state; const key: pcuint32;
140 flags: cuint8); inline;
141 begin
142 Move(key^, self^.cv[0], BLAKE3_KEY_LEN);
143 self^.chunk_counter := 0;
144 FillChar(self^.buf[0], BLAKE3_BLOCK_LEN, 0);
145 self^.buf_len := 0;
146 self^.blocks_compressed := 0;
147 self^.flags := flags;
148 end;
149
150 procedure chunk_state_reset(self: Pblake3_chunk_state; const key: pcuint32;
151 chunk_counter: cuint64); inline;
152 begin
153 Move(key^, self^.cv[0], BLAKE3_KEY_LEN);
154 self^.chunk_counter := chunk_counter;
155 self^.blocks_compressed := 0;
156 FillChar(self^.buf, BLAKE3_BLOCK_LEN, 0);
157 self^.buf_len := 0;
158 end;
159
160 function chunk_state_len(const self: Pblake3_chunk_state): csize_t; inline;
161 begin
162 Result := (BLAKE3_BLOCK_LEN * csize_t(self^.blocks_compressed)) + (csize_t(self^.buf_len));
163 end;
164
165 function chunk_state_fill_buf(self: Pblake3_chunk_state;
166 const input: pcuint8; input_len: csize_t): csize_t; inline;
167 var
168 dest: pcuint8;
169 begin
170 Result := BLAKE3_BLOCK_LEN - (csize_t(self^.buf_len));
171 if (Result > input_len) then begin
172 Result := input_len;
173 end;
174 dest := PByte(self^.buf) + (csize_t(self^.buf_len));
175 Move(input^, dest^, Result);
176 self^.buf_len += cuint8(Result);
177 end;
178
179 function chunk_state_maybe_start_flag(const self: Pblake3_chunk_state): cuint8; inline;
180 begin
181 if (self^.blocks_compressed = 0) then
182 Result := cuint8(CHUNK_START)
183 else begin
184 Result := 0;
185 end;
186 end;
187
188 function make_output(const input_cv: Tblake_cv; const block: pcuint8;
189 block_len: cuint8; counter: cuint64; flags: cuint8): output_t; inline;
190 begin
191 Move(input_cv[0], Result.input_cv[0], 32);
192 Move(block^, Result.block[0], BLAKE3_BLOCK_LEN);
193 Result.block_len := block_len;
194 Result.counter := counter;
195 Result.flags := flags;
196 end;
197
198 {$IF DEFINED(CPUX86_64)}
199 {$include blake3_sse2.inc}
200 {$include blake3_sse41.inc}
201 {$include blake3_avx2.inc}
202 {$ELSE}
203 {$include blake3_pas.inc}
204 {$ENDIF}
205
206 var
207 blake3_simd_degree: csize_t; // The dynamically detected SIMD degree of the current platform
208
209 blake3_compress_in_place: procedure(cv: pcuint32;
210 const block: pcuint8;
211 block_len: cuint8; counter: cuint64;
212 flags: cuint8);
213
214 blake3_compress_xof: procedure(const cv: pcuint32;
215 const block: pcuint8;
216 block_len: cuint8; counter: cuint64;
217 flags: cuint8; out_: pcuint8);
218
219 blake3_hash_many: procedure(inputs: ppcuint8; num_inputs: csize_t;
220 blocks: csize_t; const key: pcuint32;
221 counter: cuint64; increment_counter: boolean32;
222 flags: cuint8; flags_start: cuint8;
223 flags_end: cuint8; out_: pcuint8);
224
225 procedure output_chaining_value(const self: Poutput_t; cv: pcuint8); inline;
226 var
227 cv_words: Tblake_cv;
228 begin
229 Move(self^.input_cv[0], cv_words[0], 32);
230 blake3_compress_in_place(cv_words, self^.block, self^.block_len,
231 self^.counter, self^.flags);
232 store_cv_words(cv, cv_words);
233 end;
234
235 procedure output_root_bytes(const self: Poutput_t; seek: cuint64; out_: pcuint8;
236 out_len: csize_t); inline;
237 var
238 memcpy_len: csize_t;
239 available_bytes: csize_t;
240 offset_within_block: csize_t;
241 output_block_counter: cuint64;
242 wide_buf: array[0..63] of cuint8;
243 begin
244 output_block_counter := seek div 64;
245 offset_within_block := seek mod 64;
246 while (out_len > 0) do
247 begin
248 blake3_compress_xof(self^.input_cv, self^.block, self^.block_len,
249 output_block_counter, self^.flags or cuint8(ROOT), wide_buf);
250 available_bytes := 64 - offset_within_block;
251
252 if (out_len > available_bytes) then
253 memcpy_len := available_bytes
254 else begin
255 memcpy_len := out_len;
256 end;
257 Move(wide_buf[offset_within_block], out_^, memcpy_len);
258 out_ += memcpy_len;
259 out_len -= memcpy_len;
260 output_block_counter += 1;
261 offset_within_block := 0;
262 end;
263 end;
264
265 procedure chunk_state_update(self: Pblake3_chunk_state; input: pcuint8;
266 input_len: csize_t); inline;
267 var
268 take: csize_t;
269 begin
270 if (self^.buf_len > 0) then
271 begin
272 take := chunk_state_fill_buf(self, input, input_len);
273 input += take;
274 input_len -= take;
275 if (input_len > 0) then
276 begin
277 blake3_compress_in_place(
278 self^.cv, self^.buf, BLAKE3_BLOCK_LEN, self^.chunk_counter,
279 self^.flags or chunk_state_maybe_start_flag(self));
280 self^.blocks_compressed += 1;
281 self^.buf_len := 0;
282 FillChar(self^.buf[0], BLAKE3_BLOCK_LEN, 0);
283 end;
284 end;
285
286 while (input_len > BLAKE3_BLOCK_LEN) do
287 begin
288 blake3_compress_in_place(self^.cv, input, BLAKE3_BLOCK_LEN,
289 self^.chunk_counter,
290 self^.flags or chunk_state_maybe_start_flag(self));
291 self^.blocks_compressed += 1;
292 input += BLAKE3_BLOCK_LEN;
293 input_len -= BLAKE3_BLOCK_LEN;
294 end;
295
296 take := chunk_state_fill_buf(self, input, input_len);
297 input += take;
298 input_len -= take;
299 end;
300
301 function chunk_state_output(const self: Pblake3_chunk_state): output_t; inline;
302 var
303 block_flags: cuint8;
304 begin
305 block_flags := self^.flags or chunk_state_maybe_start_flag(self) or cuint8(CHUNK_END);
306 Result := make_output(self^.cv, self^.buf, self^.buf_len, self^.chunk_counter, block_flags);
307 end;
308
309 function parent_output(const block: pcuint8; const key: pcuint32; flags: cuint8): output_t; inline;
310 begin
311 Result := make_output(key, block, BLAKE3_BLOCK_LEN, 0, flags or cuint8(PARENT));
312 end;
313
314 function left_len(content_len: csize_t): csize_t; inline;
315 var
316 full_chunks: csize_t;
317 begin
318 full_chunks := (content_len - 1) div BLAKE3_CHUNK_LEN;
319 Result := round_down_to_power_of_2(full_chunks) * BLAKE3_CHUNK_LEN;
320 end;
321
322 function compress_chunks_parallel(const input: pcuint8; input_len: csize_t;
323 const key: pcuint32;
324 chunk_counter: cuint64; flags: cuint8;
325 out_: pcuint8): csize_t; inline;
326 var
327 counter: cuint64;
328 output: output_t;
329 input_position: csize_t = 0;
330 chunks_array_len: csize_t = 0;
331 chunk_state: blake3_chunk_state;
332 chunks_array: array[0..Pred(MAX_SIMD_DEGREE)] of pcuint8;
333 begin
334 assert(0 < input_len);
335 assert(input_len <= MAX_SIMD_DEGREE * BLAKE3_CHUNK_LEN);
336
337 while (input_len - input_position >= BLAKE3_CHUNK_LEN) do
338 begin
339 chunks_array[chunks_array_len] := @input[input_position];
340 input_position += BLAKE3_CHUNK_LEN;
341 chunks_array_len += 1;
342 end;
343
344 blake3_hash_many(chunks_array, chunks_array_len,
345 BLAKE3_CHUNK_LEN div BLAKE3_BLOCK_LEN, key, chunk_counter,
346 true, flags, cuint8(CHUNK_START), cuint8(CHUNK_END), out_);
347
348 // Hash the remaining partial chunk, if there is one. Note that the empty
349 // chunk (meaning the empty message) is a different codepath.
350 if (input_len > input_position) then
351 begin
352 counter := chunk_counter + cuint64(chunks_array_len);
353 chunk_state_init(@chunk_state, key, flags);
354 chunk_state.chunk_counter := counter;
355 chunk_state_update(@chunk_state, @input[input_position],
356 input_len - input_position);
357 output := chunk_state_output(@chunk_state);
358 output_chaining_value(@output, @out_[chunks_array_len * BLAKE3_OUT_LEN]);
359 Result := chunks_array_len + 1;
360 end
361 else begin
362 Result := chunks_array_len;
363 end;
364 end;
365
366 function compress_parents_parallel(const child_chaining_values: pcuint8;
367 num_chaining_values: csize_t;
368 const key: pcuint32; flags: cuint8;
369 out_: pcuint8): csize_t; inline;
370 var
371 parents_array_len: csize_t = 0;
372 parents_array: array[0..Pred(MAX_SIMD_DEGREE_OR_2)] of puint8;
373 begin
374 assert(2 <= num_chaining_values);
375 assert(num_chaining_values <= 2 * MAX_SIMD_DEGREE_OR_2);
376
377
378 while (num_chaining_values - (2 * parents_array_len) >= 2) do
379 begin
380 parents_array[parents_array_len] :=
381 @child_chaining_values[2 * parents_array_len * BLAKE3_OUT_LEN];
382 parents_array_len += 1;
383 end;
384
385 blake3_hash_many(parents_array, parents_array_len, 1, key,
386 0, // Parents always use counter 0.
387 false, flags or cuint8(PARENT),
388 0, // Parents have no start flags.
389 0, // Parents have no end flags.
390 out_);
391
392 // If there's an odd child left over, it becomes an output.
393 if (num_chaining_values > 2 * parents_array_len) then
394 begin
395 Move(child_chaining_values[2 * parents_array_len * BLAKE3_OUT_LEN],
396 out_[parents_array_len * BLAKE3_OUT_LEN], BLAKE3_OUT_LEN);
397 Result := parents_array_len + 1;
398 end
399 else begin
400 Result := parents_array_len;
401 end;
402 end;
403
404 function blake3_compress_subtree_wide(const input: pcuint8;
405 input_len: csize_t;
406 const key: pcuint32;
407 chunk_counter: cuint64;
408 flags: cuint8; out_: pcuint8): csize_t;
409 var
410 left_n: csize_t;
411 degree: csize_t;
412 right_n: csize_t;
413 right_cvs: pcuint8;
414 right_input: pcuint8;
415 left_input_len: csize_t;
416 right_input_len: csize_t;
417 right_chunk_counter: cuint64;
418 num_chaining_values: csize_t;
419 cv_array: array[0..Pred(2 * MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN)] of cuint8;
420 begin
421 // Note that the single chunk case does *not* bump the SIMD degree up to 2
422 // when it is 1. If this implementation adds multi-threading in the future,
423 // this gives us the option of multi-threading even the 2-chunk case, which
424 // can help performance on smaller platforms.
425 if (input_len <= blake3_simd_degree * BLAKE3_CHUNK_LEN) then
426 begin
427 Result:= compress_chunks_parallel(input, input_len, key, chunk_counter, flags, out_);
428 Exit;
429 end;
430
431 // With more than simd_degree chunks, we need to recurse. Start by dividing
432 // the input into left and right subtrees. (Note that this is only optimal
433 // as long as the SIMD degree is a power of 2. If we ever get a SIMD degree
434 // of 3 or something, we'll need a more complicated strategy.)
435 left_input_len := left_len(input_len);
436 right_input_len := input_len - left_input_len;
437 right_input := @input[left_input_len];
438 right_chunk_counter := chunk_counter + cuint64(left_input_len div BLAKE3_CHUNK_LEN);
439
440 // Make space for the child outputs. Here we use MAX_SIMD_DEGREE_OR_2 to
441 // account for the special case of returning 2 outputs when the SIMD degree
442 // is 1.
443 degree := blake3_simd_degree;
444 if (left_input_len > BLAKE3_CHUNK_LEN) and (degree = 1) then
445 begin
446 // The special case: We always use a degree of at least two, to make
447 // sure there are two outputs. Except, as noted above, at the chunk
448 // level, where we allow degree=1. (Note that the 1-chunk-input case is
449 // a different codepath.)
450 degree := 2;
451 end;
452 right_cvs := @cv_array[degree * BLAKE3_OUT_LEN];
453
454 // Recurse! If this implementation adds multi-threading support in the
455 // future, this is where it will go.
456 left_n := blake3_compress_subtree_wide(input, left_input_len, key,
457 chunk_counter, flags, cv_array);
458 right_n := blake3_compress_subtree_wide(
459 right_input, right_input_len, key, right_chunk_counter, flags, right_cvs);
460
461 // The special case again. If simd_degree=1, then we'll have left_n=1 and
462 // right_n=1. Rather than compressing them into a single output, return
463 // them directly, to make sure we always have at least two outputs.
464 if (left_n = 1) then
465 begin
466 Move(cv_array[0], out_^, 2 * BLAKE3_OUT_LEN);
467 Exit(2);
468 end;
469
470 // Otherwise, do one layer of parent node compression.
471 num_chaining_values := left_n + right_n;
472 Result := compress_parents_parallel(cv_array, num_chaining_values, key, flags, out_);
473 end;
474
475 procedure compress_subtree_to_parent_node(
476 const input: pcuint8; input_len: csize_t; const key: pcuint32;
477 chunk_counter: cuint64; flags: cuint8; out_: pcuint8); inline;
478 var
479 num_cvs: csize_t;
480 cv_array: array[0..Pred(MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN)] of cuint8;
481 out_array: array[0..Pred(MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN div 2)] of cuint8;
482 begin
483 assert(input_len > BLAKE3_CHUNK_LEN);
484
485 num_cvs := blake3_compress_subtree_wide(input, input_len, key,
486 chunk_counter, flags, cv_array);
487
488 // If MAX_SIMD_DEGREE is greater than 2 and there's enough input,
489 // compress_subtree_wide() returns more than 2 chaining values. Condense
490 // them into 2 by forming parent nodes repeatedly.
491 while (num_cvs > 2) do
492 begin
493 num_cvs :=
494 compress_parents_parallel(cv_array, num_cvs, key, flags, out_array);
495 Move(out_array[0], cv_array[0], num_cvs * BLAKE3_OUT_LEN);
496 end;
497 Move(cv_array[0], out_^, 2 * BLAKE3_OUT_LEN);
498 end;
499
500 procedure hasher_init_base(self: Pblake3_hasher; const key: pcuint32;
501 flags: cuint8); inline;
502 begin
503 Move(key^, self^.key[0], BLAKE3_KEY_LEN);
504 chunk_state_init(@self^.chunk, key, flags);
505 self^.cv_stack_len := 0;
506 end;
507
508 procedure blake3_hasher_init(self: Pblake3_hasher); inline;
509 begin
510 hasher_init_base(self, BLAKE3_IV, 0);
511 end;
512
513 procedure hasher_merge_cv_stack(self: Pblake3_hasher; total_len: cuint64); inline;
514 var
515 output: output_t;
516 parent_node: pcuint8;
517 post_merge_stack_len: csize_t;
518 begin
519 post_merge_stack_len := csize_t(popcnt(total_len));
520 while (self^.cv_stack_len > post_merge_stack_len) do
521 begin
522 parent_node := @self^.cv_stack[(self^.cv_stack_len - 2) * BLAKE3_OUT_LEN];
523 output := parent_output(parent_node, self^.key, self^.chunk.flags);
524 output_chaining_value(@output, parent_node);
525 self^.cv_stack_len -= 1;
526 end;
527 end;
528
529 procedure hasher_push_cv(self: Pblake3_hasher; new_cv: pcuint8;
530 chunk_counter: cuint64); inline;
531 begin
532 hasher_merge_cv_stack(self, chunk_counter);
533 Move(new_cv^, self^.cv_stack[self^.cv_stack_len * BLAKE3_OUT_LEN], BLAKE3_OUT_LEN);
534 self^.cv_stack_len += 1;
535 end;
536
537 procedure blake3_hasher_update(self: Pblake3_hasher; const input: Pointer;
538 input_len: csize_t);
539 var
540 take: csize_t;
541 output: output_t;
542 subtree_len: csize_t;
543 input_bytes: pcuint8;
544 count_so_far: cuint64;
545 subtree_chunks: cuint64;
546 chunk_state: blake3_chunk_state;
547 chunk_cv: array[0..31] of cuint8;
548 cv: array[0..Pred(BLAKE3_OUT_LEN)] of cuint8;
549 cv_pair: array[0..Pred(2 * BLAKE3_OUT_LEN)] of cuint8;
550 begin
551 // Explicitly checking for zero avoids causing UB by passing a null pointer
552 // to memcpy. This comes up in practice with things like:
553 // std::vector<uint8_t> v;
554 // blake3_hasher_update(&hasher, v.data(), v.size());
555 if (input_len = 0) then Exit;
556
557 input_bytes := pcuint8(input);
558
559 // If we have some partial chunk bytes in the internal chunk_state, we need
560 // to finish that chunk first.
561 if (chunk_state_len(@self^.chunk) > 0) then
562 begin
563 take := BLAKE3_CHUNK_LEN - chunk_state_len(@self^.chunk);
564 if (take > input_len) then begin
565 take := input_len;
566 end;
567 chunk_state_update(@self^.chunk, input_bytes, take);
568 input_bytes += take;
569 input_len -= take;
570 // If we've filled the current chunk and there's more coming, finalize this
571 // chunk and proceed. In this case we know it's not the root.
572 if (input_len > 0) then
573 begin
574 output := chunk_state_output(@self^.chunk);
575 output_chaining_value(@output, chunk_cv);
576 hasher_push_cv(self, chunk_cv, self^.chunk.chunk_counter);
577 chunk_state_reset(@self^.chunk, self^.key, self^.chunk.chunk_counter + 1);
578 end
579 else begin
580 Exit;
581 end;
582 end;
583
584 // Now the chunk_state is clear, and we have more input. If there's more than
585 // a single chunk (so, definitely not the root chunk), hash the largest whole
586 // subtree we can, with the full benefits of SIMD (and maybe in the future,
587 // multi-threading) parallelism. Two restrictions:
588 // - The subtree has to be a power-of-2 number of chunks. Only subtrees along
589 // the right edge can be incomplete, and we don't know where the right edge
590 // is going to be until we get to finalize().
591 // - The subtree must evenly divide the total number of chunks up until this
592 // point (if total is not 0). If the current incomplete subtree is only
593 // waiting for 1 more chunk, we can't hash a subtree of 4 chunks. We have
594 // to complete the current subtree first.
595 // Because we might need to break up the input to form powers of 2, or to
596 // evenly divide what we already have, this part runs in a loop.
597 while (input_len > BLAKE3_CHUNK_LEN) do
598 begin
599 subtree_len := round_down_to_power_of_2(input_len);
600 count_so_far := self^.chunk.chunk_counter * BLAKE3_CHUNK_LEN;
601 // Shrink the subtree_len until it evenly divides the count so far. We know
602 // that subtree_len itself is a power of 2, so we can use a bitmasking
603 // trick instead of an actual remainder operation. (Note that if the caller
604 // consistently passes power-of-2 inputs of the same size, as is hopefully
605 // typical, this loop condition will always fail, and subtree_len will
606 // always be the full length of the input.)
607 //
608 // An aside: We don't have to shrink subtree_len quite this much. For
609 // example, if count_so_far is 1, we could pass 2 chunks to
610 // compress_subtree_to_parent_node. Since we'll get 2 CVs back, we'll still
611 // get the right answer in the end, and we might get to use 2-way SIMD
612 // parallelism. The problem with this optimization, is that it gets us
613 // stuck always hashing 2 chunks. The total number of chunks will remain
614 // odd, and we'll never graduate to higher degrees of parallelism. See
615 // https://github.com/BLAKE3-team/BLAKE3/issues/69.
616 while (((cuint64(subtree_len - 1)) and count_so_far) <> 0) do
617 begin
618 subtree_len := subtree_len div 2;
619 end;
620 // The shrunken subtree_len might now be 1 chunk long. If so, hash that one
621 // chunk by itself. Otherwise, compress the subtree into a pair of CVs.
622 subtree_chunks := subtree_len div BLAKE3_CHUNK_LEN;
623 if (subtree_len <= BLAKE3_CHUNK_LEN) then
624 begin
625 chunk_state_init(@chunk_state, self^.key, self^.chunk.flags);
626 chunk_state.chunk_counter := self^.chunk.chunk_counter;
627 chunk_state_update(@chunk_state, input_bytes, subtree_len);
628 output := chunk_state_output(@chunk_state);
629 output_chaining_value(@output, cv);
630 hasher_push_cv(self, cv, chunk_state.chunk_counter);
631 end
632 else begin
633 // This is the high-performance happy path, though getting here depends
634 // on the caller giving us a long enough input.
635 compress_subtree_to_parent_node(input_bytes, subtree_len, self^.key,
636 self^.chunk.chunk_counter,
637 self^.chunk.flags, cv_pair);
638 hasher_push_cv(self, cv_pair, self^.chunk.chunk_counter);
639 hasher_push_cv(self, @cv_pair[BLAKE3_OUT_LEN],
640 self^.chunk.chunk_counter + (subtree_chunks div 2));
641 end;
642 self^.chunk.chunk_counter += subtree_chunks;
643 input_bytes += subtree_len;
644 input_len -= subtree_len;
645 end;
646
647 // If there's any remaining input less than a full chunk, add it to the chunk
648 // state. In that case, also do a final merge loop to make sure the subtree
649 // stack doesn't contain any unmerged pairs. The remaining input means we
650 // know these merges are non-root. This merge loop isn't strictly necessary
651 // here, because hasher_push_chunk_cv already does its own merge loop, but it
652 // simplifies blake3_hasher_finalize below.
653 if (input_len > 0) then
654 begin
655 chunk_state_update(@self^.chunk, input_bytes, input_len);
656 hasher_merge_cv_stack(self, self^.chunk.chunk_counter);
657 end;
658 end;
659
660 procedure blake3_hasher_finalize_seek(const self: Pblake3_hasher; seek: cuint64;
661 out_: pcuint8; out_len: csize_t);
662 var
663 output: output_t;
664 cvs_remaining: csize_t;
665 parent_block: array[0..Pred(BLAKE3_BLOCK_LEN)] of cuint8;
666 begin
667 // Explicitly checking for zero avoids causing UB by passing a null pointer
668 // to memcpy. This comes up in practice with things like:
669 // std::vector<uint8_t> v;
670 // blake3_hasher_finalize(&hasher, v.data(), v.size());
671 if (out_len = 0) then Exit;
672
673 // If the subtree stack is empty, then the current chunk is the root.
674 if (self^.cv_stack_len = 0) then
675 begin
676 output := chunk_state_output(@self^.chunk);
677 output_root_bytes(@output, seek, out_, out_len);
678 Exit;
679 end;
680 // If there are any bytes in the chunk state, finalize that chunk and do a
681 // roll-up merge between that chunk hash and every subtree in the stack. In
682 // this case, the extra merge loop at the end of blake3_hasher_update
683 // guarantees that none of the subtrees in the stack need to be merged with
684 // each other first. Otherwise, if there are no bytes in the chunk state,
685 // then the top of the stack is a chunk hash, and we start the merge from
686 // that.
687 if (chunk_state_len(@self^.chunk) > 0) then
688 begin
689 cvs_remaining := self^.cv_stack_len;
690 output := chunk_state_output(@self^.chunk);
691 end
692 else begin
693 // There are always at least 2 CVs in the stack in this case.
694 cvs_remaining := self^.cv_stack_len - 2;
695 output := parent_output(@self^.cv_stack[cvs_remaining * 32], self^.key,
696 self^.chunk.flags);
697 end;
698 while (cvs_remaining > 0) do
699 begin
700 cvs_remaining -= 1;
701 Move(self^.cv_stack[cvs_remaining * 32], parent_block[0], 32);
702 output_chaining_value(@output, @parent_block[32]);
703 output := parent_output(parent_block, self^.key, self^.chunk.flags);
704 end;
705 output_root_bytes(@output, seek, out_, out_len);
706 end;
707
708 procedure blake3_hasher_finalize(const self: Pblake3_hasher; out_: pcuint8; out_len: csize_t);
709 begin
710 blake3_hasher_finalize_seek(self, 0, out_, out_len);
711 end;
712
713 initialization
714 {$IF DEFINED(CPUX86_64)}
715 if AVX2Support then
716 begin
717 blake3_simd_degree:= 8;
718 blake3_compress_in_place:= @blake3_compress_in_place_sse41;
719 blake3_compress_xof:= @blake3_compress_xof_sse41;
720 blake3_hash_many:= @blake3_hash_many_avx2;
721 end
722 else if SSE41Support then
723 begin
724 blake3_simd_degree:= 4;
725 blake3_compress_in_place:= @blake3_compress_in_place_sse41;
726 blake3_compress_xof:= @blake3_compress_xof_sse41;
727 blake3_hash_many:= @blake3_hash_many_sse41;
728 end
729 else begin
730 blake3_simd_degree:= 4;
731 blake3_compress_in_place:= @blake3_compress_in_place_sse2;
732 blake3_compress_xof:= @blake3_compress_xof_sse2;
733 blake3_hash_many:= @blake3_hash_many_sse2;
734 end;
735 {$ELSE}
736 blake3_simd_degree:= 1;
737 blake3_compress_in_place:= @blake3_compress_in_place_portable;
738 blake3_compress_xof:= @blake3_compress_xof_portable;
739 blake3_hash_many:= @blake3_hash_many_portable;
740 {$ENDIF}
741 end.
742