1pub use crate::block::Packed;
27pub use crate::block::{Batch, Block, Part, Prepared};
28pub use crate::each::{finalize_each, hash_each, update_each};
29
30use crate::{CHUNK_LEN, ContextKey, DERIVE_KEY_CONTEXT, Hash, IV, Mode, OUT_LEN};
31
32#[inline(always)]
51pub fn hash(mode: Mode, input: &[Block], len: usize) -> Hash {
52 let mut room = core::mem::MaybeUninit::uninit();
53 let (key, flags) = mode.key(&mut room);
54 crate::hash_serial(&Block::bytes(input)[..len], key, flags)
55}
56
57#[inline(always)]
108pub fn hash_many<P: Prepared + ?Sized>(mode: Mode, batch: &P, out: &mut [[u8; OUT_LEN]]) {
109 let mut room = core::mem::MaybeUninit::uninit();
110 let (key, flags) = mode.key(&mut room);
111 crate::hash_many_serial(batch.bytes(), batch.message_len(), batch.slot(), key, flags, out);
112}
113
114#[inline(always)]
142pub fn hash_counter_range(mode: Mode, template: &[u8], counter_word: usize, start: u32, out: &mut [[u8; OUT_LEN]]) {
143 let validated = crate::ffi_counter::ValidatedTemplate::new(template, counter_word);
147 let platform = crate::Platform::detect();
148 if out.is_empty() {
149 return;
150 }
151 let mut derived = core::mem::MaybeUninit::uninit();
152 let (key, flags) = mode.key(&mut derived);
153 crate::ffi_counter::hash_counter_range_on(validated, start, key, flags, out, platform);
154}
155
156#[inline(always)]
182pub fn hash_counter_range_trunc16(mode: Mode, template: &[u8], counter_word: usize, start: u32, out: &mut [[u8; 16]]) {
183 let validated = crate::ffi_counter::ValidatedTemplate::new(template, counter_word);
184 let platform = crate::Platform::detect();
185 if out.is_empty() {
186 return;
187 }
188 let mut derived = core::mem::MaybeUninit::uninit();
189 let (key, flags) = mode.key(&mut derived);
190 crate::ffi_counter::hash_counter_range_on(validated, start, key, flags, out, platform);
191}
192
193#[inline(always)]
231#[allow(clippy::too_many_arguments)]
232pub fn find_counter_range(
233 mode: Mode,
234 template: &[u8],
235 counter_word: usize,
236 start: u32,
237 count: u64,
238 mask: u32,
239 target: u32,
240 matches: &mut [(u32, [u8; OUT_LEN])],
241) -> usize {
242 let validated = crate::ffi_counter::ValidatedTemplate::new(template, counter_word);
243 let platform = crate::Platform::detect();
244 if crate::ffi_counter::find_is_noop(count, matches.len(), mask, target) {
245 return 0;
246 }
247 let mut derived = core::mem::MaybeUninit::uninit();
248 let (key, flags) = mode.key(&mut derived);
249 crate::ffi_counter::find_counter_range_on(validated, start, count, mask, target, key, flags, matches, platform)
250}
251
252#[inline(always)]
271pub fn hash_chains_32_trunc16(mode: Mode, init: &[[u8; 32]], steps: u32, out: &mut [[u8; 16]]) {
272 assert_eq!(init.len(), out.len(), "one 16-byte output per chain");
273 let platform = crate::Platform::detect();
274 if init.is_empty() {
275 return;
276 }
277 let mut derived = core::mem::MaybeUninit::uninit();
278 let (key, flags) = mode.key(&mut derived);
279 hash_chains_32_trunc16_checked(init, steps, key, flags, out, platform);
280}
281
282#[inline(always)]
283fn hash_chains_32_trunc16_checked(init: &[[u8; 32]], steps: u32, key: &crate::CVWords, flags: u8, out: &mut [[u8; 16]], platform: crate::platform::Platform) {
284 crate::ffi_chain::hash_chains_32_trunc16_on(init, steps, key, flags, out, platform);
285}
286
287#[inline(always)]
303pub fn hash_chains_varlen_32_trunc16(mode: Mode, init: &[[u8; 32]], steps: &[u32], out: &mut [[u8; 16]]) {
304 assert_eq!(init.len(), steps.len(), "one step count per chain");
305 assert_eq!(init.len(), out.len(), "one 16-byte output per chain");
306 let platform = crate::Platform::detect();
307 if init.is_empty() {
308 return;
309 }
310 let mut derived = core::mem::MaybeUninit::uninit();
311 let (key, flags) = mode.key(&mut derived);
312 hash_chains_varlen_32_trunc16_checked(init, steps, key, flags, out, platform);
313}
314
315#[inline(always)]
316fn hash_chains_varlen_32_trunc16_checked(
317 init: &[[u8; 32]],
318 steps: &[u32],
319 key: &crate::CVWords,
320 flags: u8,
321 out: &mut [[u8; 16]],
322 platform: crate::platform::Platform,
323) {
324 crate::ffi_chain::hash_chains_varlen_32_trunc16_on(init, steps, key, flags, out, platform);
325}
326
327pub fn context_key(context: &str) -> ContextKey {
346 crate::hash_serial(context.as_bytes(), IV, DERIVE_KEY_CONTEXT).0
347}
348
349const CHUNK: u64 = CHUNK_LEN as u64;
350
351const MAX_LEVEL: u32 = 53;
354
355const LEVEL_SHIFT: u32 = 56;
360const INDEX_MASK: u64 = (1 << LEVEL_SHIFT) - 1;
361const UNSET: u64 = 0;
362
363pub const fn level_of(len: u64) -> u32 {
375 assert!(len >= CHUNK && len % CHUNK == 0 && (len / CHUNK).is_power_of_two(), "a whole subtree holds a power of two of chunks");
376 (len / CHUNK).trailing_zeros()
377}
378
379const fn place(level: u32, index: u64) -> u64 {
381 assert!(level <= MAX_LEVEL, "a whole subtree's level is at most 53");
382 assert!(index < u64::MAX >> (level + 10), "the subtree ends beyond a message's last byte");
384 ((level as u64 + 1) << LEVEL_SHIFT) + index
386}
387
388#[inline]
390fn subtree_place(level: u32, index: u64, len: usize) -> u64 {
391 let at = place(level, index);
392 assert!(len as u64 == CHUNK << level, "a whole subtree at level {level} holds {} bytes (found {len})", CHUNK << level);
393 at
394}
395
396const fn half_places(level: u32, index: u64) -> [u64; 2] {
398 let left = ((level as u64) << LEVEL_SHIFT) + 2 * index;
399 [left, left + 1]
400}
401
402const fn parent_place(place: u64) -> u64 {
404 (place & !INDEX_MASK) + (1 << LEVEL_SHIFT) + ((place & INDEX_MASK) >> 1)
405}
406
407const fn last_max(first_chunk: u64) -> u64 {
412 assert!(first_chunk <= u64::MAX / CHUNK, "the subtree starts beyond a message's last byte");
413 let room = u64::MAX - first_chunk * CHUNK;
414 if first_chunk == 0 {
415 return room;
416 }
417 let whole = CHUNK << first_chunk.trailing_zeros();
419 if whole < room { whole } else { room }
420}
421
422#[derive(Clone, Copy)]
446pub struct Cv {
447 value: crate::CVBytes,
449 place: u64,
450}
451
452impl Cv {
453 pub const fn unset() -> Self {
458 Cv { value: [0; OUT_LEN], place: UNSET }
459 }
460
461 pub const fn at(level: u32, index: u64, bytes: [u8; OUT_LEN]) -> Self {
468 Cv { value: bytes, place: place(level, index) }
469 }
470
471 #[inline]
473 pub const fn as_bytes(&self) -> &[u8; OUT_LEN] {
474 &self.value
475 }
476
477 #[inline]
481 pub const fn level(&self) -> u32 {
482 (self.set() >> LEVEL_SHIFT) as u32 - 1
483 }
484
485 #[inline]
489 pub const fn index(&self) -> u64 {
490 self.set() & INDEX_MASK
491 }
492
493 pub(crate) fn halves_bytes([left, right]: [Self; 2], level: u32, index: u64) -> [crate::CVBytes; 2] {
496 let [a, b] = half_places(level, index);
497 assert!(left.place == a && right.place == b, "not the halves of level {level} index {index}: {left:?} and {right:?}");
498 [left.value, right.value]
499 }
500
501 #[inline]
503 const fn set(&self) -> u64 {
504 assert!(self.place != UNSET, "a chaining value that was never set");
505 self.place
506 }
507}
508
509impl core::fmt::Debug for Cv {
510 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
511 if self.place == UNSET { write!(f, "a value never set") } else { write!(f, "the whole subtree at level {} index {}", self.level(), self.index()) }
512 }
513}
514
515impl PartialEq for Cv {
516 #[inline]
517 fn eq(&self, other: &Cv) -> bool {
518 (self.place == other.place) & crate::ct::eq_32(&self.value, &other.value)
519 }
520}
521
522impl Eq for Cv {}
523
524#[derive(Clone, Copy)]
557pub struct LastCv {
558 value: crate::CVBytes,
559 first_chunk: u64,
560 len: u64,
561}
562
563impl LastCv {
564 pub const fn at(first_chunk: u64, len: u64, bytes: [u8; OUT_LEN]) -> Self {
571 assert!(len >= 1 && len <= last_max(first_chunk), "the last subtree holds from one byte to the whole subtree aligned at its first chunk");
572 LastCv { value: bytes, first_chunk, len }
573 }
574
575 #[inline]
577 pub const fn as_bytes(&self) -> &[u8; OUT_LEN] {
578 &self.value
579 }
580
581 #[inline]
583 pub const fn first_chunk(&self) -> u64 {
584 self.first_chunk
585 }
586
587 #[inline]
589 #[allow(clippy::len_without_is_empty)]
590 pub const fn len(&self) -> u64 {
591 self.len
592 }
593}
594
595impl core::fmt::Debug for LastCv {
596 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
597 write!(f, "the last subtree, {} bytes from chunk {}", self.len, self.first_chunk)
598 }
599}
600
601impl PartialEq for LastCv {
602 #[inline]
603 fn eq(&self, other: &LastCv) -> bool {
604 (self.first_chunk == other.first_chunk) & (self.len == other.len) & crate::ct::eq_32(&self.value, &other.value)
605 }
606}
607
608impl Eq for LastCv {}
609
610impl From<Cv> for LastCv {
612 fn from(cv: Cv) -> LastCv {
613 let (level, index) = (cv.level(), cv.index());
614 LastCv { value: cv.value, first_chunk: index << level, len: CHUNK << level }
615 }
616}
617
618#[derive(Clone)]
706pub struct TreeHasher {
707 domain: crate::Domain,
708 on_this_core: bool,
709}
710
711impl TreeHasher {
712 pub fn new(mode: Mode) -> Self {
714 Self { domain: crate::Domain::from_mode(mode), on_this_core: false }
715 }
716
717 pub(crate) fn of_domain(domain: crate::Domain) -> Self {
720 Self { domain, on_this_core: false }
721 }
722
723 #[inline]
726 fn platform(&self) -> crate::platform::Platform {
727 if self.on_this_core { crate::platform::Platform::own_core() } else { crate::platform::Platform::detect() }
728 }
729
730 #[inline]
732 fn subtree_cv_on_platform(&self, platform: crate::platform::Platform, level: u32, index: u64, input: &[u8]) -> Cv {
733 let place = subtree_place(level, index, input.len());
734 Cv { value: self.cv_on(platform, index << level, input), place }
735 }
736
737 #[doc(hidden)]
744 pub fn subtree_cv_under(&self, turn: &crate::platform::Sme2Turn, level: u32, index: u64, input: &[u8]) -> Cv {
745 let platform = if self.on_this_core { crate::platform::Platform::own_core() } else { turn.platform() };
746 self.subtree_cv_on_platform(platform, level, index, input)
747 }
748
749 #[inline]
751 fn cv_on(&self, platform: crate::platform::Platform, first_chunk: u64, input: &[u8]) -> crate::CVBytes {
752 if input.len() <= CHUNK_LEN {
753 return crate::ChunkState::new(self.domain.key(), first_chunk, self.domain.flags(), platform).update(input).output().chaining_value();
754 }
755 let [left, right] = self.halves_on(platform, first_chunk, input);
756 crate::hasher::parent_output(&left, &right, self.domain.key(), self.domain.flags(), platform).chaining_value()
757 }
758
759 #[inline]
761 fn halves_on(&self, platform: crate::platform::Platform, first_chunk: u64, input: &[u8]) -> [crate::CVBytes; 2] {
762 crate::tree::root_children(&crate::tree::PlatformKernels { key: self.domain.key(), flags: self.domain.flags(), platform }, input, 0, first_chunk)
763 }
764
765 pub fn on_this_core(mut self) -> Self {
788 self.on_this_core = true;
789 self
790 }
791
792 #[inline]
795 fn turn(&self, len: usize) -> crate::platform::Sme2Turn {
796 self.turn_if(len >= crate::SME2_SIZED_LEN)
797 }
798
799 #[inline]
802 fn turn_if(&self, sme2_sized: bool) -> crate::platform::Sme2Turn {
803 crate::platform::Sme2Turn::take(self.platform(), sme2_sized)
806 }
807
808 #[cfg_attr(target_arch = "aarch64", inline)]
828 pub fn hash(&self, input: &[u8]) -> Hash {
829 #[cfg(target_arch = "aarch64")]
830 {
831 if input.len() <= crate::BLOCK_LEN {
832 let _ = crate::platform::Platform::detect();
833 return crate::hash_one_block_root(input, self.domain.key(), self.domain.flags());
834 }
835 self.hash_long(input)
836 }
837 #[cfg(not(target_arch = "aarch64"))]
838 {
839 let turn = self.turn(input.len());
840 crate::hash_serial_on(input, self.domain.key(), self.domain.flags(), turn.platform())
841 }
842 }
843
844 #[cfg(target_arch = "aarch64")]
845 #[inline(never)]
846 fn hash_long(&self, input: &[u8]) -> Hash {
847 #[cfg(test)]
848 TREE_HASH_LONG_CALLS.with(|c| c.set(c.get() + 1));
849 let turn = self.turn(input.len());
850 crate::hash_serial_on(input, self.domain.key(), self.domain.flags(), turn.platform())
851 }
852
853 pub fn hash_many<P: Prepared + ?Sized>(&self, batch: &P, out: &mut [[u8; OUT_LEN]]) {
858 let turn = self.turn_if(crate::many::sme2_sized(batch.message_len(), batch.slot(), out.len()));
859 crate::many::hash_many_on(batch.bytes(), batch.message_len(), batch.slot(), self.domain.key(), self.domain.flags(), out, turn.platform());
860 }
861
862 pub fn hash_counter_range(&self, template: &[u8], counter_word: usize, start: u32, out: &mut [[u8; OUT_LEN]]) {
872 let validated = crate::ffi_counter::ValidatedTemplate::new(template, counter_word);
873 let platform = self.platform();
874 if out.is_empty() {
875 return;
876 }
877 crate::ffi_counter::hash_counter_range_on(validated, start, self.domain.key(), self.domain.flags(), out, platform);
878 }
879
880 pub fn hash_counter_range_trunc16(&self, template: &[u8], counter_word: usize, start: u32, out: &mut [[u8; 16]]) {
886 let validated = crate::ffi_counter::ValidatedTemplate::new(template, counter_word);
887 let platform = self.platform();
888 if out.is_empty() {
889 return;
890 }
891 crate::ffi_counter::hash_counter_range_on(validated, start, self.domain.key(), self.domain.flags(), out, platform);
892 }
893
894 #[allow(clippy::too_many_arguments)]
902 pub fn find_counter_range(
903 &self,
904 template: &[u8],
905 counter_word: usize,
906 start: u32,
907 count: u64,
908 mask: u32,
909 target: u32,
910 matches: &mut [(u32, [u8; OUT_LEN])],
911 ) -> usize {
912 let validated = crate::ffi_counter::ValidatedTemplate::new(template, counter_word);
913 let platform = self.platform();
914 if crate::ffi_counter::find_is_noop(count, matches.len(), mask, target) {
915 return 0;
916 }
917 crate::ffi_counter::find_counter_range_on(validated, start, count, mask, target, self.domain.key(), self.domain.flags(), matches, platform)
918 }
919
920 pub fn hash_chains_32_trunc16(&self, init: &[[u8; 32]], steps: u32, out: &mut [[u8; 16]]) {
928 assert_eq!(init.len(), out.len(), "one 16-byte output per chain");
929 let platform = self.platform();
930 if init.is_empty() {
931 return;
932 }
933 hash_chains_32_trunc16_checked(init, steps, self.domain.key(), self.domain.flags(), out, platform);
934 }
935
936 pub fn hash_chains_varlen_32_trunc16(&self, init: &[[u8; 32]], steps: &[u32], out: &mut [[u8; 16]]) {
944 assert_eq!(init.len(), steps.len(), "one step count per chain");
945 assert_eq!(init.len(), out.len(), "one 16-byte output per chain");
946 let platform = self.platform();
947 if init.is_empty() {
948 return;
949 }
950 hash_chains_varlen_32_trunc16_checked(init, steps, self.domain.key(), self.domain.flags(), out, platform);
951 }
952
953 #[doc(hidden)]
956 pub fn try_hash_group<'a>(&self, count: usize, input: impl Fn(usize) -> &'a [u8], output: impl FnMut(usize, [u8; OUT_LEN])) -> bool {
957 crate::many::try_whole_group(count, input, self.domain.key(), self.domain.flags(), self.platform(), output)
958 }
959
960 pub fn hash_each(&self, items: &[(&[Block], usize)], out: &mut [[u8; OUT_LEN]]) {
966 assert_eq!(items.len(), out.len(), "one digest per item");
967 crate::each::hash_each_on(self.domain.key(), self.domain.flags(), items, out, self.platform(), |item| self.hash(item));
968 }
969
970 fn bare_parent_cv(&self, left: &crate::CVBytes, right: &crate::CVBytes) -> crate::CVBytes {
972 crate::hasher::parent_output(left, right, self.domain.key(), self.domain.flags(), self.platform()).chaining_value()
973 }
974
975 fn bare_parent_cvs_on(&self, platform: crate::platform::Platform, children: &[crate::CVBytes], out: &mut [crate::CVBytes]) {
981 assert_eq!(children.len() % 2, 0, "parents take their children in pairs");
982 assert_eq!(out.len(), children.len() / 2, "one parent per pair of children");
983 let pairs = crate::platform::MAX_SIMD_DEGREE;
985 for (children, out) in children.chunks(2 * pairs).zip(out.chunks_mut(pairs)) {
986 if children.len() == 2 {
987 out[0] = crate::hasher::parent_output(&children[0], &children[1], self.domain.key(), self.domain.flags(), platform).chaining_value();
988 continue;
989 }
990 let _ = crate::compress_parents_parallel(children.as_flattened(), self.domain.key(), self.domain.flags(), platform, out.as_flattened_mut());
991 }
992 }
993
994 fn bare_root_hash(&self, left: &crate::CVBytes, right: &crate::CVBytes) -> Hash {
997 crate::hasher::parent_output(left, right, self.domain.key(), self.domain.flags(), self.platform()).root_hash()
998 }
999
1000 fn bare_root_output(&self, left: &crate::CVBytes, right: &crate::CVBytes) -> crate::OutputReader {
1003 crate::OutputReader::new(crate::hasher::parent_output(left, right, self.domain.key(), self.domain.flags(), self.platform()))
1004 }
1005 pub fn subtree_cv(&self, level: u32, index: u64, input: &[u8]) -> Cv {
1010 let turn = self.turn(input.len());
1011 self.subtree_cv_on_platform(turn.platform(), level, index, input)
1012 }
1013
1014 pub fn subtree_halves(&self, level: u32, index: u64, input: &[u8]) -> [Cv; 2] {
1021 subtree_place(level, index, input.len());
1022 assert!(level > 0, "a subtree of one chunk has no halves");
1023 let [a, b] = half_places(level, index);
1024 let turn = self.turn(input.len());
1025 let [left, right] = self.halves_on(turn.platform(), index << level, input);
1026 [Cv { value: left, place: a }, Cv { value: right, place: b }]
1027 }
1028
1029 pub fn last_cv(&self, first_chunk: u64, input: &[u8]) -> LastCv {
1037 let (len, max) = (input.len() as u64, last_max(first_chunk));
1038 assert!(len >= 1 && len <= max, "the last subtree at chunk {first_chunk} holds 1 to {max} bytes (found {len})");
1039 let turn = self.turn(input.len());
1040 LastCv { value: self.cv_on(turn.platform(), first_chunk, input), first_chunk, len }
1041 }
1042
1043 pub fn parent_cv(&self, left: &Cv, right: &Cv) -> Cv {
1048 let place = left.set();
1049 assert!(place & 1 == 0 && right.place == place + 1, "the children are not siblings: {left:?} and {right:?}");
1050 Cv { value: self.bare_parent_cv(&left.value, &right.value), place: parent_place(place) }
1051 }
1052
1053 pub fn last_parent_cv(&self, left: &Cv, right: &LastCv) -> LastCv {
1060 let (level, index) = (left.level(), left.index());
1061 assert!(index & 1 == 0 && right.first_chunk == (index + 1) << level, "the children are not siblings: {left:?} and {right:?}");
1062 LastCv { value: self.bare_parent_cv(&left.value, &right.value), first_chunk: index << level, len: (CHUNK << level) + right.len }
1063 }
1064
1065 pub fn parent_cvs(&self, children: &[Cv], out: &mut [Cv]) {
1077 assert_eq!(children.len() % 2, 0, "parents take their children in pairs");
1078 assert_eq!(out.len(), children.len() / 2, "one parent per pair of children");
1079 let Some(first) = children.first() else { return };
1080 let base = first.set();
1081 assert!(base & 1 == 0, "the first child is at an odd index: {first:?}");
1082 for (k, child) in children.iter().enumerate() {
1083 assert!(child.place == base + k as u64, "child {k} is not the next subtree of its size: {child:?}");
1084 }
1085 const PAIRS: usize = 16;
1089 let turn = self.turn_if(children.len() >= 32);
1092 let platform = turn.platform();
1093 let mut values = [[0u8; OUT_LEN]; 2 * PAIRS];
1094 let mut parents = [[0u8; OUT_LEN]; PAIRS];
1095 for (children, out) in children.chunks(2 * PAIRS).zip(out.chunks_mut(PAIRS)) {
1096 for (value, child) in values.iter_mut().zip(children) {
1097 *value = child.value;
1098 }
1099 self.bare_parent_cvs_on(platform, &values[..children.len()], &mut parents[..out.len()]);
1100 for (i, parent) in out.iter_mut().enumerate() {
1101 *parent = Cv { value: parents[i], place: parent_place(children[2 * i].place) };
1102 }
1103 }
1104 }
1105
1106 fn root_children(left: &Cv, right: &LastCv, len: u64) {
1109 let (level, index) = (left.level(), left.index());
1110 assert!(index == 0 && right.first_chunk == 1 << level, "not a root's children: {left:?} and {right:?}");
1111 let held = (CHUNK << level) + right.len;
1112 assert!(held == len, "the root's children hold {held} bytes, and the message {len}");
1113 }
1114
1115 pub fn root_hash(&self, left: &Cv, right: &LastCv, len: u64) -> Hash {
1123 Self::root_children(left, right, len);
1124 self.bare_root_hash(&left.value, &right.value)
1125 }
1126
1127 pub fn root_output(&self, left: &Cv, right: &LastCv, len: u64) -> crate::OutputReader {
1133 Self::root_children(left, right, len);
1134 self.bare_root_output(&left.value, &right.value)
1135 }
1136}
1137
1138pub const fn left_len(len: u64) -> u64 {
1144 assert!(len > CHUNK_LEN as u64, "a chunk or less does not split");
1145 let chunks = (len - 1) / CHUNK_LEN as u64;
1146 (1u64 << (u64::BITS - 1 - chunks.leading_zeros())) * CHUNK_LEN as u64
1147}
1148
1149#[cfg(test)]
1150mod tree_test {
1151 use super::*;
1152 use std::vec::Vec;
1153
1154 mod official {
1157 pub(super) use crate::test::official::parent;
1158 use blake3::hazmat::HasherExt;
1159 pub(super) fn hasher(mode: crate::Mode) -> blake3::Hasher {
1160 match mode {
1161 crate::Mode::Plain => blake3::Hasher::new(),
1162 crate::Mode::Keyed(key) => blake3::Hasher::new_keyed(key),
1163 crate::Mode::DeriveKey(context) => blake3::Hasher::new_derive_key(context),
1164 crate::Mode::DeriveKeyWith(_) => unreachable!("the tests derive from a context string"),
1165 }
1166 }
1167 pub(super) fn subtree_cv(mode: crate::Mode, first_chunk: u64, input: &[u8]) -> [u8; 32] {
1168 let mut hasher = hasher(mode);
1169 hasher.set_input_offset(first_chunk * 1024);
1170 hasher.update(input);
1171 hasher.finalize_non_root()
1172 }
1173 }
1174
1175 const KEY: [u8; 32] = [0x6b; 32];
1176
1177 fn modes() -> [Mode<'static>; 3] {
1178 [Mode::Plain, Mode::Keyed(&KEY), Mode::DeriveKey("blake3-servil tree api test")]
1179 }
1180
1181 fn painted(len: usize) -> Vec<u8> {
1182 let mut input = std::vec![0u8; len];
1183 crate::test::paint_test_input(&mut input);
1184 input
1185 }
1186
1187 #[test]
1194 fn a_subtrees_chaining_value_matches_official_blake3_at_every_place() {
1195 crate::initialize();
1196 let input = painted(70 * CHUNK_LEN + 100);
1197 let mut checked = 0;
1198 for mode in modes() {
1199 for tree in [TreeHasher::new(mode), TreeHasher::new(mode).on_this_core()] {
1200 for first_chunk in [0u64, 1, 2, 4, 6, 8, 16, 48, 64, 1 << 20, (1 << 33) + 4, 3 << 40] {
1201 let max = if first_chunk == 0 { input.len() } else { ((1u64 << first_chunk.trailing_zeros()) as usize * CHUNK_LEN).min(70 * CHUNK_LEN) };
1202 for len in [
1203 1,
1204 63,
1205 64,
1206 65,
1207 1023,
1208 1024,
1209 1025,
1210 2047,
1211 2048,
1212 2049,
1213 4096,
1214 5000,
1215 8 * 1024,
1216 16 * 1024 - 1,
1217 16 * 1024,
1218 16 * 1024 + 1,
1219 33 * 1024 - 5,
1220 64 * 1024,
1221 70 * 1024,
1222 ] {
1223 if len > max {
1224 continue;
1225 }
1226 let bytes = &input[100..100 + len];
1227 checked += 1;
1228 let want = official::subtree_cv(mode, first_chunk, bytes);
1229 assert_eq!(*tree.last_cv(first_chunk, bytes).as_bytes(), want, "first_chunk={first_chunk} len={len}");
1230 if len > CHUNK_LEN {
1231 let turn = tree.turn(len);
1232 let [left, right] = tree.halves_on(turn.platform(), first_chunk, bytes);
1233 assert_eq!(tree.bare_parent_cv(&left, &right), want, "the halves' parent, first_chunk={first_chunk} len={len}");
1234 let split = left_len(len as u64) as usize;
1235 assert_eq!(left, official::subtree_cv(mode, first_chunk, &bytes[..split]), "the left half, first_chunk={first_chunk} len={len}");
1236 assert_eq!(
1237 right,
1238 official::subtree_cv(mode, first_chunk + (split / CHUNK_LEN) as u64, &bytes[split..]),
1239 "the right half, first_chunk={first_chunk} len={len}"
1240 );
1241 }
1242 }
1243 }
1244 }
1245 }
1246 assert_eq!(checked, 3 * 2 * 164, "the places and lengths checked");
1249 }
1250
1251 #[test]
1252 fn whole_subtree_halves_keep_their_places_and_values() {
1253 crate::initialize();
1254 let input = painted(64 * CHUNK_LEN);
1255 for mode in modes() {
1256 for tree in [TreeHasher::new(mode), TreeHasher::new(mode).on_this_core()] {
1257 for (level, index) in [(1, 0), (2, 3), (5, 7), (6, (1 << 30) + 1)] {
1258 let bytes = &input[..CHUNK_LEN << level];
1259 let (head, tail) = bytes.split_at(bytes.len() / 2);
1260 let first = index << level;
1261 let want_left = official::subtree_cv(mode, first, head);
1262 let want_right = official::subtree_cv(mode, first + (head.len() / CHUNK_LEN) as u64, tail);
1263 assert_eq!(
1264 tree.subtree_halves(level, index, bytes),
1265 [Cv::at(level - 1, 2 * index, want_left), Cv::at(level - 1, 2 * index + 1, want_right)]
1266 );
1267 }
1268 }
1269 }
1270 }
1271
1272 #[test]
1277 fn parents_and_the_root_match_official_blake3() {
1278 crate::initialize();
1279 let bytes = painted(32 * 300);
1280 let cvs: Vec<crate::CVBytes> = bytes.as_chunks::<32>().0.to_vec();
1281 for mode in modes() {
1282 let tree = TreeHasher::new(mode);
1283 for pair in cvs[..40].chunks(2) {
1284 let (left, right) = (&pair[0], &pair[1]);
1285 assert_eq!(tree.bare_parent_cv(left, right), official::parent(mode, left, right, false));
1286 assert_eq!(*tree.bare_root_hash(left, right).as_bytes(), official::parent(mode, left, right, true));
1287 let mut out = [0u8; 150];
1288 tree.bare_root_output(left, right).fill(&mut out);
1289 assert_eq!(out[..32], *tree.bare_root_hash(left, right).as_bytes());
1290 assert_ne!(&tree.bare_parent_cv(left, right), tree.bare_root_hash(left, right).as_bytes(), "the root is not a chaining value");
1291 }
1292 for pairs in (0..=40).chain([63, 64, 65, 127, 128, 129, 150]) {
1293 let children = &cvs[..2 * pairs];
1294 let mut out = std::vec![[0u8; 32]; pairs];
1295 tree.bare_parent_cvs_on(tree.platform(), children, &mut out);
1296 for (i, got) in out.iter().enumerate() {
1297 assert_eq!(*got, tree.bare_parent_cv(&children[2 * i], &children[2 * i + 1]), "pair {i} of {pairs}");
1298 }
1299 }
1300 }
1301 }
1302
1303 #[test]
1308 fn a_tree_built_from_its_pieces_gives_the_messages_hash() {
1309 crate::initialize();
1310 fn cv(tree: &TreeHasher, input: &[u8], first_chunk: u64) -> crate::CVBytes {
1311 if input.len() <= 16 * CHUNK_LEN {
1312 return tree.last_cv(first_chunk, input).value;
1313 }
1314 let split = left_len(input.len() as u64) as usize;
1315 let left = cv(tree, &input[..split], first_chunk);
1316 let right = cv(tree, &input[split..], first_chunk + (split / CHUNK_LEN) as u64);
1317 tree.bare_parent_cv(&left, &right)
1318 }
1319 let input = painted((1 << 20) + 7);
1320 for mode in modes() {
1321 let tree = TreeHasher::new(mode).on_this_core();
1322 for len in [1025, 2048, 5000, 16 * 1024, 16 * 1024 + 1, 100_000, 1 << 19, (1 << 19) + 1, (1 << 20) + 7] {
1323 let message = &input[..len];
1324 let split = left_len(len as u64) as usize;
1325 let left = cv(&tree, &message[..split], 0);
1326 let right = cv(&tree, &message[split..], (split / CHUNK_LEN) as u64);
1327 assert_eq!(*tree.bare_root_hash(&left, &right).as_bytes(), crate::test::official::hash(mode, message), "len={len}");
1328 let mut out = [0u8; 200];
1329 tree.bare_root_output(&left, &right).fill(&mut out);
1330 assert_eq!(out.as_slice(), crate::test::official::xof(mode, message, 0, out.len()), "len={len}");
1331 }
1332 }
1333 }
1334
1335 #[test]
1338 fn left_len_is_official_blake3s() {
1339 for power in 0..=40u32 {
1340 let chunks = 1u64 << power;
1341 for len in [chunks * 1024 - 1, chunks * 1024, chunks * 1024 + 1, chunks * 1024 + 1024, chunks * 1536] {
1342 if len > CHUNK_LEN as u64 {
1343 assert_eq!(left_len(len), blake3::hazmat::left_subtree_len(len), "len={len}");
1344 }
1345 }
1346 }
1347 }
1348
1349 #[test]
1350 #[should_panic(expected = "a chunk or less does not split")]
1351 fn left_len_requires_more_than_a_chunk() {
1352 left_len(1024);
1353 }
1354
1355 #[test]
1356 #[should_panic(expected = "the last subtree at chunk 0 holds 1 to")]
1357 fn a_subtree_is_not_empty() {
1358 crate::initialize();
1359 TreeHasher::new(Mode::Plain).last_cv(0, &[]);
1360 }
1361
1362 #[test]
1363 #[should_panic(expected = "the last subtree at chunk 6 holds 1 to 2048 bytes (found 2049)")]
1364 fn a_subtree_is_no_longer_than_its_place_allows() {
1365 crate::initialize();
1366 TreeHasher::new(Mode::Plain).last_cv(6, &[0; 2049]);
1367 }
1368
1369 #[test]
1370 #[should_panic(expected = "a subtree of one chunk has no halves")]
1371 fn the_halves_of_a_chunk_do_not_exist() {
1372 crate::initialize();
1373 TreeHasher::new(Mode::Plain).subtree_halves(0, 0, &[0; 1024]);
1374 }
1375
1376 #[test]
1377 #[should_panic(expected = "a whole subtree at level 1 holds 2048 bytes (found 2047)")]
1378 fn halves_need_the_whole_subtree() {
1379 crate::initialize();
1380 TreeHasher::new(Mode::Plain).subtree_halves(1, 0, &[0; 2047]);
1381 }
1382
1383 #[test]
1384 #[should_panic(expected = "parents take their children in pairs")]
1385 fn a_layer_of_parents_takes_pairs() {
1386 crate::initialize();
1387 let cvs = [[1u8; 32]; 3];
1388 let tree = TreeHasher::new(Mode::Plain);
1389 tree.bare_parent_cvs_on(tree.platform(), &cvs, &mut [[0u8; 32]]);
1390 }
1391
1392 #[test]
1393 #[should_panic(expected = "one parent per pair of children")]
1394 fn a_layer_of_parents_takes_one_output_a_pair() {
1395 crate::initialize();
1396 let cvs = [[1u8; 32]; 4];
1397 let tree = TreeHasher::new(Mode::Plain);
1398 tree.bare_parent_cvs_on(tree.platform(), &cvs, &mut [[0u8; 32]]);
1399 }
1400
1401 #[test]
1406 fn a_whole_message_a_batch_and_a_collection_match_official_blake3() {
1407 crate::initialize();
1408 let input = painted(40 * CHUNK_LEN + 7);
1409 let lens = [0, 1, 63, 64, 65, 1023, 1024, 1025, 2048, 3 * 1024 + 5, 15 * 1024, 16 * 1024 - 1, 16 * 1024, 16 * 1024 + 1, 40 * 1024 + 7];
1410 for mode in modes() {
1411 let want = |message: &[u8]| *official::hasher(mode).update(message).finalize().as_bytes();
1412 for tree in [TreeHasher::new(mode), TreeHasher::new(mode).on_this_core()] {
1413 for len in lens {
1414 assert_eq!(*tree.hash(&input[..len]).as_bytes(), want(&input[..len]), "a message of {len} bytes");
1415 }
1416 for (len, count) in [(1, 1), (32, 300), (64, 3), (64, 40), (100, 17), (1024, 9), (5000, 4), (5000, 20), (16 * 1024, 2)] {
1419 let mut batch = Batch::new(len, count);
1420 for i in 0..count {
1421 batch.set(i, &input[i..i + len]);
1422 }
1423 let mut out = std::vec![[0u8; 32]; count];
1424 tree.hash_many(&batch, &mut out);
1425 for (i, digest) in out.iter().enumerate() {
1426 assert_eq!(*digest, want(&input[i..i + len]), "message {i} of {count} of {len} bytes");
1427 }
1428 }
1429 let mut packed = Packed::<32>::new(50);
1430 for (i, message) in packed.iter_mut().enumerate() {
1431 message.copy_from_slice(&input[i..i + 32]);
1432 }
1433 let mut out = std::vec![[0u8; 32]; 50];
1434 tree.hash_many(&packed, &mut out);
1435 for (i, digest) in out.iter().enumerate() {
1436 assert_eq!(*digest, want(&input[i..i + 32]), "packed message {i}");
1437 }
1438 let blocks: Vec<Vec<Block>> = lens
1442 .iter()
1443 .chain(&lens)
1444 .map(|&len| {
1445 let mut blocks = std::vec![Block([0; 64]); len.div_ceil(64)];
1446 Block::bytes_mut(&mut blocks)[..len].copy_from_slice(&input[..len]);
1447 blocks
1448 })
1449 .collect();
1450 let items: Vec<(&[Block], usize)> = blocks.iter().zip(lens.iter().chain(&lens)).map(|(b, &len)| (&b[..], len)).collect();
1451 let mut out = std::vec![[0u8; 32]; items.len()];
1452 tree.hash_each(&items, &mut out);
1453 for (digest, &len) in out.iter().zip(lens.iter().chain(&lens)) {
1454 assert_eq!(*digest, want(&input[..len]), "an item of {len} bytes");
1455 }
1456 }
1457 }
1458 }
1459
1460 #[test]
1461 #[should_panic(expected = "one digest per item")]
1462 fn a_collection_takes_one_output_an_item() {
1463 crate::initialize();
1464 let block = [Block([0; 64])];
1465 TreeHasher::new(Mode::Plain).hash_each(&[(&block[..], 3), (&block[..], 4)], &mut [[0u8; 32]]);
1466 }
1467
1468 #[test]
1472 fn a_batchs_parts_hash_as_the_batch_does() {
1473 crate::initialize();
1474 let input = painted(64 * 1024);
1475 let tree = TreeHasher::new(Mode::Keyed(&KEY));
1476 let mut batch = Batch::new(100, 9);
1477 let mut packed = Packed::<16>::new(9);
1478 for i in 0..9 {
1479 batch.set(i, &input[i..i + 100]);
1480 packed[i].copy_from_slice(&input[i..i + 16]);
1481 }
1482 let (mut whole, mut whole_packed) = ([[0u8; 32]; 9], [[0u8; 32]; 9]);
1483 tree.hash_many(&batch, &mut whole);
1484 tree.hash_many(&packed, &mut whole_packed);
1485 for cut in 0..=9 {
1486 let (mut parts, mut parts_packed) = ([[0u8; 32]; 9], [[0u8; 32]; 9]);
1487 tree.hash_many(&batch.part(0..cut), &mut parts[..cut]);
1488 tree.hash_many(&batch.part(cut..9), &mut parts[cut..]);
1489 tree.hash_many(&packed.part(0..cut), &mut parts_packed[..cut]);
1490 tree.hash_many(&packed.part(1.min(cut)..9).part(cut - 1.min(cut)..9 - 1.min(cut)), &mut parts_packed[cut..]);
1492 assert_eq!((whole, whole_packed), (parts, parts_packed), "cut at {cut}");
1493 }
1494 for level in [0, 1, 4, 6] {
1495 let len = 1024 << level;
1496 let turn = crate::platform::Sme2Turn::acquire();
1498 let under = tree.subtree_cv_under(&turn, level, 64 >> level, &input[..len]);
1499 let pinned = tree.clone().on_this_core().subtree_cv_under(&turn, level, 64 >> level, &input[..len]);
1500 drop(turn);
1501 assert!(under == pinned, "pinned subtree_cv_under matches unpinned at {len} bytes");
1502 assert!(under == tree.subtree_cv(level, 64 >> level, &input[..len]), "{len} bytes");
1503 assert_eq!(*under.as_bytes(), official::subtree_cv(Mode::Keyed(&KEY), 64, &input[..len]), "{len} bytes");
1504 }
1505 {
1507 let turn = crate::platform::Sme2Turn::acquire();
1508 assert!(
1509 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| tree.subtree_cv_under(&turn, 3, 0, &input[..7 * 1024]))).is_err(),
1510 "subtree_cv_under must reject a short subtree"
1511 );
1512 }
1513 #[cfg(target_arch = "aarch64")]
1517 if matches!(crate::platform::Platform::detect(), crate::platform::Platform::SME2) {
1518 let sme2_entries: std::vec::Vec<usize> = crate::sme2::entries().into_iter().map(|(_, p)| p as usize).collect();
1519 let ran_sme2 = || crate::RAN_ENTRIES.with(|e| e.borrow().iter().any(|p| sme2_entries.contains(p)));
1520 let turn = crate::platform::Sme2Turn::acquire();
1521 assert!(turn.is_sme2());
1522 crate::RAN_ENTRIES.with(|e| e.borrow_mut().clear());
1523 let _ = tree.subtree_cv_under(&turn, 6, 0, &input[..64 * 1024]);
1524 assert!(ran_sme2(), "unpinned subtree_cv_under with granted turn must use SME2");
1525
1526 crate::RAN_ENTRIES.with(|e| e.borrow_mut().clear());
1527 let _ = tree.clone().on_this_core().subtree_cv_under(&turn, 6, 0, &input[..64 * 1024]);
1528 assert!(!ran_sme2(), "on_this_core().subtree_cv_under must stay on NEON");
1529
1530 let contended = crate::platform::Sme2Turn::acquire();
1531 assert!(!contended.is_sme2());
1532 crate::RAN_ENTRIES.with(|e| e.borrow_mut().clear());
1533 let _ = tree.subtree_cv_under(&contended, 6, 0, &input[..64 * 1024]);
1534 assert!(!ran_sme2(), "subtree_cv_under with contended turn must stay on NEON");
1535 drop(contended);
1536 drop(turn);
1537 }
1538 }
1539
1540 #[test]
1541 #[should_panic(expected = "lies within the batch")]
1542 fn a_part_lies_within_its_batch() {
1543 let batch = Batch::new(100, 9);
1544 let _ = batch.part(3..10);
1545 }
1546
1547 #[test]
1548 #[should_panic(expected = "lies within the batch")]
1549 fn a_part_runs_forward() {
1550 let batch = Batch::new(100, 9);
1551 #[allow(clippy::reversed_empty_ranges)]
1552 let _ = batch.part(3..2);
1553 }
1554
1555 #[cfg(target_arch = "aarch64")]
1556 #[test]
1557 fn parent_cvs_and_hash_each_honor_a_held_sme2_turn() {
1558 crate::initialize();
1559 if !matches!(crate::platform::Platform::detect(), crate::platform::Platform::SME2) {
1560 return;
1561 }
1562 let tree = TreeHasher::new(Mode::Plain);
1563 let input = painted(32 * CHUNK_LEN);
1565 let children: std::vec::Vec<Cv> = (0..32).map(|i| tree.subtree_cv(0, i as u64, &input[i * CHUNK_LEN..(i + 1) * CHUNK_LEN])).collect();
1566 let mut expected_parents = std::vec![Cv::unset(); 16];
1567 tree.clone().on_this_core().parent_cvs(&children, &mut expected_parents);
1568
1569 let mut blocks = Batch::new(2 * CHUNK_LEN, 16);
1571 for i in 0..16 {
1572 blocks.message_mut(i).copy_from_slice(&input[i * 37..i * 37 + 2 * CHUNK_LEN]);
1573 }
1574 let items: std::vec::Vec<(&[Block], usize)> = (0..16).map(|i| (&blocks.blocks()[i * 32..(i + 1) * 32], 2 * CHUNK_LEN)).collect();
1575 let mut expected_each = std::vec![[0u8; OUT_LEN]; 16];
1576 tree.clone().on_this_core().hash_each(&items, &mut expected_each);
1577 let big_raw: std::vec::Vec<std::vec::Vec<u8>> = (0..3).map(|k| (0..15 * CHUNK_LEN).map(|i| ((i + k * 29) & 0xff) as u8).collect()).collect();
1581 let big_slices: std::vec::Vec<&[u8]> = big_raw.iter().map(|v| v.as_slice()).collect();
1582 let big_blocks = crate::test::messages(&big_slices);
1583 let items_3x15k: std::vec::Vec<(&[Block], usize)> = big_blocks.iter().map(|b| (b.as_slice(), 15 * CHUNK_LEN)).collect();
1584 let items_16_pairs: std::vec::Vec<(&[Block], usize)> =
1585 std::vec![(big_blocks[0].as_slice(), 15 * CHUNK_LEN), (big_blocks[1].as_slice(), 15 * CHUNK_LEN), (&big_blocks[2][..64], 4 * CHUNK_LEN)];
1586 let items_15_pairs: std::vec::Vec<(&[Block], usize)> = std::vec![
1587 (&big_blocks[0][..176], 11 * CHUNK_LEN),
1588 (&big_blocks[1][..176], 11 * CHUNK_LEN),
1589 (&big_blocks[2][..176], 11 * CHUNK_LEN),
1590 (&big_blocks[0][..32], 2 * CHUNK_LEN),
1591 ];
1592 let mut expected_3x15k = [[0u8; OUT_LEN]; 3];
1593 let mut expected_16_pairs = [[0u8; OUT_LEN]; 3];
1594 let mut expected_15_pairs = [[0u8; OUT_LEN]; 4];
1595 tree.clone().on_this_core().hash_each(&items_3x15k, &mut expected_3x15k);
1596 tree.clone().on_this_core().hash_each(&items_16_pairs, &mut expected_16_pairs);
1597 tree.clone().on_this_core().hash_each(&items_15_pairs, &mut expected_15_pairs);
1598 let tmpl = [0x5au8; 52];
1599 let mut expected_counter = std::vec![[0u8; OUT_LEN]; 18];
1600 tree.clone().on_this_core().hash_counter_range(&tmpl, 12, 7, &mut expected_counter);
1601 let chain_init: [[u8; 32]; 18] = core::array::from_fn(|i| [0x33u8.wrapping_add(i as u8); 32]);
1602 let mut got_chain = [[0u8; 16]; 18];
1603 let mut expected_chain = [[0u8; 16]; 18];
1604 tree.clone().on_this_core().hash_chains_32_trunc16(&chain_init, 3, &mut expected_chain);
1605 let chain_steps_small = [63u32; 18]; let chain_steps_large = [64u32; 18]; let mut expected_chain_large = [[0u8; 16]; 18];
1608 tree.clone().on_this_core().hash_chains_varlen_32_trunc16(&chain_init, &chain_steps_large, &mut expected_chain_large);
1609
1610 let mut held = None;
1612 for _ in 0..10_000 {
1613 let t = crate::platform::Sme2Turn::take(crate::platform::Platform::SME2, true);
1614 if matches!(t.platform(), crate::platform::Platform::SME2) {
1615 held = Some(t);
1616 break;
1617 }
1618 std::thread::yield_now();
1619 }
1620 let held = held.expect("failed to acquire SME2 turn within bounded retries");
1621 let parents_fn = crate::sme2::ffi::blake3_servil_sme2_hash16_parents_512 as *const () as usize;
1622 let messages_fn = crate::sme2::ffi::blake3_servil_sme2_hash16_messages_512 as *const () as usize;
1623
1624 let mut got_parents = std::vec![Cv::unset(); 16];
1627 let mut got_each = std::vec![[0u8; OUT_LEN]; 16];
1628 let mut got_counter = std::vec![[0u8; OUT_LEN]; 18];
1629 let mut got_counter16 = std::vec![[0u8; 16]; 18];
1630 let mut got_find = [(0u32, [0u8; OUT_LEN]); 1];
1631 crate::RAN.with(|r| r.set(0));
1632 crate::RAN_ENTRIES.with(|r| r.borrow_mut().clear());
1633 tree.parent_cvs(&children[..30], &mut got_parents[..15]);
1634 assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "15 parent pairs must not try to take the SME2 turn");
1635 tree.hash_each(&items[..15], &mut got_each[..15]);
1636 assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "15 two-chunk messages must not try to take the SME2 turn");
1637 let mut got_3 = [[0u8; OUT_LEN]; 3];
1638 let mut got_4 = [[0u8; OUT_LEN]; 4];
1639 tree.hash_each(&items_15_pairs, &mut got_4);
1640 assert_eq!(
1641 crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32,
1642 0,
1643 "3 x 11 KiB + 1 x 2 KiB (15 parent pairs) must not try to take the SME2 turn"
1644 );
1645 assert_eq!(got_4, expected_15_pairs);
1646 tree.hash_counter_range(&tmpl, 12, 7, &mut got_counter[..17]);
1647 assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "17 TreeHasher counters must not try to take the SME2 turn");
1648 assert_eq!(&got_counter[..17], &expected_counter[..17]);
1649 hash_counter_range(Mode::Plain, &tmpl, 12, 7, &mut got_counter[..17]);
1650 assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "17 free counters must not try to take the SME2 turn");
1651 tree.hash_counter_range_trunc16(&tmpl, 12, 7, &mut got_counter16[..17]);
1652 assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "17 TreeHasher trunc16 counters must not try to take the SME2 turn");
1653 hash_counter_range_trunc16(Mode::Plain, &tmpl, 12, 7, &mut got_counter16[..17]);
1654 assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "17 free trunc16 counters must not try to take the SME2 turn");
1655 let _ = tree.find_counter_range(&tmpl, 12, 7, 17, u32::MAX, 0, &mut got_find);
1656 assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "17 TreeHasher find counters must not try to take the SME2 turn");
1657 let _ = find_counter_range(Mode::Plain, &tmpl, 12, 7, 17, u32::MAX, 0, &mut got_find);
1658 assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "17 free find counters must not try to take the SME2 turn");
1659 tree.hash_chains_32_trunc16(&chain_init[..17], 3, &mut got_chain[..17]);
1660 assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "17 fixed chains must not try to take the SME2 turn");
1661 tree.hash_chains_32_trunc16(&chain_init, 0, &mut got_chain);
1662 assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "0-step fixed chains must not try to take the SME2 turn");
1663 tree.hash_chains_varlen_32_trunc16(&chain_init, &chain_steps_small, &mut got_chain);
1664 assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "subthreshold varlen chains must not try to take the SME2 turn");
1665 assert_eq!(&got_parents[..15], &expected_parents[..15]);
1666 assert_eq!(&got_each[..15], &expected_each[..15]);
1667 assert_eq!(&got_counter[..17], &expected_counter[..17]);
1668
1669 crate::RAN.with(|r| r.set(0));
1672 crate::RAN_ENTRIES.with(|r| r.borrow_mut().clear());
1673 tree.parent_cvs(&children, &mut got_parents);
1674 assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "16 parent pairs must consult the SME2 turn");
1675 crate::RAN.with(|r| r.set(0));
1676 tree.hash_each(&items, &mut got_each);
1677 assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "16 two-chunk messages must consult the SME2 turn");
1678 crate::RAN.with(|r| r.set(0));
1679 tree.hash_each(&items_16_pairs, &mut got_3);
1680 assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "16 first-round parent pairs must consult the SME2 turn");
1681 assert_eq!(got_3, expected_16_pairs);
1682 crate::RAN.with(|r| r.set(0));
1683 tree.hash_each(&items_3x15k, &mut got_3);
1684 assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "3 x 15 KiB (21 parent pairs) must consult the SME2 turn");
1685 assert_eq!(got_3, expected_3x15k);
1686 crate::RAN.with(|r| r.set(0));
1687 tree.hash_counter_range(&tmpl, 12, 7, &mut got_counter);
1688 assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "18 TreeHasher counters must consult the SME2 turn");
1689 assert_eq!(got_counter, expected_counter);
1690 crate::RAN.with(|r| r.set(0));
1691 tree.hash_chains_32_trunc16(&chain_init, 3, &mut got_chain);
1692 assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "18 fixed chains must consult the SME2 turn");
1693 assert_eq!(got_chain, expected_chain);
1694 crate::RAN.with(|r| r.set(0));
1695 hash_chains_32_trunc16(Mode::Plain, &chain_init, 3, &mut got_chain);
1696 assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "18 free fixed chains must consult the SME2 turn");
1697 assert_eq!(got_chain, expected_chain);
1698 crate::RAN.with(|r| r.set(0));
1699 tree.hash_chains_varlen_32_trunc16(&chain_init, &chain_steps_large, &mut got_chain);
1700 assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "eligible varlen chains must consult the SME2 turn");
1701 assert_eq!(got_chain, expected_chain_large);
1702 crate::RAN.with(|r| r.set(0));
1703 hash_counter_range(Mode::Plain, &tmpl, 12, 7, &mut got_counter);
1704 assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "18 free counters must consult the SME2 turn");
1705 assert_eq!(got_counter, expected_counter);
1706 crate::RAN.with(|r| r.set(0));
1707 tree.hash_counter_range_trunc16(&tmpl, 12, 7, &mut got_counter16);
1708 assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "18 TreeHasher trunc16 counters must consult the SME2 turn");
1709 crate::RAN.with(|r| r.set(0));
1710 hash_counter_range_trunc16(Mode::Plain, &tmpl, 12, 7, &mut got_counter16);
1711 assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "18 free trunc16 counters must consult the SME2 turn");
1712 crate::RAN.with(|r| r.set(0));
1713 let _ = tree.find_counter_range(&tmpl, 12, 7, 18, u32::MAX, 0, &mut got_find);
1714 assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "18 TreeHasher find counters must consult the SME2 turn");
1715 crate::RAN.with(|r| r.set(0));
1716 let _ = find_counter_range(Mode::Plain, &tmpl, 12, 7, 18, u32::MAX, 0, &mut got_find);
1717 assert_ne!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "18 free find counters must consult the SME2 turn");
1718 crate::RAN_ENTRIES.with(|r| {
1719 let ran = r.borrow();
1720 assert!(!ran.contains(&parents_fn), "parent_cvs bypassed a held SME2 turn");
1721 assert!(!ran.contains(&messages_fn), "hash_each bypassed a held SME2 turn");
1722 });
1723 assert_eq!(got_parents, expected_parents);
1724 assert_eq!(got_each, expected_each);
1725 drop(held);
1726
1727 crate::RAN.with(|r| r.set(0));
1730 crate::RAN_ENTRIES.with(|r| r.borrow_mut().clear());
1731 tree.parent_cvs(&children, &mut got_parents);
1732 tree.hash_each(&items, &mut got_each);
1733 assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "SME2 turn must be free after dropping held guard");
1734 let ran = crate::RAN_ENTRIES.with(|r| r.borrow().clone());
1735 assert!(ran.contains(&parents_fn), "16 parent pairs should enter SME2 when turn is free");
1736 assert!(ran.contains(&messages_fn), "16 two-chunk messages should enter SME2 when turn is free");
1737 assert_eq!(got_parents, expected_parents);
1738 assert_eq!(got_each, expected_each);
1739
1740 crate::RAN.with(|r| r.set(0));
1742 crate::RAN_ENTRIES.with(|r| r.borrow_mut().clear());
1743 tree.hash_each(&items_3x15k, &mut got_3);
1744 assert_eq!(crate::RAN.with(|r| r.get()) & crate::Ran::TurnTaken as u32, 0, "SME2 turn must be free for 3 x 15 KiB");
1745 let ran_3x15k = crate::RAN_ENTRIES.with(|r| r.borrow().clone());
1746 assert!(ran_3x15k.contains(&parents_fn), "3 x 15 KiB (21 parent pairs) should enter SME2 parents when turn is free");
1747 assert_eq!(got_3, expected_3x15k);
1748 }
1749
1750 #[test]
1751 fn tree_hasher_short_and_boundary_inputs_match_official() {
1752 crate::initialize();
1753 let key = [0x3du8; 32];
1754 let ctx = "blake3-servil tree hasher single-block fast path";
1755 let mut buf = std::vec![0u8; 1025];
1756 for (i, b) in buf.iter_mut().enumerate() {
1757 *b = ((i.wrapping_mul(41) ^ 0x5c) & 0xff) as u8;
1758 }
1759 for mode in [Mode::Plain, Mode::Keyed(&key), Mode::DeriveKey(ctx)] {
1760 let tree = TreeHasher::new(mode);
1761 let local = TreeHasher::new(mode).on_this_core();
1762 for len in (0usize..=65).chain([127, 128, 1023, 1024, 1025]) {
1763 let slice = &buf[..len];
1764 let want = crate::test::official::hash(mode, slice);
1765 assert_eq!(*tree.hash(slice).as_bytes(), want, "TreeHasher::hash len={len}");
1766 assert_eq!(*local.hash(slice).as_bytes(), want, "TreeHasher::on_this_core().hash len={len}");
1767 }
1768 }
1769 for (label, tree) in [("default", TreeHasher::new(Mode::Keyed(&key))), ("on_this_core", TreeHasher::new(Mode::Keyed(&key)).on_this_core())] {
1774 for short_len in [48usize, crate::BLOCK_LEN] {
1775 #[cfg(target_arch = "aarch64")]
1776 TREE_HASH_LONG_CALLS.with(|c| c.set(0));
1777 crate::RAN_ENTRIES.with(|r| r.borrow_mut().clear());
1778 crate::RAN_KERNEL_CALLS.with(|c| c.set(0));
1779 let _ = tree.hash(&buf[..short_len]);
1780 assert_eq!(crate::RAN_KERNEL_CALLS.with(|c| c.get()), 1, "{label} len={short_len} must invoke exactly one kernel");
1781 let ran = crate::RAN_ENTRIES.with(|r| r.borrow().clone());
1782 assert_eq!(ran.len(), 1, "{label} len={short_len} must run a single root kernel: {ran:?}");
1783 #[cfg(target_arch = "aarch64")]
1784 {
1785 let c1_entry = crate::neon_hybrid::entries()
1786 .into_iter()
1787 .find_map(|(name, addr)| (name == "c1").then_some(addr as usize))
1788 .expect("neon_hybrid::entries must list c1");
1789 assert_eq!(TREE_HASH_LONG_CALLS.with(|c| c.get()), 0, "{label} len={short_len} must bypass hash_long");
1790 assert!(ran.contains(&c1_entry), "{label} len={short_len} must dispatch directly to c1");
1791 }
1792 }
1793
1794 #[cfg(target_arch = "aarch64")]
1795 {
1796 TREE_HASH_LONG_CALLS.with(|c| c.set(0));
1797 let _ = tree.hash(&buf[..crate::BLOCK_LEN + 1]);
1798 assert_eq!(TREE_HASH_LONG_CALLS.with(|c| c.get()), 1, "{label} len=65 must enter hash_long");
1799 }
1800 }
1801 }
1802}
1803
1804#[cfg(all(test, target_arch = "aarch64"))]
1805std::thread_local! {
1806 static TREE_HASH_LONG_CALLS: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
1807}