1use super::*;
6use crate::throughput::{Cv, TreeHasher};
7
8#[derive(Clone, Copy, PartialEq, Eq)]
12enum HasherState {
13 Ready,
14 Finishing,
17 Poisoned,
22}
23
24#[cold]
25#[inline(never)]
26fn panic_poisoned() -> ! {
27 panic!("Hasher was poisoned by an earlier panicked update_with call");
28}
29
30struct PoisonOnUnwind<'a>(&'a mut HasherCore, &'a mut HasherState);
31
32impl Drop for PoisonOnUnwind<'_> {
33 #[cold]
34 fn drop(&mut self) {
35 *self.1 = HasherState::Poisoned;
36 self.0.chunk_state.saturate_count();
37 }
38}
39
40pub struct Hasher {
104 core: HasherCore,
105 stage: stage::Stage,
106 state: HasherState,
107}
108
109impl Clone for Hasher {
110 #[inline]
111 fn clone(&self) -> Self {
112 Self { core: self.core.clone(), stage: self.stage.clone(), state: self.state }
113 }
114
115 #[inline]
116 fn clone_from(&mut self, source: &Self) {
117 self.core.clone_from(&source.core);
118 self.stage.clone_from(&source.stage);
119 self.state = source.state;
120 }
121}
122
123pub(crate) const STAGE_LEN: usize = 16 * CHUNK_LEN;
126
127mod stage {
131 use crate::{BLOCK_LEN, STAGE_LEN};
132
133 pub(crate) struct Stage {
134 len: usize,
135 buf: [core::mem::MaybeUninit<u8>; STAGE_LEN],
136 }
137
138 impl Clone for Stage {
139 #[inline]
140 fn clone(&self) -> Self {
141 Self { len: self.len, buf: self.buf }
142 }
143
144 #[inline]
145 fn clone_from(&mut self, source: &Self) {
146 let prefix = &source.buf[..if source.len == 0 { 0 } else { source.len.max(BLOCK_LEN) }];
150 self.len = source.len;
151 self.buf[..prefix.len()].copy_from_slice(prefix);
152 }
153 }
154
155 impl Stage {
156 #[inline(always)]
157 pub(crate) fn new() -> Self {
158 Self { len: 0, buf: [core::mem::MaybeUninit::uninit(); STAGE_LEN] }
159 }
160
161 #[inline(always)]
162 pub(crate) fn len(&self) -> usize {
163 self.len
164 }
165
166 #[inline(always)]
167 pub(crate) fn is_empty(&self) -> bool {
168 self.len == 0
169 }
170
171 #[inline(always)]
172 pub(crate) fn clear(&mut self) {
173 self.len = 0;
174 }
175
176 #[inline(always)]
181 pub(crate) fn first_block(&self) -> &[u8; BLOCK_LEN] {
182 static EMPTY: [u8; BLOCK_LEN] = [0; BLOCK_LEN];
183 if self.len == 0 {
184 return &EMPTY;
185 }
186 unsafe { &*(self.buf.as_ptr() as *const [u8; BLOCK_LEN]) }
189 }
190
191 #[inline(always)]
193 pub(crate) fn as_bytes(&self) -> &[u8] {
194 unsafe { core::slice::from_raw_parts(self.buf.as_ptr() as *const u8, self.len) }
196 }
197
198 pub(crate) fn append(&mut self, bytes: &[u8]) {
201 assert!(bytes.len() <= STAGE_LEN - self.len, "staged bytes exceed STAGE_LEN");
202 crate::counted(crate::Counted::Staged);
203 if self.len == 0 {
204 self.buf[bytes.len().min(BLOCK_LEN)..BLOCK_LEN].fill(core::mem::MaybeUninit::new(0));
206 }
207 self.buf[self.len..self.len + bytes.len()].write_copy_of_slice(bytes);
208 self.len += bytes.len();
209 }
210
211 #[cfg(target_arch = "x86_64")]
214 #[inline(always)]
215 pub(crate) fn pad_first_block(&mut self, input: &[u8]) {
216 assert!(self.len == 0 && input.len() <= BLOCK_LEN, "pad_first_block requires empty stage and at most one block");
217 let first: &mut [core::mem::MaybeUninit<u8>; BLOCK_LEN] = (&mut self.buf[..BLOCK_LEN]).try_into().expect("STAGE_LEN >= BLOCK_LEN");
218 crate::chunk_root::pad_block(first, input);
219 self.len = input.len();
220 }
221
222 #[inline(always)]
225 pub(crate) fn take_with(&mut self, f: impl FnOnce(&[u8])) {
226 let len = core::mem::replace(&mut self.len, 0);
227 let bytes = unsafe { core::slice::from_raw_parts(self.buf.as_ptr() as *const u8, len) };
230 f(bytes);
231 }
232
233 #[cfg(test)]
234 pub(crate) fn fill_from_for_test(&mut self, start: usize, byte: u8) {
235 self.buf[start..].fill(core::mem::MaybeUninit::new(byte));
236 }
237
238 #[cfg(test)]
242 pub(crate) unsafe fn byte_for_test(&self, i: usize) -> u8 {
243 unsafe { self.buf[i].assume_init() }
245 }
246 }
247}
248
249pub(crate) struct HasherCore {
252 domain: Domain,
253 chunk_state: ChunkState,
254 cv_stack: CvStack,
260}
261
262impl Clone for HasherCore {
263 fn clone(&self) -> Self {
264 Self { domain: self.domain, chunk_state: self.chunk_state.clone(), cv_stack: self.cv_stack.clone() }
265 }
266
267 fn clone_from(&mut self, source: &Self) {
270 self.domain = source.domain;
271 self.chunk_state.clone_from(&source.chunk_state);
272 self.cv_stack.clone_from(&source.cv_stack);
273 }
274}
275
276#[inline(always)]
279fn check_input_room(count: u64, incoming: usize) {
280 assert!(incoming as u64 <= u64::MAX - count, "BLAKE3 messages contain at most 2^64 - 1 bytes (have {count}, adding {incoming})");
281}
282
283struct HasherHooks<'a> {
288 domain: &'a Domain,
289 chunk_platform: Platform,
290 platform: Platform,
291 pooled: Option<&'a Pool<'a>>,
292}
293
294pub(crate) struct Pool<'a> {
296 pub min_len: usize,
297 pub halves: &'a dyn Fn(&TreeHasher, u32, u64, &[u8]) -> [Cv; 2],
298}
299
300impl hasher::Hooks for HasherHooks<'_> {
301 #[inline(always)]
302 #[allow(unused_variables)]
303 fn subtree_cv(&self, input: &[u8], ahead: usize, counter: u64) -> Option<CVBytes> {
304 #[cfg(target_arch = "aarch64")]
310 if self.pooled.is_none() && matches!(self.platform, Platform::SME2) && sme2::flat_takes(input.len()) {
311 crate::counted(crate::Counted::Flat);
312 return Some(unsafe { sme2::compress_subtree_flat_to_cv(input, ahead, self.domain.key(), counter, self.domain.flags()) });
314 }
315 None
316 }
317
318 #[inline(always)]
319 fn children(&self, input: &[u8], ahead: usize, counter: u64) -> [CVBytes; 2] {
320 if let Some(pool) = self.pooled.filter(|pool| input.len() >= pool.min_len) {
321 let level = crate::throughput::level_of(input.len() as u64);
322 let index = counter >> level;
323 assert!(index << level == counter, "a subtree of {} bytes starts at its own boundary, not chunk {counter}", input.len());
324 let halves = (pool.halves)(&TreeHasher::of_domain(*self.domain), level, index, input);
325 return Cv::halves_bytes(halves, level, index);
326 }
327 if self.pooled.is_some() {
328 let own = platform::Sme2Turn::take(self.chunk_platform, input.len() >= SME2_SIZED_LEN);
331 compress_subtree_to_parent_node(input, ahead, self.domain.key(), counter, self.domain.flags(), own.platform())
332 } else {
333 compress_subtree_to_parent_node(input, ahead, self.domain.key(), counter, self.domain.flags(), self.platform)
334 }
335 }
336
337 #[inline(always)]
341 fn cuts(&self, len: usize) -> bool {
342 self.pooled.is_none() && len >= STAGE_LEN && (4..=hasher::ROW).contains(&self.platform.simd_degree())
343 }
344
345 #[inline(always)]
346 fn cut(&self, input: &[u8], ahead: usize, counter: u64, out: &mut [CVBytes; hasher::ROW]) -> usize {
347 crate::counted(crate::Counted::Row);
348 let kernels = crate::tree::PlatformKernels { key: self.domain.key(), flags: self.domain.flags(), platform: self.platform };
349 crate::tree::wide(&kernels, input, ahead, counter, out)
350 }
351
352 #[inline(always)]
353 fn parents(&self, children: &[CVBytes], out: &mut [CVBytes]) -> usize {
354 compress_parents_parallel(children.as_flattened(), self.domain.key(), self.domain.flags(), self.platform, out.as_flattened_mut())
355 }
356}
357
358type HasherKernels<'a> = hasher::Kernels<'a, HasherHooks<'a>>;
361
362#[inline(always)]
364fn kernels_on<'a>(domain: &'a Domain, chunk_state: &ChunkState, platform: Platform, pooled: Option<&'a Pool<'a>>) -> HasherKernels<'a> {
365 hasher::Kernels {
366 key: domain.key(),
367 flags: domain.flags(),
368 platform: chunk_state.platform(),
369 hooks: HasherHooks { domain, chunk_platform: chunk_state.platform(), platform, pooled },
370 }
371}
372
373impl Hasher {
374 #[inline(always)]
375 pub(crate) fn from_core(core: HasherCore) -> Self {
376 Self { core, stage: stage::Stage::new(), state: HasherState::Ready }
386 }
387
388 #[inline(always)]
391 fn assert_not_poisoned(&self) {
392 if self.state == HasherState::Poisoned {
393 panic_poisoned();
394 }
395 }
396
397 #[inline(always)]
398 fn check_room(&self, incoming: usize) {
399 let count = self.count();
400 if incoming as u64 > u64::MAX - count {
401 self.panic_room(count, incoming);
402 }
403 }
404
405 #[cold]
406 #[inline(never)]
407 fn panic_room(&self, count: u64, incoming: usize) -> ! {
408 self.assert_not_poisoned();
409 panic!("BLAKE3 messages contain at most 2^64 - 1 bytes (have {count}, adding {incoming})");
410 }
411
412 #[inline(always)]
414 pub(crate) fn domain(&self) -> &Domain {
415 &self.core.domain
416 }
417
418 #[inline(always)]
419 pub(crate) fn is_plain(&self) -> bool {
420 self.core.domain.is_plain()
421 }
422
423 #[inline(always)]
424 pub(crate) fn platform(&self) -> Platform {
425 self.core.chunk_state.platform()
426 }
427
428 #[inline(always)]
432 pub(crate) fn mark_finishing(&mut self) -> bool {
433 self.assert_not_poisoned();
434 core::mem::replace(&mut self.state, HasherState::Finishing) == HasherState::Finishing
435 }
436
437 #[inline(always)]
438 pub(crate) fn clear_finishing(&mut self) {
439 self.state = HasherState::Ready;
440 }
441
442 #[cfg(test)]
443 pub(crate) fn set_platform_for_test(&mut self, platform: Platform) {
444 self.core.chunk_state.set_platform(platform);
445 }
446
447 #[inline(always)]
448 pub(crate) fn staged_len(&self) -> usize {
449 self.stage.len()
450 }
451
452 #[inline(always)]
453 pub(crate) fn chunk_state(&self) -> &ChunkState {
454 &self.core.chunk_state
455 }
456
457 #[inline(always)]
458 pub(crate) fn stage_first_block(&self) -> &[u8; BLOCK_LEN] {
459 self.stage.first_block()
460 }
461
462 #[inline(always)]
465 pub(crate) fn is_plain_single_chunk_staged(&self) -> bool {
466 self.stage.len() <= CHUNK_LEN && self.core.count() == 0 && self.core.domain.is_plain()
467 }
468
469 pub(crate) fn staged_bytes(&self) -> &[u8] {
471 self.stage.as_bytes()
472 }
473
474 #[cfg(test)]
476 pub(crate) fn stage(&mut self, bytes: &[u8]) {
477 self.stage.append(bytes);
478 }
479
480 fn gather(&mut self, input: &[u8], pooled: Option<&Pool<'_>>) -> &mut Self {
487 self.gather_part(input, pooled, false);
488 self
489 }
490
491 pub(crate) fn gather_part<'a>(&mut self, mut input: &'a [u8], pooled: Option<&Pool<'_>>, hold: bool) -> &'a [u8] {
495 self.check_room(input.len());
496 while !input.is_empty() {
497 #[cfg(target_arch = "x86_64")]
509 if crate::ffi_partial::first_chunk_to_core(self.stage.is_empty(), hold, self.core.domain.is_plain(), self.core.count(), input.len()) {
510 self.core.update_pooled(input, pooled);
511 return &[];
512 }
513 let at = self.count() % STAGE_LEN as u64;
514 if self.stage.is_empty() && at == 0 && input.len() >= STAGE_LEN {
521 let groups = input.len() / STAGE_LEN * STAGE_LEN;
522 assert!(groups > 0, "no whole group went to the core");
524 self.update_groups_guarded(&input[..groups], pooled);
525 input = &input[groups..];
526 continue;
527 }
528 let to_boundary = STAGE_LEN - usize::try_from(at).expect("at < STAGE_LEN");
529 let take = cmp::min(to_boundary, input.len());
530 assert!(take > 0, "the stage took nothing");
533 self.stage.append(&input[..take]);
534 input = &input[take..];
535 if take < to_boundary {
536 return &[];
537 }
538 if hold && self.held_group().is_some() {
539 return input;
540 }
541 self.flush_stage_guarded(pooled);
542 }
543 self.assert_not_poisoned();
544 &[]
545 }
546
547 #[inline(never)]
551 fn update_groups_guarded(&mut self, bytes: &[u8], pooled: Option<&Pool<'_>>) {
552 let guard = PoisonOnUnwind(&mut self.core, &mut self.state);
553 guard.0.update_groups(bytes, pooled);
554 core::mem::forget(guard);
555 }
556
557 #[inline(never)]
558 fn flush_stage_guarded(&mut self, pooled: Option<&Pool<'_>>) {
559 let core = &mut self.core;
560 let state = &mut self.state;
561 self.stage.take_with(|bytes| {
562 let guard = PoisonOnUnwind(core, state);
563 guard.0.update_groups(bytes, pooled);
564 core::mem::forget(guard);
565 });
566 }
567
568 pub(crate) fn held_group(&self) -> Option<(u64, &[u8; STAGE_LEN])> {
570 (self.stage.len() == STAGE_LEN).then(|| (self.core.count() / CHUNK_LEN as u64, self.stage.as_bytes().try_into().unwrap()))
571 }
572
573 pub(crate) fn take_held(&mut self, result: &[u8; BLOCK_LEN]) {
577 assert_eq!(self.stage.len(), STAGE_LEN, "a held group fills the stage");
578 self.stage.clear();
579 self.core.push_group(result);
580 }
581
582 #[inline(always)]
592 fn fresh_key(&self) -> &CVWords {
593 assert_eq!(self.core.count(), 0, "a fresh core's chaining value is its key");
594 self.core.chunk_state.cv()
595 }
596
597 fn root_output(&self) -> Output {
607 if self.stage.is_empty() {
608 return self.core.final_output();
609 }
610 let core = &self.core;
611 let counter = core.chunk_state.chunk_counter();
612 if core.chunk_state.count() > 0 || counter % (STAGE_LEN / CHUNK_LEN) as u64 != 0 {
613 let mut core = self.core.clone();
614 core.update(self.stage.as_bytes());
615 return core.final_output();
616 }
617 crate::counted(crate::Counted::TailApart);
618 let kernels = core.kernels();
619 let mut tail_chunk = ChunkState::new(core.domain.key(), counter, core.domain.flags(), core.chunk_state.platform());
620 let mut tail_stack = CvStack::new();
621 hasher::feed(&kernels, &mut tail_chunk, &mut tail_stack, counter, self.stage.as_bytes());
622 let node = hasher::final_node(&kernels, &tail_chunk, &tail_stack);
623 if counter == 0 {
624 return node;
625 }
626 hasher::above(&kernels, &core.cv_stack, hasher::ones(counter), node)
627 }
628
629 pub(crate) fn take_root_hash(&mut self) -> Hash {
633 if self.core.count() == 0 {
634 return self.finalize();
635 }
636 self.take_output().root_hash()
637 }
638
639 pub(crate) fn take_output(&mut self) -> Output {
642 self.stage.take_with(|staged| {
643 self.core.update(staged);
644 });
645 self.core.final_output()
646 }
647
648 pub fn new(mode: Mode, length_hint: Option<u64>) -> Self {
658 let _ = length_hint;
659 Self::from_core(HasherCore::new_internal(Domain::from_mode(mode)))
660 }
661
662 pub(crate) fn reset(&mut self) {
665 self.core.reset();
666 self.stage.clear();
667 self.state = HasherState::Ready;
668 }
669
670 #[inline]
687 pub fn update(&mut self, input: &[u8]) -> &mut Self {
688 #[cfg(target_arch = "x86_64")]
696 if input.len() <= BLOCK_LEN && self.stage.is_empty() && self.core.chunk_state.chunk_counter() < (1u64 << 54) - 1 {
697 crate::counted(crate::Counted::PaddedFirstBlock);
698 self.stage.pad_first_block(input);
699 return self;
700 }
701 self.update_longer(input)
702 }
703
704 #[inline(never)]
707 fn update_longer(&mut self, input: &[u8]) -> &mut Self {
708 #[cfg(target_arch = "aarch64")]
715 if self.count() == 0 && (CHUNK_LEN + 1..PREFETCH_BELOW).contains(&input.len()) {
716 prefetch_cold(input.len(), self.core.chunk_state.platform(), input.len() >= STAGE_LEN);
717 }
718 self.gather(input, None)
719 }
720
721 pub fn update_with(&mut self, input: &[u8], min_len: usize, halves: &dyn Fn(&TreeHasher, u32, u64, &[u8]) -> [Cv; 2]) -> &mut Self {
738 self.gather(input, Some(&Pool { min_len, halves }))
739 }
740
741 #[inline]
753 pub fn finalize(&self) -> Hash {
754 self.assert_not_poisoned();
755 if self.core.count() == 0 {
758 #[cfg(target_arch = "x86_64")]
762 if self.stage.len() <= BLOCK_LEN {
763 let n = u8::try_from(self.stage.len()).expect("stage length <= BLOCK_LEN");
764 return Hash(crate::chunk_root::block_root(
765 self.core.chunk_state.platform(),
766 self.stage.first_block(),
767 n,
768 self.fresh_key(),
769 self.core.chunk_state.flags(),
770 ));
771 }
772 return crate::hash_serial_from(self.core.chunk_state.platform(), self.stage.as_bytes(), self.fresh_key(), self.core.domain.flags(), false);
773 }
774 self.root_output().root_hash()
775 }
776
777 pub fn finalize_xof(&self) -> OutputReader {
781 self.assert_not_poisoned();
782 OutputReader::new(self.root_output())
783 }
784
785 pub(crate) fn count(&self) -> u64 {
787 self.core.count() + self.stage.len() as u64
788 }
789
790 pub fn update_reader(&mut self, reader: impl std::io::Read) -> std::io::Result<&mut Self> {
831 self.assert_not_poisoned();
832 io::copy_wide(reader, self)?;
833 Ok(self)
834 }
835}
836
837impl HasherCore {
838 #[inline(always)]
839 pub(crate) fn new_internal(domain: Domain) -> Self {
840 Self::new_from(domain, Platform::detect())
841 }
842
843 #[inline(always)]
846 pub(crate) fn new_from(domain: Domain, platform: Platform) -> Self {
847 Self { domain, chunk_state: ChunkState::new(domain.key(), 0, domain.flags(), platform), cv_stack: CvStack::new() }
848 }
849
850 pub(crate) fn reset(&mut self) -> &mut Self {
852 self.chunk_state = ChunkState::new(self.domain.key(), 0, self.domain.flags(), self.chunk_state.platform());
853 self.cv_stack.clear();
854 self
855 }
856
857 fn merge_cv_stack(&mut self, chunk_counter: u64) {
869 let post_merge_stack_len = hasher::ones(chunk_counter);
870 let kernels = kernels_on(&self.domain, &self.chunk_state, self.chunk_state.platform(), None);
871 self.cv_stack.merge(&kernels, post_merge_stack_len);
872 }
873
874 fn push_cv(&mut self, new_cv: &CVBytes, chunk_counter: u64) {
875 self.merge_cv_stack(chunk_counter);
876 self.cv_stack.push(*new_cv);
877 }
878
879 pub fn push_group(&mut self, result: &[u8; BLOCK_LEN]) {
886 const CHUNKS: u64 = (STAGE_LEN / CHUNK_LEN) as u64;
887 check_input_room(self.count(), STAGE_LEN);
888 let counter = self.chunk_state.chunk_counter();
889 assert!(self.chunk_state.count() == 0 && counter % CHUNKS == 0, "a held group starts at a group boundary, the core's chunk empty");
890 if counter == 0 {
891 self.push_cv(result[..OUT_LEN].try_into().unwrap(), 0);
892 self.push_cv(result[OUT_LEN..].try_into().unwrap(), CHUNKS / 2);
893 } else {
894 self.push_cv(result[..OUT_LEN].try_into().unwrap(), counter);
895 }
896 self.chunk_state.advance_chunks(CHUNKS);
897 }
898
899 #[inline(always)]
917 pub(crate) fn update_groups(&mut self, groups: &[u8], pooled: Option<&Pool<'_>>) {
918 self.update_pooled(groups, pooled.filter(|pool| groups.len() >= pool.min_len));
919 }
920
921 pub(crate) fn update_pooled(&mut self, input: &[u8], pooled: Option<&Pool<'_>>) -> &mut Self {
924 check_input_room(self.count(), input.len());
925 let fill_kernels = kernels_on(&self.domain, &self.chunk_state, self.chunk_state.platform(), pooled);
928 let rest = hasher::fill(&fill_kernels, &mut self.chunk_state, &mut self.cv_stack, 0, input);
929 let turn = platform::Sme2Turn::take(self.chunk_state.platform(), pooled.is_none() && rest.len() >= SME2_SIZED_LEN);
931 let kernels = kernels_on(&self.domain, &self.chunk_state, turn.platform(), pooled);
932 hasher::feed(&kernels, &mut self.chunk_state, &mut self.cv_stack, 0, rest);
933 self
934 }
935
936 #[inline(always)]
938 fn kernels(&self) -> HasherKernels<'_> {
939 kernels_on(&self.domain, &self.chunk_state, self.chunk_state.platform(), None)
940 }
941
942 pub fn final_output(&self) -> Output {
943 hasher::final_node(&self.kernels(), &self.chunk_state, &self.cv_stack)
944 }
945
946 pub fn update(&mut self, input: &[u8]) -> &mut Self {
948 self.update_pooled(input, None)
949 }
950
951 pub fn count(&self) -> u64 {
953 self.chunk_state.chunk_counter() * CHUNK_LEN as u64 + self.chunk_state.count() as u64
954 }
955}
956
957impl fmt::Debug for Hasher {
959 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
960 f.debug_struct("Hasher").field("flags", &self.core.domain.flags()).field("platform", &self.core.chunk_state.platform()).finish()
961 }
962}
963
964impl std::io::Write for Hasher {
965 #[inline]
967 fn write(&mut self, input: &[u8]) -> std::io::Result<usize> {
968 self.update(input);
969 Ok(input.len())
970 }
971
972 #[inline]
973 fn flush(&mut self) -> std::io::Result<()> {
974 Ok(())
975 }
976}
977
978#[cfg(test)]
979mod test {
980 use super::*;
981
982 fn update_with_one_wrong_half(wrong: usize) {
983 crate::initialize();
984 Hasher::new(Mode::Plain, None).update_with(&[0; STAGE_LEN], STAGE_LEN, &|tree, level, index, input| {
985 let mut halves = tree.subtree_halves(level, index, input);
986 halves[wrong] = halves[1 - wrong];
987 halves
988 });
989 }
990
991 #[test]
992 #[should_panic(expected = "not the halves of level 4 index 0")]
993 fn pool_rejects_a_wrong_left_half_alone() {
994 update_with_one_wrong_half(0);
995 }
996
997 #[test]
998 #[should_panic(expected = "not the halves of level 4 index 0")]
999 fn pool_rejects_a_wrong_right_half_alone() {
1000 update_with_one_wrong_half(1);
1001 }
1002
1003 #[test]
1010 fn a_callbacks_panic_comes_out_of_update_with() {
1011 crate::initialize();
1012 let mut input = vec![0u8; 2 * STAGE_LEN];
1013 crate::test::paint_test_input(&mut input);
1014 let panics = |_: &TreeHasher, _: u32, _: u64, _: &[u8]| -> [Cv; 2] { panic!("this callback panics") };
1015 for whole in [true, false] {
1016 let mut hasher = Hasher::new(Mode::Plain, None);
1017 let call = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| {
1018 if whole {
1019 hasher.update_with(&input, STAGE_LEN, &panics);
1020 } else {
1021 hasher.update(&input[..STAGE_LEN + 1]);
1022 hasher.update(&input[STAGE_LEN + 1..2 * STAGE_LEN - 1]);
1023 hasher.update_with(&input[2 * STAGE_LEN - 1..], STAGE_LEN, &panics);
1024 }
1025 }));
1026 let message = call.expect_err("the callback's panic did not come out");
1027 assert_eq!(message.downcast_ref::<&str>(), Some(&"this callback panics"), "whole: {whole}");
1028 let mut hasher = Hasher::new(Mode::Plain, None);
1029 hasher.update_with(&input, STAGE_LEN, &|tree, level, index, bytes| tree.subtree_halves(level, index, bytes));
1030 assert_eq!(*hasher.finalize().as_bytes(), crate::test::official::hash(Mode::Plain, &input), "whole: {whole}");
1031 }
1032 }
1033
1034 #[test]
1050 fn an_update_below_the_pools_threshold_is_the_serial_update() {
1051 crate::initialize();
1052 let mut input = std::vec![0u8; 16 * STAGE_LEN];
1053 crate::test::paint_test_input(&mut input);
1054 let counts = || [crate::Counted::Row, crate::Counted::Flat].map(|what| crate::COUNTED.with(|c| c[what as usize].replace(0)));
1055 const THRESHOLD: usize = 32 * STAGE_LEN;
1058 let key = [0x52u8; 32];
1059 let platform = Platform::detect();
1060 let rows_here = (4..=hasher::ROW).contains(&platform.simd_degree());
1061 #[cfg(target_arch = "aarch64")]
1062 let flat_here = matches!(platform, Platform::SME2);
1063 #[cfg(not(target_arch = "aarch64"))]
1064 let flat_here = false;
1065 for mode in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey("below the pool's threshold")] {
1066 let (mut serial, mut pooled) = (Hasher::new(mode, None), Hasher::new(mode, None));
1067 let (mut fed, mut seen) = (0, [0u64; 2]);
1068 for n in [STAGE_LEN, STAGE_LEN + 100, STAGE_LEN - 100, STAGE_LEN, 4 * STAGE_LEN, 2 * STAGE_LEN + 7] {
1072 let piece = &input[fed..fed + n];
1073 fed += n;
1074 counts();
1075 serial.update(piece);
1076 let want = counts();
1077 pooled.update_with(piece, THRESHOLD, &|_, _, _, _| panic!("an input below the threshold holds no subtree for the callback"));
1078 assert_eq!(counts(), want, "{fed} bytes in, a piece of {n}: the serial update's rows and flat walks");
1079 assert_eq!(pooled.finalize(), serial.finalize(), "{fed} bytes");
1080 seen = [seen[0] + want[0], seen[1] + want[1]];
1081 }
1082 assert_eq!((seen[0] > 0, seen[1] > 0), (rows_here, flat_here), "rows and flat walks counted: {seen:?}");
1086 let calls = core::cell::Cell::new(0);
1090 assert_eq!(fed, 10 * STAGE_LEN + 7);
1091 pooled.update(&input[fed..12 * STAGE_LEN]);
1092 pooled.update_with(&input[12 * STAGE_LEN..], STAGE_LEN, &|tree, level, index, bytes| {
1093 calls.set(calls.get() + 1);
1094 tree.subtree_halves(level, index, bytes)
1095 });
1096 assert_eq!(calls.get(), 1, "one subtree of 64 KiB, above a threshold of 16 KiB");
1097 assert_eq!(*pooled.finalize().as_bytes(), crate::test::official::hash(mode, &input));
1098 }
1099 }
1100
1101 #[test]
1113 fn a_staged_group_is_held_to_the_threshold_by_its_own_length() {
1114 crate::initialize();
1115 let input = painted();
1116 let input = &input[..2 * STAGE_LEN + 5];
1117 let asked = core::cell::RefCell::new(std::vec::Vec::new());
1118 let mut hasher = Hasher::new(Mode::Plain, None);
1119 hasher.update(&input[..STAGE_LEN - 1]);
1120 hasher.update_with(&input[STAGE_LEN - 1..STAGE_LEN], STAGE_LEN, &|tree, level, index, bytes| {
1121 asked.borrow_mut().push((level, index, bytes.len()));
1122 tree.subtree_halves(level, index, bytes)
1123 });
1124 assert_eq!(asked.borrow().as_slice(), &[(4, 0, STAGE_LEN)], "a group of the threshold's length, completed by one byte");
1125 hasher.update(&input[STAGE_LEN..]);
1126 assert_eq!(*hasher.finalize().as_bytes(), crate::test::official::hash(Mode::Plain, input));
1127 let rows = || crate::COUNTED.with(|c| c[crate::Counted::Row as usize].replace(0));
1130 let (mut serial, mut pooled) = (Hasher::new(Mode::Plain, None), Hasher::new(Mode::Plain, None));
1131 serial.update(&input[..2 * STAGE_LEN - 1]);
1132 pooled.update(&input[..2 * STAGE_LEN - 1]);
1133 let last = &input[2 * STAGE_LEN - 1..2 * STAGE_LEN];
1134 rows();
1135 serial.update(last);
1136 let want = rows();
1137 pooled.update_with(last, STAGE_LEN + 1, &|_, _, _, _| panic!("a group one byte under the threshold holds no subtree for the callback"));
1138 assert_eq!(rows(), want, "a group one byte under the threshold: the serial update's rows");
1139 let rows_here = (4..=hasher::ROW).contains(&Platform::detect().simd_degree());
1140 assert_eq!(want > 0, rows_here, "the comparison is of something wherever the kernels cut rows");
1141 assert_eq!(pooled.finalize(), serial.finalize());
1142 assert_eq!(*pooled.finalize().as_bytes(), crate::test::official::hash(Mode::Plain, &input[..2 * STAGE_LEN]));
1143 }
1144
1145 #[test]
1146 fn pool_halves_use_the_subtrees_nonzero_place() {
1147 let calls = core::cell::Cell::new(0);
1148 crate::initialize();
1149 let input = painted();
1150 let input = &input[..2 * STAGE_LEN];
1151 let key = [3; KEY_LEN];
1152 let mut hasher = Hasher::new(Mode::Keyed(&key), None);
1153 hasher.update(&input[..STAGE_LEN]);
1154 hasher.update_with(&input[STAGE_LEN..], STAGE_LEN, &|tree, level, index, input| {
1155 assert_eq!((level, index, input.len()), (4, 1, STAGE_LEN));
1156 calls.set(calls.get() + 1);
1157 tree.subtree_halves(level, index, input)
1158 });
1159 assert_eq!(calls.get(), 1);
1160 assert_eq!(hasher.finalize().as_bytes(), blake3::keyed_hash(&key, input).as_bytes());
1161 }
1162
1163 fn painted() -> std::vec::Vec<u8> {
1164 let mut input = std::vec![0u8; 3 * STAGE_LEN];
1165 crate::test::paint_test_input(&mut input);
1166 input
1167 }
1168
1169 #[test]
1174 fn test_the_length_hint_never_changes_the_digest() {
1175 let input = painted();
1176 let key = [3u8; 32];
1177 for mode in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey("hint test")] {
1178 for len in [0, 1, CHUNK_LEN, CHUNK_LEN + 1, STAGE_LEN + 7, input.len()] {
1179 let message = &input[..len];
1180 let want = crate::convenience::hash_with(mode, message);
1181 let hints = [None, Some(0), Some(1), Some(len as u64), Some(len as u64 / 2), Some(2 * len as u64 + 1), Some(u64::MAX)];
1182 let mut reused = Hasher::new(mode, Some(7));
1183 for hint in hints {
1184 let mut fresh = Hasher::new(mode, hint);
1185 for piece in message.chunks(1000) {
1186 fresh.update(piece);
1187 }
1188 assert_eq!(fresh.finalize(), want, "{len} bytes, hint {hint:?}");
1189 reused.reset();
1190 reused.update(message);
1191 assert_eq!(reused.clone().finalize(), want, "{len} bytes, hint {hint:?}, after reset");
1192 }
1193 }
1194 }
1195 }
1196
1197 #[test]
1202 fn clone_from_copies_only_the_live_stage_prefix() {
1203 crate::initialize();
1204 let input = painted();
1205 let key = [0x42u8; 32];
1206 let other_key = [0x73u8; 32];
1207 for mode in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey("in-place prefix checkpoint")] {
1208 for len in [0usize, 64, 1024, 1025, 2048, STAGE_LEN - 1, STAGE_LEN, 2 * STAGE_LEN + 17] {
1209 let mut source = Hasher::new(mode, None);
1210 for part in input[..len].chunks(17) {
1211 source.update(part);
1212 }
1213 let live = if source.stage.len() == 0 { 0 } else { source.stage.len().max(BLOCK_LEN) };
1217 source.stage.fill_from_for_test(live, 0xbb);
1218 let mut copy = Hasher::new(Mode::Keyed(&other_key), None);
1219 copy.update(&input[..2 * STAGE_LEN]);
1220 copy.stage.fill_from_for_test(0, 0xaa);
1221 copy.clone_from(&source);
1222 let expected = crate::test::official::hash(mode, &input[..len]);
1223 assert_eq!(copy.count(), source.count());
1224 assert_eq!(*copy.clone().finalize().as_bytes(), expected);
1225 assert_eq!(copy.stage.as_bytes(), source.stage.as_bytes());
1226 assert!((live..STAGE_LEN).all(|i| unsafe { copy.stage.byte_for_test(i) } == 0xaa), "unused stage copied at len={len}");
1229 if source.core.count() == 0 {
1230 assert!(
1231 (source.stage.len()..live).all(|i| unsafe { copy.stage.byte_for_test(i) } == 0),
1232 "the first block is zero past a message whole in the stage, len={len}"
1233 );
1234 }
1235 copy.update(&input[len..len + 129]);
1236 assert_eq!(*copy.clone().finalize().as_bytes(), crate::test::official::hash(mode, &input[..len + 129]));
1237 assert_eq!(*source.finalize().as_bytes(), expected, "checkpoint source is untouched");
1238 let mut out = [0u8; 129];
1239 copy.finalize_xof().fill(&mut out);
1240 assert_eq!(out.as_slice(), crate::test::official::xof(mode, &input[..len + 129], 0, out.len()));
1241 }
1242 }
1243 }
1244
1245 #[test]
1251 fn test_update_stages_exactly_what_it_must() {
1252 let input = painted();
1253 let mut h = Hasher::new(Mode::Plain, None);
1254 for (end, staged) in [(CHUNK_LEN, CHUNK_LEN), (CHUNK_LEN + 100, CHUNK_LEN + 100), (STAGE_LEN, 0), (2 * STAGE_LEN, 0)] {
1255 let from = h.count() as usize;
1256 h.update(&input[from..end]);
1257 assert_eq!(h.stage.len(), staged, "after {end} bytes");
1258 }
1259 assert_eq!(h.finalize(), crate::convenience::hash(&input[..2 * STAGE_LEN]));
1260 }
1261
1262 #[test]
1268 fn finalize_leaves_the_hasher_as_it_was_and_later_updates_extend_the_message() {
1269 crate::initialize();
1270 let input = painted();
1271 let key = [0x5a; 32];
1272 for mode in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey("finalize, then more")] {
1273 for first in [0usize, 1, 17, 63, 64, 65, 1000, 1024, 1025, STAGE_LEN - 1, STAGE_LEN, STAGE_LEN + 1, 2 * STAGE_LEN - 300] {
1274 for more in [0usize, 1, 64, 1500, STAGE_LEN] {
1275 for piece in [usize::MAX, 7] {
1276 let what = std::format!("first={first} more={more} piece={piece}");
1277 let mut h = Hasher::new(mode, None);
1278 for part in input[..first].chunks(piece.min(first.max(1))) {
1279 h.update(part);
1280 }
1281 let state = (h.stage.len(), h.core.count());
1282 let want = crate::test::official::hash(mode, &input[..first]);
1283 assert_eq!(*h.finalize().as_bytes(), want, "{what}");
1284 let mut out = [0u8; 100];
1285 h.finalize_xof().fill(&mut out);
1286 assert_eq!(out.as_slice(), crate::test::official::xof(mode, &input[..first], 0, out.len()), "{what}");
1287 assert_eq!(*h.finalize().as_bytes(), want, "asked again, {what}");
1288 assert_eq!((h.stage.len(), h.core.count()), state, "untouched, {what}");
1289 h.update(&input[first..first + more]);
1290 assert_eq!(*h.finalize().as_bytes(), crate::test::official::hash(mode, &input[..first + more]), "extended, {what}");
1291 h.finalize_xof().fill(&mut out);
1292 assert_eq!(out.as_slice(), crate::test::official::xof(mode, &input[..first + more], 0, out.len()), "extended, {what}");
1293 }
1294 }
1295 }
1296 }
1297 }
1298
1299 #[test]
1306 fn a_block_or_less_is_padded_whatever_the_hasher_held_before() {
1307 crate::initialize();
1308 let input = painted();
1309 let key = [0x77; 32];
1310 for mode in [Mode::Plain, Mode::Keyed(&key)] {
1311 for long in [0usize, 30, 64, 100, 5000, STAGE_LEN, STAGE_LEN + 300] {
1312 for short in [0usize, 1, 10, 31, 63, 64] {
1313 let what = std::format!("long={long} short={short}");
1314 let message = &input[1000..1000 + short];
1315 let want = crate::test::official::hash(mode, message);
1316 for split in [0, short / 2] {
1318 let mut hashers = std::vec![Hasher::new(mode, None)];
1319 hashers[0].update(&input[..long]);
1320 let mut out = [[0u8; OUT_LEN]];
1321 crate::each::finalize_each(&mut hashers, &[0], &mut out);
1322 assert_eq!(out[0], crate::test::official::hash(mode, &input[..long]), "{what}");
1323 hashers[0].update(&message[..split]);
1324 hashers[0].update(&message[split..]);
1325 assert_eq!(*hashers[0].finalize().as_bytes(), want, "after a reset, {what} split={split}");
1326 crate::each::finalize_each(&mut hashers, &[0], &mut out);
1327 assert_eq!(out[0], want, "finished with others after a reset, {what} split={split}");
1328 }
1329 let mut source = Hasher::new(mode, None);
1331 source.update(message);
1332 let mut copy = Hasher::new(mode, None);
1333 copy.update(&input[..long]);
1334 copy.clone_from(&source);
1335 assert_eq!(*copy.finalize().as_bytes(), want, "after clone_from, {what}");
1336 assert_eq!(*source.clone().finalize().as_bytes(), want, "a clone, {what}");
1337 let mut gathered = Hasher::new(mode, None);
1339 gathered.gather(&message[..short / 2], None);
1340 gathered.gather(&message[short / 2..], None);
1341 assert_eq!(*gathered.finalize().as_bytes(), want, "gathered, {what}");
1342 }
1343 }
1344 }
1345 }
1346
1347 fn entries_run(f: &mut dyn FnMut()) -> std::collections::BTreeSet<usize> {
1349 crate::RAN_ENTRIES.with(|r| r.borrow_mut().clear());
1350 f();
1351 crate::RAN_ENTRIES.with(|r| r.borrow().clone())
1352 }
1353
1354 #[test]
1362 fn a_message_whole_in_the_stage_runs_the_one_shot_calls_kernels() {
1363 crate::initialize();
1364 let input = painted();
1365 let key = [0x21; 32];
1366 for mode in [Mode::Plain, Mode::Keyed(&key)] {
1367 for len in [0usize, 1, 64, 65, 1000, 1024, 1025, 5000, STAGE_LEN - 1] {
1368 let message = &input[..len];
1369 let one_shot = entries_run(&mut || {
1370 crate::convenience::hash_with(mode, message);
1371 });
1372 assert!(len > CHUNK_LEN || !one_shot.is_empty(), "a kernel ran, len={len}");
1375 let mut hashers = std::vec![Hasher::new(mode, None)];
1376 assert!(
1377 entries_run(&mut || {
1378 hashers[0].update(message);
1379 })
1380 .is_empty(),
1381 "staging runs no kernel, len={len}"
1382 );
1383 assert_eq!(
1384 entries_run(&mut || {
1385 hashers[0].finalize();
1386 }),
1387 one_shot,
1388 "finalize, len={len}"
1389 );
1390 let mut out = [[0u8; OUT_LEN]];
1391 assert_eq!(entries_run(&mut || crate::each::finalize_each(&mut hashers, &[0], &mut out)), one_shot, "finalize_each alone, len={len}");
1392 #[cfg(not(target_arch = "aarch64"))]
1393 if (65..=CHUNK_LEN).contains(&len) {
1394 let mut turn = Hasher::new(mode, None);
1395 turn.gather_part(message, None, true);
1396 if matches!(mode, Mode::Plain) {
1397 assert_eq!(
1398 entries_run(&mut || {
1399 turn.finalize();
1400 }),
1401 one_shot,
1402 "plain turn stages first chunk, len={len}"
1403 );
1404 } else {
1405 assert_ne!(
1406 entries_run(&mut || {
1407 turn.finalize();
1408 }),
1409 one_shot,
1410 "the control: from a chunk state, len={len}"
1411 );
1412 }
1413 }
1414 }
1415 }
1416 }
1417
1418 #[test]
1423 #[cfg(target_arch = "x86_64")]
1424 fn an_update_of_a_block_or_less_into_an_empty_stage_is_stored_padded() {
1425 crate::initialize();
1426 let input = painted();
1427 let padded = |hasher: &mut Hasher, bytes: &[u8]| {
1428 crate::COUNTED.with(|c| c[crate::Counted::PaddedFirstBlock as usize].set(0));
1429 hasher.update(bytes);
1430 crate::COUNTED.with(|c| c[crate::Counted::PaddedFirstBlock as usize].get())
1431 };
1432 for (len, expected) in [(0usize, 1), (1, 1), (63, 1), (64, 1), (65, 0), (1024, 0), (STAGE_LEN, 0)] {
1433 let mut h = Hasher::new(Mode::Plain, None);
1434 assert_eq!(padded(&mut h, &input[..len]), expected, "a fresh hasher, {len} bytes");
1435 }
1436 let mut h = Hasher::new(Mode::Plain, None);
1439 assert_eq!(padded(&mut h, &input[..10]), 1);
1440 assert_eq!(padded(&mut h, &input[10..20]), 0, "the stage holds bytes");
1441 assert_eq!(padded(&mut h, &input[20..STAGE_LEN]), 0);
1442 assert_eq!(h.stage.len(), 0, "the stage went to the core");
1443 assert_eq!(padded(&mut h, &input[STAGE_LEN..STAGE_LEN + 64]), 1, "an empty stage again");
1444 assert_eq!(h.finalize(), crate::convenience::hash(&input[..STAGE_LEN + 64]));
1445 }
1446
1447 #[test]
1455 fn later_groups_are_rows_and_finalize_hashes_the_tail_apart() {
1456 crate::initialize();
1457 let mut input = std::vec![0u8; 8 * STAGE_LEN];
1458 crate::test::paint_test_input(&mut input);
1459 let count = |what: crate::Counted| crate::COUNTED.with(|c| c[what as usize].replace(0));
1460 let key = [0x51u8; 32];
1461 let rows_here = (4..=hasher::ROW).contains(&Platform::detect().simd_degree());
1462 for mode in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey("rows and tails")] {
1463 let mut h = Hasher::new(mode, None);
1464 let (mut fed, mut rows) = (0, 0);
1465 for (n, new_rows) in [(STAGE_LEN, 0), (STAGE_LEN + 100, 1), (STAGE_LEN - 100, 1), (2 * STAGE_LEN + 7, 2), (STAGE_LEN - 7, 1)] {
1469 count(crate::Counted::Row);
1470 h.update(&input[fed..fed + n]);
1471 fed += n;
1472 rows += new_rows;
1473 assert_eq!(count(crate::Counted::Row), if rows_here { new_rows } else { 0 }, "{fed} bytes in: the update's subtrees after the first");
1474 count(crate::Counted::TailApart);
1475 assert_eq!(*h.finalize().as_bytes(), crate::test::official::hash(mode, &input[..fed]), "{fed} bytes");
1476 let apart = u64::from(h.stage.len() > 0);
1477 assert_eq!(count(crate::Counted::TailApart), apart, "{fed} bytes: {} staged", h.stage.len());
1478 let mut xof = [0u8; 100];
1479 h.finalize_xof().fill(&mut xof);
1480 assert_eq!(xof[..32], *h.finalize().as_bytes());
1481 }
1482 let _ = rows;
1483 }
1484 let mut h = Hasher::new(Mode::Plain, None);
1489 h.update(&input[..3000]);
1490 h.reset();
1491 h.gather_part(&input[..5], None, false);
1492 assert_eq!((h.stage.len(), h.core.count()), (5, 0));
1493 assert_eq!(*h.finalize().as_bytes(), crate::test::official::hash(Mode::Plain, &input[..5]));
1494 h.gather_part(&input[5..70], None, false);
1495 assert_eq!(*h.finalize().as_bytes(), crate::test::official::hash(Mode::Plain, &input[..70]));
1496 }
1497
1498 #[test]
1502 fn finalize_after_a_turn_that_left_a_chunk_in_the_core() {
1503 crate::initialize();
1504 let input = painted();
1505 let key = [0x53u8; 32];
1506 let mode = Mode::Keyed(&key);
1507 let mut hashers = [Hasher::new(mode, None), Hasher::new(mode, None)];
1508 crate::throughput::update_each(&mut hashers, &[(0, &input[..700]), (1, &input[..64])]);
1509 crate::throughput::update_each(&mut hashers, &[(0, &input[700..2500]), (1, &input[64..65])]);
1510 crate::COUNTED.with(|c| c[crate::Counted::TailApart as usize].set(0));
1511 for (h, len) in hashers.iter().zip([2500, 65]) {
1512 assert_eq!(*h.finalize().as_bytes(), crate::test::official::hash(mode, &input[..len]), "{len} bytes");
1513 }
1514 if !cfg!(target_arch = "aarch64") {
1515 assert!(hashers[0].core.chunk_state.count() > 0 && hashers[0].stage.len() > 0, "a chunk in the core, bytes in the stage");
1516 assert_eq!(crate::COUNTED.with(|c| c[crate::Counted::TailApart as usize].get()), 0);
1517 }
1518 for in_core in [700, 3 * CHUNK_LEN, STAGE_LEN + CHUNK_LEN] {
1521 let mut h = Hasher::new(Mode::Plain, None);
1522 h.core.update(&input[..in_core]);
1523 h.stage(&input[in_core..in_core + 900]);
1524 assert_eq!(h.count(), (in_core + 900) as u64, "{in_core} bytes in the core: the count");
1530 crate::COUNTED.with(|c| c[crate::Counted::TailApart as usize].set(0));
1531 assert_eq!(*h.finalize().as_bytes(), crate::test::official::hash(Mode::Plain, &input[..in_core + 900]), "{in_core} bytes in the core");
1532 assert_eq!(crate::COUNTED.with(|c| c[crate::Counted::TailApart as usize].get()), 0, "{in_core} bytes in the core: the copy");
1533 }
1534 }
1535
1536 #[test]
1543 fn test_an_updates_whole_groups_skip_the_stage_and_its_end_is_staged() {
1544 let mut input = std::vec![0u8; 65536 + 6 * STAGE_LEN];
1545 crate::test::paint_test_input(&mut input);
1546 let mut h = Hasher::new(Mode::Plain, None);
1547 let third = 65536 / 3;
1548 for (end, staged, copies) in [
1552 (third, third - STAGE_LEN, 1),
1553 (2 * third, 2 * third - 2 * STAGE_LEN, 2),
1554 (65536, 0, 1),
1555 (65536 + STAGE_LEN + 5, 5, 1),
1556 (65536 + 2 * STAGE_LEN, 0, 1),
1557 (65536 + 2 * STAGE_LEN + 100, 100, 1),
1558 (65536 + 4 * STAGE_LEN + 100, 100, 2),
1559 (65536 + 5 * STAGE_LEN, 0, 1),
1560 (65536 + 6 * STAGE_LEN, 0, 0),
1561 ] {
1562 let from = h.count() as usize;
1563 crate::COUNTED.with(|c| c[crate::Counted::Staged as usize].set(0));
1564 h.update(&input[from..end]);
1565 assert_eq!(crate::COUNTED.with(|c| c[crate::Counted::Staged as usize].get()), copies, "copies into the stage, after {end} bytes");
1566 let _ = copies;
1567 assert_eq!(h.stage.len(), staged, "after {end} bytes");
1568 assert_eq!(h.finalize(), crate::convenience::hash(&input[..end]), "after {end} bytes");
1569 }
1570 }
1571
1572 fn near_limit(remaining_bytes: u64) -> Hasher {
1577 assert!(remaining_bytes >= 1 && remaining_bytes <= CHUNK_LEN as u64 - 1);
1578 let mut h = Hasher::new(Mode::Plain, None);
1579 h.core.chunk_state.set_chunk_counter((1u64 << 54) - 1);
1581 let fill = (CHUNK_LEN as u64 - 1 - remaining_bytes) as usize;
1582 if fill > 0 {
1583 h.core.chunk_state.update(&std::vec![0u8; fill]);
1584 }
1585 assert_eq!(u64::MAX - h.count(), remaining_bytes);
1586 h
1587 }
1588
1589 #[test]
1590 fn accepts_last_legal_byte_at_u64_max() {
1591 crate::initialize();
1592 let mut h = near_limit(10);
1593 h.update(&[1u8; 9]);
1594 h.update(&[2u8; 1]);
1595 assert_eq!(h.count(), u64::MAX);
1596 h.update(&[]);
1598 assert_eq!(h.count(), u64::MAX);
1599 }
1600
1601 #[test]
1602 #[should_panic(expected = "BLAKE3 messages contain at most 2^64 - 1 bytes")]
1603 fn refuses_byte_past_u64_max_on_short_fast_path() {
1604 crate::initialize();
1605 let mut h = near_limit(1);
1606 h.update(&[0u8; 2]);
1607 }
1608
1609 #[test]
1610 #[should_panic(expected = "BLAKE3 messages contain at most 2^64 - 1 bytes")]
1611 fn refuses_byte_past_u64_max_after_filling_to_limit() {
1612 crate::initialize();
1613 let mut h = near_limit(1);
1614 h.update(&[0u8; 1]);
1615 assert_eq!(h.count(), u64::MAX);
1616 h.update(&[0u8; 1]);
1617 }
1618
1619 #[test]
1620 #[should_panic(expected = "BLAKE3 messages contain at most 2^64 - 1 bytes")]
1621 fn push_group_refuses_group_past_u64_max() {
1622 crate::initialize();
1623 let mut h = Hasher::new(Mode::Plain, None);
1624 h.core.chunk_state.set_chunk_counter((1u64 << 54) - (STAGE_LEN / CHUNK_LEN) as u64);
1627 h.core.push_group(&[0u8; BLOCK_LEN]);
1628 }
1629
1630 #[test]
1631 #[should_panic(expected = "staged bytes exceed STAGE_LEN")]
1632 fn stage_append_checks_capacity() {
1633 crate::initialize();
1634 let mut h = Hasher::new(Mode::Plain, None);
1635 h.stage(&[0u8; STAGE_LEN]);
1636 h.stage(&[0u8; 1]);
1637 }
1638
1639 #[test]
1643 fn test_gather_part_holds_a_whole_group() {
1644 let input = painted();
1645 let mut h = Hasher::new(Mode::Plain, None);
1646 h.update(&input[..STAGE_LEN]);
1647 h.update(&input[STAGE_LEN..STAGE_LEN + 100]);
1648 let rest = h.gather_part(&input[STAGE_LEN + 100..2 * STAGE_LEN + 50], None, true);
1649 assert_eq!(rest.len(), 50, "the rest handed back");
1650 let (counter, bytes) = h.held_group().expect("a whole group held");
1651 assert_eq!((counter, &bytes[..]), ((STAGE_LEN / CHUNK_LEN) as u64, &input[STAGE_LEN..2 * STAGE_LEN]));
1652 }
1653
1654 #[cfg(target_arch = "aarch64")]
1655 #[test]
1656 fn set_platform_for_test_updates_chunk_state_platform() {
1657 crate::initialize();
1658 let mut h = Hasher::new(Mode::Plain, None);
1659 h.set_platform_for_test(Platform::SME2);
1660 assert_eq!(h.platform(), Platform::SME2);
1661 h.set_platform_for_test(Platform::NEON);
1662 assert_eq!(h.platform(), Platform::NEON);
1663 }
1664
1665 #[test]
1675 fn update_with_callback_panic_poisons_hasher_fail_stop() {
1676 use core::panic::AssertUnwindSafe;
1677 use std::io::{Read, Write as _};
1678
1679 fn panic_message(res: std::thread::Result<()>) -> String {
1680 let payload = res.expect_err("expected panic");
1681 payload.downcast_ref::<&str>().map(|s| (*s).to_owned()).or_else(|| payload.downcast_ref::<String>().cloned()).unwrap_or_default()
1682 }
1683 fn assert_poison_panic(label: &str, f: impl FnOnce()) {
1684 let msg = panic_message(std::panic::catch_unwind(AssertUnwindSafe(f)));
1685 assert!(msg.contains("Hasher was poisoned"), "{label}: expected poison panic, got {msg:?}");
1686 }
1687 struct MustNotRead;
1688 impl Read for MustNotRead {
1689 fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
1690 panic!("read must not be invoked on poisoned Hasher");
1691 }
1692 }
1693
1694 crate::initialize();
1695 let data = painted();
1696
1697 let mut ok = Hasher::new(Mode::Plain, None);
1699 ok.update(&data[..8_192]);
1700 ok.update_with(&data[8_192..3 * STAGE_LEN], STAGE_LEN, &|tree, level, index, bytes| tree.subtree_halves(level, index, bytes));
1701 assert_eq!(ok.finalize(), crate::convenience::hash(&data[..3 * STAGE_LEN]));
1702
1703 let mut near_limit = Hasher::new(Mode::Plain, None);
1705 near_limit.core.chunk_state.set_chunk_counter((1u64 << 54) - 1);
1706 near_limit.update(&[0u8; CHUNK_LEN - 2]);
1707 let over_msg = panic_message(std::panic::catch_unwind(AssertUnwindSafe(|| {
1708 near_limit.update_with(&[0u8; 2], STAGE_LEN, &|t, l, i, b| t.subtree_halves(l, i, b));
1709 })));
1710 assert!(over_msg.contains("2^64 - 1"), "expected length refusal, got {over_msg:?}");
1711 near_limit.update(&[]);
1712 near_limit.update(&[0u8; 1]);
1713 assert_eq!(near_limit.count(), u64::MAX);
1714
1715 let mut h = Hasher::new(Mode::Plain, None);
1717 h.update(&data[..8_192]);
1718 let boom = panic_message(std::panic::catch_unwind(AssertUnwindSafe(|| {
1719 h.update_with(&data[8_192..3 * STAGE_LEN], STAGE_LEN, &|_, _, _, _| panic!("callback boom"));
1720 })));
1721 assert!(boom.contains("callback boom"), "expected callback panic, got {boom:?}");
1722
1723 let cloned = h.clone();
1725 assert_poison_panic("cloned finalize", || {
1726 let _ = cloned.finalize();
1727 });
1728 let mut target = Hasher::new(Mode::Plain, None);
1729 target.clone_from(&h);
1730 assert_poison_panic("clone_from poisoned", || {
1731 let _ = target.finalize();
1732 });
1733 assert_poison_panic("finalize", || {
1734 let _ = h.finalize();
1735 });
1736 assert_poison_panic("finalize_xof", || {
1737 let _ = h.finalize_xof();
1738 });
1739 assert_poison_panic("empty update", || {
1740 h.update(&[]);
1741 });
1742 assert_poison_panic("1-byte update", || {
1743 h.update(b"x");
1744 });
1745 assert_poison_panic("short update", || {
1746 h.update(b"short");
1747 });
1748 assert_poison_panic("Write::write", || {
1749 let _ = h.write(b"abc");
1750 });
1751 assert_poison_panic("update_reader before read", || {
1752 let _ = h.update_reader(MustNotRead);
1753 });
1754 assert_poison_panic("subsequent update_with", || {
1755 h.update_with(b"more", STAGE_LEN, &|t, l, i, b| t.subtree_halves(l, i, b));
1756 });
1757
1758 let mut good = Hasher::new(Mode::Plain, None);
1762 good.update(b"still-good");
1763 let mut pair = [good, h];
1764 assert_poison_panic("update_each", || {
1765 crate::each::update_each(&mut pair, &[(1, &[])]);
1766 });
1767 let mut out = [[0xAAu8; OUT_LEN]; 2];
1768 assert_poison_panic("finalize_each", || {
1769 crate::each::finalize_each(&mut pair, &[0, 1], &mut out);
1770 });
1771 assert_eq!(out, [[0xAAu8; OUT_LEN]; 2], "refused finalize_each must leave outputs untouched");
1772 assert_poison_panic("rejected entry remains poisoned after finalize_each", || {
1773 let _ = pair[1].finalize();
1774 });
1775 let mut one = [[0u8; OUT_LEN]; 1];
1776 crate::each::finalize_each(&mut pair, &[0], &mut one);
1777 assert_eq!(one[0], *crate::convenience::hash(b"still-good").as_bytes());
1778
1779 let mut fresh = Hasher::new(Mode::Plain, None);
1781 fresh.update(b"healthy");
1782 pair[1].clone_from(&fresh);
1783 assert_eq!(pair[1].finalize(), crate::convenience::hash(b"healthy"));
1784
1785 let mut direct = Hasher::new(Mode::Plain, None);
1787 let direct_boom = panic_message(std::panic::catch_unwind(AssertUnwindSafe(|| {
1788 direct.update_with(&data[..2 * STAGE_LEN], STAGE_LEN, &|_, _, _, _| panic!("direct boom"));
1789 })));
1790 assert!(direct_boom.contains("direct boom"), "expected direct callback panic, got {direct_boom:?}");
1791 assert_poison_panic("direct-path finalize", || {
1792 let _ = direct.finalize();
1793 });
1794
1795 let mut wrong_cv = Hasher::new(Mode::Plain, None);
1797 let cv_err = panic_message(std::panic::catch_unwind(AssertUnwindSafe(|| {
1798 wrong_cv.update_with(&data[..2 * STAGE_LEN], STAGE_LEN, &|_, _, _, _| [Cv::at(0, 0, [0; 32]), Cv::at(0, 1, [0; 32])]);
1799 })));
1800 assert!(!cv_err.contains("Hasher was poisoned"), "expected Cv position panic, got {cv_err:?}");
1801 assert_poison_panic("wrong-cv finalize", || {
1802 let _ = wrong_cv.finalize();
1803 });
1804 }
1805}