Merge rust-bitcoin/rust-bitcoin#954: Add Script conversion method p2wpkh_script_code

d882b68a2c 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 d882b68a2c
  sanket1729:
    code review ACK d882b68a2c.

Tree-SHA512: 9a3244b5aac4e2911edf4d3bb634d3d2b98006b864280a2a04b45c55c263c2541bf25f01196f2a65bf9acbdd0cf28c69c3a020a7e6c8da6fddf7c7cfbb62836d
This commit is contained in:
sanket1729 2022-04-20 14:35:44 -07:00
commit 30574020ef
No known key found for this signature in database
GPG Key ID: 648FFB183E0870A2
1 changed files with 19 additions and 0 deletions

View File

@ -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 {