From 4feb2b6bce73a42ec6499f1e0ed9523b5d3618c1 Mon Sep 17 00:00:00 2001 From: ryan Date: Wed, 16 Aug 2023 06:12:01 -0500 Subject: [PATCH] keyfork-mnemonic-generate: extract converters --- keyfork-mnemonic-generate/src/main.rs | 60 ++++++++++++++------------- 1 file changed, 32 insertions(+), 28 deletions(-) diff --git a/keyfork-mnemonic-generate/src/main.rs b/keyfork-mnemonic-generate/src/main.rs index fdfe30e..c410820 100644 --- a/keyfork-mnemonic-generate/src/main.rs +++ b/keyfork-mnemonic-generate/src/main.rs @@ -70,6 +70,34 @@ fn build_wordlist() -> Vec { .collect() } +#[allow(clippy::trivially_copy_pass_by_ref)] +fn u8_to_bitslice(byte: &u8) -> [bool; 8] { + [ + byte & (1 << 0) != 0, + byte & (1 << 1) != 0, + byte & (1 << 2) != 0, + byte & (1 << 3) != 0, + byte & (1 << 4) != 0, + byte & (1 << 5) != 0, + byte & (1 << 6) != 0, + byte & (1 << 7) != 0, + ] +} + +fn bitslice_to_usize(bitslice: [bool; 11]) -> usize { + usize::from(bitslice[0]) + + (usize::from(bitslice[1]) << 1) + + (usize::from(bitslice[2]) << 2) + + (usize::from(bitslice[3]) << 3) + + (usize::from(bitslice[4]) << 4) + + (usize::from(bitslice[5]) << 5) + + (usize::from(bitslice[6]) << 6) + + (usize::from(bitslice[7]) << 7) + + (usize::from(bitslice[8]) << 8) + + (usize::from(bitslice[9]) << 9) + + (usize::from(bitslice[10]) << 10) +} + fn main() -> Result<(), Box> { if !env::vars() .any(|(name, _)| name == "SHOOT_SELF_IN_FOOT" || name == "INSECURE_HARDWARE_ALLOWED") @@ -105,35 +133,11 @@ fn main() -> Result<(), Box> { let checksum = &hash[..bit_size / 32 / 8]; let seed = [&entropy[..bit_size / 8], checksum].concat(); - let seed_bits = seed - .iter() - .flat_map(|byte| { - [ - byte & (1 << 0) != 0, - byte & (1 << 1) != 0, - byte & (1 << 2) != 0, - byte & (1 << 3) != 0, - byte & (1 << 4) != 0, - byte & (1 << 5) != 0, - byte & (1 << 6) != 0, - byte & (1 << 7) != 0, - ] - }) + let seed_bits = seed.iter().flat_map(u8_to_bitslice).collect::>(); + let words = seed_bits + .chunks_exact(11) + .map(|chunk| wordlist[bitslice_to_usize(chunk.try_into().expect("11 bit chunks"))].clone()) .collect::>(); - let words = seed_bits.chunks_exact(11).map(|chunk| { - let index = usize::from(chunk[0]) - + (usize::from(chunk[1]) << 1) - + (usize::from(chunk[2]) << 2) - + (usize::from(chunk[3]) << 3) - + (usize::from(chunk[4]) << 4) - + (usize::from(chunk[5]) << 5) - + (usize::from(chunk[6]) << 6) - + (usize::from(chunk[7]) << 7) - + (usize::from(chunk[8]) << 8) - + (usize::from(chunk[9]) << 9) - + (usize::from(chunk[10]) << 10); - wordlist[index].clone() - }).collect::>(); println!("{}", words.join(" ")); Ok(())