Add Script conversion method p2wpkh_script_code

In order to sign a utxo that does a p2wpkh spend we need to create the
script that can be used to create a sighash. In the libbitcoin docs this
is referred to as the 'script code' [0].

The script is the same as a p2pkh script but the pubkey_hash is found in
the scriptPubkey.

Add a `Script` conversion method that checks if `self` is a v0 p2wpkh
script and if so extracts the pubkey_hash and returns the required
script.

[0] https://github.com/libbitcoin/libbitcoin-system/wiki/P2WPKH-Transactions#spending-a-p2wpkh-output
This commit is contained in:
Tobin Harding 2022-04-07 15:13:07 +10:00
parent 8ca18f75dd
commit d882b68a2c
1 changed files with 19 additions and 0 deletions

View File

@ -427,6 +427,25 @@ impl Script {
Script::new_p2sh(&self.script_hash()) Script::new_p2sh(&self.script_hash())
} }
/// Returns the script code used for spending a P2WPKH output if this script is a script pubkey
/// for a P2WPKH output. The `scriptCode` is described in [BIP143].
///
/// [BIP143]: <https://github.com/bitcoin/bips/blob/99701f68a88ce33b2d0838eb84e115cef505b4c2/bip-0143.mediawiki>
pub fn p2wpkh_script_code(&self) -> Option<Script> {
if !self.is_v0_p2wpkh() {
return None
}
let script = Builder::new()
.push_opcode(opcodes::all::OP_DUP)
.push_opcode(opcodes::all::OP_HASH160)
.push_slice(&self[2..]) // The `self` script is 0x00, 0x14, <pubkey_hash>
.push_opcode(opcodes::all::OP_EQUALVERIFY)
.push_opcode(opcodes::all::OP_CHECKSIG)
.into_script();
Some(script)
}
/// Computes the P2WSH output corresponding to this witnessScript (aka the "witness redeem /// Computes the P2WSH output corresponding to this witnessScript (aka the "witness redeem
/// script"). /// script").
pub fn to_v0_p2wsh(&self) -> Script { pub fn to_v0_p2wsh(&self) -> Script {