use bip39::{Language, Mnemonic};
use zeroize::Zeroizing;
use crate::{Error, PrivateKey, Result};
const WORDS: usize = 24;
pub fn private_key_from_mnemonic(phrase: &str) -> Result<PrivateKey> {
let normalized = Zeroizing::new(
phrase
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.to_lowercase(),
);
if normalized.split(' ').count() != WORDS {
return Err(Error::InvalidMnemonic);
}
let mnemonic =
Mnemonic::parse_in_normalized(Language::English, &normalized).map_err(|_| Error::InvalidMnemonic)?;
let entropy = Zeroizing::new(mnemonic.to_entropy());
let bytes: &[u8; 32] = entropy
.as_slice()
.try_into()
.map_err(|_| Error::InvalidMnemonic)?;
PrivateKey::from_bytes(bytes).map_err(|_| Error::InvalidMnemonic)
}
pub fn mnemonic_from_private_key(key: &PrivateKey) -> Zeroizing<String> {
let bytes = key.to_bytes();
let words = Mnemonic::from_entropy_in(Language::English, bytes.as_ref()).map(|m| m.to_string());
Zeroizing::new(words.unwrap_or_default())
}