torvyon-core 0.1.3

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

use serde::{Deserialize, Deserializer, Serialize, Serializer};

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

const PAYLOAD_HEX_LEN: usize = 40;
const CHECKSUM_LEN: usize = 4;

/// A validated `bt1` address.
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Address(String);

impl Address {
    /// Parses and validates, with the node's checks in the node's order.
    pub fn parse(s: &str) -> Result<Self> {
        Self::parse_for_network(s, Network::Mainnet)
    }

    /// Parses and validates for a specific network.
    pub fn parse_for_network(s: &str, network: Network) -> Result<Self> {
        let prefix = network.address_prefix();
        let address_len = prefix.len() + PAYLOAD_HEX_LEN + CHECKSUM_LEN * 2;
        if s.len() != address_len {
            return Err(Error::AddressLength);
        }
        if !s.starts_with(prefix) {
            return Err(Error::AddressPrefix);
        }
        let (base, checksum_hex) = s.split_at(prefix.len() + PAYLOAD_HEX_LEN);
        hex::decode(&base[prefix.len()..]).map_err(|_| Error::AddressPayload)?;
        let got = hex::decode(checksum_hex).map_err(|_| Error::AddressChecksum)?;
        if got != checksum(base) {
            return Err(Error::AddressChecksum);
        }
        Ok(Self(s.to_owned()))
    }

    /// Derives the address of a raw 32-byte public key. Does not check that
    /// the bytes are a valid curve point (the node doesn't either).
    pub(crate) fn from_public_key_bytes(public_key: &[u8]) -> Self {
        Self::from_public_key_bytes_for_network(public_key, Network::Mainnet)
    }

    /// Derives the network-specific address of a raw 32-byte public key.
    pub(crate) fn from_public_key_bytes_for_network(public_key: &[u8], network: Network) -> Self {
        let payload = &sha256(public_key)[..20];
        let base = format!("{}{}", network.address_prefix(), hex::encode(payload));
        let check = hex::encode(checksum(&base));
        Self(base + &check)
    }

    /// The address text.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

fn checksum(base: &str) -> [u8; CHECKSUM_LEN] {
    let second = sha256(&sha256(base.as_bytes()));
    let mut out = [0u8; CHECKSUM_LEN];
    out.copy_from_slice(&second[..CHECKSUM_LEN]);
    out
}

impl fmt::Display for Address {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

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

impl FromStr for Address {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self> {
        Self::parse(s)
    }
}

impl AsRef<str> for Address {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Serialize for Address {
    fn serialize<S: Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
        s.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for Address {
    fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        Self::parse(&s).map_err(serde::de::Error::custom)
    }
}