mailcycle 0.1.0

Rust client for the Mailcycle API. Create addresses that receive mail, read and decrypt it on your machine, send, and listen for events.
Documentation
//! Recovery phrases.
//!
//! A Mailcycle account is a twelve-word phrase. Nothing server-side can reset
//! it.
//!
//! Encoding, as BIP-39 does it but over Mailcycle's own [`wordlist`]: 128 bits
//! of entropy, plus a 4-bit checksum taken from the first bits of
//! SHA-256(entropy), split into twelve 11-bit groups, each an index into the
//! list.
//!
//! [`wordlist`]: super::wordlist

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;

/// Derivation cost.
///
/// Changing it changes every account id ever derived, so this number is part
/// of the format, not a tuning knob. Stretching buys little over a 128-bit
/// phrase and earns its keep only for the optional passphrase, which may be
/// low entropy.
pub const SEED_ITERATIONS: u32 = 120_000;
pub const SEED_BYTES: usize = 64;

const SEED_SALT_PREFIX: &[u8] = b"mailcycle-seed";

/// Lowercases, drops everything that is not a letter, and splits on whitespace.
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;
        }
    }

    // 128 bits leaves 7 over; the 4 checksum bits complete the last word.
    words.push(WORDLIST[(((buffer << CHECKSUM_BITS) | checksum) & 0x7ff) as usize].to_string());
    words
}

/// A fresh twelve-word phrase from the operating system's CSPRNG.
pub fn generate_phrase() -> Vec<String> {
    entropy_to_phrase(&random_bytes(ENTROPY_BITS / 8))
}

/// Full validation, checksum included.
///
/// A single mistyped word fails here roughly fifteen times out of sixteen,
/// which is what the checksum is for: it turns "your mail is gone" into
/// "word 7 is wrong".
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()
}

/// Phrase to 64-byte root seed.
///
/// The optional passphrase is BIP-39's "25th word": it changes which account
/// the phrase opens, and nothing anywhere records whether one was used.
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)
}