keyfork-mnemonic-generate: extract converters

This commit is contained in:
Ryan Heywood 2023-08-16 06:12:01 -05:00
parent d4036d8b72
commit 4feb2b6bce
Signed by: ryan
GPG Key ID: 8E401478A3FBEF72
1 changed files with 32 additions and 28 deletions

View File

@ -70,6 +70,34 @@ fn build_wordlist() -> Vec<String> {
.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<dyn Error>> {
if !env::vars()
.any(|(name, _)| name == "SHOOT_SELF_IN_FOOT" || name == "INSECURE_HARDWARE_ALLOWED")
@ -105,35 +133,11 @@ fn main() -> Result<(), Box<dyn Error>> {
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::<Vec<_>>();
let words = seed_bits
.chunks_exact(11)
.map(|chunk| wordlist[bitslice_to_usize(chunk.try_into().expect("11 bit chunks"))].clone())
.collect::<Vec<_>>();
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::<Vec<_>>();
println!("{}", words.join(" "));
Ok(())