use serde::{Deserialize, Serialize};
use crate::Address;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct ScriptPubKey {
pub version: i64,
#[serde(rename = "type")]
pub kind: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub pubkey_hash: String,
#[serde(default, skip_serializing_if = "is_zero")]
pub threshold: i64,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub signers: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub lock_height: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub lock_time_ms: Option<i64>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub hash: String,
}
fn is_zero(v: &i64) -> bool {
*v == 0
}
impl ScriptPubKey {
pub fn p2pkh(owner: &Address) -> Self {
Self {
version: 1,
kind: "p2pkh".into(),
pubkey_hash: owner.to_string(),
..Self::default()
}
}
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)
}
pub fn is_p2pkh_to(&self, owner: &Address) -> bool {
self.kind == "p2pkh" && self.pubkey_hash == owner.as_str()
}
}