Skip to content

Commit

Permalink
Merge #954: Add Script conversion method p2wpkh_script_code
Browse files Browse the repository at this point in the history
d882b68 Add Script conversion method p2wpkh_script_code (Tobin Harding)

Pull request description:

  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] (also described in BIP143)

  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.

  Includes a link to BIP143

  [0] https://github.com/libbitcoin/libbitcoin-system/wiki/P2WPKH-Transactions#spending-a-p2wpkh-output

ACKs for top commit:
  apoelstra:
    ACK d882b68
  sanket1729:
    code review ACK d882b68.

Tree-SHA512: 9a3244b5aac4e2911edf4d3bb634d3d2b98006b864280a2a04b45c55c263c2541bf25f01196f2a65bf9acbdd0cf28c69c3a020a7e6c8da6fddf7c7cfbb62836d
  • Loading branch information
sanket1729 committed Apr 20, 2022
2 parents 94f8c4b + d882b68 commit 3057402
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/blockdata/script.rs
Expand Up @@ -427,6 +427,25 @@ impl Script {
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
/// script").
pub fn to_v0_p2wsh(&self) -> Script {
Expand Down

0 comments on commit 3057402

Please sign in to comment.