use crate::error::PhraseProblem;
use super::primitives::{pbkdf2_sha256, random_bytes, sha256};
use super::wordlist::{index_of, WORDLIST};
pub const PHRASE_WORD_COUNT: usize = 12;
const ENTROPY_BITS: usize = 128;
const CHECKSUM_BITS: u32 = (ENTROPY_BITS / 32) as u32;
pub const SEED_ITERATIONS: u32 = 120_000;
pub const SEED_BYTES: usize = 64;
const SEED_SALT_PREFIX: &[u8] = b"mailcycle-seed";
pub fn normalize_phrase(phrase: &str) -> Vec<String> {
phrase
.to_lowercase()
.chars()
.map(|c| if c.is_ascii_lowercase() || c.is_whitespace() { c } else { ' ' })
.collect::<String>()
.split_whitespace()
.map(str::to_string)
.collect()
}
pub fn entropy_to_phrase(entropy: &[u8]) -> Vec<String> {
assert_eq!(entropy.len(), ENTROPY_BITS / 8, "a phrase needs exactly 16 bytes of entropy");
let checksum = (sha256(entropy)[0] >> (8 - CHECKSUM_BITS)) as u32;
let mut words = Vec::with_capacity(PHRASE_WORD_COUNT);
let mut buffer: u32 = 0;
let mut bits: u32 = 0;
for byte in entropy {
buffer = (buffer << 8) | *byte as u32;
bits += 8;
while bits >= 11 {
bits -= 11;
words.push(WORDLIST[((buffer >> bits) & 0x7ff) as usize].to_string());
buffer &= (1 << bits) - 1;
}
}
words.push(WORDLIST[(((buffer << CHECKSUM_BITS) | checksum) & 0x7ff) as usize].to_string());
words
}
pub fn generate_phrase() -> Vec<String> {
entropy_to_phrase(&random_bytes(ENTROPY_BITS / 8))
}
pub fn validate_phrase(phrase: &str) -> Option<PhraseProblem> {
let words = normalize_phrase(phrase);
if words.len() != PHRASE_WORD_COUNT {
return Some(PhraseProblem::Length(words.len()));
}
let mut indices = Vec::with_capacity(PHRASE_WORD_COUNT);
for (position, word) in words.iter().enumerate() {
match index_of(word) {
Some(index) => indices.push(index as u64),
None => return Some(PhraseProblem::UnknownWord { word: word.clone(), index: position }),
}
}
let mut entropy = vec![0u8; ENTROPY_BITS / 8];
let mut buffer: u64 = 0;
let mut bits: u32 = 0;
let mut written = 0usize;
for index in indices {
buffer = buffer * 2048 + index;
bits += 11;
while bits >= 8 && written < entropy.len() {
bits -= 8;
entropy[written] = ((buffer >> bits) & 0xff) as u8;
buffer %= 1 << bits;
written += 1;
}
}
let expected = (sha256(&entropy)[0] >> (8 - CHECKSUM_BITS)) as u64;
if (buffer & ((1 << CHECKSUM_BITS) - 1)) != expected {
return Some(PhraseProblem::Checksum);
}
None
}
pub fn is_valid_word(word: &str) -> bool {
index_of(&word.to_lowercase()).is_some()
}
pub fn phrase_to_seed(phrase: &str, passphrase: &str) -> Vec<u8> {
let words = normalize_phrase(phrase).join(" ");
let mut salt = SEED_SALT_PREFIX.to_vec();
salt.extend_from_slice(passphrase.as_bytes());
pbkdf2_sha256(words.as_bytes(), &salt, SEED_ITERATIONS, SEED_BYTES)
}