Merge rust-bitcoin/rust-bitcoin#6956: bitcoin: introduce ScriptCode for sighash computation
What changed, and why it matters
This is a code-quality and type-safety refactor for the rust-bitcoin library. It introduces a dedicated ScriptCode type for computing Bitcoin transaction signatures (sighashes), replacing the previous practice of reusing the WitnessScriptBuf type. The change makes the API clearer and reduces the chance that developers accidentally pass the wrong kind of script when signing transactions. There is no direct security vulnerability being patched here; it is a preventive correctness improvement.
No urgent action required. Downstream users should review the API changes (new ScriptCode type, P2wpkhScriptCode, and AsRef<ScriptCode> conversions) when upgrading, and update sighash call sites accordingly. The change is a routine refactor with preventive security benefits.
Security signals we found
Type-system hardening: new ScriptCode type prevents misuse of witness/redeem/scriptPubKey types in sighash APIs
API change: legacy and segwit v0 sighash functions now accept ScriptCode instead of arbitrary script types
Correctness: OP_CODESEPARATOR encoding logic now operates on ScriptCode
New test coverage: BIP-143 P2WSH OP_CODESEPARATOR sighash vectors added
No direct vulnerability or exploit path identified in the diff
Evidence from the diff
The merge introduces ScriptCode and P2wpkhScriptCode as first-class types for sighash computation. Previously, p2wpkh_script_code returned a WitnessScriptBuf even though the BIP-143 scriptCode is not a witness script, and legacy/segwit sighash APIs accepted generic ScriptHashableTag scripts. The patch changes APIs to accept impl AsRef
Changed components
bitcoin/src/blockdata/script/script_code.rs (new)bitcoin/src/blockdata/script/borrowed.rsbitcoin/src/blockdata/script/mod.rsbitcoin/src/crypto/sighash.rsbitcoin/src/crypto/key.rsprimitives/src/script/mod.rsprimitives/src/script/tag.rsbitcoin/tests/sighash.rsbitcoin/examples/script.rsInspect captured patch +255 / −92
### bitcoin/examples/script.rs
@@ -7,75 +7,76 @@
//!
//! [`CompactSize`]: <https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer>
-use bitcoin::key::WPubkeyHash;
-use bitcoin::{encoding, script, WitnessScriptBuf};
+use bitcoin::key::PubkeyHash;
+use bitcoin::script::ScriptPubKeyBufExt as _;
+use bitcoin::{encoding, ScriptPubKeyBuf};
fn main() {
- let pk = "b472a266d0bd89c13706a4132ccfb16f7c3b9fcb".parse::<WPubkeyHash>().unwrap();
+ let pk = "b472a266d0bd89c13706a4132ccfb16f7c3b9fcb".parse::<PubkeyHash>().unwrap();
// TL;DR Use `to_hex_string_prefixed` and `from_hex_prefixed`.
- let script_code = script::p2wpkh_script_code(pk);
- let hex = script_code.to_hex_string_prefixed();
- let decoded = WitnessScriptBuf::from_hex_prefixed(&hex).unwrap();
- assert_eq!(decoded, script_code);
+ let script = ScriptPubKeyBuf::new_p2pkh(pk);
+ let hex = script.to_hex_string_prefixed();
+ let decoded = ScriptPubKeyBuf::from_hex_prefixed(&hex).unwrap();
+ assert_eq!(decoded, script);
// Or if you prefer: `to_hex_string_no_length_prefix` and `from_hex_no_length_prefix`.
- let script_code = script::p2wpkh_script_code(pk);
- let hex = script_code.to_hex_string_no_length_prefix();
- let decoded = WitnessScriptBuf::from_hex_no_length_prefix(&hex).unwrap();
- assert_eq!(decoded, script_code);
+ let script = ScriptPubKeyBuf::new_p2pkh(pk);
+ let hex = script.to_hex_string_no_length_prefix();
+ let decoded = ScriptPubKeyBuf::from_hex_no_length_prefix(&hex).unwrap();
+ assert_eq!(decoded, script);
// Writes the script as human-readable eg, OP_DUP OP_HASH160 OP_PUSHBYTES_20 ...
- println!("human-readable script: {script_code}");
+ println!("human-readable script: {script}");
// We do not implement parsing scripts from human-readable format.
- // let decoded = s.parse::<WitnessScriptBuf>().unwrap();
+ // let decoded = s.parse::<ScriptPubKeyBuf>().unwrap();
// This is not equivalent to consensus encoding i.e., does not include the length prefix.
- let hex_lower_hex_trait = format!("{script_code:x}");
+ let hex_lower_hex_trait = format!("{script:x}");
println!("hex created using `LowerHex`: {hex_lower_hex_trait}");
// The `deserialize_hex` function requires the length prefix.
- assert!(encoding::decode_from_hex::<WitnessScriptBuf>(&hex_lower_hex_trait).is_err());
+ assert!(encoding::decode_from_hex::<ScriptPubKeyBuf>(&hex_lower_hex_trait).is_err());
// And so does `from_hex_prefixed`.
- assert!(WitnessScriptBuf::from_hex_prefixed(&hex_lower_hex_trait).is_err());
+ assert!(ScriptPubKeyBuf::from_hex_prefixed(&hex_lower_hex_trait).is_err());
// But we provide an explicit constructor that does not.
assert_eq!(
- WitnessScriptBuf::from_hex_no_length_prefix(&hex_lower_hex_trait).unwrap(),
- script_code
+ ScriptPubKeyBuf::from_hex_no_length_prefix(&hex_lower_hex_trait).unwrap(),
+ script
);
// This is consensus encoding i.e., includes the length prefix.
- let hex_inherent = script_code.to_hex_string_prefixed(); // Defined in `ScriptExt`.
+ let hex_inherent = script.to_hex_string_prefixed(); // Defined in `ScriptExt`.
println!("hex created using inherent `to_hex_string_prefixed`: {hex_inherent}");
// The inverse of `to_hex_string_prefixed` is `from_hex_prefixed`.
- let decoded = WitnessScriptBuf::from_hex_prefixed(&hex_inherent).unwrap(); // Defined in `ScriptBufExt`.
- assert_eq!(decoded, script_code);
+ let decoded = ScriptPubKeyBuf::from_hex_prefixed(&hex_inherent).unwrap(); // Defined in `ScriptBufExt`.
+ assert_eq!(decoded, script);
// We can also parse the output of `to_hex_string_prefixed` using `deserialize_hex`.
- let decoded = encoding::decode_from_hex::<WitnessScriptBuf>(&hex_inherent).unwrap();
- assert_eq!(decoded, script_code);
+ let decoded = encoding::decode_from_hex::<ScriptPubKeyBuf>(&hex_inherent).unwrap();
+ assert_eq!(decoded, script);
// We also support encode/decode using `consensus::encode` functions.
- let encoded = encoding::encode_to_hex(script_code.as_script(), hex::Case::Lower);
+ let encoded = encoding::encode_to_hex(script.as_script(), hex::Case::Lower);
println!("hex created using consensus::encode::serialize_hex: {encoded}");
- let decoded: WitnessScriptBuf = encoding::decode_from_hex(&encoded).unwrap();
- assert_eq!(decoded, script_code);
+ let decoded: ScriptPubKeyBuf = encoding::decode_from_hex(&encoded).unwrap();
+ assert_eq!(decoded, script);
// And we can mix these two calls because both include the length prefix.
- let encoded = encoding::encode_to_hex(script_code.as_script(), hex::Case::Lower);
- let decoded = WitnessScriptBuf::from_hex_prefixed(&encoded).unwrap();
- assert_eq!(decoded, script_code);
+ let encoded = encoding::encode_to_hex(script.as_script(), hex::Case::Lower);
+ let decoded = ScriptPubKeyBuf::from_hex_prefixed(&encoded).unwrap();
+ assert_eq!(decoded, script);
// Encode/decode using a byte vector.
- let encoded = encoding::encode_to_vec(script_code.as_script());
- assert_eq!(&encoded[1..], script_code.as_bytes()); // Shows that prefix is the first byte.
- let decoded: WitnessScriptBuf = encoding::decode_from_slice(&encoded).unwrap();
- assert_eq!(decoded, script_code);
+ let encoded = encoding::encode_to_vec(script.as_script());
+ assert_eq!(&encoded[1..], script.as_bytes()); // Shows that prefix is the first byte.
+ let decoded: ScriptPubKeyBuf = encoding::decode_from_slice(&encoded).unwrap();
+ assert_eq!(decoded, script);
// to/from bytes excludes the prefix, these are not encoding/decoding functions so this is sane.
- let bytes = script_code.to_vec();
- let got = WitnessScriptBuf::from_bytes(bytes);
- assert_eq!(got, script_code);
+ let bytes = script.to_vec();
+ let got = ScriptPubKeyBuf::from_bytes(bytes);
+ assert_eq!(got, script);
}
### bitcoin/src/blockdata/script/borrowed.rs
@@ -18,7 +18,7 @@ use crate::policy::{DUST_RELAY_TX_FEE, MAX_OP_RETURN_RELAY};
use crate::prelude::{String, ToString};
use crate::script::{self, ScriptPubKeyBufExt as _};
use crate::taproot::{LeafVersion, TapLeafHash, TapLeafHashExt as _, TapNodeHash};
-use crate::{internal_macros, Amount, FeeRate, ScriptPubKeyBuf, ToU64 as _, WitnessScriptBuf};
+use crate::{internal_macros, Amount, FeeRate, P2wpkhScriptCode, ScriptPubKeyBuf, ToU64 as _};
internal_macros::define_extension_trait! {
/// Extension functionality for the [`Script`] type.
@@ -150,12 +150,8 @@ internal_macros::define_extension_trait! {
/// 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 [BIP-0143].
///
- /// While the type returned is [`WitnessScriptBuf`], this is **not** a witness script and
- /// should not be used as one. It is a special template defined in BIP 143 which is used
- /// in place of a witness script for purposes of sighash computation.
- ///
/// [BIP-0143]: <https://github.com/bitcoin/bips/blob/99701f68a88ce33b2d0838eb84e115cef505b4c2/bip-0143.mediawiki>
- fn p2wpkh_script_code(&self) -> Option<WitnessScriptBuf>
+ fn p2wpkh_script_code(&self) -> Option<P2wpkhScriptCode>
where T: ScriptHashableTag
{
if self.is_p2wpkh() {
### bitcoin/src/blockdata/script/mod.rs
@@ -50,6 +50,7 @@ mod builder;
mod instruction;
mod owned;
mod push_bytes;
+mod script_code;
#[cfg(test)]
mod tests;
pub mod witness_version;
@@ -67,6 +68,7 @@ pub use self::{
instruction::{Instruction, Instructions, InstructionIndices},
owned::{ScriptBufExt, ScriptPubKeyBufExt, ScriptSigBufExt},
push_bytes::{PushBytes, PushBytesBuf, PushBytesExt, PushBytesErrorReport},
+ script_code::P2wpkhScriptCode
};
#[doc(inline)]
pub use addresses::witness_program;
@@ -78,7 +80,7 @@ pub use primitives::script::{
ScriptEncoder, ScriptHash, ScriptHashableTag, ScriptPubKey, ScriptPubKeyBuf, ScriptPubKeyTag,
ScriptSig, ScriptSigBuf, ScriptSigTag, SignetBlockScript, SignetBlockScriptBuf,
SignetBlockScriptTag, Tag, TapScript, TapScriptBuf, TapScriptTag, WScriptHash, WitnessScript,
- WitnessScriptBuf, WitnessScriptTag,
+ WitnessScriptBuf, WitnessScriptTag, ScriptCode, ScriptCodeTag,
};
pub(crate) use self::borrowed::ScriptExtPriv;
@@ -90,23 +92,13 @@ pub use self::error::{
};
pub(crate) use self::owned::ScriptBufExtPriv;
-/// Constructs a new [`WitnessScriptBuf`] containing the script code used for spending a P2WPKH output.
+/// Constructs a new [`P2wpkhScriptCode`] containing the script code used for spending a P2WPKH output.
///
/// The `scriptCode` is described in [BIP-0143].
///
-/// While the type returned is [`WitnessScriptBuf`], this is **not** a witness script and
-/// should not be used as one. It is a special template defined in BIP-0143 which is used
-/// in place of a witness script for purposes of sighash computation.
-///
/// [BIP-0143]: <https://github.com/bitcoin/bips/blob/99701f68a88ce33b2d0838eb84e115cef505b4c2/bip-0143.mediawiki>
-pub fn p2wpkh_script_code(wpkh: WPubkeyHash) -> WitnessScriptBuf {
- Builder::new()
- .push_opcode(OP_DUP)
- .push_opcode(OP_HASH160)
- .push_slice(wpkh)
- .push_opcode(OP_EQUALVERIFY)
- .push_opcode(OP_CHECKSIG)
- .into_script()
+pub fn p2wpkh_script_code(wpkh: WPubkeyHash) -> P2wpkhScriptCode {
+ P2wpkhScriptCode::new_p2wpkh(wpkh)
}
/// Encodes an integer in script(minimal CScriptNum) format.
### bitcoin/src/blockdata/script/script_code.rs
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: CC0-1.0
+
+use core::ops::Deref;
+
+use crate::key::WPubkeyHash;
+use crate::script::ScriptCode;
+
+use crate::opcodes::all::{
+ OP_CHECKSIG, OP_DUP, OP_EQUALVERIFY, OP_HASH160, OP_PUSHBYTES_20,
+};
+const P2WPKH_SCRIPT_CODE_LEN: usize = 25;
+
+/// Owned script code used for P2WPKH sighash computation.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct P2wpkhScriptCode([u8; P2WPKH_SCRIPT_CODE_LEN]);
+
+impl P2wpkhScriptCode {
+ /// Constructs a new [`P2wpkhScriptCode`] containing the script code used for spending a P2WPKH output.
+ pub fn new_p2wpkh(wpkh: WPubkeyHash) -> Self {
+ let mut bytes = [0u8; P2WPKH_SCRIPT_CODE_LEN];
+
+ bytes[0] = OP_DUP.to_u8();
+ bytes[1] = OP_HASH160.to_u8();
+ bytes[2] = OP_PUSHBYTES_20.to_u8();
+ bytes[3..23].copy_from_slice(wpkh.as_byte_array());
+ bytes[23] = OP_EQUALVERIFY.to_u8();
+ bytes[24] = OP_CHECKSIG.to_u8();
+
+ Self(bytes)
+ }
+
+ /// Borrows the script code without modifyign or copying its bytes.
+ pub fn as_script(&self) -> &ScriptCode {
+ ScriptCode::from_bytes(&self.0)
+ }
+}
+
+impl AsRef<ScriptCode> for P2wpkhScriptCode {
+ fn as_ref(&self) -> &ScriptCode {
+ self.as_script()
+ }
+}
+
+impl Deref for P2wpkhScriptCode {
+ type Target = ScriptCode;
+
+ fn deref(&self) -> &Self::Target {
+ self.as_script()
+ }
+}
### bitcoin/src/blockdata/script/tests.rs
@@ -1034,3 +1034,23 @@ fn instruction_indices_nth_extended() {
let pos_skip = script.instruction_indices().skip(2).next().unwrap().unwrap().0;
assert_eq!(pos_skip, 3, "skip(2).next() returned wrong position");
}
+
+#[test]
+fn p2wpkh_script_code() {
+ let wpkh = WPubkeyHash::from_byte_array(
+ hex!("1d0f172a0ecb48aee1be1f2687d2963ae33f71a1"),
+ );
+ let owned = P2wpkhScriptCode::new_p2wpkh(wpkh);
+ let script_code: &ScriptCode = &owned;
+
+ assert_eq!(
+ script_code.as_bytes(),
+ &hex!("76a9141d0f172a0ecb48aee1be1f2687d2963ae33f71a188ac"),
+ );
+
+ // Check that encoding includes the CompactSize prefix.
+ assert_eq!(
+ encode_to_vec(script_code),
+ hex!("1976a9141d0f172a0ecb48aee1be1f2687d2963ae33f71a188ac"),
+ );
+}
### bitcoin/src/crypto/key.rs
@@ -6,7 +6,7 @@
//! (de)serialized.
use crate::internal_macros::define_extension_trait;
-use crate::script::{self, WitnessScriptBuf};
+use crate::{script, P2wpkhScriptCode};
#[rustfmt::skip] // Keep public re-exports separate.
pub use secp256k1::{constants, Parity};
@@ -37,11 +37,7 @@ define_extension_trait! {
/// Extension functionality for the [`FullPublicKey`] type.
pub trait FullPublicKeyExt impl for FullPublicKey {
/// Returns the script code used to spend a P2WPKH input.
- ///
- /// While the type returned is [`WitnessScriptBuf`], this is **not** a witness script and
- /// should not be used as one. It is a special template defined in BIP 143 which is used
- /// in place of a witness script for purposes of sighash computation.
- fn p2wpkh_script_code(&self) -> WitnessScriptBuf {
+ fn p2wpkh_script_code(&self) -> P2wpkhScriptCode {
script::p2wpkh_script_code(self.wpubkey_hash())
}
}
@@ -52,14 +48,10 @@ define_extension_trait! {
pub trait LegacyPublicKeyExt impl for LegacyPublicKey {
/// Returns the script code used to spend a P2WPKH input.
///
- /// While the type returned is [`WitnessScriptBuf`], this is **not** a witness script and
- /// should not be used as one. It is a special template defined in BIP 143 which is used
- /// in place of a witness script for purposes of sighash computation.
- ///
/// # Errors
///
/// Errors if this key is not compressed.
- fn p2wpkh_script_code(&self) -> Result<WitnessScriptBuf, UncompressedPublicKeyError> {
+ fn p2wpkh_script_code(&self) -> Result<P2wpkhScriptCode, UncompressedPublicKeyError> {
let key = FullPublicKey::try_from(*self)?;
Ok(key.p2wpkh_script_code())
}
### bitcoin/src/crypto/sighash.rs
@@ -24,12 +24,14 @@ use io::Write;
use crate::opcodes::all::OP_CODESEPARATOR;
use crate::prelude::{Borrow, BorrowMut};
-use crate::script::{Instruction, ScriptExt as _, ScriptHashableTag};
+use crate::script::{Instruction, ScriptCodeTag, ScriptExt as _, ScriptHashableTag};
use crate::taproot::{LeafVersion, TapLeafHash, TapLeafTag, TAPROOT_ANNEX_PREFIX};
use crate::transaction::TransactionExt as _;
use crate::witness::Witness;
+#[cfg(doc)]
+use crate::ScriptPubKey;
use crate::{
- transaction, Amount, ScriptPubKey, Sequence, TapScript, Transaction, TxOut, WitnessScript,
+ transaction, Amount, Sequence, TapScript, Transaction, TxOut, ScriptCode
};
#[rustfmt::skip] // Keep public re-exports separate.
@@ -565,7 +567,7 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
/// [`std::io::Write`] trait.
///
/// `script_code` is dependent on the type of the spend transaction. For p2wpkh use
- /// [`WitnessScript::p2wpkh_script_code`], for p2wsh just pass in the witness script. (Also see
+ /// [`ScriptPubKey::p2wpkh_script_code`], for p2wsh just pass in the witness script. (Also see
/// [`Self::p2wpkh_signature_hash`] and [`SighashCache::p2wsh_signature_hash`].)
///
/// In order to sign, the data written by this function must be hashed using a double SHA256
@@ -575,10 +577,11 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
&mut self,
mut writer: W,
input_index: usize,
- script_code: &WitnessScript,
+ script_code: impl AsRef<ScriptCode>,
amount: Amount,
sighash_type: EcdsaSighashType,
) -> Result<(), SigningDataError<transaction::InputsIndexError>> {
+ let script_code = script_code.as_ref();
let zero_hash = [0; 32];
let (sighash, anyone_can_pay) = sighash_type.split_anyonecanpay_flag();
@@ -653,20 +656,20 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
/// Computes the BIP-0143 sighash to spend a p2wsh transaction for any flag type.
///
- /// `witness_script` is the script that goes into the [`Witness`],
- /// not the one that goes into `script_pubkey` of a [`TxOut`].
+ /// `script_code` is the prepared P2WSH script code derived from the witness script,
+ /// the script that goes into the [`Witness`], not the `script_pubkey` of a [`TxOut`].
pub fn p2wsh_signature_hash(
&mut self,
input_index: usize,
- witness_script: &WitnessScript,
+ script_code: impl AsRef<ScriptCode>,
amount: Amount,
sighash_type: EcdsaSighashType,
) -> Result<SegwitV0Sighash, transaction::InputsIndexError> {
let mut enc = SegwitV0Sighash::engine();
self.segwit_v0_encode_signing_data_to(
&mut enc,
input_index,
- witness_script,
+ script_code,
amount,
sighash_type,
)
@@ -697,13 +700,14 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
///
/// This function can't handle the SIGHASH_SINGLE bug internally, so it returns [`EncodeSigningDataResult`]
/// that must be handled by the caller (see [`EncodeSigningDataResult::is_sighash_single_bug`]).
- pub fn legacy_encode_signing_data_to<W: Write, T: ScriptHashableTag>(
+ pub fn legacy_encode_signing_data_to<W: Write>(
&self,
mut writer: W,
input_index: usize,
- script_code: &crate::script::Script<T>,
+ script_code: impl AsRef<ScriptCode>,
sighash_type: EcdsaSighashType,
) -> EncodeSigningDataResult<SigningDataError<transaction::InputsIndexError>> {
+ let script_code = script_code.as_ref();
// Validate input_index.
if let Err(e) = self.tx.borrow().tx_in(input_index) {
return EncodeSigningDataResult::WriteResult(Err(SigningDataError::Sighash(e)));
@@ -721,11 +725,11 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
return EncodeSigningDataResult::SighashSingleBug;
}
- fn encode_signing_data_to_inner<W: Write, T: ScriptHashableTag>(
+ fn encode_signing_data_to_inner<W: Write>(
self_: &Transaction,
mut writer: W,
input_index: usize,
- script_code: &crate::script::Script<T>,
+ script_code: &ScriptCode,
sighash_type: EcdsaSighashType,
) -> Result<(), io::Error> {
let (sighash, anyone_can_pay) = sighash_type.split_anyonecanpay_flag();
@@ -744,8 +748,7 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
if n == input_index {
legacy_encode_script_code_to(script_code, &mut writer)?;
} else {
- // TODO: Use ScriptCode instead of ScriptPubKey once it exists (see #6079)
- io::encode_to_writer(ScriptPubKey::new(), &mut writer)?;
+ io::encode_to_writer(ScriptCode::new(), &mut writer)?;
}
if n != input_index
&& (sighash == EcdsaSighashType::Single
@@ -816,10 +819,10 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
///
/// See [`Self::legacy_encode_signing_data_to`] for the requirements on
/// `script_code` and the handling of `OP_CODESEPARATOR`.
- pub fn legacy_signature_hash<T: ScriptHashableTag>(
+ pub fn legacy_signature_hash(
&self,
input_index: usize,
- script_code: &crate::script::Script<T>,
+ script_code: impl AsRef<ScriptCode>,
sighash_type: EcdsaSighashType,
) -> Result<LegacySighash, transaction::InputsIndexError> {
let mut engine = LegacySighash::engine();
@@ -956,8 +959,8 @@ fn is_invalid_use_of_sighash_single(
sighash.is_single() && input_index >= outputs_len
}
-fn legacy_encode_script_code_to<W: Write, T: ScriptHashableTag>(
- script_code: &crate::script::Script<T>,
+fn legacy_encode_script_code_to<W: Write>(
+ script_code: &ScriptCode,
writer: &mut W,
) -> Result<(), io::Error> {
let bytes = script_code.as_bytes();
@@ -985,7 +988,7 @@ fn legacy_encode_script_code_to<W: Write, T: ScriptHashableTag>(
let mut instructions = script_code.instruction_indices();
loop {
- let offset = bytes.len() - instructions.as_script::<T>().len();
+ let offset = bytes.len() - instructions.as_script::<ScriptCodeTag>().len();
match instructions.next() {
Some(Ok((index, Instruction::Op(OP_CODESEPARATOR)))) => {
writer.write_all(&bytes[start..index])?;
@@ -1436,15 +1439,15 @@ mod tests {
#[test]
fn legacy_script_code_separator() {
- let script_code = ScriptPubKey::from_bytes(&[0xab, 0x4c, 0x01, 0xab, 0xab]);
+ let script_code = ScriptCode::from_bytes(&[0xab, 0x4c, 0x01, 0xab, 0xab]);
let mut encoded = Vec::new();
legacy_encode_script_code_to(script_code, &mut encoded).expect("vecs don't error");
assert_eq!(encoded, [0x03, 0x4c, 0x01, 0xab]);
}
#[test]
fn legacy_script_code_incomplete_push() {
- let script_code = ScriptPubKey::from_bytes(&[0xab, 0x4c, 0x02, 0xab]);
+ let script_code = ScriptCode::from_bytes(&[0xab, 0x4c, 0x02, 0xab]);
let mut encoded = Vec::new();
legacy_encode_script_code_to(script_code, &mut encoded).expect("vecs don't error");
assert_eq!(encoded, [0x03, 0x4c, 0x02]);
@@ -1909,6 +1912,48 @@ mod tests {
);
}
+ #[test]
+ fn bip143_p2wsh_separator() {
+ // Source: https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki#native-p2wsh
+ let tx = decode_from_slice::<Transaction>(&hex!(
+ "0100000002fe3dc9208094f3ffd12645477b3dc56f60ec4fa8e6f5d67c565d1c6b9216b36e00000000\
+ 00ffffffff0815cf020f013ed6cf91d29f4202e8a58726b1ac6c79da47c23d1bee0a6925f800000000\
+ 00ffffffff0100f2052a010000001976a914a30741f8145e5acadf23f751864167f32e0963f788ac00000000"
+ ))
+ .unwrap();
+ let witness_script = hex!(
+ "21026dccc749adc2a9d0d89497ac511f760f45c47dc5ed9cf352a58ac706453880aeadab\
+ 210255a9626aebf5e29c0e6538428ba0d1dcf6ca98ffdf086aa8ced5e0d0215ea465ac"
+ );
+ let amount = Amount::from_sat(4_900_000_000).unwrap();
+ let mut cache = SighashCache::new(&tx);
+
+ for (script_code, expected) in [
+ // At CHECKSIGVERIFY, OP_CODESEPARATOR has not executed and must be kept.
+ (
+ ScriptCode::from_bytes(&witness_script),
+ "82dde6e4f1e94d02c2b7ad03d2115d691f48d064e9d52f58194a6637e4194391",
+ ),
+ // At CHECKSIG, the caller removes the prefix through OP_CODESEPARATOR at byte 35.
+ (
+ ScriptCode::from_bytes(&witness_script[36..]),
+ "fef7bd749cce710c5c052bd796df1af0d935e59cea63736268bcbe2d2134fc47",
+ ),
+ ] {
+ let mut enc = SegwitV0Sighash::engine();
+ cache
+ .segwit_v0_encode_signing_data_to(
+ &mut enc,
+ 1,
+ script_code,
+ amount,
+ EcdsaSighashType::Single,
+ )
+ .unwrap();
+ assert_eq!(SegwitV0Sighash::from_engine(enc), expected.parse().unwrap());
+ }
+ }
+
// Note, if you are looking at the test vectors in BIP-0143 and wondering why there is a `cf`
// prepended to all the script_code hex it is the length byte, it gets added when we consensus
// encode a script.
### bitcoin/src/lib.rs
@@ -145,7 +145,7 @@ pub use primitives::{
RedeemScript, RedeemScriptBuf, RedeemScriptTag, ScriptHashableTag, ScriptPubKey,
ScriptPubKeyBuf, ScriptPubKeyTag, ScriptSig, ScriptSigBuf, ScriptSigTag, SignetBlockScript,
SignetBlockScriptBuf, SignetBlockScriptTag, Tag, TapScript, TapScriptBuf, TapScriptTag,
- WitnessScript, WitnessScriptBuf, WitnessScriptTag,
+ WitnessScript, WitnessScriptBuf, WitnessScriptTag, ScriptCode, ScriptCodeTag,
},
transaction::{OutPoint, Transaction, TxIn, TxOut, Txid, Version as TransactionVersion, Wtxid},
witness::Witness,
@@ -204,6 +204,7 @@ pub use crate::{
blockdata::script::witness_version::{self, WitnessVersion},
// These modules also re-export all the respective `primitives` types.
blockdata::{block, constants, fee_rate, locktime, script, transaction, weight, witness},
+ blockdata::script::P2wpkhScriptCode,
};
#[rustfmt::skip]
### bitcoin/tests/sighash.rs
@@ -5,7 +5,7 @@
use bitcoin::sighash::{
EcdsaSighashType, LegacySighash, Prevouts, SighashCache, TapSighash, TapSighashType,
};
-use bitcoin::{Amount, ScriptPubKeyBuf, Transaction, TxOut};
+use bitcoin::{Amount, ScriptCode, ScriptPubKeyBuf, Transaction, TxOut};
#[test]
fn legacy_sighash() {
@@ -36,6 +36,17 @@ fn legacy_sighash() {
.unwrap();
assert_eq!(got, want);
+
+ let script_code = ScriptCode::from_bytes(script.as_bytes());
+ let got = cache
+ .legacy_signature_hash(
+ input_index,
+ script_code,
+ EcdsaSighashType::from_consensus(hash_type as u32),
+ )
+ .unwrap();
+
+ assert_eq!(got, want);
}
// These test vectors were stolen from libbtc, which is Copyright 2014 Jonas Schnelli MIT.
### primitives/src/lib.rs
@@ -106,7 +106,7 @@ pub use self::{
script::{
RedeemScript, RedeemScriptBuf, ScriptPubKey, ScriptPubKeyBuf, ScriptSig, ScriptSigBuf,
SignetBlockScript, SignetBlockScriptBuf, TapScript, TapScriptBuf, WitnessScript,
- WitnessScriptBuf,
+ WitnessScriptBuf, ScriptCode,
},
transaction::{Transaction, TxIn, TxOut},
witness::Witness,
### primitives/src/script/mod.rs
@@ -50,7 +50,7 @@ pub use self::{
builder::Builder,
owned::{ScriptBuf, ScriptBufDecoder},
push_bytes::{PushBytes, PushBytesBuf, PushBytesErrorReport},
- tag::{Tag, RedeemScriptTag, ScriptPubKeyTag, ScriptSigTag, SignetBlockScriptTag, TapScriptTag, WitnessScriptTag},
+ tag::{Tag, RedeemScriptTag, ScriptPubKeyTag, ScriptSigTag, SignetBlockScriptTag, TapScriptTag, WitnessScriptTag, ScriptCodeTag},
};
#[doc(no_inline)]
pub use self::error::{
@@ -102,6 +102,9 @@ pub type WitnessScriptBuf = ScriptBuf<WitnessScriptTag>;
/// A reference to a Segwit v0 witness script.
pub type WitnessScript = Script<WitnessScriptTag>;
+/// A reference to a script code (scriptCode) used in sighash computation.
+pub type ScriptCode = Script<ScriptCodeTag>;
+
/// The maximum allowed redeem script size for a P2SH output.
pub const MAX_REDEEM_SCRIPT_SIZE: usize = 520;
/// The maximum allowed redeem script size of the witness script.
@@ -202,6 +205,52 @@ impl TryFrom<&WitnessScript> for WScriptHash {
}
}
+/// Borrows `WitnessScript` as `ScriptCode` without modifying its bytes.
+///
+/// If the witness script contains `OP_CODESEPARATOR`s, it is up to the caller
+/// to remove everything up to and including the last **executed**
+/// `OP_CODESEPARATOR` before the signature check.
+impl AsRef<ScriptCode> for WitnessScript {
+ fn as_ref(&self) -> &ScriptCode {
+ ScriptCode::from_bytes(self.as_bytes())
+ }
+}
+
+impl AsRef<ScriptCode> for WitnessScriptBuf {
+ #[inline]
+ fn as_ref(&self) -> &ScriptCode {
+ let witness_script: &WitnessScript = self.as_script();
+ witness_script.as_ref()
+ }
+}
+
+/// Borrows `RedeemScript` as `ScriptCode` without modifying its bytes.
+impl AsRef<ScriptCode> for RedeemScript {
+ fn as_ref(&self) -> &ScriptCode {
+ ScriptCode::from_bytes(self.as_bytes())
+ }
+}
+
+impl AsRef<ScriptCode> for RedeemScriptBuf {
+ fn as_ref(&self) -> &ScriptCode {
+ let redeem_script: &RedeemScript = self.as_script();
+ redeem_script.as_ref()
+ }
+}
+
+/// Borrows `ScriptPubKey` as `ScriptCode` without modifying its bytes.
+impl AsRef<ScriptCode> for ScriptPubKey {
+ fn as_ref(&self) -> &ScriptCode {
+ ScriptCode::from_bytes(self.as_bytes())
+ }
+}
+
+impl AsRef<ScriptCode> for ScriptPubKeyBuf {
+ fn as_ref(&self) -> &ScriptCode {
+ let script_pub_key: &ScriptPubKey = self.as_script();
+ script_pub_key.as_ref()
+ }
+}
impl From<WitnessScriptBuf> for SignetBlockScriptBuf {
#[inline]
fn from(buf: WitnessScriptBuf) -> Self { Self::from_bytes(buf.into_bytes()) }
### primitives/src/script/tag.rs
@@ -16,6 +16,7 @@ mod sealed {
impl Sealed for super::SignetBlockScriptTag {}
impl Sealed for super::TapScriptTag {}
impl Sealed for super::WitnessScriptTag {}
+ impl Sealed for super::ScriptCodeTag {}
}
/// A P2SH redeem script.
@@ -47,3 +48,8 @@ impl Tag for TapScriptTag {}
#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub enum WitnessScriptTag {}
impl Tag for WitnessScriptTag {}
+
+/// A script code (scriptCode) used in sighash computation.
+#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
+pub enum ScriptCodeTag {}
+impl Tag for ScriptCodeTag {}
\ No newline at end of fileWhy this scored 19/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.