libhardcopy 1.0.0

Generalized library for hardcopy/softcopy command line utilities.
Documentation
/// BIP-39 is a standard mnemonic encoding used by hardware wallets to back up
/// cryptographic seed phrases. The 2048-word list was chosen for clarity and
/// distinctiveness across multiple languages. Each word encodes 11 bits, so
/// every 6-word group encodes 64 bits of data plus a 2-bit checksum (same
/// block structure as S/KEY OTP, different vocabulary).
///
/// References
/// * BIP-39 specification: https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki
///
mod algo;

pub use crate::plugins::bip39::algo::BIP39_INSTRUCTIONS;
use crate::plugins::bip39::algo::{bytes_to_wordlist, max_word_len, wordlist_to_bytes};
use crate::plugins::{GenerationError, HardCopyGenerator, LibPlugin, SoftCopyGenerator};
use crate::{
    HardCopy, HardCopyInput, HardCopySection, HardCopySectionContent, SoftCopy, SoftCopyInput,
};

const WORDS_PER_LINE: usize = 6;

pub struct Bip39Plugin;

const PLUGIN_NAME: &str = "BIP-39";
const PLUGIN_DESCRIPTION: &str = "Wordlist generation using BIP-39 mnemonic words.";

impl LibPlugin for Bip39Plugin {
    fn name(&self) -> String {
        PLUGIN_NAME.to_string()
    }
    fn description(&self) -> String {
        PLUGIN_DESCRIPTION.to_string()
    }
    fn instructions(&self) -> String {
        BIP39_INSTRUCTIONS.to_string()
    }
}

impl HardCopyGenerator for Bip39Plugin {
    fn generate_hard_copy(&self, softinput: &SoftCopyInput) -> Result<HardCopy, GenerationError> {
        let words = bytes_to_wordlist(softinput.to_bytes());
        let col_width = max_word_len();
        let lines: Vec<String> = words
            .chunks(WORDS_PER_LINE)
            .enumerate()
            .map(|(i, chunk)| {
                let padded: Vec<String> = chunk
                    .iter()
                    .map(|w| format!("{:width$}", w, width = col_width))
                    .collect();
                format!("{:04}: {}", i + 1, padded.join(" "))
            })
            .collect();
        let mut hardcopy = HardCopy::new();
        hardcopy.push(HardCopySection {
            name: PLUGIN_NAME.to_string(),
            content: HardCopySectionContent::Words(lines),
        });
        Ok(hardcopy)
    }
}

impl SoftCopyGenerator for Bip39Plugin {
    fn generate_soft_copy(&self, input: &mut HardCopyInput) -> Result<SoftCopy, GenerationError> {
        let word_refs: Vec<&str> = input.words().iter().map(String::as_str).collect();
        let bytes = wordlist_to_bytes(&word_refs);
        Ok(SoftCopy { bytes })
    }
}

#[cfg(test)]
mod test {
    use super::BIP39_INSTRUCTIONS;

    #[test]
    fn validate_instructions_non_empty() {
        assert!(
            !BIP39_INSTRUCTIONS.is_empty(),
            "Verify the instructions are not empty."
        );
    }
}