use super::address::Address;
use super::chunk::ScriptChunk;
use super::script::Script;
use crate::Result;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LockingScript(Script);
impl LockingScript {
pub fn new() -> Self {
Self(Script::new())
}
pub fn from_chunks(chunks: Vec<ScriptChunk>) -> Self {
Self(Script::from_chunks(chunks))
}
pub fn from_asm(asm: &str) -> Result<Self> {
Ok(Self(Script::from_asm(asm)?))
}
pub fn from_hex(hex: &str) -> Result<Self> {
Ok(Self(Script::from_hex(hex)?))
}
pub fn from_binary(bin: &[u8]) -> Result<Self> {
Ok(Self(Script::from_binary(bin)?))
}
pub fn from_script(script: Script) -> Self {
Self(script)
}
pub fn as_script(&self) -> &Script {
&self.0
}
pub fn into_script(self) -> Script {
self.0
}
pub fn to_asm(&self) -> String {
self.0.to_asm()
}
pub fn to_hex(&self) -> String {
self.0.to_hex()
}
pub fn to_binary(&self) -> Vec<u8> {
self.0.to_binary()
}
pub fn chunks(&self) -> Vec<ScriptChunk> {
self.0.chunks()
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn is_push_only(&self) -> bool {
self.0.is_push_only()
}
pub fn is_locking_script(&self) -> bool {
true
}
pub fn is_unlocking_script(&self) -> bool {
false
}
pub fn to_address(&self) -> Option<Address> {
let hash = self.0.extract_pubkey_hash()?;
Address::new_from_public_key_hash(&hash, true).ok()
}
}
impl Default for LockingScript {
fn default() -> Self {
Self::new()
}
}
impl From<Script> for LockingScript {
fn from(script: Script) -> Self {
Self(script)
}
}
impl From<LockingScript> for Script {
fn from(locking: LockingScript) -> Self {
locking.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_locking_script() {
let script = LockingScript::new();
assert!(script.is_locking_script());
assert!(!script.is_unlocking_script());
}
#[test]
fn test_from_hex() {
let hex = "76a914000000000000000000000000000000000000000088ac";
let script = LockingScript::from_hex(hex).unwrap();
assert_eq!(script.to_hex(), hex);
}
#[test]
fn test_from_asm() {
let asm = "OP_DUP OP_HASH160";
let script = LockingScript::from_asm(asm).unwrap();
assert_eq!(script.to_hex(), "76a9");
}
#[test]
fn test_conversion() {
let script = Script::from_hex("76a9").unwrap();
let locking = LockingScript::from_script(script.clone());
let back: Script = locking.into();
assert_eq!(back.to_hex(), script.to_hex());
}
}