keyfork-mnemonic-util: allow seeds of arbitrary size

This commit is contained in:
Ryan Heywood 2023-12-21 15:02:59 -05:00
parent 30a582ed8c
commit bfb44292f4
Signed by: ryan
GPG Key ID: 8E401478A3FBEF72
1 changed files with 17 additions and 1 deletions

View File

@ -170,6 +170,11 @@ impl Mnemonic {
return Err(MnemonicGenerationError::InvalidByteLength(bit_count)); return Err(MnemonicGenerationError::InvalidByteLength(bit_count));
} }
Ok(unsafe {Self::from_raw_entropy(bytes, wordlist)})
}
pub unsafe fn from_raw_entropy(bytes: &[u8], wordlist: Arc<Wordlist>) -> Mnemonic {
let bit_count = bytes.len() * 8;
let mut bits = vec![false; bit_count + bit_count / 32]; let mut bits = vec![false; bit_count + bit_count / 32];
for byte_index in 0..bit_count / 8 { for byte_index in 0..bit_count / 8 {
@ -197,7 +202,7 @@ impl Mnemonic {
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
Ok(Mnemonic { words, wordlist }) Mnemonic { words, wordlist }
} }
pub fn entropy(&self) -> Vec<u8> { pub fn entropy(&self) -> Vec<u8> {
@ -342,4 +347,15 @@ mod tests {
count / f64::from(tests) count / f64::from(tests)
); );
} }
#[test]
fn can_do_up_to_1024_bits() {
let entropy = &mut [0u8; 128];
let wordlist = Wordlist::default().arc();
let mut random = std::fs::File::open("/dev/urandom").unwrap();
random.read_exact(&mut entropy[..]).unwrap();
let mnemonic = unsafe { Mnemonic::from_raw_entropy(&entropy[..], wordlist.clone()) };
let (words, _) = mnemonic.into_inner();
assert!(words.len() == 96);
}
} }