torvyon-core 0.1.2

Keys, addresses, post-quantum signing and transaction building for the Torvyon blockchain
Documentation
use std::fmt;

use k256::schnorr::{signature::hazmat::PrehashVerifier, SigningKey, VerifyingKey};
use zeroize::Zeroizing;

use crate::{hash::sha256, Address, Error, Network, Result};

/// A secp256k1 private key. Never printed; zeroized on drop.
#[derive(Clone)]
pub struct PrivateKey {
    // BIP340 signing keys are stored negated when the public key has an odd
    // Y, so the original bytes are kept for export and recovery phrases.
    bytes: Zeroizing<[u8; 32]>,
    signing: SigningKey,
}

impl PrivateKey {
    /// Generates a new random key from the OS random source.
    pub fn generate() -> Result<Self> {
        loop {
            let mut raw = Zeroizing::new([0u8; 32]);
            getrandom::getrandom(raw.as_mut()).map_err(|_| Error::InvalidPrivateKey)?;
            if let Ok(key) = Self::from_bytes(&raw) {
                return Ok(key);
            }
        }
    }

    /// Parses 32 raw bytes. Rejects zero and values ≥ the curve order.
    pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self> {
        let signing = SigningKey::from_bytes(bytes).map_err(|_| Error::InvalidPrivateKey)?;
        Ok(Self {
            bytes: Zeroizing::new(*bytes),
            signing,
        })
    }

    /// Parses 64 hex characters.
    pub fn from_hex(s: &str) -> Result<Self> {
        let mut raw = Zeroizing::new([0u8; 32]);
        hex::decode_to_slice(s.trim(), raw.as_mut()).map_err(|_| Error::InvalidPrivateKey)?;
        Self::from_bytes(&raw)
    }

    /// Raw 32 bytes.
    pub fn to_bytes(&self) -> Zeroizing<[u8; 32]> {
        self.bytes.clone()
    }

    /// Lowercase hex.
    pub fn to_hex(&self) -> Zeroizing<String> {
        Zeroizing::new(hex::encode(self.to_bytes().as_ref()))
    }

    /// The matching x-only public key.
    pub fn public_key(&self) -> PublicKey {
        PublicKey(self.signing.verifying_key().to_bytes().into())
    }

    /// The matching `bt1` address.
    pub fn address(&self) -> Address {
        self.public_key().address()
    }

    /// The matching address for the selected network.
    pub fn address_for_network(&self, network: Network) -> Address {
        self.public_key().address_for_network(network)
    }

    /// Signs `SHA256(message)` — the node's signing rule.
    pub fn sign(&self, message: &[u8]) -> Result<Signature> {
        self.sign_digest(&sha256(message))
    }

    /// Signs an already-computed 32-byte digest (for example a transaction sighash).
    pub fn sign_digest(&self, digest: &[u8; 32]) -> Result<Signature> {
        let mut aux = [0u8; 32];
        getrandom::getrandom(&mut aux).map_err(|_| Error::InvalidSignature)?;
        let sig = self
            .signing
            .sign_raw(digest, &aux)
            .map_err(|_| Error::InvalidSignature)?;
        Ok(Signature(sig.to_bytes()))
    }
}

impl fmt::Debug for PrivateKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("PrivateKey(<redacted>)")
    }
}

/// A 32-byte x-only (BIP340) public key.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct PublicKey([u8; 32]);

impl PublicKey {
    /// Parses 32 bytes; must be a valid curve point.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
        let arr: [u8; 32] = bytes.try_into().map_err(|_| Error::InvalidPublicKey)?;
        VerifyingKey::from_bytes(&arr).map_err(|_| Error::InvalidPublicKey)?;
        Ok(Self(arr))
    }

    /// Parses 64 hex characters.
    pub fn from_hex(s: &str) -> Result<Self> {
        Self::from_bytes(&hex::decode(s.trim()).map_err(|_| Error::InvalidPublicKey)?)
    }

    /// Raw 32 bytes.
    pub fn to_bytes(&self) -> [u8; 32] {
        self.0
    }

    /// Lowercase hex.
    pub fn to_hex(&self) -> String {
        hex::encode(self.0)
    }

    /// The `bt1` address of this key.
    pub fn address(&self) -> Address {
        Address::from_public_key_bytes(&self.0)
    }

    /// The address of this key for the selected network.
    pub fn address_for_network(&self, network: Network) -> Address {
        Address::from_public_key_bytes_for_network(&self.0, network)
    }

    /// Verifies a signature over `SHA256(message)`.
    pub fn verify(&self, message: &[u8], signature: &Signature) -> bool {
        self.verify_digest(&sha256(message), signature)
    }

    /// Verifies a signature over a 32-byte digest.
    pub fn verify_digest(&self, digest: &[u8; 32], signature: &Signature) -> bool {
        let (Ok(key), Ok(sig)) = (
            VerifyingKey::from_bytes(&self.0),
            k256::schnorr::Signature::try_from(&signature.0[..]),
        ) else {
            return false;
        };
        key.verify_prehash(digest, &sig).is_ok()
    }
}

impl fmt::Debug for PublicKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "PublicKey({})", self.to_hex())
    }
}

/// A 64-byte BIP340 Schnorr signature.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Signature([u8; 64]);

impl Signature {
    /// Wraps 64 bytes.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
        bytes.try_into().map(Self).map_err(|_| Error::InvalidSignature)
    }

    /// Parses 128 hex characters.
    pub fn from_hex(s: &str) -> Result<Self> {
        Self::from_bytes(&hex::decode(s.trim()).map_err(|_| Error::InvalidSignature)?)
    }

    /// Raw 64 bytes.
    pub fn to_bytes(&self) -> [u8; 64] {
        self.0
    }

    /// Lowercase hex.
    pub fn to_hex(&self) -> String {
        hex::encode(self.0)
    }
}

impl fmt::Debug for Signature {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Signature({})", self.to_hex())
    }
}