torvyon-core 0.1.3

Keys, addresses, post-quantum signing and transaction building for the Torvyon blockchain
Documentation
use bip39::{Language, Mnemonic};
use zeroize::Zeroizing;

use crate::{Error, PrivateKey, Result};

const WORDS: usize = 24;

/// Recovers the private key from a 24-word phrase. The phrase's BIP39
/// entropy *is* the key (no seed derivation, no HD path) — see
/// `spec/keys-and-addresses.md`. Case and whitespace are normalized.
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)
}

/// The 24-word phrase for a private key.
pub fn mnemonic_from_private_key(key: &PrivateKey) -> Zeroizing<String> {
    let bytes = key.to_bytes();
    // 32 bytes is always valid BIP39 entropy, so this cannot fail.
    let words = Mnemonic::from_entropy_in(Language::English, bytes.as_ref()).map(|m| m.to_string());
    Zeroizing::new(words.unwrap_or_default())
}