torvyon-core 0.1.3

Keys, addresses, post-quantum signing and transaction building for the Torvyon blockchain
Documentation
use serde::{Deserialize, Serialize};

use crate::Address;

/// A locking script, mirroring the node's `script.Script` JSON.
///
/// SDK builders only ever create p2pkh. Other types exist so any on-chain
/// or historical transaction can be decoded and its payload re-encoded.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct ScriptPubKey {
    /// Script version (1).
    pub version: i64,
    /// `p2pkh`, `multisig`, `timelock` or `hashlock`.
    #[serde(rename = "type")]
    pub kind: String,
    /// For p2pkh: the owner's full `bt1` address as text.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub pubkey_hash: String,
    /// Multisig threshold.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub threshold: i64,
    /// Multisig signer addresses.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub signers: Vec<String>,
    /// Timelock height.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lock_height: Option<u64>,
    /// Timelock time in milliseconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lock_time_ms: Option<i64>,
    /// Hashlock hash (hex).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub hash: String,
}

fn is_zero(v: &i64) -> bool {
    *v == 0
}

impl ScriptPubKey {
    /// A pay-to-address script.
    pub fn p2pkh(owner: &Address) -> Self {
        Self {
            version: 1,
            kind: "p2pkh".into(),
            pubkey_hash: owner.to_string(),
            ..Self::default()
        }
    }

    /// The node's `Canonicalize()`: normalizes type/version and validates.
    /// Returns `None` where the node returns an error.
    pub fn canonicalize(&self) -> Option<Self> {
        let mut s = self.clone();
        s.kind = s.kind.trim().to_lowercase();
        if s.version == 0 {
            s.version = 1;
        }
        if s.version != 1 {
            return None;
        }
        let valid = match s.kind.as_str() {
            "p2pkh" => !s.pubkey_hash.is_empty(),
            "multisig" => {
                s.signers.sort();
                s.threshold > 0 && !s.signers.is_empty() && s.threshold as usize <= s.signers.len()
            }
            "timelock" => s.lock_height.is_some() || s.lock_time_ms.is_some(),
            "hashlock" => !s.hash.is_empty(),
            _ => false,
        };
        valid.then_some(s)
    }

    /// True if this is a p2pkh script paying `owner`.
    pub fn is_p2pkh_to(&self, owner: &Address) -> bool {
        self.kind == "p2pkh" && self.pubkey_hash == owner.as_str()
    }
}