From 8ec5dc0dece864aa0443406edab72a4ac49403ad Mon Sep 17 00:00:00 2001 From: ryan Date: Fri, 18 Aug 2023 00:58:42 -0500 Subject: [PATCH] keyfork-mnemonic-generate: test ensure entropy floats around what we expect from birthday values --- keyfork-mnemonic-generate/src/main.rs | 40 +++++++++++++-------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/keyfork-mnemonic-generate/src/main.rs b/keyfork-mnemonic-generate/src/main.rs index f4ccfe6..78f93a2 100644 --- a/keyfork-mnemonic-generate/src/main.rs +++ b/keyfork-mnemonic-generate/src/main.rs @@ -1,9 +1,9 @@ use std::{ env, error::Error, + fmt::Display, fs::{read_dir, read_to_string, File}, io::Read, - fmt::Display, }; use sha2::{Digest, Sha256}; @@ -252,24 +252,14 @@ mod tests { #[test] fn count_to_get_duplicate_words() { let mut count = 0.; - let mut smallest = 2048; - let mut largest = 0; + let tests = 10_000; let mut random_handle = File::open("/dev/random").unwrap(); let entropy = &mut [0u8; 256 / 8]; - let mut set = std::collections::HashMap::<&str, u32>::new(); - for _ in 0..100_000 { + for _ in 0..tests { random_handle.read_exact(&mut entropy[..]).unwrap(); // let bits = generate_slice_hash(entropy); - let mnemonic = bip39::Mnemonic::from_entropy(&entropy[..256 / 8]).unwrap(); - /* - mnemonic.words.dedup(); - */ - // NOTE: This pulls everything BUT the last word, just for testing. - // Change to ..24 to include the last word. - for (word, _) in mnemonic.word_iter().zip(0..23) { - *set.entry(word).or_insert(0) += 1; - } - let mut words = mnemonic.word_iter().collect::>(); + let mnemonic = Mnemonic::from_entropy(&entropy[..256 / 8]).unwrap(); + let mut words = mnemonic.words.clone(); words.sort(); assert_eq!(words.len(), 24); words.dedup(); @@ -277,10 +267,20 @@ mod tests { count += 1.; } } - for entry in &set { - smallest = std::cmp::min(smallest, *entry.1); - largest = std::cmp::max(largest, *entry.1); - } - panic!("{count} len:{} smallest:{smallest} largest:{largest}", set.len()) + // NOTE: Birthday problem math is: 0.126532 + // Set values to (about) 1 below, 1 above + // Source: https://en.wikipedia.org/wiki/Birthday_problem + let min = 11.5; + let max = 13.5; + assert!( + count > f64::from(tests) * min / 100., + "{count} probability should be more than {min}%: {}", + count / f64::from(tests) + ); + assert!( + count < f64::from(tests) * max / 100., + "{count} probability should be more than {max}%: {}", + count / f64::from(tests) + ); } }