keyfork-mnemonic-generate: test ensure entropy floats around what we expect from birthday values

This commit is contained in:
Ryan Heywood 2023-08-18 00:58:42 -05:00
parent ac40930b2f
commit 8ec5dc0dec
Signed by: ryan
GPG Key ID: 8E401478A3FBEF72
1 changed files with 20 additions and 20 deletions

View File

@ -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::<Vec<_>>();
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)
);
}
}