Module script

Module script 

Source
Expand description

Script pubkey types and operations.

This module provides types for working with script pubkeys (also known as “locking scripts”), which define the conditions that must be met to spend a crate::TxOut.

§Types

The module provides two types:

  • ScriptPubkey: An owned script pubkey that manages its own memory
  • ScriptPubkeyRef: A borrowed reference to a script pubkey with a specific lifetime

Both types implement the ScriptPubkeyExt trait, providing a unified interface for all script pubkey operations regardless of ownership.

§Examples

§Creating and working with script pubkeys

// Create a simple script from raw bytes
let script = ScriptPubkey::new(&[0x76, 0xa9, 0x14]).unwrap();

// Serialize back to bytes
let bytes = script.to_bytes();
assert_eq!(bytes, vec![0x76, 0xa9, 0x14]);

// Use TryFrom for conversion
let script2 = ScriptPubkey::try_from(bytes.as_slice()).unwrap();

§Creating standard script types

// P2PKH: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
let p2pkh_hex = "76a914deadbeefdeadbeefdeadbeefdeadbeefdeadbeef88ac";
let p2pkh = ScriptPubkey::new(&hex::decode(p2pkh_hex).unwrap()).unwrap();

// P2SH: OP_HASH160 <scriptHash> OP_EQUAL
let p2sh_hex = "a914deadbeefdeadbeefdeadbeefdeadbeefdeadbeef87";
let p2sh = ScriptPubkey::new(&hex::decode(p2sh_hex).unwrap()).unwrap();

// P2WPKH: OP_0 <20-byte-pubkey-hash>
let p2wpkh_hex = "0014deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
let p2wpkh = ScriptPubkey::new(&hex::decode(p2wpkh_hex).unwrap()).unwrap();

Structs§

ScriptPubkey
A single script pubkey containing spending conditions for a crate::TxOut.
ScriptPubkeyRef
A borrowed reference to a script pubkey.

Traits§

ScriptPubkeyExt
Common operations for script pubkeys, implemented by both owned and borrowed types.