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::{ use std::{
env, env,
error::Error, error::Error,
fmt::Display,
fs::{read_dir, read_to_string, File}, fs::{read_dir, read_to_string, File},
io::Read, io::Read,
fmt::Display,
}; };
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
@ -252,24 +252,14 @@ mod tests {
#[test] #[test]
fn count_to_get_duplicate_words() { fn count_to_get_duplicate_words() {
let mut count = 0.; let mut count = 0.;
let mut smallest = 2048; let tests = 10_000;
let mut largest = 0;
let mut random_handle = File::open("/dev/random").unwrap(); let mut random_handle = File::open("/dev/random").unwrap();
let entropy = &mut [0u8; 256 / 8]; let entropy = &mut [0u8; 256 / 8];
let mut set = std::collections::HashMap::<&str, u32>::new(); for _ in 0..tests {
for _ in 0..100_000 {
random_handle.read_exact(&mut entropy[..]).unwrap(); random_handle.read_exact(&mut entropy[..]).unwrap();
// let bits = generate_slice_hash(entropy); // let bits = generate_slice_hash(entropy);
let mnemonic = bip39::Mnemonic::from_entropy(&entropy[..256 / 8]).unwrap(); let mnemonic = Mnemonic::from_entropy(&entropy[..256 / 8]).unwrap();
/* let mut words = mnemonic.words.clone();
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<_>>();
words.sort(); words.sort();
assert_eq!(words.len(), 24); assert_eq!(words.len(), 24);
words.dedup(); words.dedup();
@ -277,10 +267,20 @@ mod tests {
count += 1.; count += 1.;
} }
} }
for entry in &set { // NOTE: Birthday problem math is: 0.126532
smallest = std::cmp::min(smallest, *entry.1); // Set values to (about) 1 below, 1 above
largest = std::cmp::max(largest, *entry.1); // Source: https://en.wikipedia.org/wiki/Birthday_problem
} let min = 11.5;
panic!("{count} len:{} smallest:{smallest} largest:{largest}", set.len()) 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)
);
} }
} }