libhardcopy 1.0.0

Generalized library for hardcopy/softcopy command line utilities.
Documentation
use std::convert::TryInto;

use wordlists::BIP39_WORDLIST;

pub const BIP39_INSTRUCTIONS: &str =
    include_str!("../../../static/wordlists/bip39/instructions.txt");

/// Returns the length of the longest word in the BIP-39 list.
pub(crate) fn max_word_len() -> usize {
    BIP39_WORDLIST.iter().map(|w| w.len()).max().unwrap_or(0)
}

/// Compute the S/KEY-style 2-bit checksum: sum of all 32 two-bit pairs of a
/// 64-bit data block, taken mod 4.
fn sum_of_pairs(block: u64) -> u8 {
    let mut sum: u32 = 0;
    let mut v = block;
    for _ in 0..32 {
        sum += (v & 0x03) as u32;
        v >>= 2;
    }
    (sum & 0x03) as u8
}

/// Encode one 8-byte block into 6 BIP-39 words.
///
/// 64 data bits + 2-bit checksum = 66 bits, split into 6 × 11-bit indices.
fn block_to_words(block: u64) -> [&'static str; 6] {
    let checksum = sum_of_pairs(block) as u128;
    let value66: u128 = ((block as u128) << 2) | checksum;
    let mut words = [""; 6];
    for i in 0..6usize {
        let shift = (5 - i) * 11;
        let index = ((value66 >> shift) & 0x7FF) as usize;
        words[i] = BIP39_WORDLIST[index];
    }
    words
}

/// Decode 6 BIP-39 words back into a 64-bit data block.
fn words_to_block(words: &[&str; 6]) -> u64 {
    let mut value66: u128 = 0;
    for (i, word) in words.iter().enumerate() {
        let index = BIP39_WORDLIST
            .iter()
            .position(|s| s.eq_ignore_ascii_case(word))
            .expect("Unknown BIP-39 word") as u128;
        let shift = (5 - i) * 11;
        value66 |= index << shift;
    }
    (value66 >> 2) as u64
}

/// Encode `bytes` as BIP-39 words.
///
/// A 4-byte little-endian length prefix is prepended, then the data is
/// zero-padded to an 8-byte boundary. Each 8-byte block is encoded into 6
/// words (64 data bits + 2-bit checksum = 66 bits = 6 × 11-bit indices).
pub(crate) fn bytes_to_wordlist(bytes: &[u8]) -> Vec<&'static str> {
    let len = bytes.len() as u32;
    let mut data = Vec::with_capacity(4 + bytes.len());
    data.extend_from_slice(&len.to_le_bytes());
    data.extend_from_slice(bytes);
    while data.len() % 8 != 0 {
        data.push(0u8);
    }
    let mut words = Vec::with_capacity(data.len() / 8 * 6);
    for chunk in data.chunks_exact(8) {
        let block = u64::from_be_bytes(chunk.try_into().unwrap());
        words.extend_from_slice(&block_to_words(block));
    }
    words
}

/// Decode BIP-39 words back to the original bytes, stripping the 4-byte
/// length prefix inserted by `bytes_to_wordlist`.
pub(crate) fn wordlist_to_bytes(words: &[&str]) -> Vec<u8> {
    assert_eq!(words.len() % 6, 0, "word count must be a multiple of 6");
    let mut data = Vec::with_capacity(words.len() / 6 * 8);
    for chunk in words.chunks_exact(6) {
        let block_words: &[&str; 6] = chunk.try_into().unwrap();
        let block = words_to_block(block_words);
        data.extend_from_slice(&block.to_be_bytes());
    }
    if data.len() < 4 {
        return Vec::new();
    }
    let len = u32::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
    data[4..][..len].to_vec()
}

#[cfg(test)]
mod test {
    use super::{bytes_to_wordlist, wordlist_to_bytes, BIP39_INSTRUCTIONS, BIP39_WORDLIST};

    #[test]
    fn validate_list_complete() {
        assert_eq!(2048, BIP39_WORDLIST.len());
        BIP39_WORDLIST.iter().for_each(|v| assert!(!v.is_empty()));
    }

    #[test]
    fn validate_instructions_non_empty() {
        assert!(!BIP39_INSTRUCTIONS.is_empty());
    }

    #[test]
    fn validate_roundtrip_short() {
        let original: Vec<u8> = vec![0x85, 0xc4, 0x3e, 0xe0, 0x38, 0x57, 0x76, 0x5b];
        let words = bytes_to_wordlist(&original);
        assert_eq!(words.len() % 6, 0);
        let word_refs: Vec<&str> = words.iter().copied().collect();
        assert_eq!(original, wordlist_to_bytes(&word_refs));
    }

    #[test]
    fn validate_roundtrip_unaligned() {
        let original: Vec<u8> = vec![1, 2, 3, 4, 5, 6, 7];
        let words = bytes_to_wordlist(&original);
        assert_eq!(words.len() % 6, 0);
        let word_refs: Vec<&str> = words.iter().copied().collect();
        assert_eq!(original, wordlist_to_bytes(&word_refs));
    }

    #[test]
    fn validate_roundtrip_empty() {
        let original: Vec<u8> = vec![];
        let words = bytes_to_wordlist(&original);
        let word_refs: Vec<&str> = words.iter().copied().collect();
        assert_eq!(original, wordlist_to_bytes(&word_refs));
    }
}