Implemented unsized `Script`

This renames `Script` to `ScriptBuf` and adds unsized `Script` modeled
after `PathBuf`/`Path`. The change cleans up the API a bit, especially
all functions that previously accepted `&Script` now accept truly
borrowed version. Some functions that perviously accepted `&[u8]` can
now accept `&Script` because constructing it is no loger costly.
This commit is contained in:
Martin Habovstiak 2022-07-30 14:22:18 +02:00
parent f231617103
commit 8e428562cb
22 changed files with 1525 additions and 708 deletions

View File

@ -20,6 +20,7 @@ serde = ["actual-serde", "bitcoin_hashes/serde", "secp256k1/serde"]
secp-lowmemory = ["secp256k1/lowmemory"] secp-lowmemory = ["secp256k1/lowmemory"]
secp-recovery = ["secp256k1/recovery"] secp-recovery = ["secp256k1/recovery"]
bitcoinconsensus-std = ["bitcoinconsensus/std", "std"] bitcoinconsensus-std = ["bitcoinconsensus/std", "std"]
rust_v_1_53 = []
# At least one of std, no-std must be enabled. # At least one of std, no-std must be enabled.
# #

View File

@ -42,7 +42,7 @@ use bitcoin::locktime::absolute;
use bitcoin::psbt::{self, Input, Psbt, PsbtSighashType}; use bitcoin::psbt::{self, Input, Psbt, PsbtSighashType};
use bitcoin::secp256k1::{Secp256k1, Signing, Verification}; use bitcoin::secp256k1::{Secp256k1, Signing, Verification};
use bitcoin::{ use bitcoin::{
Address, Amount, Network, OutPoint, PublicKey, Script, Sequence, Transaction, TxIn, TxOut, Address, Amount, Network, OutPoint, PublicKey, ScriptBuf, Sequence, Transaction, TxIn, TxOut,
Txid, Witness, Txid, Witness,
}; };
@ -191,7 +191,7 @@ impl WatchOnly {
txid: Txid::from_hex(INPUT_UTXO_TXID)?, txid: Txid::from_hex(INPUT_UTXO_TXID)?,
vout: INPUT_UTXO_VOUT, vout: INPUT_UTXO_VOUT,
}, },
script_sig: Script::new(), script_sig: ScriptBuf::new(),
sequence: Sequence::MAX, // Disable LockTime and RBF. sequence: Sequence::MAX, // Disable LockTime and RBF.
witness: Witness::default(), witness: Witness::default(),
}], }],
@ -216,7 +216,7 @@ impl WatchOnly {
let pk = self.input_xpub.to_pub(); let pk = self.input_xpub.to_pub();
let wpkh = pk.wpubkey_hash().expect("a compressed pubkey"); let wpkh = pk.wpubkey_hash().expect("a compressed pubkey");
let redeem_script = Script::new_v0_p2wpkh(&wpkh); let redeem_script = ScriptBuf::new_v0_p2wpkh(&wpkh);
input.redeem_script = Some(redeem_script); input.redeem_script = Some(redeem_script);
let fingerprint = self.master_fingerprint; let fingerprint = self.master_fingerprint;
@ -284,7 +284,7 @@ fn input_derivation_path() -> Result<DerivationPath> {
} }
fn previous_output() -> TxOut { fn previous_output() -> TxOut {
let script_pubkey = Script::from_hex(INPUT_UTXO_SCRIPT_PUBKEY) let script_pubkey = ScriptBuf::from_hex(INPUT_UTXO_SCRIPT_PUBKEY)
.expect("failed to parse input utxo scriptPubkey"); .expect("failed to parse input utxo scriptPubkey");
let amount = Amount::from_str(INPUT_UTXO_VALUE).expect("failed to parse input utxo value"); let amount = Amount::from_str(INPUT_UTXO_VALUE).expect("failed to parse input utxo value");

View File

@ -94,7 +94,7 @@ use bitcoin::taproot::{
LeafVersion, TapLeafHash, TapSighashHash, TaprootBuilder, TaprootSpendInfo, LeafVersion, TapLeafHash, TapSighashHash, TaprootBuilder, TaprootSpendInfo,
}; };
use bitcoin::{ use bitcoin::{
absolute, script, Address, Amount, OutPoint, Script, Transaction, TxIn, TxOut, Txid, Witness, absolute, script, Address, Amount, OutPoint, ScriptBuf, Transaction, TxIn, TxOut, Txid, Witness,
}; };
fn main() -> Result<(), Box<dyn std::error::Error>> { fn main() -> Result<(), Box<dyn std::error::Error>> {
@ -241,7 +241,7 @@ fn generate_bip86_key_spend_tx(
txid: Txid::from_hex(input_utxo.txid)?, txid: Txid::from_hex(input_utxo.txid)?,
vout: input_utxo.vout, vout: input_utxo.vout,
}, },
script_sig: Script::new(), script_sig: ScriptBuf::new(),
sequence: bitcoin::Sequence(0xFFFFFFFF), // Ignore nSequence. sequence: bitcoin::Sequence(0xFFFFFFFF), // Ignore nSequence.
witness: Witness::default(), witness: Witness::default(),
}], }],
@ -263,7 +263,7 @@ fn generate_bip86_key_spend_tx(
let mut input = Input { let mut input = Input {
witness_utxo: { witness_utxo: {
let script_pubkey = Script::from_hex(input_utxo.script_pubkey) let script_pubkey = ScriptBuf::from_hex(input_utxo.script_pubkey)
.expect("failed to parse input utxo scriptPubkey"); .expect("failed to parse input utxo scriptPubkey");
let amount = Amount::from_sat(from_amount); let amount = Amount::from_sat(from_amount);
@ -289,7 +289,7 @@ fn generate_bip86_key_spend_tx(
vout, vout,
&sighash::Prevouts::All(&[TxOut { &sighash::Prevouts::All(&[TxOut {
value: from_amount, value: from_amount,
script_pubkey: Script::from_str(input_utxo.script_pubkey)?, script_pubkey: ScriptBuf::from_str(input_utxo.script_pubkey)?,
}]), }]),
hash_ty, hash_ty,
)?; )?;
@ -333,7 +333,7 @@ fn generate_bip86_key_spend_tx(
tx.verify(|_| { tx.verify(|_| {
Some(TxOut { Some(TxOut {
value: from_amount, value: from_amount,
script_pubkey: Script::from_hex(input_utxo.script_pubkey).unwrap(), script_pubkey: ScriptBuf::from_hex(input_utxo.script_pubkey).unwrap(),
}) })
}) })
.expect("failed to verify transaction"); .expect("failed to verify transaction");
@ -367,7 +367,7 @@ impl BenefactorWallet {
}) })
} }
fn time_lock_script(locktime: absolute::LockTime, beneficiary_key: XOnlyPublicKey) -> Script { fn time_lock_script(locktime: absolute::LockTime, beneficiary_key: XOnlyPublicKey) -> ScriptBuf {
script::Builder::new() script::Builder::new()
.push_int(locktime.to_consensus_u32() as i64) .push_int(locktime.to_consensus_u32() as i64)
.push_opcode(OP_CLTV) .push_opcode(OP_CLTV)
@ -404,7 +404,7 @@ impl BenefactorWallet {
.finalize(&self.secp, internal_keypair.x_only_public_key().0) .finalize(&self.secp, internal_keypair.x_only_public_key().0)
.expect("Should be finalizable"); .expect("Should be finalizable");
self.current_spend_info = Some(taproot_spend_info.clone()); self.current_spend_info = Some(taproot_spend_info.clone());
let script_pubkey = Script::new_v1_p2tr( let script_pubkey = ScriptBuf::new_v1_p2tr(
&self.secp, &self.secp,
taproot_spend_info.internal_key(), taproot_spend_info.internal_key(),
taproot_spend_info.merkle_root(), taproot_spend_info.merkle_root(),
@ -425,7 +425,7 @@ impl BenefactorWallet {
lock_time, lock_time,
input: vec![TxIn { input: vec![TxIn {
previous_output: OutPoint { txid: tx.txid(), vout: 0 }, previous_output: OutPoint { txid: tx.txid(), vout: 0 },
script_sig: Script::new(), script_sig: ScriptBuf::new(),
sequence: bitcoin::Sequence(0xFFFFFFFD), // enable locktime and opt-in RBF sequence: bitcoin::Sequence(0xFFFFFFFD), // enable locktime and opt-in RBF
witness: Witness::default(), witness: Witness::default(),
}], }],
@ -505,7 +505,7 @@ impl BenefactorWallet {
.expect("Should be finalizable"); .expect("Should be finalizable");
self.current_spend_info = Some(taproot_spend_info.clone()); self.current_spend_info = Some(taproot_spend_info.clone());
let prevout_script_pubkey = input.witness_utxo.as_ref().unwrap().script_pubkey.clone(); let prevout_script_pubkey = input.witness_utxo.as_ref().unwrap().script_pubkey.clone();
let output_script_pubkey = Script::new_v1_p2tr( let output_script_pubkey = ScriptBuf::new_v1_p2tr(
&self.secp, &self.secp,
taproot_spend_info.internal_key(), taproot_spend_info.internal_key(),
taproot_spend_info.merkle_root(), taproot_spend_info.merkle_root(),
@ -573,7 +573,7 @@ impl BenefactorWallet {
lock_time, lock_time,
input: vec![TxIn { input: vec![TxIn {
previous_output: OutPoint { txid: tx.txid(), vout: 0 }, previous_output: OutPoint { txid: tx.txid(), vout: 0 },
script_sig: Script::new(), script_sig: ScriptBuf::new(),
sequence: bitcoin::Sequence(0xFFFFFFFD), // enable locktime and opt-in RBF sequence: bitcoin::Sequence(0xFFFFFFFD), // enable locktime and opt-in RBF
witness: Witness::default(), witness: Witness::default(),
}], }],

View File

@ -6,7 +6,7 @@ use bitcoin::blockdata::script;
use bitcoin::consensus::encode; use bitcoin::consensus::encode;
fn do_test(data: &[u8]) { fn do_test(data: &[u8]) {
let s: Result<script::Script, _> = encode::deserialize(data); let s: Result<script::ScriptBuf, _> = encode::deserialize(data);
if let Ok(script) = s { if let Ok(script) = s {
let _: Result<Vec<script::Instruction>, script::Error> = script.instructions().collect(); let _: Result<Vec<script::Instruction>, script::Error> = script.instructions().collect();

View File

@ -17,7 +17,7 @@ impl fmt::Write for NullWriter {
fn do_test(data: &[u8]) { fn do_test(data: &[u8]) {
let mut writer = NullWriter; let mut writer = NullWriter;
bitcoin::Script::bytes_to_asm_fmt(data, &mut writer); bitcoin::Script::from_bytes(data).fmt_asm(&mut writer);
} }
#[cfg(feature = "afl")] #[cfg(feature = "afl")]

View File

@ -409,9 +409,11 @@ impl Payload {
return Err(Error::InvalidSegwitV0ProgramLength(script.len() - 2)); return Err(Error::InvalidSegwitV0ProgramLength(script.len() - 2));
} }
let opcode = script.first_opcode().expect("witness_version guarantees len() > 4");
Payload::WitnessProgram { Payload::WitnessProgram {
version: WitnessVersion::try_from(opcodes::All::from(script[0]))?, version: WitnessVersion::try_from(opcode)?,
program: script[2..].to_vec(), program: script.as_bytes()[2..].to_vec(),
} }
} else { } else {
return Err(Error::UnrecognizedScript); return Err(Error::UnrecognizedScript);
@ -419,12 +421,12 @@ impl Payload {
} }
/// Generates a script pubkey spending to this [Payload]. /// Generates a script pubkey spending to this [Payload].
pub fn script_pubkey(&self) -> script::Script { pub fn script_pubkey(&self) -> script::ScriptBuf {
match *self { match *self {
Payload::PubkeyHash(ref hash) => script::Script::new_p2pkh(hash), Payload::PubkeyHash(ref hash) => script::ScriptBuf::new_p2pkh(hash),
Payload::ScriptHash(ref hash) => script::Script::new_p2sh(hash), Payload::ScriptHash(ref hash) => script::ScriptBuf::new_p2sh(hash),
Payload::WitnessProgram { version, program: ref prog } => Payload::WitnessProgram { version, program: ref prog } =>
script::Script::new_witness_program(version, prog), script::ScriptBuf::new_witness_program(version, prog)
} }
} }
@ -674,7 +676,7 @@ impl Address {
} }
/// Generates a script pubkey spending to this address. /// Generates a script pubkey spending to this address.
pub fn script_pubkey(&self) -> script::Script { self.payload.script_pubkey() } pub fn script_pubkey(&self) -> script::ScriptBuf { self.payload.script_pubkey() }
/// Creates a URI string *bitcoin:address* optimized to be encoded in QR codes. /// Creates a URI string *bitcoin:address* optimized to be encoded in QR codes.
/// ///

View File

@ -377,7 +377,7 @@ mod test {
use crate::consensus::encode::{deserialize, serialize}; use crate::consensus::encode::{deserialize, serialize};
use crate::hashes::hex::FromHex; use crate::hashes::hex::FromHex;
use crate::{ use crate::{
CompactTarget, OutPoint, Script, Sequence, Transaction, TxIn, TxMerkleNode, TxOut, Txid, CompactTarget, OutPoint, ScriptBuf, Sequence, Transaction, TxIn, TxMerkleNode, TxOut, Txid,
Witness, Witness,
}; };
@ -387,11 +387,11 @@ mod test {
lock_time: absolute::LockTime::from_consensus(2), lock_time: absolute::LockTime::from_consensus(2),
input: vec![TxIn { input: vec![TxIn {
previous_output: OutPoint::new(Txid::hash(nonce), 0), previous_output: OutPoint::new(Txid::hash(nonce), 0),
script_sig: Script::new(), script_sig: ScriptBuf::new(),
sequence: Sequence(1), sequence: Sequence(1),
witness: Witness::new(), witness: Witness::new(),
}], }],
output: vec![TxOut { value: 1, script_pubkey: Script::new() }], output: vec![TxOut { value: 1, script_pubkey: ScriptBuf::new() }],
} }
} }

View File

@ -20,7 +20,7 @@
//! # Examples //! # Examples
//! //!
//! ```ignore //! ```ignore
//! fn get_script_for_coin(coin: &OutPoint) -> Result<Script, BlockFilterError> { //! fn get_script_for_coin(coin: &OutPoint) -> Result<ScriptBuf, BlockFilterError> {
//! // get utxo ... //! // get utxo ...
//! } //! }
//! //!
@ -32,7 +32,7 @@
//! //!
//! // read and evaluate a filter //! // read and evaluate a filter
//! //!
//! let query: Iterator<Item=Script> = // .. some scripts you care about //! let query: Iterator<Item=ScriptBuf> = // .. some scripts you care about
//! if filter.match_any(&block_hash, &mut query.map(|s| s.as_bytes())) { //! if filter.match_any(&block_hash, &mut query.map(|s| s.as_bytes())) {
//! // get this block //! // get this block
//! } //! }
@ -117,9 +117,10 @@ impl BlockFilter {
pub fn new(content: &[u8]) -> BlockFilter { BlockFilter { content: content.to_vec() } } pub fn new(content: &[u8]) -> BlockFilter { BlockFilter { content: content.to_vec() } }
/// Computes a SCRIPT_FILTER that contains spent and output scripts. /// Computes a SCRIPT_FILTER that contains spent and output scripts.
pub fn new_script_filter<M>(block: &Block, script_for_coin: M) -> Result<BlockFilter, Error> pub fn new_script_filter<M, S>(block: &Block, script_for_coin: M) -> Result<BlockFilter, Error>
where where
M: Fn(&OutPoint) -> Result<Script, Error>, M: Fn(&OutPoint) -> Result<S, Error>,
S: Borrow<Script>,
{ {
let mut out = Vec::new(); let mut out = Vec::new();
let mut writer = BlockFilterWriter::new(&mut out, block); let mut writer = BlockFilterWriter::new(&mut out, block);
@ -188,9 +189,10 @@ impl<'a, W: io::Write> BlockFilterWriter<'a, W> {
} }
/// Adds consumed output scripts of a block to filter. /// Adds consumed output scripts of a block to filter.
pub fn add_input_scripts<M>(&mut self, script_for_coin: M) -> Result<(), Error> pub fn add_input_scripts<M, S>(&mut self, script_for_coin: M) -> Result<(), Error>
where where
M: Fn(&OutPoint) -> Result<Script, Error>, M: Fn(&OutPoint) -> Result<S, Error>,
S: Borrow<Script>,
{ {
for script in self for script in self
.block .block
@ -201,7 +203,7 @@ impl<'a, W: io::Write> BlockFilterWriter<'a, W> {
.map(script_for_coin) .map(script_for_coin)
{ {
match script { match script {
Ok(script) => self.add_element(script.as_bytes()), Ok(script) => self.add_element(script.borrow().as_bytes()),
Err(e) => return Err(e), Err(e) => return Err(e),
} }
} }
@ -560,6 +562,7 @@ mod test {
use crate::consensus::encode::deserialize; use crate::consensus::encode::deserialize;
use crate::hash_types::BlockHash; use crate::hash_types::BlockHash;
use crate::hashes::hex::FromHex; use crate::hashes::hex::FromHex;
use crate::ScriptBuf;
#[test] #[test]
fn test_blockfilters() { fn test_blockfilters() {
@ -585,7 +588,7 @@ mod test {
for input in tx.input.iter() { for input in tx.input.iter() {
txmap.insert( txmap.insert(
input.previous_output, input.previous_output,
Script::from(Vec::from_hex(si.next().unwrap().as_str().unwrap()).unwrap()), ScriptBuf::from(Vec::from_hex(si.next().unwrap().as_str().unwrap()).unwrap()),
); );
} }
} }

View File

@ -240,7 +240,7 @@ impl Block {
// Commitment is in the last output that starts with magic bytes. // Commitment is in the last output that starts with magic bytes.
if let Some(pos) = coinbase.output.iter() if let Some(pos) = coinbase.output.iter()
.rposition(|o| o.script_pubkey.len () >= 38 && o.script_pubkey[0..6] == MAGIC) .rposition(|o| o.script_pubkey.len () >= 38 && o.script_pubkey.as_bytes()[0..6] == MAGIC)
{ {
let commitment = WitnessCommitment::from_slice(&coinbase.output[pos].script_pubkey.as_bytes()[6..38]).unwrap(); let commitment = WitnessCommitment::from_slice(&coinbase.output[pos].script_pubkey.as_bytes()[6..38]).unwrap();
// Witness reserved value is in coinbase input witness. // Witness reserved value is in coinbase input witness.

File diff suppressed because it is too large Load Diff

View File

@ -26,7 +26,7 @@ use crate::hashes::hex::FromHex;
use crate::blockdata::constants::WITNESS_SCALE_FACTOR; use crate::blockdata::constants::WITNESS_SCALE_FACTOR;
#[cfg(feature="bitcoinconsensus")] use crate::blockdata::script; #[cfg(feature="bitcoinconsensus")] use crate::blockdata::script;
use crate::blockdata::script::Script; use crate::blockdata::script::{ScriptBuf, Script};
use crate::blockdata::witness::Witness; use crate::blockdata::witness::Witness;
use crate::blockdata::locktime::absolute::{self, Height, Time}; use crate::blockdata::locktime::absolute::{self, Height, Time};
use crate::blockdata::locktime::relative; use crate::blockdata::locktime::relative;
@ -198,7 +198,7 @@ pub struct TxIn {
pub previous_output: OutPoint, pub previous_output: OutPoint,
/// The script which pushes values on the stack which will cause /// The script which pushes values on the stack which will cause
/// the referenced output's script to be accepted. /// the referenced output's script to be accepted.
pub script_sig: Script, pub script_sig: ScriptBuf,
/// The sequence number, which suggests to miners which of two /// The sequence number, which suggests to miners which of two
/// conflicting transactions should be preferred, or 0xFFFFFFFF /// conflicting transactions should be preferred, or 0xFFFFFFFF
/// to ignore this feature. This is generally never used since /// to ignore this feature. This is generally never used since
@ -231,7 +231,7 @@ impl Default for TxIn {
fn default() -> TxIn { fn default() -> TxIn {
TxIn { TxIn {
previous_output: OutPoint::default(), previous_output: OutPoint::default(),
script_sig: Script::new(), script_sig: ScriptBuf::new(),
sequence: Sequence::MAX, sequence: Sequence::MAX,
witness: Witness::default(), witness: Witness::default(),
} }
@ -466,13 +466,13 @@ pub struct TxOut {
/// The value of the output, in satoshis. /// The value of the output, in satoshis.
pub value: u64, pub value: u64,
/// The script which must be satisfied for the output to be spent. /// The script which must be satisfied for the output to be spent.
pub script_pubkey: Script pub script_pubkey: ScriptBuf
} }
// This is used as a "null txout" in consensus signing code. // This is used as a "null txout" in consensus signing code.
impl Default for TxOut { impl Default for TxOut {
fn default() -> TxOut { fn default() -> TxOut {
TxOut { value: 0xffffffffffffffff, script_pubkey: Script::new() } TxOut { value: 0xffffffffffffffff, script_pubkey: ScriptBuf::new() }
} }
} }
@ -505,7 +505,7 @@ impl<E> EncodeSigningDataResult<E> {
/// # use bitcoin_hashes::{Hash, hex::FromHex}; /// # use bitcoin_hashes::{Hash, hex::FromHex};
/// # let mut writer = Sighash::engine(); /// # let mut writer = Sighash::engine();
/// # let input_index = 0; /// # let input_index = 0;
/// # let script_pubkey = bitcoin::Script::new(); /// # let script_pubkey = bitcoin::ScriptBuf::new();
/// # let sighash_u32 = 0u32; /// # let sighash_u32 = 0u32;
/// # const SOME_TX: &'static str = "0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000"; /// # const SOME_TX: &'static str = "0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000";
/// # let raw_tx = Vec::from_hex(SOME_TX).unwrap(); /// # let raw_tx = Vec::from_hex(SOME_TX).unwrap();
@ -622,7 +622,7 @@ impl Transaction {
let cloned_tx = Transaction { let cloned_tx = Transaction {
version: self.version, version: self.version,
lock_time: self.lock_time, lock_time: self.lock_time,
input: self.input.iter().map(|txin| TxIn { script_sig: Script::new(), witness: Witness::default(), .. *txin }).collect(), input: self.input.iter().map(|txin| TxIn { script_sig: ScriptBuf::new(), witness: Witness::default(), .. *txin }).collect(),
output: self.output.clone(), output: self.output.clone(),
}; };
cloned_tx.txid().into() cloned_tx.txid().into()
@ -1073,7 +1073,7 @@ mod tests {
use core::str::FromStr; use core::str::FromStr;
use crate::blockdata::constants::WITNESS_SCALE_FACTOR; use crate::blockdata::constants::WITNESS_SCALE_FACTOR;
use crate::blockdata::script::Script; use crate::blockdata::script::ScriptBuf;
use crate::blockdata::locktime::absolute; use crate::blockdata::locktime::absolute;
use crate::consensus::encode::serialize; use crate::consensus::encode::serialize;
use crate::consensus::encode::deserialize; use crate::consensus::encode::deserialize;
@ -1139,7 +1139,7 @@ mod tests {
fn test_txin_default() { fn test_txin_default() {
let txin = TxIn::default(); let txin = TxIn::default();
assert_eq!(txin.previous_output, OutPoint::default()); assert_eq!(txin.previous_output, OutPoint::default());
assert_eq!(txin.script_sig, Script::new()); assert_eq!(txin.script_sig, ScriptBuf::new());
assert_eq!(txin.sequence, Sequence::from_consensus(0xFFFFFFFF)); assert_eq!(txin.sequence, Sequence::from_consensus(0xFFFFFFFF));
assert_eq!(txin.previous_output, OutPoint::default()); assert_eq!(txin.previous_output, OutPoint::default());
assert_eq!(txin.witness.len(), 0); assert_eq!(txin.witness.len(), 0);
@ -1288,10 +1288,10 @@ mod tests {
let old_ntxid = tx.ntxid(); let old_ntxid = tx.ntxid();
assert_eq!(format!("{:x}", old_ntxid), "c3573dbea28ce24425c59a189391937e00d255150fa973d59d61caf3a06b601d"); assert_eq!(format!("{:x}", old_ntxid), "c3573dbea28ce24425c59a189391937e00d255150fa973d59d61caf3a06b601d");
// changing sigs does not affect it // changing sigs does not affect it
tx.input[0].script_sig = Script::new(); tx.input[0].script_sig = ScriptBuf::new();
assert_eq!(old_ntxid, tx.ntxid()); assert_eq!(old_ntxid, tx.ntxid());
// changing pks does // changing pks does
tx.output[0].script_pubkey = Script::new(); tx.output[0].script_pubkey = ScriptBuf::new();
assert!(old_ntxid != tx.ntxid()); assert!(old_ntxid != tx.ntxid());
} }

View File

@ -88,7 +88,7 @@ mod test_macros {
pub(crate) use hex_into; pub(crate) use hex_into;
// Script is commonly used in places where inference may fail // Script is commonly used in places where inference may fail
macro_rules! hex_script (($hex:expr) => ($crate::internal_macros::hex_into!($crate::Script, $hex))); macro_rules! hex_script (($hex:expr) => ($crate::internal_macros::hex_into!($crate::ScriptBuf, $hex)));
pub(crate) use hex_script; pub(crate) use hex_script;
// For types that can't use TestFromHex due to coherence rules or reversed hex // For types that can't use TestFromHex due to coherence rules or reversed hex

View File

@ -59,7 +59,6 @@ compile_error!(
#[cfg(bench)] #[cfg(bench)]
extern crate test; extern crate test;
#[cfg(feature = "no-std")]
#[macro_use] #[macro_use]
extern crate alloc; extern crate alloc;
@ -128,7 +127,7 @@ pub use crate::address::{Address, AddressType};
pub use crate::amount::{Amount, Denomination, SignedAmount}; pub use crate::amount::{Amount, Denomination, SignedAmount};
pub use crate::blockdata::block::{self, Block}; pub use crate::blockdata::block::{self, Block};
pub use crate::blockdata::locktime::{self, absolute, relative}; pub use crate::blockdata::locktime::{self, absolute, relative};
pub use crate::blockdata::script::{self, Script}; pub use crate::blockdata::script::{self, Script, ScriptBuf};
pub use crate::blockdata::transaction::{self, OutPoint, Sequence, Transaction, TxIn, TxOut}; pub use crate::blockdata::transaction::{self, OutPoint, Sequence, Transaction, TxIn, TxOut};
pub use crate::blockdata::witness::{self, Witness}; pub use crate::blockdata::witness::{self, Witness};
pub use crate::blockdata::{constants, opcodes}; pub use crate::blockdata::{constants, opcodes};

View File

@ -516,7 +516,7 @@ mod test {
use super::{CommandString, NetworkMessage, RawNetworkMessage, *}; use super::{CommandString, NetworkMessage, RawNetworkMessage, *};
use crate::bip152::BlockTransactionsRequest; use crate::bip152::BlockTransactionsRequest;
use crate::blockdata::block::{self, Block}; use crate::blockdata::block::{self, Block};
use crate::blockdata::script::Script; use crate::blockdata::script::ScriptBuf;
use crate::blockdata::transaction::Transaction; use crate::blockdata::transaction::Transaction;
use crate::consensus::encode::{deserialize, deserialize_partial, serialize}; use crate::consensus::encode::{deserialize, deserialize_partial, serialize};
use crate::hashes::hex::FromHex; use crate::hashes::hex::FromHex;
@ -540,7 +540,7 @@ mod test {
let tx: Transaction = deserialize(&Vec::from_hex("0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000").unwrap()).unwrap(); let tx: Transaction = deserialize(&Vec::from_hex("0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000").unwrap()).unwrap();
let block: Block = deserialize(&include_bytes!("../../tests/data/testnet_block_000000000000045e0b1660b6445b5e5c5ab63c9a4f956be7e1e69be04fa4497b.raw")[..]).unwrap(); let block: Block = deserialize(&include_bytes!("../../tests/data/testnet_block_000000000000045e0b1660b6445b5e5c5ab63c9a4f956be7e1e69be04fa4497b.raw")[..]).unwrap();
let header: block::Header = deserialize(&Vec::from_hex("010000004ddccd549d28f385ab457e98d1b11ce80bfea2c5ab93015ade4973e400000000bf4473e53794beae34e64fccc471dace6ae544180816f89591894e0f417a914cd74d6e49ffff001d323b3a7b").unwrap()).unwrap(); let header: block::Header = deserialize(&Vec::from_hex("010000004ddccd549d28f385ab457e98d1b11ce80bfea2c5ab93015ade4973e400000000bf4473e53794beae34e64fccc471dace6ae544180816f89591894e0f417a914cd74d6e49ffff001d323b3a7b").unwrap()).unwrap();
let script: Script = deserialize( let script: ScriptBuf = deserialize(
&Vec::from_hex("1976a91431a420903c05a0a7de2de40c9f02ebedbacdc17288ac").unwrap(), &Vec::from_hex("1976a91431a420903c05a0a7de2de40c9f02ebedbacdc17288ac").unwrap(),
) )
.unwrap(); .unwrap();

View File

@ -9,7 +9,7 @@ use core::convert::TryFrom;
use secp256k1::XOnlyPublicKey; use secp256k1::XOnlyPublicKey;
use crate::blockdata::script::Script; use crate::blockdata::script::ScriptBuf;
use crate::blockdata::witness::Witness; use crate::blockdata::witness::Witness;
use crate::blockdata::transaction::{Transaction, TxOut}; use crate::blockdata::transaction::{Transaction, TxOut};
use crate::consensus::encode; use crate::consensus::encode;
@ -85,16 +85,16 @@ pub struct Input {
/// must use the sighash type. /// must use the sighash type.
pub sighash_type: Option<PsbtSighashType>, pub sighash_type: Option<PsbtSighashType>,
/// The redeem script for this input. /// The redeem script for this input.
pub redeem_script: Option<Script>, pub redeem_script: Option<ScriptBuf>,
/// The witness script for this input. /// The witness script for this input.
pub witness_script: Option<Script>, pub witness_script: Option<ScriptBuf>,
/// A map from public keys needed to sign this input to their corresponding /// A map from public keys needed to sign this input to their corresponding
/// master key fingerprints and derivation paths. /// master key fingerprints and derivation paths.
#[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::btreemap_as_seq"))] #[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::btreemap_as_seq"))]
pub bip32_derivation: BTreeMap<secp256k1::PublicKey, KeySource>, pub bip32_derivation: BTreeMap<secp256k1::PublicKey, KeySource>,
/// The finalized, fully-constructed scriptSig with signatures and any other /// The finalized, fully-constructed scriptSig with signatures and any other
/// scripts necessary for this input to pass validation. /// scripts necessary for this input to pass validation.
pub final_script_sig: Option<Script>, pub final_script_sig: Option<ScriptBuf>,
/// The finalized, fully-constructed scriptWitness with signatures and any /// The finalized, fully-constructed scriptWitness with signatures and any
/// other scripts necessary for this input to pass validation. /// other scripts necessary for this input to pass validation.
pub final_script_witness: Option<Witness>, pub final_script_witness: Option<Witness>,
@ -118,7 +118,7 @@ pub struct Input {
pub tap_script_sigs: BTreeMap<(XOnlyPublicKey, TapLeafHash), schnorr::Signature>, pub tap_script_sigs: BTreeMap<(XOnlyPublicKey, TapLeafHash), schnorr::Signature>,
/// Map of Control blocks to Script version pair. /// Map of Control blocks to Script version pair.
#[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::btreemap_as_seq"))] #[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::btreemap_as_seq"))]
pub tap_scripts: BTreeMap<ControlBlock, (Script, LeafVersion)>, pub tap_scripts: BTreeMap<ControlBlock, (ScriptBuf, LeafVersion)>,
/// Map of tap root x only keys to origin info and leaf hashes contained in it. /// Map of tap root x only keys to origin info and leaf hashes contained in it.
#[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::btreemap_as_seq"))] #[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::btreemap_as_seq"))]
pub tap_key_origins: BTreeMap<XOnlyPublicKey, (Vec<TapLeafHash>, KeySource)>, pub tap_key_origins: BTreeMap<XOnlyPublicKey, (Vec<TapLeafHash>, KeySource)>,
@ -277,12 +277,12 @@ impl Input {
} }
PSBT_IN_REDEEM_SCRIPT => { PSBT_IN_REDEEM_SCRIPT => {
impl_psbt_insert_pair! { impl_psbt_insert_pair! {
self.redeem_script <= <raw_key: _>|<raw_value: Script> self.redeem_script <= <raw_key: _>|<raw_value: ScriptBuf>
} }
} }
PSBT_IN_WITNESS_SCRIPT => { PSBT_IN_WITNESS_SCRIPT => {
impl_psbt_insert_pair! { impl_psbt_insert_pair! {
self.witness_script <= <raw_key: _>|<raw_value: Script> self.witness_script <= <raw_key: _>|<raw_value: ScriptBuf>
} }
} }
PSBT_IN_BIP32_DERIVATION => { PSBT_IN_BIP32_DERIVATION => {
@ -292,7 +292,7 @@ impl Input {
} }
PSBT_IN_FINAL_SCRIPTSIG => { PSBT_IN_FINAL_SCRIPTSIG => {
impl_psbt_insert_pair! { impl_psbt_insert_pair! {
self.final_script_sig <= <raw_key: _>|<raw_value: Script> self.final_script_sig <= <raw_key: _>|<raw_value: ScriptBuf>
} }
} }
PSBT_IN_FINAL_SCRIPTWITNESS => { PSBT_IN_FINAL_SCRIPTWITNESS => {
@ -324,7 +324,7 @@ impl Input {
} }
PSBT_IN_TAP_LEAF_SCRIPT => { PSBT_IN_TAP_LEAF_SCRIPT => {
impl_psbt_insert_pair! { impl_psbt_insert_pair! {
self.tap_scripts <= <raw_key: ControlBlock>|< raw_value: (Script, LeafVersion)> self.tap_scripts <= <raw_key: ControlBlock>|< raw_value: (ScriptBuf, LeafVersion)>
} }
} }
PSBT_IN_TAP_BIP32_DERIVATION => { PSBT_IN_TAP_BIP32_DERIVATION => {

View File

@ -6,7 +6,7 @@ use core::convert::TryFrom;
use crate::io; use crate::io;
use crate::blockdata::script::Script; use crate::blockdata::script::ScriptBuf;
use crate::consensus::encode; use crate::consensus::encode;
use secp256k1::XOnlyPublicKey; use secp256k1::XOnlyPublicKey;
use crate::bip32::KeySource; use crate::bip32::KeySource;
@ -17,9 +17,9 @@ use crate::psbt::Error;
use crate::taproot::{ScriptLeaf, TapLeafHash, NodeInfo, TaprootBuilder}; use crate::taproot::{ScriptLeaf, TapLeafHash, NodeInfo, TaprootBuilder};
/// Type: Redeem Script PSBT_OUT_REDEEM_SCRIPT = 0x00 /// Type: Redeem ScriptBuf PSBT_OUT_REDEEM_SCRIPT = 0x00
const PSBT_OUT_REDEEM_SCRIPT: u8 = 0x00; const PSBT_OUT_REDEEM_SCRIPT: u8 = 0x00;
/// Type: Witness Script PSBT_OUT_WITNESS_SCRIPT = 0x01 /// Type: Witness ScriptBuf PSBT_OUT_WITNESS_SCRIPT = 0x01
const PSBT_OUT_WITNESS_SCRIPT: u8 = 0x01; const PSBT_OUT_WITNESS_SCRIPT: u8 = 0x01;
/// Type: BIP 32 Derivation Path PSBT_OUT_BIP32_DERIVATION = 0x02 /// Type: BIP 32 Derivation Path PSBT_OUT_BIP32_DERIVATION = 0x02
const PSBT_OUT_BIP32_DERIVATION: u8 = 0x02; const PSBT_OUT_BIP32_DERIVATION: u8 = 0x02;
@ -39,9 +39,9 @@ const PSBT_OUT_PROPRIETARY: u8 = 0xFC;
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))] #[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
pub struct Output { pub struct Output {
/// The redeem script for this output. /// The redeem script for this output.
pub redeem_script: Option<Script>, pub redeem_script: Option<ScriptBuf>,
/// The witness script for this output. /// The witness script for this output.
pub witness_script: Option<Script>, pub witness_script: Option<ScriptBuf>,
/// A map from public keys needed to spend this output to their /// A map from public keys needed to spend this output to their
/// corresponding master key fingerprints and derivation paths. /// corresponding master key fingerprints and derivation paths.
#[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::btreemap_as_seq"))] #[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::btreemap_as_seq"))]
@ -216,12 +216,12 @@ impl Output {
match raw_key.type_value { match raw_key.type_value {
PSBT_OUT_REDEEM_SCRIPT => { PSBT_OUT_REDEEM_SCRIPT => {
impl_psbt_insert_pair! { impl_psbt_insert_pair! {
self.redeem_script <= <raw_key: _>|<raw_value: Script> self.redeem_script <= <raw_key: _>|<raw_value: ScriptBuf>
} }
} }
PSBT_OUT_WITNESS_SCRIPT => { PSBT_OUT_WITNESS_SCRIPT => {
impl_psbt_insert_pair! { impl_psbt_insert_pair! {
self.witness_script <= <raw_key: _>|<raw_value: Script> self.witness_script <= <raw_key: _>|<raw_value: ScriptBuf>
} }
} }
PSBT_OUT_BIP32_DERIVATION => { PSBT_OUT_BIP32_DERIVATION => {

View File

@ -19,7 +19,7 @@ use bitcoin_internals::write_err;
use crate::{prelude::*, Amount}; use crate::{prelude::*, Amount};
use crate::io; use crate::io;
use crate::blockdata::script::Script; use crate::blockdata::script::ScriptBuf;
use crate::blockdata::transaction::{Transaction, TxOut}; use crate::blockdata::transaction::{Transaction, TxOut};
use crate::consensus::{encode, Encodable, Decodable}; use crate::consensus::{encode, Encodable, Decodable};
use crate::bip32::{self, ExtendedPrivKey, ExtendedPubKey, KeySource}; use crate::bip32::{self, ExtendedPrivKey, ExtendedPubKey, KeySource};
@ -136,7 +136,7 @@ impl PartiallySignedTransaction {
let mut tx: Transaction = self.unsigned_tx; let mut tx: Transaction = self.unsigned_tx;
for (vin, psbtin) in tx.input.iter_mut().zip(self.inputs.into_iter()) { for (vin, psbtin) in tx.input.iter_mut().zip(self.inputs.into_iter()) {
vin.script_sig = psbtin.final_script_sig.unwrap_or_else(Script::new); vin.script_sig = psbtin.final_script_sig.unwrap_or_default();
vin.witness = psbtin.final_script_witness.unwrap_or_default(); vin.witness = psbtin.final_script_witness.unwrap_or_default();
} }
@ -339,11 +339,11 @@ impl PartiallySignedTransaction {
cache.legacy_signature_hash(input_index, script_code, hash_ty.to_u32())? cache.legacy_signature_hash(input_index, script_code, hash_ty.to_u32())?
}, },
Wpkh => { Wpkh => {
let script_code = Script::p2wpkh_script_code(spk).ok_or(SignError::NotWpkh)?; let script_code = ScriptBuf::p2wpkh_script_code(spk).ok_or(SignError::NotWpkh)?;
cache.segwit_signature_hash(input_index, &script_code, utxo.value, hash_ty)? cache.segwit_signature_hash(input_index, &script_code, utxo.value, hash_ty)?
} }
ShWpkh => { ShWpkh => {
let script_code = Script::p2wpkh_script_code(input.redeem_script.as_ref().expect("checked above")) let script_code = ScriptBuf::p2wpkh_script_code(input.redeem_script.as_ref().expect("checked above"))
.ok_or(SignError::NotWpkh)?; .ok_or(SignError::NotWpkh)?;
cache.segwit_signature_hash(input_index, &script_code, utxo.value, hash_ty)? cache.segwit_signature_hash(input_index, &script_code, utxo.value, hash_ty)?
}, },
@ -890,7 +890,7 @@ mod tests {
#[cfg(feature = "rand")] #[cfg(feature = "rand")]
use secp256k1::{All, SecretKey}; use secp256k1::{All, SecretKey};
use crate::blockdata::script::Script; use crate::blockdata::script::ScriptBuf;
use crate::blockdata::transaction::{Transaction, TxIn, TxOut, OutPoint, Sequence}; use crate::blockdata::transaction::{Transaction, TxIn, TxOut, OutPoint, Sequence};
use crate::network::constants::Network::Bitcoin; use crate::network::constants::Network::Bitcoin;
use crate::consensus::encode::{deserialize, serialize, serialize_hex}; use crate::consensus::encode::{deserialize, serialize, serialize_hex};
@ -985,7 +985,7 @@ mod tests {
).unwrap(), ).unwrap(),
vout: 0, vout: 0,
}, },
script_sig: Script::new(), script_sig: ScriptBuf::new(),
sequence: Sequence::ENABLE_LOCKTIME_NO_RBF, sequence: Sequence::ENABLE_LOCKTIME_NO_RBF,
witness: Witness::default(), witness: Witness::default(),
}], }],
@ -1096,7 +1096,7 @@ mod tests {
}, },
unsigned_tx: { unsigned_tx: {
let mut unsigned = tx.clone(); let mut unsigned = tx.clone();
unsigned.input[0].script_sig = Script::new(); unsigned.input[0].script_sig = ScriptBuf::new();
unsigned.input[0].witness = Witness::default(); unsigned.input[0].witness = Witness::default();
unsigned unsigned
}, },
@ -1145,7 +1145,7 @@ mod tests {
use crate::hashes::hex::FromHex; use crate::hashes::hex::FromHex;
use crate::hash_types::Txid; use crate::hash_types::Txid;
use crate::blockdata::script::Script; use crate::blockdata::script::ScriptBuf;
use crate::blockdata::transaction::{Transaction, TxIn, TxOut, OutPoint, Sequence}; use crate::blockdata::transaction::{Transaction, TxIn, TxOut, OutPoint, Sequence};
use crate::consensus::encode::serialize_hex; use crate::consensus::encode::serialize_hex;
use crate::blockdata::locktime::absolute; use crate::blockdata::locktime::absolute;
@ -1245,7 +1245,7 @@ mod tests {
).unwrap(), ).unwrap(),
vout: 0, vout: 0,
}, },
script_sig: Script::new(), script_sig: ScriptBuf::new(),
sequence: Sequence::ENABLE_LOCKTIME_NO_RBF, sequence: Sequence::ENABLE_LOCKTIME_NO_RBF,
witness: Witness::default(), witness: Witness::default(),
}], }],
@ -1557,7 +1557,7 @@ mod tests {
).unwrap(), ).unwrap(),
vout: 0, vout: 0,
}, },
script_sig: Script::new(), script_sig: ScriptBuf::new(),
sequence: Sequence::ENABLE_LOCKTIME_NO_RBF, sequence: Sequence::ENABLE_LOCKTIME_NO_RBF,
witness: Witness::default(), witness: Witness::default(),
}], }],
@ -1834,7 +1834,7 @@ mod tests {
// First input we can spend. See comment above on key_map for why we use defaults here. // First input we can spend. See comment above on key_map for why we use defaults here.
let txout_wpkh = TxOut{ let txout_wpkh = TxOut{
value: 10, value: 10,
script_pubkey: Script::new_v0_p2wpkh(&WPubkeyHash::hash(&pk.to_bytes())), script_pubkey: ScriptBuf::new_v0_p2wpkh(&WPubkeyHash::hash(&pk.to_bytes())),
}; };
psbt.inputs[0].witness_utxo = Some(txout_wpkh); psbt.inputs[0].witness_utxo = Some(txout_wpkh);
@ -1845,7 +1845,7 @@ mod tests {
// Second input is unspendable by us e.g., from another wallet that supports future upgrades. // Second input is unspendable by us e.g., from another wallet that supports future upgrades.
let txout_unknown_future = TxOut{ let txout_unknown_future = TxOut{
value: 10, value: 10,
script_pubkey: Script::new_witness_program(crate::address::WitnessVersion::V4, &[0xaa; 34]), script_pubkey: ScriptBuf::new_witness_program(crate::address::WitnessVersion::V4, &[0xaa; 34]),
}; };
psbt.inputs[1].witness_utxo = Some(txout_unknown_future); psbt.inputs[1].witness_utxo = Some(txout_unknown_future);

View File

@ -10,7 +10,7 @@ use crate::prelude::*;
use crate::io; use crate::io;
use crate::blockdata::script::Script; use crate::blockdata::script::ScriptBuf;
use crate::blockdata::witness::Witness; use crate::blockdata::witness::Witness;
use crate::blockdata::transaction::{Transaction, TxOut}; use crate::blockdata::transaction::{Transaction, TxOut};
use crate::consensus::encode::{self, serialize, Decodable, Encodable, deserialize_partial}; use crate::consensus::encode::{self, serialize, Decodable, Encodable, deserialize_partial};
@ -51,13 +51,13 @@ impl_psbt_hash_de_serialize!(sha256d::Hash);
// taproot // taproot
impl_psbt_de_serialize!(Vec<TapLeafHash>); impl_psbt_de_serialize!(Vec<TapLeafHash>);
impl Serialize for Script { impl Serialize for ScriptBuf {
fn serialize(&self) -> Vec<u8> { fn serialize(&self) -> Vec<u8> {
self.to_bytes() self.to_bytes()
} }
} }
impl Deserialize for Script { impl Deserialize for ScriptBuf {
fn deserialize(bytes: &[u8]) -> Result<Self, encode::Error> { fn deserialize(bytes: &[u8]) -> Result<Self, encode::Error> {
Ok(Self::from(bytes.to_vec())) Ok(Self::from(bytes.to_vec()))
} }
@ -262,8 +262,8 @@ impl Deserialize for ControlBlock {
} }
} }
// Versioned Script // Versioned ScriptBuf
impl Serialize for (Script, LeafVersion) { impl Serialize for (ScriptBuf, LeafVersion) {
fn serialize(&self) -> Vec<u8> { fn serialize(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(self.0.len() + 1); let mut buf = Vec::with_capacity(self.0.len() + 1);
buf.extend(self.0.as_bytes()); buf.extend(self.0.as_bytes());
@ -272,13 +272,13 @@ impl Serialize for (Script, LeafVersion) {
} }
} }
impl Deserialize for (Script, LeafVersion) { impl Deserialize for (ScriptBuf, LeafVersion) {
fn deserialize(bytes: &[u8]) -> Result<Self, encode::Error> { fn deserialize(bytes: &[u8]) -> Result<Self, encode::Error> {
if bytes.is_empty() { if bytes.is_empty() {
return Err(io::Error::from(io::ErrorKind::UnexpectedEof).into()) return Err(io::Error::from(io::ErrorKind::UnexpectedEof).into())
} }
// The last byte is LeafVersion. // The last byte is LeafVersion.
let script = Script::deserialize(&bytes[..bytes.len() - 1])?; let script = ScriptBuf::deserialize(&bytes[..bytes.len() - 1])?;
let leaf_ver = LeafVersion::from_consensus(bytes[bytes.len() - 1]) let leaf_ver = LeafVersion::from_consensus(bytes[bytes.len() - 1])
.map_err(|_| encode::Error::ParseFailed("invalid leaf version"))?; .map_err(|_| encode::Error::ParseFailed("invalid leaf version"))?;
Ok((script, leaf_ver)) Ok((script, leaf_ver))
@ -332,7 +332,7 @@ impl Deserialize for TapTree {
let mut bytes_iter = bytes.iter(); let mut bytes_iter = bytes.iter();
while let Some(depth) = bytes_iter.next() { while let Some(depth) = bytes_iter.next() {
let version = bytes_iter.next().ok_or(encode::Error::ParseFailed("Invalid Taproot Builder"))?; let version = bytes_iter.next().ok_or(encode::Error::ParseFailed("Invalid Taproot Builder"))?;
let (script, consumed) = deserialize_partial::<Script>(bytes_iter.as_slice())?; let (script, consumed) = deserialize_partial::<ScriptBuf>(bytes_iter.as_slice())?;
if consumed > 0 { if consumed > 0 {
bytes_iter.nth(consumed - 1); bytes_iter.nth(consumed - 1);
} }
@ -369,7 +369,7 @@ mod tests {
let mut val = opcode; let mut val = opcode;
let mut builder = TaprootBuilder::new(); let mut builder = TaprootBuilder::new();
for depth in depth_map { for depth in depth_map {
let script = Script::from_hex(&format!("{:02x}", val)).unwrap(); let script = ScriptBuf::from_hex(&format!("{:02x}", val)).unwrap();
builder = builder.add_leaf(*depth, script).unwrap(); builder = builder.add_leaf(*depth, script).unwrap();
let (new_val, _) = val.overflowing_add(1); let (new_val, _) = val.overflowing_add(1);
val = new_val; val = new_val;
@ -380,7 +380,7 @@ mod tests {
#[test] #[test]
fn taptree_hidden() { fn taptree_hidden() {
let mut builder = compose_taproot_builder(0x51, &[2, 2, 2]); let mut builder = compose_taproot_builder(0x51, &[2, 2, 2]);
builder = builder.add_leaf_with_ver(3, Script::from_hex("b9").unwrap(), LeafVersion::from_consensus(0xC2).unwrap()).unwrap(); builder = builder.add_leaf_with_ver(3, ScriptBuf::from_hex("b9").unwrap(), LeafVersion::from_consensus(0xC2).unwrap()).unwrap();
builder = builder.add_hidden_node(3, sha256::Hash::all_zeros()).unwrap(); builder = builder.add_hidden_node(3, sha256::Hash::all_zeros()).unwrap();
assert!(TapTree::try_from(builder).is_err()); assert!(TapTree::try_from(builder).is_err());
} }
@ -388,7 +388,7 @@ mod tests {
#[test] #[test]
fn taptree_roundtrip() { fn taptree_roundtrip() {
let mut builder = compose_taproot_builder(0x51, &[2, 2, 2, 3]); let mut builder = compose_taproot_builder(0x51, &[2, 2, 2, 3]);
builder = builder.add_leaf_with_ver(3, Script::from_hex("b9").unwrap(), LeafVersion::from_consensus(0xC2).unwrap()).unwrap(); builder = builder.add_leaf_with_ver(3, ScriptBuf::from_hex("b9").unwrap(), LeafVersion::from_consensus(0xC2).unwrap()).unwrap();
let tree = TapTree::try_from(builder).unwrap(); let tree = TapTree::try_from(builder).unwrap();
let tree_prime = TapTree::deserialize(&tree.serialize()).unwrap(); let tree_prime = TapTree::deserialize(&tree.serialize()).unwrap();
assert_eq!(tree, tree_prime); assert_eq!(tree, tree_prime);

View File

@ -12,6 +12,7 @@ use core::borrow::Borrow;
use core::ops::{Deref, DerefMut}; use core::ops::{Deref, DerefMut};
use core::{fmt, str}; use core::{fmt, str};
use crate::{io, Script, ScriptBuf, Transaction, TxIn, TxOut, Sequence, Sighash};
use crate::blockdata::transaction::EncodeSigningDataResult; use crate::blockdata::transaction::EncodeSigningDataResult;
use crate::blockdata::witness::Witness; use crate::blockdata::witness::Witness;
use crate::consensus::{encode, Encodable}; use crate::consensus::{encode, Encodable};
@ -19,7 +20,6 @@ use crate::error::impl_std_error;
use crate::hashes::{sha256, sha256d, Hash}; use crate::hashes::{sha256, sha256d, Hash};
use crate::prelude::*; use crate::prelude::*;
use crate::taproot::{LeafVersion, TapLeafHash, TapSighashHash, TAPROOT_ANNEX_PREFIX}; use crate::taproot::{LeafVersion, TapLeafHash, TapSighashHash, TAPROOT_ANNEX_PREFIX};
use crate::{io, Script, Sequence, Sighash, Transaction, TxIn, TxOut};
/// Used for signature hash for invalid use of SIGHASH_SINGLE. /// Used for signature hash for invalid use of SIGHASH_SINGLE.
#[rustfmt::skip] #[rustfmt::skip]
@ -824,7 +824,7 @@ impl<R: Deref<Target = Transaction>> SighashCache<R> {
if anyone_can_pay { if anyone_can_pay {
tx.input = vec![TxIn { tx.input = vec![TxIn {
previous_output: self_.input[input_index].previous_output, previous_output: self_.input[input_index].previous_output,
script_sig: script_pubkey.clone(), script_sig: script_pubkey.to_owned(),
sequence: self_.input[input_index].sequence, sequence: self_.input[input_index].sequence,
witness: Witness::default(), witness: Witness::default(),
}]; }];
@ -834,9 +834,9 @@ impl<R: Deref<Target = Transaction>> SighashCache<R> {
tx.input.push(TxIn { tx.input.push(TxIn {
previous_output: input.previous_output, previous_output: input.previous_output,
script_sig: if n == input_index { script_sig: if n == input_index {
script_pubkey.clone() script_pubkey.to_owned()
} else { } else {
Script::new() ScriptBuf::new()
}, },
sequence: if n != input_index sequence: if n != input_index
&& (sighash == EcdsaSighashType::Single && (sighash == EcdsaSighashType::Single
@ -1006,8 +1006,8 @@ impl<R: DerefMut<Target = Transaction>> SighashCache<R> {
/// ///
/// let mut sig_hasher = SighashCache::new(&mut tx_to_sign); /// let mut sig_hasher = SighashCache::new(&mut tx_to_sign);
/// for inp in 0..input_count { /// for inp in 0..input_count {
/// let prevout_script = Script::new(); /// let prevout_script = Script::empty();
/// let _sighash = sig_hasher.segwit_signature_hash(inp, &prevout_script, 42, EcdsaSighashType::All); /// let _sighash = sig_hasher.segwit_signature_hash(inp, prevout_script, 42, EcdsaSighashType::All);
/// // ... sign the sighash /// // ... sign the sighash
/// sig_hasher.witness_mut(inp).unwrap().push(&Vec::new()); /// sig_hasher.witness_mut(inp).unwrap().push(&Vec::new());
/// } /// }
@ -1079,7 +1079,7 @@ mod tests {
input: vec![TxIn::default(), TxIn::default()], input: vec![TxIn::default(), TxIn::default()],
output: vec![TxOut::default()], output: vec![TxOut::default()],
}; };
let script = Script::new(); let script = ScriptBuf::new();
let cache = SighashCache::new(&tx); let cache = SighashCache::new(&tx);
let got = cache.legacy_signature_hash(1, &script, SIGHASH_SINGLE).expect("sighash"); let got = cache.legacy_signature_hash(1, &script, SIGHASH_SINGLE).expect("sighash");
@ -1103,7 +1103,7 @@ mod tests {
expected_result: &str, expected_result: &str,
) { ) {
let tx: Transaction = deserialize(&Vec::from_hex(tx).unwrap()[..]).unwrap(); let tx: Transaction = deserialize(&Vec::from_hex(tx).unwrap()[..]).unwrap();
let script = Script::from(Vec::from_hex(script).unwrap()); let script = ScriptBuf::from(Vec::from_hex(script).unwrap());
let mut raw_expected = Vec::from_hex(expected_result).unwrap(); let mut raw_expected = Vec::from_hex(expected_result).unwrap();
raw_expected.reverse(); raw_expected.reverse();
let want = Sighash::from_slice(&raw_expected[..]).unwrap(); let want = Sighash::from_slice(&raw_expected[..]).unwrap();
@ -1309,7 +1309,7 @@ mod tests {
}) })
); );
assert_eq!( assert_eq!(
c.legacy_signature_hash(10, &Script::default(), 0u32), c.legacy_signature_hash(10, Script::empty(), 0u32),
Err(Error::IndexOutOfInputsBounds { Err(Error::IndexOutOfInputsBounds {
index: 10, index: 10,
inputs_size: 1 inputs_size: 1
@ -1350,7 +1350,7 @@ mod tests {
let leaf_hash = match (script_hex, script_leaf_hash) { let leaf_hash = match (script_hex, script_leaf_hash) {
(Some(script_hex), _) => { (Some(script_hex), _) => {
let script_inner = Script::from_hex(script_hex).unwrap(); let script_inner = ScriptBuf::from_hex(script_hex).unwrap();
Some(ScriptPath::with_defaults(&script_inner).leaf_hash()) Some(ScriptPath::with_defaults(&script_inner).leaf_hash())
} }
(_, Some(script_leaf_hash)) => Some(TapLeafHash::from_hex(script_leaf_hash).unwrap()), (_, Some(script_leaf_hash)) => Some(TapLeafHash::from_hex(script_leaf_hash).unwrap()),
@ -1404,7 +1404,7 @@ mod tests {
#[serde(crate = "actual_serde")] #[serde(crate = "actual_serde")]
struct UtxoSpent { struct UtxoSpent {
#[serde(rename = "scriptPubKey")] #[serde(rename = "scriptPubKey")]
script_pubkey: Script, script_pubkey: ScriptBuf,
#[serde(rename = "amountSats")] #[serde(rename = "amountSats")]
value: u64, value: u64,
} }
@ -1605,7 +1605,7 @@ mod tests {
} }
} }
fn p2pkh_hex(pk: &str) -> Script { fn p2pkh_hex(pk: &str) -> ScriptBuf {
let pk: PublicKey = PublicKey::from_str(pk).unwrap(); let pk: PublicKey = PublicKey::from_str(pk).unwrap();
Address::p2pkh(&pk, Network::Bitcoin).script_pubkey() Address::p2pkh(&pk, Network::Bitcoin).script_pubkey()
} }

View File

@ -16,7 +16,7 @@ use crate::consensus::Encodable;
use crate::crypto::schnorr::{TapTweak, TweakedPublicKey, UntweakedPublicKey, XOnlyPublicKey}; use crate::crypto::schnorr::{TapTweak, TweakedPublicKey, UntweakedPublicKey, XOnlyPublicKey};
use crate::hashes::{sha256, sha256t_hash_newtype, Hash, HashEngine}; use crate::hashes::{sha256, sha256t_hash_newtype, Hash, HashEngine};
use crate::prelude::*; use crate::prelude::*;
use crate::{io, Script}; use crate::{io, Script, ScriptBuf};
/// The SHA-256 midstate value for the TapLeaf hash. /// The SHA-256 midstate value for the TapLeaf hash.
const MIDSTATE_TAPLEAF: [u8; 32] = [ const MIDSTATE_TAPLEAF: [u8; 32] = [
@ -149,7 +149,7 @@ pub const TAPROOT_CONTROL_MAX_SIZE: usize =
TAPROOT_CONTROL_BASE_SIZE + TAPROOT_CONTROL_NODE_SIZE * TAPROOT_CONTROL_MAX_NODE_COUNT; TAPROOT_CONTROL_BASE_SIZE + TAPROOT_CONTROL_NODE_SIZE * TAPROOT_CONTROL_MAX_NODE_COUNT;
// type alias for versioned tap script corresponding merkle proof // type alias for versioned tap script corresponding merkle proof
type ScriptMerkleProofMap = BTreeMap<(Script, LeafVersion), BTreeSet<TaprootMerkleBranch>>; type ScriptMerkleProofMap = BTreeMap<(ScriptBuf, LeafVersion), BTreeSet<TaprootMerkleBranch>>;
/// Represents taproot spending information. /// Represents taproot spending information.
/// ///
@ -200,7 +200,7 @@ impl TaprootSpendInfo {
script_weights: I, script_weights: I,
) -> Result<Self, TaprootBuilderError> ) -> Result<Self, TaprootBuilderError>
where where
I: IntoIterator<Item = (u32, Script)>, I: IntoIterator<Item = (u32, ScriptBuf)>,
C: secp256k1::Verification, C: secp256k1::Verification,
{ {
let builder = TaprootBuilder::with_huffman_tree(script_weights)?; let builder = TaprootBuilder::with_huffman_tree(script_weights)?;
@ -286,13 +286,13 @@ impl TaprootSpendInfo {
/// ///
/// - If there are multiple control blocks possible, returns the shortest one. /// - If there are multiple control blocks possible, returns the shortest one.
/// - If the script is not contained in the [`TaprootSpendInfo`], returns `None`. /// - If the script is not contained in the [`TaprootSpendInfo`], returns `None`.
pub fn control_block(&self, script_ver: &(Script, LeafVersion)) -> Option<ControlBlock> { pub fn control_block(&self, script_ver: &(ScriptBuf, LeafVersion)) -> Option<ControlBlock> {
let merkle_branch_set = self.script_map.get(script_ver)?; let merkle_branch_set = self.script_map.get(script_ver)?;
// Choose the smallest one amongst the multiple script maps // Choose the smallest one amongst the multiple script maps
let smallest = merkle_branch_set let smallest = merkle_branch_set
.iter() .iter()
.min_by(|x, y| x.0.len().cmp(&y.0.len())) .min_by(|x, y| x.0.len().cmp(&y.0.len()))
.expect("Invariant: Script map key must contain non-empty set value"); .expect("Invariant: ScriptBuf map key must contain non-empty set value");
Some(ControlBlock { Some(ControlBlock {
internal_key: self.internal_key, internal_key: self.internal_key,
output_key_parity: self.output_key_parity, output_key_parity: self.output_key_parity,
@ -364,7 +364,7 @@ impl TaprootBuilder {
/// The weights represent the probability of each branch being taken. If probabilities/weights /// The weights represent the probability of each branch being taken. If probabilities/weights
/// for each condition are known, constructing the tree as a Huffman Tree is the optimal way to /// for each condition are known, constructing the tree as a Huffman Tree is the optimal way to
/// minimize average case satisfaction cost. This function takes as input an iterator of /// minimize average case satisfaction cost. This function takes as input an iterator of
/// `tuple(u32, &Script)` where `u32` represents the satisfaction weights of the branch. For /// `tuple(u32, ScriptBuf)` where `u32` represents the satisfaction weights of the branch. For
/// example, [(3, S1), (2, S2), (5, S3)] would construct a [`TapTree`] that has optimal /// example, [(3, S1), (2, S2), (5, S3)] would construct a [`TapTree`] that has optimal
/// satisfaction weight when probability for S1 is 30%, S2 is 20% and S3 is 50%. /// satisfaction weight when probability for S1 is 30%, S2 is 20% and S3 is 50%.
/// ///
@ -381,7 +381,7 @@ impl TaprootBuilder {
/// [`TapTree`]: crate::psbt::TapTree /// [`TapTree`]: crate::psbt::TapTree
pub fn with_huffman_tree<I>(script_weights: I) -> Result<Self, TaprootBuilderError> pub fn with_huffman_tree<I>(script_weights: I) -> Result<Self, TaprootBuilderError>
where where
I: IntoIterator<Item = (u32, Script)>, I: IntoIterator<Item = (u32, ScriptBuf)>,
{ {
let mut node_weights = BinaryHeap::<(Reverse<u32>, NodeInfo)>::new(); let mut node_weights = BinaryHeap::<(Reverse<u32>, NodeInfo)>::new();
for (p, leaf) in script_weights { for (p, leaf) in script_weights {
@ -414,7 +414,7 @@ impl TaprootBuilder {
pub fn add_leaf_with_ver( pub fn add_leaf_with_ver(
self, self,
depth: u8, depth: u8,
script: Script, script: ScriptBuf,
ver: LeafVersion, ver: LeafVersion,
) -> Result<Self, TaprootBuilderError> { ) -> Result<Self, TaprootBuilderError> {
let leaf = NodeInfo::new_leaf_with_ver(script, ver); let leaf = NodeInfo::new_leaf_with_ver(script, ver);
@ -425,7 +425,7 @@ impl TaprootBuilder {
/// leaves are not provided in DFS walk order. The depth of the root node is 0. /// leaves are not provided in DFS walk order. The depth of the root node is 0.
/// ///
/// See [`TaprootBuilder::add_leaf_with_ver`] for adding a leaf with specific version. /// See [`TaprootBuilder::add_leaf_with_ver`] for adding a leaf with specific version.
pub fn add_leaf(self, depth: u8, script: Script) -> Result<Self, TaprootBuilderError> { pub fn add_leaf(self, depth: u8, script: ScriptBuf) -> Result<Self, TaprootBuilderError> {
self.add_leaf_with_ver(depth, script, LeafVersion::TapScript) self.add_leaf_with_ver(depth, script, LeafVersion::TapScript)
} }
@ -547,8 +547,8 @@ impl NodeInfo {
Self { hash, leaves: vec![], has_hidden_nodes: true } Self { hash, leaves: vec![], has_hidden_nodes: true }
} }
/// Creates a new leaf [`NodeInfo`] with given [`Script`] and [`LeafVersion`]. /// Creates a new leaf [`NodeInfo`] with given [`ScriptBuf`] and [`LeafVersion`].
pub fn new_leaf_with_ver(script: Script, ver: LeafVersion) -> Self { pub fn new_leaf_with_ver(script: ScriptBuf, ver: LeafVersion) -> Self {
let leaf = ScriptLeaf::new(script, ver); let leaf = ScriptLeaf::new(script, ver);
Self { Self {
hash: sha256::Hash::from_inner(leaf.leaf_hash().into_inner()), hash: sha256::Hash::from_inner(leaf.leaf_hash().into_inner()),
@ -583,7 +583,7 @@ impl NodeInfo {
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))] #[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
pub struct ScriptLeaf { pub struct ScriptLeaf {
/// The underlying script. /// The underlying script.
script: Script, script: ScriptBuf,
/// The leaf version. /// The leaf version.
ver: LeafVersion, ver: LeafVersion,
/// The merkle proof (hashing partners) to get this node. /// The merkle proof (hashing partners) to get this node.
@ -592,7 +592,7 @@ pub struct ScriptLeaf {
impl ScriptLeaf { impl ScriptLeaf {
/// Creates an new [`ScriptLeaf`] from `script` and `ver` and no merkle branch. /// Creates an new [`ScriptLeaf`] from `script` and `ver` and no merkle branch.
fn new(script: Script, ver: LeafVersion) -> Self { fn new(script: ScriptBuf, ver: LeafVersion) -> Self {
Self { script, ver, merkle_branch: TaprootMerkleBranch(vec![]) } Self { script, ver, merkle_branch: TaprootMerkleBranch(vec![]) }
} }
@ -1187,7 +1187,7 @@ mod test {
) { ) {
let out_pk = XOnlyPublicKey::from_str(&out_spk_hex[4..]).unwrap(); let out_pk = XOnlyPublicKey::from_str(&out_spk_hex[4..]).unwrap();
let out_pk = TweakedPublicKey::dangerous_assume_tweaked(out_pk); let out_pk = TweakedPublicKey::dangerous_assume_tweaked(out_pk);
let script = Script::from_hex(script_hex).unwrap(); let script = ScriptBuf::from_hex(script_hex).unwrap();
let control_block = let control_block =
ControlBlock::from_slice(&Vec::<u8>::from_hex(control_block_hex).unwrap()).unwrap(); ControlBlock::from_slice(&Vec::<u8>::from_hex(control_block_hex).unwrap()).unwrap();
assert_eq!(control_block_hex, control_block.serialize().to_hex()); assert_eq!(control_block_hex, control_block.serialize().to_hex());
@ -1255,11 +1255,11 @@ mod test {
.unwrap(); .unwrap();
let script_weights = vec![ let script_weights = vec![
(10, Script::from_hex("51").unwrap()), // semantics of script don't matter for this test (10, ScriptBuf::from_hex("51").unwrap()), // semantics of script don't matter for this test
(20, Script::from_hex("52").unwrap()), (20, ScriptBuf::from_hex("52").unwrap()),
(20, Script::from_hex("53").unwrap()), (20, ScriptBuf::from_hex("53").unwrap()),
(30, Script::from_hex("54").unwrap()), (30, ScriptBuf::from_hex("54").unwrap()),
(19, Script::from_hex("55").unwrap()), (19, ScriptBuf::from_hex("55").unwrap()),
]; ];
let tree_info = let tree_info =
TaprootSpendInfo::with_huffman_tree(&secp, internal_key, script_weights.clone()) TaprootSpendInfo::with_huffman_tree(&secp, internal_key, script_weights.clone())
@ -1280,7 +1280,7 @@ mod test {
*length, *length,
tree_info tree_info
.script_map .script_map
.get(&(Script::from_hex(script).unwrap(), LeafVersion::TapScript)) .get(&(ScriptBuf::from_hex(script).unwrap(), LeafVersion::TapScript))
.expect("Present Key") .expect("Present Key")
.iter() .iter()
.next() .next()
@ -1323,11 +1323,11 @@ mod test {
// / \ / \ // / \ / \
// A B C / \ // A B C / \
// D E // D E
let a = Script::from_hex("51").unwrap(); let a = ScriptBuf::from_hex("51").unwrap();
let b = Script::from_hex("52").unwrap(); let b = ScriptBuf::from_hex("52").unwrap();
let c = Script::from_hex("53").unwrap(); let c = ScriptBuf::from_hex("53").unwrap();
let d = Script::from_hex("54").unwrap(); let d = ScriptBuf::from_hex("54").unwrap();
let e = Script::from_hex("55").unwrap(); let e = ScriptBuf::from_hex("55").unwrap();
let builder = builder.add_leaf(2, a.clone()).unwrap(); let builder = builder.add_leaf(2, a.clone()).unwrap();
let builder = builder.add_leaf(2, b.clone()).unwrap(); let builder = builder.add_leaf(2, b.clone()).unwrap();
let builder = builder.add_leaf(2, c.clone()).unwrap(); let builder = builder.add_leaf(2, c.clone()).unwrap();
@ -1356,7 +1356,7 @@ mod test {
fn process_script_trees( fn process_script_trees(
v: &serde_json::Value, v: &serde_json::Value,
mut builder: TaprootBuilder, mut builder: TaprootBuilder,
leaves: &mut Vec<(Script, LeafVersion)>, leaves: &mut Vec<(ScriptBuf, LeafVersion)>,
depth: u8, depth: u8,
) -> TaprootBuilder { ) -> TaprootBuilder {
if v.is_null() { if v.is_null() {
@ -1366,7 +1366,7 @@ mod test {
builder = process_script_trees(leaf, builder, leaves, depth + 1); builder = process_script_trees(leaf, builder, leaves, depth + 1);
} }
} else { } else {
let script = Script::from_str(v["script"].as_str().unwrap()).unwrap(); let script = ScriptBuf::from_str(v["script"].as_str().unwrap()).unwrap();
let ver = let ver =
LeafVersion::from_consensus(v["leafVersion"].as_u64().unwrap() as u8).unwrap(); LeafVersion::from_consensus(v["leafVersion"].as_u64().unwrap() as u8).unwrap();
leaves.push((script.clone(), ver)); leaves.push((script.clone(), ver));
@ -1418,7 +1418,7 @@ mod test {
let expected_tweak = let expected_tweak =
TapTweakHash::from_str(arr["intermediary"]["tweak"].as_str().unwrap()).unwrap(); TapTweakHash::from_str(arr["intermediary"]["tweak"].as_str().unwrap()).unwrap();
let expected_spk = let expected_spk =
Script::from_str(arr["expected"]["scriptPubKey"].as_str().unwrap()).unwrap(); ScriptBuf::from_str(arr["expected"]["scriptPubKey"].as_str().unwrap()).unwrap();
let expected_addr = let expected_addr =
Address::from_str(arr["expected"]["bip350Address"].as_str().unwrap()).unwrap(); Address::from_str(arr["expected"]["bip350Address"].as_str().unwrap()).unwrap();

View File

@ -12,7 +12,7 @@ use bitcoin::hashes::hex::FromHex;
use bitcoin::psbt::{Psbt, PsbtSighashType}; use bitcoin::psbt::{Psbt, PsbtSighashType};
use bitcoin::secp256k1::{self, Secp256k1}; use bitcoin::secp256k1::{self, Secp256k1};
use bitcoin::{ use bitcoin::{
absolute, Amount, Denomination, Network, OutPoint, PrivateKey, PublicKey, Script, Sequence, absolute, Amount, Denomination, Network, OutPoint, PrivateKey, PublicKey, ScriptBuf, Sequence,
Transaction, TxIn, TxOut, Txid, Witness, Transaction, TxIn, TxOut, Txid, Witness,
}; };
@ -20,7 +20,7 @@ const NETWORK: Network = Network::Testnet;
macro_rules! hex_script { macro_rules! hex_script {
($s:expr) => { ($s:expr) => {
<Script as FromStr>::from_str($s).unwrap() <ScriptBuf as FromStr>::from_str($s).unwrap()
}; };
} }
@ -169,7 +169,7 @@ fn create_transaction() -> Transaction {
txid: Txid::from_hex(input_0.txid).expect("failed to parse txid"), txid: Txid::from_hex(input_0.txid).expect("failed to parse txid"),
vout: input_0.index, vout: input_0.index,
}, },
script_sig: Script::new(), script_sig: ScriptBuf::new(),
sequence: Sequence::MAX, // Disable nSequence. sequence: Sequence::MAX, // Disable nSequence.
witness: Witness::default(), witness: Witness::default(),
}, },
@ -178,7 +178,7 @@ fn create_transaction() -> Transaction {
txid: Txid::from_hex(input_1.txid).expect("failed to parse txid"), txid: Txid::from_hex(input_1.txid).expect("failed to parse txid"),
vout: input_1.index, vout: input_1.index,
}, },
script_sig: Script::new(), script_sig: ScriptBuf::new(),
sequence: Sequence::MAX, sequence: Sequence::MAX,
witness: Witness::default(), witness: Witness::default(),
}, },
@ -188,14 +188,14 @@ fn create_transaction() -> Transaction {
value: Amount::from_str_in(output_0.amount, Denomination::Bitcoin) value: Amount::from_str_in(output_0.amount, Denomination::Bitcoin)
.expect("failed to parse amount") .expect("failed to parse amount")
.to_sat(), .to_sat(),
script_pubkey: Script::from_str(output_0.script_pubkey) script_pubkey: ScriptBuf::from_str(output_0.script_pubkey)
.expect("failed to parse script"), .expect("failed to parse script"),
}, },
TxOut { TxOut {
value: Amount::from_str_in(output_1.amount, Denomination::Bitcoin) value: Amount::from_str_in(output_1.amount, Denomination::Bitcoin)
.expect("failed to parse amount") .expect("failed to parse amount")
.to_sat(), .to_sat(),
script_pubkey: Script::from_str(output_1.script_pubkey) script_pubkey: ScriptBuf::from_str(output_1.script_pubkey)
.expect("failed to parse script"), .expect("failed to parse script"),
}, },
], ],

View File

@ -15,7 +15,7 @@
// //
// use std::fs::File; // use std::fs::File;
// use std::io::Write; // use std::io::Write;
// let script = Script::from(vec![0u8, 1u8, 2u8]); // let script = ScriptBuf::from(vec![0u8, 1u8, 2u8]);
// let got = serialize(&script).unwrap(); // let got = serialize(&script).unwrap();
// let mut file = File::create("/tmp/script_bincode").unwrap(); // let mut file = File::create("/tmp/script_bincode").unwrap();
// file.write_all(&got).unwrap(); // file.write_all(&got).unwrap();
@ -38,7 +38,7 @@ use bitcoin::schnorr::{self, UntweakedPublicKey};
use bitcoin::sighash::{EcdsaSighashType, SchnorrSighashType}; use bitcoin::sighash::{EcdsaSighashType, SchnorrSighashType};
use bitcoin::taproot::{ControlBlock, LeafVersion, TaprootBuilder, TaprootSpendInfo}; use bitcoin::taproot::{ControlBlock, LeafVersion, TaprootBuilder, TaprootSpendInfo};
use bitcoin::{ use bitcoin::{
ecdsa, Address, Block, Network, OutPoint, PrivateKey, PublicKey, Script, Sequence, Target, ecdsa, Address, Block, Network, OutPoint, PrivateKey, PublicKey, ScriptBuf, Sequence, Target,
Transaction, TxIn, TxOut, Txid, Work, Transaction, TxIn, TxOut, Txid, Work,
}; };
use secp256k1::Secp256k1; use secp256k1::Secp256k1;
@ -95,7 +95,7 @@ fn serde_regression_relative_lock_time_time() {
#[test] #[test]
fn serde_regression_script() { fn serde_regression_script() {
let script = Script::from(vec![0u8, 1u8, 2u8]); let script = ScriptBuf::from(vec![0u8, 1u8, 2u8]);
let got = serialize(&script).unwrap(); let got = serialize(&script).unwrap();
let want = include_bytes!("data/serde/script_bincode") as &[_]; let want = include_bytes!("data/serde/script_bincode") as &[_];
assert_eq!(got, want) assert_eq!(got, want)
@ -114,7 +114,7 @@ fn serde_regression_txin() {
#[test] #[test]
fn serde_regression_txout() { fn serde_regression_txout() {
let txout = let txout =
TxOut { value: 0xDEADBEEFCAFEBABE, script_pubkey: Script::from(vec![0u8, 1u8, 2u8]) }; TxOut { value: 0xDEADBEEFCAFEBABE, script_pubkey: ScriptBuf::from(vec![0u8, 1u8, 2u8]) };
let got = serialize(&txout).unwrap(); let got = serialize(&txout).unwrap();
let want = include_bytes!("data/serde/txout_bincode") as &[_]; let want = include_bytes!("data/serde/txout_bincode") as &[_];
assert_eq!(got, want) assert_eq!(got, want)
@ -232,7 +232,7 @@ fn serde_regression_psbt() {
.unwrap(), .unwrap(),
vout: 1, vout: 1,
}, },
script_sig: Script::from_str("160014be18d152a9b012039daf3da7de4f53349eecb985").unwrap(), script_sig: ScriptBuf::from_str("160014be18d152a9b012039daf3da7de4f53349eecb985").unwrap(),
sequence: Sequence::from_consensus(4294967295), sequence: Sequence::from_consensus(4294967295),
witness: Witness::from_slice(&[Vec::from_hex( witness: Witness::from_slice(&[Vec::from_hex(
"03d2e15674941bad4a996372cb87e1856d3652606d98562fe39c5e9e7e413f2105", "03d2e15674941bad4a996372cb87e1856d3652606d98562fe39c5e9e7e413f2105",
@ -241,7 +241,7 @@ fn serde_regression_psbt() {
}], }],
output: vec![TxOut { output: vec![TxOut {
value: 190303501938, value: 190303501938,
script_pubkey: Script::from_str("a914339725ba21efd62ac753a9bcd067d6c7a6a39d0587") script_pubkey: ScriptBuf::from_str("a914339725ba21efd62ac753a9bcd067d6c7a6a39d0587")
.unwrap(), .unwrap(),
}], }],
}; };
@ -275,7 +275,7 @@ fn serde_regression_psbt() {
}, },
unsigned_tx: { unsigned_tx: {
let mut unsigned = tx.clone(); let mut unsigned = tx.clone();
unsigned.input[0].script_sig = Script::new(); unsigned.input[0].script_sig = ScriptBuf::new();
unsigned.input[0].witness = Witness::default(); unsigned.input[0].witness = Witness::default();
unsigned unsigned
}, },
@ -286,7 +286,7 @@ fn serde_regression_psbt() {
non_witness_utxo: Some(tx), non_witness_utxo: Some(tx),
witness_utxo: Some(TxOut { witness_utxo: Some(TxOut {
value: 190303501938, value: 190303501938,
script_pubkey: Script::from_str("a914339725ba21efd62ac753a9bcd067d6c7a6a39d0587").unwrap(), script_pubkey: ScriptBuf::from_str("a914339725ba21efd62ac753a9bcd067d6c7a6a39d0587").unwrap(),
}), }),
sighash_type: Some(PsbtSighashType::from(EcdsaSighashType::from_str("SIGHASH_SINGLE|SIGHASH_ANYONECANPAY").unwrap())), sighash_type: Some(PsbtSighashType::from(EcdsaSighashType::from_str("SIGHASH_SINGLE|SIGHASH_ANYONECANPAY").unwrap())),
redeem_script: Some(vec![0x51].into()), redeem_script: Some(vec![0x51].into()),
@ -357,7 +357,7 @@ fn serde_regression_schnorr_sig() {
#[test] #[test]
fn serde_regression_taproot_builder() { fn serde_regression_taproot_builder() {
let ver = LeafVersion::from_consensus(0).unwrap(); let ver = LeafVersion::from_consensus(0).unwrap();
let script = Script::from(vec![0u8, 1u8, 2u8]); let script = ScriptBuf::from(vec![0u8, 1u8, 2u8]);
let builder = TaprootBuilder::new().add_leaf_with_ver(1, script, ver).unwrap(); let builder = TaprootBuilder::new().add_leaf_with_ver(1, script, ver).unwrap();
let got = serialize(&builder).unwrap(); let got = serialize(&builder).unwrap();
@ -374,11 +374,11 @@ fn serde_regression_taproot_spend_info() {
.unwrap(); .unwrap();
let script_weights = vec![ let script_weights = vec![
(10, Script::from_hex("51").unwrap()), // semantics of script don't matter for this test (10, ScriptBuf::from_hex("51").unwrap()), // semantics of script don't matter for this test
(20, Script::from_hex("52").unwrap()), (20, ScriptBuf::from_hex("52").unwrap()),
(20, Script::from_hex("53").unwrap()), (20, ScriptBuf::from_hex("53").unwrap()),
(30, Script::from_hex("54").unwrap()), (30, ScriptBuf::from_hex("54").unwrap()),
(19, Script::from_hex("55").unwrap()), (19, ScriptBuf::from_hex("55").unwrap()),
]; ];
let tree_info = let tree_info =
TaprootSpendInfo::with_huffman_tree(&secp, internal_key, script_weights).unwrap(); TaprootSpendInfo::with_huffman_tree(&secp, internal_key, script_weights).unwrap();