Debian Codegraph @

debian/rust-vendor/blake3/src/test.rs

raw
1 use crate::{BLOCK_LEN, CHUNK_LEN, CVBytes, CVWords, IncrementCounter, OUT_LEN};
2 use arrayvec::ArrayVec;
3 use rand::prelude::*;
4
5 // Interesting input lengths to run tests on.
6 pub const TEST_CASES: &[usize] = &[
7 0,
8 1,
9 2,
10 3,
11 4,
12 5,
13 6,
14 7,
15 8,
16 BLOCK_LEN - 1,
17 BLOCK_LEN,
18 BLOCK_LEN + 1,
19 2 * BLOCK_LEN - 1,
20 2 * BLOCK_LEN,
21 2 * BLOCK_LEN + 1,
22 CHUNK_LEN - 1,
23 CHUNK_LEN,
24 CHUNK_LEN + 1,
25 2 * CHUNK_LEN,
26 2 * CHUNK_LEN + 1,
27 3 * CHUNK_LEN,
28 3 * CHUNK_LEN + 1,
29 4 * CHUNK_LEN,
30 4 * CHUNK_LEN + 1,
31 5 * CHUNK_LEN,
32 5 * CHUNK_LEN + 1,
33 6 * CHUNK_LEN,
34 6 * CHUNK_LEN + 1,
35 7 * CHUNK_LEN,
36 7 * CHUNK_LEN + 1,
37 8 * CHUNK_LEN,
38 8 * CHUNK_LEN + 1,
39 16 * CHUNK_LEN - 1,
40 16 * CHUNK_LEN, // AVX512's bandwidth
41 16 * CHUNK_LEN + 1,
42 31 * CHUNK_LEN - 1,
43 31 * CHUNK_LEN, // 16 + 8 + 4 + 2 + 1
44 31 * CHUNK_LEN + 1,
45 100 * CHUNK_LEN, // subtrees larger than MAX_SIMD_DEGREE chunks
46 ];
47
48 pub const TEST_CASES_MAX: usize = 100 * CHUNK_LEN;
49
50 // There's a test to make sure these two are equal below.
51 pub const TEST_KEY: CVBytes = *b"whats the Elvish word for friend";
52 pub const TEST_KEY_WORDS: CVWords = [
53 1952540791, 1752440947, 1816469605, 1752394102, 1919907616, 1868963940, 1919295602, 1684956521,
54 ];
55
56 // Paint the input with a repeating byte pattern. We use a cycle length of 251,
57 // because that's the largest prime number less than 256. This makes it
58 // unlikely to swapping any two adjacent input blocks or chunks will give the
59 // same answer.
60 pub fn paint_test_input(buf: &mut [u8]) {
61 for (i, b) in buf.iter_mut().enumerate() {
62 *b = (i % 251) as u8;
63 }
64 }
65
66 type CompressInPlaceFn =
67 unsafe fn(cv: &mut CVWords, block: &[u8; BLOCK_LEN], block_len: u8, counter: u64, flags: u8);
68
69 type CompressXofFn = unsafe fn(
70 cv: &CVWords,
71 block: &[u8; BLOCK_LEN],
72 block_len: u8,
73 counter: u64,
74 flags: u8,
75 ) -> [u8; 64];
76
77 // A shared helper function for platform-specific tests.
78 pub fn test_compress_fn(compress_in_place_fn: CompressInPlaceFn, compress_xof_fn: CompressXofFn) {
79 let initial_state = TEST_KEY_WORDS;
80 let block_len: u8 = 61;
81 let mut block = [0; BLOCK_LEN];
82 paint_test_input(&mut block[..block_len as usize]);
83 // Use a counter with set bits in both 32-bit words.
84 let counter = (5u64 << 32) + 6;
85 let flags = crate::CHUNK_END | crate::ROOT | crate::KEYED_HASH;
86
87 let portable_out =
88 crate::portable::compress_xof(&initial_state, &block, block_len, counter as u64, flags);
89
90 let mut test_state = initial_state;
91 unsafe { compress_in_place_fn(&mut test_state, &block, block_len, counter as u64, flags) };
92 let test_state_bytes = crate::platform::le_bytes_from_words_32(&test_state);
93 let test_xof =
94 unsafe { compress_xof_fn(&initial_state, &block, block_len, counter as u64, flags) };
95
96 assert_eq!(&portable_out[..32], &test_state_bytes[..]);
97 assert_eq!(&portable_out[..], &test_xof[..]);
98 }
99
100 type HashManyFn<A> = unsafe fn(
101 inputs: &[&A],
102 key: &CVWords,
103 counter: u64,
104 increment_counter: IncrementCounter,
105 flags: u8,
106 flags_start: u8,
107 flags_end: u8,
108 out: &mut [u8],
109 );
110
111 // A shared helper function for platform-specific tests.
112 pub fn test_hash_many_fn(
113 hash_many_chunks_fn: HashManyFn<[u8; CHUNK_LEN]>,
114 hash_many_parents_fn: HashManyFn<[u8; 2 * OUT_LEN]>,
115 ) {
116 // Test a few different initial counter values.
117 // - 0: The base case.
118 // - u32::MAX: The low word of the counter overflows for all inputs except the first.
119 // - i32::MAX: *No* overflow. But carry bugs in tricky SIMD code can screw this up, if you XOR
120 // when you're supposed to ANDNOT...
121 let initial_counters = [0, u32::MAX as u64, i32::MAX as u64];
122 for counter in initial_counters {
123 #[cfg(feature = "std")]
124 dbg!(counter);
125
126 // 31 (16 + 8 + 4 + 2 + 1) inputs
127 const NUM_INPUTS: usize = 31;
128 let mut input_buf = [0; CHUNK_LEN * NUM_INPUTS];
129 crate::test::paint_test_input(&mut input_buf);
130
131 // First hash chunks.
132 let mut chunks = ArrayVec::<&[u8; CHUNK_LEN], NUM_INPUTS>::new();
133 for i in 0..NUM_INPUTS {
134 chunks.push(
135 (&input_buf[i * CHUNK_LEN..][..CHUNK_LEN])
136 .try_into()
137 .unwrap(),
138 );
139 }
140 let mut portable_chunks_out = [0; NUM_INPUTS * OUT_LEN];
141 crate::portable::hash_many(
142 &chunks,
143 &TEST_KEY_WORDS,
144 counter,
145 IncrementCounter::Yes,
146 crate::KEYED_HASH,
147 crate::CHUNK_START,
148 crate::CHUNK_END,
149 &mut portable_chunks_out,
150 );
151
152 let mut test_chunks_out = [0; NUM_INPUTS * OUT_LEN];
153 unsafe {
154 hash_many_chunks_fn(
155 &chunks[..],
156 &TEST_KEY_WORDS,
157 counter,
158 IncrementCounter::Yes,
159 crate::KEYED_HASH,
160 crate::CHUNK_START,
161 crate::CHUNK_END,
162 &mut test_chunks_out,
163 );
164 }
165 for n in 0..NUM_INPUTS {
166 #[cfg(feature = "std")]
167 dbg!(n);
168 assert_eq!(
169 &portable_chunks_out[n * OUT_LEN..][..OUT_LEN],
170 &test_chunks_out[n * OUT_LEN..][..OUT_LEN]
171 );
172 }
173
174 // Then hash parents.
175 let mut parents = ArrayVec::<&[u8; 2 * OUT_LEN], NUM_INPUTS>::new();
176 for i in 0..NUM_INPUTS {
177 parents.push(
178 (&input_buf[i * 2 * OUT_LEN..][..2 * OUT_LEN])
179 .try_into()
180 .unwrap(),
181 );
182 }
183 let mut portable_parents_out = [0; NUM_INPUTS * OUT_LEN];
184 crate::portable::hash_many(
185 &parents,
186 &TEST_KEY_WORDS,
187 counter,
188 IncrementCounter::No,
189 crate::KEYED_HASH | crate::PARENT,
190 0,
191 0,
192 &mut portable_parents_out,
193 );
194
195 let mut test_parents_out = [0; NUM_INPUTS * OUT_LEN];
196 unsafe {
197 hash_many_parents_fn(
198 &parents[..],
199 &TEST_KEY_WORDS,
200 counter,
201 IncrementCounter::No,
202 crate::KEYED_HASH | crate::PARENT,
203 0,
204 0,
205 &mut test_parents_out,
206 );
207 }
208 for n in 0..NUM_INPUTS {
209 #[cfg(feature = "std")]
210 dbg!(n);
211 assert_eq!(
212 &portable_parents_out[n * OUT_LEN..][..OUT_LEN],
213 &test_parents_out[n * OUT_LEN..][..OUT_LEN]
214 );
215 }
216 }
217 }
218
219 #[allow(unused)]
220 type XofManyFunction = unsafe fn(
221 cv: &CVWords,
222 block: &[u8; BLOCK_LEN],
223 block_len: u8,
224 counter: u64,
225 flags: u8,
226 out: &mut [u8],
227 );
228
229 // A shared helper function for platform-specific tests.
230 #[allow(unused)]
231 pub fn test_xof_many_fn(xof_many_function: XofManyFunction) {
232 let mut block = [0; BLOCK_LEN];
233 let block_len = 42;
234 crate::test::paint_test_input(&mut block[..block_len]);
235 let cv = [40, 41, 42, 43, 44, 45, 46, 47];
236 let flags = crate::KEYED_HASH;
237
238 // Test a few different initial counter values.
239 // - 0: The base case.
240 // - u32::MAX: The low word of the counter overflows for all inputs except the first.
241 // - i32::MAX: *No* overflow. But carry bugs in tricky SIMD code can screw this up, if you XOR
242 // when you're supposed to ANDNOT...
243 let initial_counters = [0, u32::MAX as u64, i32::MAX as u64];
244 for counter in initial_counters {
245 #[cfg(feature = "std")]
246 dbg!(counter);
247
248 // 31 (16 + 8 + 4 + 2 + 1) outputs
249 const OUTPUT_SIZE: usize = 31 * BLOCK_LEN;
250
251 let mut portable_out = [0u8; OUTPUT_SIZE];
252 for (i, out_block) in portable_out.chunks_exact_mut(64).enumerate() {
253 out_block.copy_from_slice(&crate::portable::compress_xof(
254 &cv,
255 &block,
256 block_len as u8,
257 counter + i as u64,
258 flags,
259 ));
260 }
261
262 let mut test_out = [0u8; OUTPUT_SIZE];
263 unsafe {
264 xof_many_function(&cv, &block, block_len as u8, counter, flags, &mut test_out);
265 }
266
267 assert_eq!(portable_out, test_out);
268 }
269
270 // Test that xof_many doesn't write more blocks than requested. Note that the current assembly
271 // implementation always outputs at least one block, so we don't test the zero case.
272 for block_count in 1..=32 {
273 let mut array = [0; BLOCK_LEN * 33];
274 let output_start = 17;
275 let output_len = block_count * BLOCK_LEN;
276 let output_end = output_start + output_len;
277 let output = &mut array[output_start..output_end];
278 unsafe {
279 xof_many_function(&cv, &block, block_len as u8, 0, flags, output);
280 }
281 for i in 0..array.len() {
282 if i < output_start || output_end <= i {
283 assert_eq!(0, array[i], "index {i}");
284 }
285 }
286 }
287 }
288
289 #[test]
290 fn test_key_bytes_equal_key_words() {
291 assert_eq!(
292 TEST_KEY_WORDS,
293 crate::platform::words_from_le_bytes_32(&TEST_KEY),
294 );
295 }
296
297 #[test]
298 fn test_reference_impl_size() {
299 // Because the Rust compiler optimizes struct layout, it's possible that
300 // some future version of the compiler will produce a different size. If
301 // that happens, we can either disable this test, or test for multiple
302 // expected values. For now, the purpose of this test is to make sure we
303 // notice if that happens.
304 assert_eq!(1880, core::mem::size_of::<reference_impl::Hasher>());
305 }
306
307 #[test]
308 fn test_counter_words() {
309 let counter: u64 = (1 << 32) + 2;
310 assert_eq!(crate::counter_low(counter), 2);
311 assert_eq!(crate::counter_high(counter), 1);
312 }
313
314 #[test]
315 fn test_largest_power_of_two_leq() {
316 let input_output = &[
317 // The zero case is nonsensical, but it does work.
318 (0, 1),
319 (1, 1),
320 (2, 2),
321 (3, 2),
322 (4, 4),
323 (5, 4),
324 (6, 4),
325 (7, 4),
326 (8, 8),
327 // the largest possible usize
328 (usize::MAX, (usize::MAX >> 1) + 1),
329 ];
330 for &(input, output) in input_output {
331 assert_eq!(
332 output,
333 crate::largest_power_of_two_leq(input),
334 "wrong output for n={}",
335 input
336 );
337 }
338 }
339
340 #[test]
341 fn test_compare_reference_impl() {
342 const OUT: usize = 303; // more than 64, not a multiple of 4
343 let mut input_buf = [0; TEST_CASES_MAX];
344 paint_test_input(&mut input_buf);
345 for &case in TEST_CASES {
346 let input = &input_buf[..case];
347 #[cfg(feature = "std")]
348 dbg!(case);
349
350 // regular
351 {
352 let mut reference_hasher = reference_impl::Hasher::new();
353 reference_hasher.update(input);
354 let mut expected_out = [0; OUT];
355 reference_hasher.finalize(&mut expected_out);
356
357 // all at once
358 let test_out = crate::hash(input);
359 assert_eq!(
360 test_out,
361 *<&[u8; 32]>::try_from(&expected_out[..32]).unwrap()
362 );
363 // incremental
364 let mut hasher = crate::Hasher::new();
365 hasher.update(input);
366 assert_eq!(
367 hasher.finalize(),
368 *<&[u8; 32]>::try_from(&expected_out[..32]).unwrap()
369 );
370 assert_eq!(hasher.finalize(), test_out);
371 // incremental (rayon)
372 #[cfg(feature = "rayon")]
373 {
374 let mut hasher = crate::Hasher::new();
375 hasher.update_rayon(input);
376 assert_eq!(
377 hasher.finalize(),
378 *<&[u8; 32]>::try_from(&expected_out[..32]).unwrap()
379 );
380 assert_eq!(hasher.finalize(), test_out);
381 }
382 // xof
383 let mut extended = [0; OUT];
384 hasher.finalize_xof().fill(&mut extended);
385 assert_eq!(extended, expected_out);
386 }
387
388 // keyed
389 {
390 let mut reference_hasher = reference_impl::Hasher::new_keyed(&TEST_KEY);
391 reference_hasher.update(input);
392 let mut expected_out = [0; OUT];
393 reference_hasher.finalize(&mut expected_out);
394
395 // all at once
396 let test_out = crate::keyed_hash(&TEST_KEY, input);
397 assert_eq!(
398 test_out,
399 *<&[u8; 32]>::try_from(&expected_out[..32]).unwrap()
400 );
401 // incremental
402 let mut hasher = crate::Hasher::new_keyed(&TEST_KEY);
403 hasher.update(input);
404 assert_eq!(
405 hasher.finalize(),
406 *<&[u8; 32]>::try_from(&expected_out[..32]).unwrap()
407 );
408 assert_eq!(hasher.finalize(), test_out);
409 // incremental (rayon)
410 #[cfg(feature = "rayon")]
411 {
412 let mut hasher = crate::Hasher::new_keyed(&TEST_KEY);
413 hasher.update_rayon(input);
414 assert_eq!(
415 hasher.finalize(),
416 *<&[u8; 32]>::try_from(&expected_out[..32]).unwrap()
417 );
418 assert_eq!(hasher.finalize(), test_out);
419 }
420 // xof
421 let mut extended = [0; OUT];
422 hasher.finalize_xof().fill(&mut extended);
423 assert_eq!(extended, expected_out);
424 }
425
426 // derive_key
427 {
428 let context = "BLAKE3 2019-12-27 16:13:59 example context (not the test vector one)";
429 let mut reference_hasher = reference_impl::Hasher::new_derive_key(context);
430 reference_hasher.update(input);
431 let mut expected_out = [0; OUT];
432 reference_hasher.finalize(&mut expected_out);
433
434 // all at once
435 let test_out = crate::derive_key(context, input);
436 assert_eq!(test_out, expected_out[..32]);
437 // incremental
438 let mut hasher = crate::Hasher::new_derive_key(context);
439 hasher.update(input);
440 assert_eq!(
441 hasher.finalize(),
442 *<&[u8; 32]>::try_from(&expected_out[..32]).unwrap()
443 );
444 assert_eq!(
445 hasher.finalize(),
446 *<&[u8; 32]>::try_from(&test_out[..32]).unwrap()
447 );
448 // incremental (rayon)
449 #[cfg(feature = "rayon")]
450 {
451 let mut hasher = crate::Hasher::new_derive_key(context);
452 hasher.update_rayon(input);
453 assert_eq!(
454 hasher.finalize(),
455 *<&[u8; 32]>::try_from(&expected_out[..32]).unwrap()
456 );
457 assert_eq!(
458 hasher.finalize(),
459 *<&[u8; 32]>::try_from(&test_out[..32]).unwrap()
460 );
461 }
462 // xof
463 let mut extended = [0; OUT];
464 hasher.finalize_xof().fill(&mut extended);
465 assert_eq!(extended, expected_out);
466 }
467 }
468 }
469
470 #[test]
471 fn test_compare_reference_impl_long_xof() {
472 let mut reference_output = [0u8; 32 * BLOCK_LEN - 1];
473 let mut reference_hasher = reference_impl::Hasher::new_keyed(&TEST_KEY);
474 reference_hasher.update(b"hello world");
475 reference_hasher.finalize(&mut reference_output);
476
477 let mut test_output = [0u8; 32 * BLOCK_LEN - 1];
478 let mut test_hasher = crate::Hasher::new_keyed(&TEST_KEY);
479 test_hasher.update(b"hello world");
480 test_hasher.finalize_xof().fill(&mut test_output);
481
482 assert_eq!(reference_output, test_output);
483 }
484
485 #[test]
486 fn test_xof_partial_blocks() {
487 const OUT_LEN: usize = 6 * BLOCK_LEN;
488 let mut reference_out = [0u8; OUT_LEN];
489 reference_impl::Hasher::new().finalize(&mut reference_out);
490
491 let mut all_at_once_out = [0u8; OUT_LEN];
492 crate::Hasher::new()
493 .finalize_xof()
494 .fill(&mut all_at_once_out);
495 assert_eq!(reference_out, all_at_once_out);
496
497 let mut partial_out = [0u8; OUT_LEN];
498 let partial_start = 32;
499 let partial_end = OUT_LEN - 32;
500 let mut xof = crate::Hasher::new().finalize_xof();
501 xof.fill(&mut partial_out[..partial_start]);
502 xof.fill(&mut partial_out[partial_start..partial_end]);
503 xof.fill(&mut partial_out[partial_end..]);
504 assert_eq!(reference_out, partial_out);
505 }
506
507 fn reference_hash(input: &[u8]) -> crate::Hash {
508 let mut hasher = reference_impl::Hasher::new();
509 hasher.update(input);
510 let mut bytes = [0; 32];
511 hasher.finalize(&mut bytes);
512 bytes.into()
513 }
514
515 #[test]
516 fn test_compare_update_multiple() {
517 // Don't use all the long test cases here, since that's unnecessarily slow
518 // in debug mode.
519 let mut short_test_cases = TEST_CASES;
520 while *short_test_cases.last().unwrap() > 4 * CHUNK_LEN {
521 short_test_cases = &short_test_cases[..short_test_cases.len() - 1];
522 }
523 assert_eq!(*short_test_cases.last().unwrap(), 4 * CHUNK_LEN);
524
525 let mut input_buf = [0; 2 * TEST_CASES_MAX];
526 paint_test_input(&mut input_buf);
527
528 for &first_update in short_test_cases {
529 #[cfg(feature = "std")]
530 dbg!(first_update);
531 let first_input = &input_buf[..first_update];
532 let mut test_hasher = crate::Hasher::new();
533 test_hasher.update(first_input);
534
535 for &second_update in short_test_cases {
536 #[cfg(feature = "std")]
537 dbg!(second_update);
538 let second_input = &input_buf[first_update..][..second_update];
539 let total_input = &input_buf[..first_update + second_update];
540
541 // Clone the hasher with first_update bytes already written, so
542 // that the next iteration can reuse it.
543 let mut test_hasher = test_hasher.clone();
544 test_hasher.update(second_input);
545 let expected = reference_hash(total_input);
546 assert_eq!(expected, test_hasher.finalize());
547 }
548 }
549 }
550
551 #[test]
552 fn test_fuzz_hasher() {
553 const INPUT_MAX: usize = 4 * CHUNK_LEN;
554 let mut input_buf = [0; 3 * INPUT_MAX];
555 paint_test_input(&mut input_buf);
556
557 // Don't do too many iterations in debug mode, to keep the tests under a
558 // second or so. CI should run tests in release mode also. Provide an
559 // environment variable for specifying a larger number of fuzz iterations.
560 let num_tests = if cfg!(debug_assertions) { 100 } else { 10_000 };
561
562 // Use a fixed RNG seed for reproducibility.
563 let mut rng = chacha20::ChaCha8Rng::from_seed([1; 32]);
564 for _num_test in 0..num_tests {
565 #[cfg(feature = "std")]
566 dbg!(_num_test);
567 let mut hasher = crate::Hasher::new();
568 let mut total_input = 0;
569 // For each test, write 3 inputs of random length.
570 for _ in 0..3 {
571 let input_len = rng.random_range(0..(INPUT_MAX + 1));
572 #[cfg(feature = "std")]
573 dbg!(input_len);
574 let input = &input_buf[total_input..][..input_len];
575 hasher.update(input);
576 total_input += input_len;
577 }
578 let expected = reference_hash(&input_buf[..total_input]);
579 assert_eq!(expected, hasher.finalize());
580 }
581 }
582
583 #[test]
584 fn test_fuzz_xof() {
585 let mut input_buf = [0u8; 3 * BLOCK_LEN];
586 paint_test_input(&mut input_buf);
587
588 // Don't do too many iterations in debug mode, to keep the tests under a
589 // second or so. CI should run tests in release mode also. Provide an
590 // environment variable for specifying a larger number of fuzz iterations.
591 let num_tests = if cfg!(debug_assertions) { 100 } else { 2500 };
592
593 // Use a fixed RNG seed for reproducibility.
594 let mut rng = chacha20::ChaCha8Rng::from_seed([1; 32]);
595 for _num_test in 0..num_tests {
596 #[cfg(feature = "std")]
597 dbg!(_num_test);
598 // 31 (16 + 8 + 4 + 2 + 1) outputs
599 let mut output_buf = [0; 31 * CHUNK_LEN];
600 let input_len = rng.random_range(0..input_buf.len());
601 let mut xof = crate::Hasher::new()
602 .update(&input_buf[..input_len])
603 .finalize_xof();
604 let partial_start = rng.random_range(0..output_buf.len());
605 let partial_end = rng.random_range(partial_start..output_buf.len());
606 xof.fill(&mut output_buf[..partial_start]);
607 xof.fill(&mut output_buf[partial_start..partial_end]);
608 xof.fill(&mut output_buf[partial_end..]);
609
610 let mut reference_buf = [0; 31 * CHUNK_LEN];
611 let mut reference_hasher = reference_impl::Hasher::new();
612 reference_hasher.update(&input_buf[..input_len]);
613 reference_hasher.finalize(&mut reference_buf);
614
615 assert_eq!(reference_buf, output_buf);
616 }
617 }
618
619 #[test]
620 fn test_xof_seek() {
621 let mut out = [0; 533];
622 let mut hasher = crate::Hasher::new();
623 hasher.update(b"foo");
624 hasher.finalize_xof().fill(&mut out);
625 assert_eq!(hasher.finalize().as_bytes(), &out[0..32]);
626
627 let mut reader = hasher.finalize_xof();
628 reader.set_position(303);
629 let mut out2 = [0; 102];
630 reader.fill(&mut out2);
631 assert_eq!(&out[303..][..102], &out2[..]);
632
633 #[cfg(feature = "std")]
634 {
635 use std::io::prelude::*;
636 let mut reader = hasher.finalize_xof();
637 reader.seek(std::io::SeekFrom::Start(303)).unwrap();
638 let mut out3 = Vec::new();
639 reader.by_ref().take(102).read_to_end(&mut out3).unwrap();
640 assert_eq!(&out[303..][..102], &out3[..]);
641
642 assert_eq!(
643 reader.seek(std::io::SeekFrom::Current(0)).unwrap(),
644 303 + 102
645 );
646 reader.seek(std::io::SeekFrom::Current(-5)).unwrap();
647 assert_eq!(
648 reader.seek(std::io::SeekFrom::Current(0)).unwrap(),
649 303 + 102 - 5
650 );
651 let mut out4 = [0; 17];
652 assert_eq!(reader.read(&mut out4).unwrap(), 17);
653 assert_eq!(&out[303 + 102 - 5..][..17], &out4[..]);
654 assert_eq!(
655 reader.seek(std::io::SeekFrom::Current(0)).unwrap(),
656 303 + 102 - 5 + 17
657 );
658 assert!(reader.seek(std::io::SeekFrom::End(0)).is_err());
659 assert!(reader.seek(std::io::SeekFrom::Current(-1000)).is_err());
660 }
661 }
662
663 #[test]
664 fn test_msg_schedule_permutation() {
665 let permutation = [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8];
666
667 let mut generated = [[0; 16]; 7];
668 generated[0] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
669
670 for round in 1..7 {
671 for i in 0..16 {
672 generated[round][i] = generated[round - 1][permutation[i]];
673 }
674 }
675
676 assert_eq!(generated, crate::MSG_SCHEDULE);
677 }
678
679 #[test]
680 fn test_reset() {
681 let mut hasher = crate::Hasher::new();
682 hasher.update(&[42; 3 * CHUNK_LEN + 7]);
683 hasher.reset();
684 hasher.update(&[42; CHUNK_LEN + 3]);
685 assert_eq!(hasher.finalize(), crate::hash(&[42; CHUNK_LEN + 3]));
686
687 let key = &[99; crate::KEY_LEN];
688 let mut keyed_hasher = crate::Hasher::new_keyed(key);
689 keyed_hasher.update(&[42; 3 * CHUNK_LEN + 7]);
690 keyed_hasher.reset();
691 keyed_hasher.update(&[42; CHUNK_LEN + 3]);
692 assert_eq!(
693 keyed_hasher.finalize(),
694 crate::keyed_hash(key, &[42; CHUNK_LEN + 3]),
695 );
696
697 let context = "BLAKE3 2020-02-12 10:20:58 reset test";
698 let mut kdf = crate::Hasher::new_derive_key(context);
699 kdf.update(&[42; 3 * CHUNK_LEN + 7]);
700 kdf.reset();
701 kdf.update(&[42; CHUNK_LEN + 3]);
702 let expected = crate::derive_key(context, &[42; CHUNK_LEN + 3]);
703 assert_eq!(kdf.finalize(), expected);
704 }
705
706 #[test]
707 fn test_hex_encoding_decoding() {
708 let digest_str = "04e0bb39f30b1a3feb89f536c93be15055482df748674b00d26e5a75777702e9";
709 let mut hasher = crate::Hasher::new();
710 hasher.update(b"foo");
711 let digest = hasher.finalize();
712 assert_eq!(digest.to_hex().as_str(), digest_str);
713 #[cfg(feature = "std")]
714 assert_eq!(digest.to_string(), digest_str);
715
716 // Test round trip
717 let digest = crate::Hash::from_hex(digest_str).unwrap();
718 assert_eq!(digest.to_hex().as_str(), digest_str);
719
720 // Test uppercase
721 let digest = crate::Hash::from_hex(digest_str.to_uppercase()).unwrap();
722 assert_eq!(digest.to_hex().as_str(), digest_str);
723
724 // Test string parsing via FromStr
725 let digest: crate::Hash = digest_str.parse().unwrap();
726 assert_eq!(digest.to_hex().as_str(), digest_str);
727
728 // Test errors
729 let bad_len = "04e0bb39f30b1";
730 let _result = crate::Hash::from_hex(bad_len).unwrap_err();
731 #[cfg(feature = "std")]
732 assert_eq!(_result.to_string(), "expected 64 hex bytes, received 13");
733
734 let bad_char = "Z4e0bb39f30b1a3feb89f536c93be15055482df748674b00d26e5a75777702e9";
735 let _result = crate::Hash::from_hex(bad_char).unwrap_err();
736 #[cfg(feature = "std")]
737 assert_eq!(_result.to_string(), "invalid hex character: 'Z'");
738
739 let _result = crate::Hash::from_hex([128; 64]).unwrap_err();
740 #[cfg(feature = "std")]
741 assert_eq!(_result.to_string(), "invalid hex character: 0x80");
742 }
743
744 // This test is a mimized failure case for the Windows SSE2 bug described in
745 // https://github.com/BLAKE3-team/BLAKE3/issues/206.
746 //
747 // Before that issue was fixed, this test would fail on Windows in the following configuration:
748 //
749 // cargo test --features=no_avx512,no_avx2,no_sse41 --release
750 //
751 // Bugs like this one (stomping on a caller's register) are very sensitive to the details of
752 // surrounding code, so it's not especially likely that this test will catch another bug (or even
753 // the same bug) in the future. Still, there's no harm in keeping it.
754 #[test]
755 fn test_issue_206_windows_sse2() {
756 // This stupid loop has to be here to trigger the bug. I don't know why.
757 for _ in &[0] {
758 // The length 65 (two blocks) is significant. It doesn't repro with 64 (one block). It also
759 // doesn't repro with an all-zero input.
760 let input = &[0xff; 65];
761 let expected_hash = [
762 183, 235, 50, 217, 156, 24, 190, 219, 2, 216, 176, 255, 224, 53, 28, 95, 57, 148, 179,
763 245, 162, 90, 37, 121, 0, 142, 219, 62, 234, 204, 225, 161,
764 ];
765
766 // This throwaway call has to be here to trigger the bug.
767 crate::Hasher::new().update(input);
768
769 // This assert fails when the bug is triggered.
770 assert_eq!(crate::Hasher::new().update(input).finalize(), expected_hash);
771 }
772 }
773
774 #[test]
775 fn test_hash_conversions() {
776 let bytes1 = [42; 32];
777 let hash1: crate::Hash = bytes1.into();
778 let bytes2: [u8; 32] = hash1.into();
779 assert_eq!(bytes1, bytes2);
780
781 let bytes3 = *hash1.as_bytes();
782 assert_eq!(bytes1, bytes3);
783
784 let hash2 = crate::Hash::from_bytes(bytes1);
785 assert_eq!(hash1, hash2);
786
787 let hex = hash1.to_hex();
788 let hash3 = crate::Hash::from_hex(hex.as_bytes()).unwrap();
789 assert_eq!(hash1, hash3);
790
791 let slice1: &[u8] = bytes1.as_slice();
792 let hash4 = crate::Hash::from_slice(slice1).expect("correct length");
793 assert_eq!(hash1, hash4);
794
795 let slice2 = hash1.as_slice();
796 assert_eq!(slice1, slice2);
797
798 assert!(crate::Hash::from_slice(&[]).is_err());
799 assert!(crate::Hash::from_slice(&[42]).is_err());
800 assert!(crate::Hash::from_slice([42; 31].as_slice()).is_err());
801 assert!(crate::Hash::from_slice([42; 33].as_slice()).is_err());
802 assert!(crate::Hash::from_slice([42; 100].as_slice()).is_err());
803 }
804
805 #[test]
806 const fn test_hash_const_conversions() {
807 let bytes = [42; 32];
808 let hash = crate::Hash::from_bytes(bytes);
809 _ = hash.as_bytes();
810 }
811
812 #[cfg(feature = "zeroize")]
813 #[test]
814 fn test_zeroize() {
815 use zeroize::Zeroize;
816
817 let mut hash = crate::Hash([42; 32]);
818 hash.zeroize();
819 assert_eq!(hash.0, [0u8; 32]);
820
821 let mut hasher = crate::Hasher {
822 chunk_state: crate::ChunkState {
823 cv: [42; 8],
824 chunk_counter: 42,
825 buf: [42; 64],
826 buf_len: 42,
827 blocks_compressed: 42,
828 flags: 42,
829 platform: crate::Platform::Portable,
830 },
831 initial_chunk_counter: 42,
832 key: [42; 8],
833 cv_stack: [[42; 32]; { crate::MAX_DEPTH + 1 }].into(),
834 };
835 hasher.zeroize();
836 assert_eq!(hasher.chunk_state.cv, [0; 8]);
837 assert_eq!(hasher.chunk_state.chunk_counter, 0);
838 assert_eq!(hasher.chunk_state.buf, [0; 64]);
839 assert_eq!(hasher.chunk_state.buf_len, 0);
840 assert_eq!(hasher.chunk_state.blocks_compressed, 0);
841 assert_eq!(hasher.chunk_state.flags, 0);
842 assert!(matches!(
843 hasher.chunk_state.platform,
844 crate::Platform::Portable
845 ));
846 assert_eq!(hasher.initial_chunk_counter, 0);
847 assert_eq!(hasher.key, [0; 8]);
848 assert_eq!(&*hasher.cv_stack, &[[0u8; 32]; 0]);
849
850 let mut output_reader = crate::OutputReader {
851 inner: crate::Output {
852 input_chaining_value: [42; 8],
853 block: [42; 64],
854 counter: 42,
855 block_len: 42,
856 flags: 42,
857 platform: crate::Platform::Portable,
858 },
859 position_within_block: 42,
860 };
861
862 output_reader.zeroize();
863 assert_eq!(output_reader.inner.input_chaining_value, [0; 8]);
864 assert_eq!(output_reader.inner.block, [0; 64]);
865 assert_eq!(output_reader.inner.counter, 0);
866 assert_eq!(output_reader.inner.block_len, 0);
867 assert_eq!(output_reader.inner.flags, 0);
868 assert!(matches!(
869 output_reader.inner.platform,
870 crate::Platform::Portable
871 ));
872 assert_eq!(output_reader.position_within_block, 0);
873 }
874
875 #[test]
876 #[cfg(feature = "std")]
877 fn test_update_reader() -> Result<(), std::io::Error> {
878 // This is a brief test, since update_reader() is mostly a wrapper around update(), which already
879 // has substantial testing.
880 let mut input = vec![0; 1_000_000];
881 paint_test_input(&mut input);
882 assert_eq!(
883 crate::Hasher::new().update_reader(&input[..])?.finalize(),
884 crate::hash(&input),
885 );
886 Ok(())
887 }
888
889 #[test]
890 #[cfg(feature = "std")]
891 fn test_update_reader_interrupted() -> std::io::Result<()> {
892 use std::io;
893 struct InterruptingReader<'a> {
894 already_interrupted: bool,
895 slice: &'a [u8],
896 }
897 impl<'a> InterruptingReader<'a> {
898 fn new(slice: &'a [u8]) -> Self {
899 Self {
900 already_interrupted: false,
901 slice,
902 }
903 }
904 }
905 impl<'a> io::Read for InterruptingReader<'a> {
906 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
907 if !self.already_interrupted {
908 self.already_interrupted = true;
909 return Err(io::Error::from(io::ErrorKind::Interrupted));
910 }
911 let take = std::cmp::min(self.slice.len(), buf.len());
912 buf[..take].copy_from_slice(&self.slice[..take]);
913 self.slice = &self.slice[take..];
914 Ok(take)
915 }
916 }
917
918 let input = b"hello world";
919 let mut reader = InterruptingReader::new(input);
920 let mut hasher = crate::Hasher::new();
921 hasher.update_reader(&mut reader)?;
922 assert_eq!(hasher.finalize(), crate::hash(input));
923 Ok(())
924 }
925
926 #[test]
927 #[cfg(feature = "mmap")]
928 // NamedTempFile isn't Miri-compatible
929 #[cfg(not(miri))]
930 fn test_mmap() -> Result<(), std::io::Error> {
931 // This is a brief test, since update_mmap() is mostly a wrapper around update(), which already
932 // has substantial testing.
933 use std::io::prelude::*;
934 let mut input = vec![0; 1_000_000];
935 paint_test_input(&mut input);
936 let mut tempfile = tempfile::NamedTempFile::new()?;
937 tempfile.write_all(&input)?;
938 tempfile.flush()?;
939 assert_eq!(
940 crate::Hasher::new()
941 .update_mmap(tempfile.path())?
942 .finalize(),
943 crate::hash(&input),
944 );
945 Ok(())
946 }
947
948 #[test]
949 #[cfg(feature = "mmap")]
950 #[cfg(target_os = "linux")]
951 fn test_mmap_virtual_file() -> Result<(), std::io::Error> {
952 // Virtual files like /proc/version can't be mmapped, because their contents don't actually
953 // exist anywhere in memory. Make sure we fall back to regular file IO in these cases.
954 let virtual_filepath = "/proc/version";
955 let mut mmap_hasher = crate::Hasher::new();
956 // We'll fail right here if the fallback doesn't work.
957 mmap_hasher.update_mmap(virtual_filepath)?;
958 let mut read_hasher = crate::Hasher::new();
959 read_hasher.update_reader(std::fs::File::open(virtual_filepath)?)?;
960 assert_eq!(mmap_hasher.finalize(), read_hasher.finalize());
961 Ok(())
962 }
963
964 #[test]
965 #[cfg(feature = "mmap")]
966 #[cfg(feature = "rayon")]
967 // NamedTempFile isn't Miri-compatible
968 #[cfg(not(miri))]
969 fn test_mmap_rayon() -> Result<(), std::io::Error> {
970 // This is a brief test, since update_mmap_rayon() is mostly a wrapper around update_rayon(),
971 // which already has substantial testing.
972 use std::io::prelude::*;
973 let mut input = vec![0; 1_000_000];
974 paint_test_input(&mut input);
975 let mut tempfile = tempfile::NamedTempFile::new()?;
976 tempfile.write_all(&input)?;
977 tempfile.flush()?;
978 assert_eq!(
979 crate::Hasher::new()
980 .update_mmap_rayon(tempfile.path())?
981 .finalize(),
982 crate::hash(&input),
983 );
984 Ok(())
985 }
986
987 #[test]
988 #[cfg(feature = "std")]
989 #[cfg(feature = "serde")]
990 fn test_serde() {
991 // Henrik suggested that we use 0xfe / 254 for byte test data instead of 0xff / 255, due to the
992 // fact that 0xfe is not a well formed CBOR item.
993 let hash: crate::Hash = [0xfe; 32].into();
994
995 let json = serde_json::to_string(&hash).unwrap();
996 assert_eq!(
997 json,
998 "[254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254,254]",
999 );
1000 let hash2: crate::Hash = serde_json::from_str(&json).unwrap();
1001 assert_eq!(hash, hash2);
1002
1003 let mut cbor = Vec::<u8>::new();
1004 ciborium::into_writer(&hash, &mut cbor).unwrap();
1005 assert_eq!(
1006 cbor,
1007 [
1008 0x98, 0x20, 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe,
1009 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe,
1010 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe,
1011 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe,
1012 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe, 0x18, 0xfe,
1013 ]
1014 );
1015 let hash_from_cbor: crate::Hash = ciborium::from_reader(&cbor[..]).unwrap();
1016 assert_eq!(hash_from_cbor, hash);
1017
1018 // Version 1.5.2 of this crate changed the default serialization format to a bytestring
1019 // (instead of an array/list) to save bytes on the wire. That was a backwards compatibility
1020 // mistake for non-self-describing formats, and it's been reverted. Since some small number of
1021 // serialized bytestrings will probably exist forever in the wild, we should test that we can
1022 // still deserialize these from self-describing formats.
1023 let bytestring_cbor: &[u8] = &[
1024 0x58, 0x20, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe,
1025 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe,
1026 0xfe, 0xfe, 0xfe, 0xfe,
1027 ];
1028 let hash_from_bytestring_cbor: crate::Hash = ciborium::from_reader(bytestring_cbor).unwrap();
1029 assert_eq!(hash_from_bytestring_cbor, hash);
1030 }
1031
1032 // `cargo +nightly miri test` currently works, but it takes forever, because some of our test
1033 // inputs are quite large. Most of our unsafe code is platform specific and incompatible with Miri
1034 // anyway, but we'd like it to be possible for callers to run their own tests under Miri, assuming
1035 // they don't use incompatible features like Rayon or mmap. This test should get reasonable
1036 // coverage of our public API without using any large inputs, so we can run it in CI and catch
1037 // obvious breaks. (For example, constant_time_eq is not compatible with Miri.)
1038 #[test]
1039 fn test_miri_smoketest() {
1040 let mut hasher = crate::Hasher::new_derive_key("Miri smoketest");
1041 hasher.update(b"foo");
1042 #[cfg(feature = "std")]
1043 hasher.update_reader(&b"bar"[..]).unwrap();
1044 assert_eq!(hasher.finalize(), hasher.finalize());
1045 let mut reader = hasher.finalize_xof();
1046 reader.set_position(999999);
1047 reader.fill(&mut [0]);
1048 }
1049
1050 // I had to move these tests out of the deprecated guts module, because leaving them there causes
1051 // an un-silenceable warning: https://github.com/rust-lang/rust/issues/47238
1052 #[cfg(test)]
1053 #[allow(deprecated)]
1054 mod guts_tests {
1055 use crate::guts::*;
1056
1057 #[test]
1058 fn test_chunk() {
1059 assert_eq!(
1060 crate::hash(b"foo"),
1061 ChunkState::new(0).update(b"foo").finalize(true)
1062 );
1063 }
1064
1065 #[test]
1066 fn test_parents() {
1067 let mut hasher = crate::Hasher::new();
1068 let mut buf = [0; crate::CHUNK_LEN];
1069
1070 buf[0] = 'a' as u8;
1071 hasher.update(&buf);
1072 let chunk0_cv = ChunkState::new(0).update(&buf).finalize(false);
1073
1074 buf[0] = 'b' as u8;
1075 hasher.update(&buf);
1076 let chunk1_cv = ChunkState::new(1).update(&buf).finalize(false);
1077
1078 hasher.update(b"c");
1079 let chunk2_cv = ChunkState::new(2).update(b"c").finalize(false);
1080
1081 let parent = parent_cv(&chunk0_cv, &chunk1_cv, false);
1082 let root = parent_cv(&parent, &chunk2_cv, true);
1083 assert_eq!(hasher.finalize(), root);
1084 }
1085 }