pub struct ScriptBuf(/* private fields */);
Expand description
An owned, growable script.
ScriptBuf
is the most common script type that has the ownership over the contents of the
script. It has a close relationship with its borrowed counterpart, Script
.
Just as other similar types, this implements Deref
, so deref coercions apply. Also note
that all the safety/validity restrictions that apply to Script
apply to ScriptBuf
as well.
Implementations§
source§impl ScriptBuf
impl ScriptBuf
sourcepub fn with_capacity(capacity: usize) -> Self
pub fn with_capacity(capacity: usize) -> Self
Creates a new empty script with pre-allocated capacity.
sourcepub fn reserve(&mut self, additional_len: usize)
pub fn reserve(&mut self, additional_len: usize)
Pre-allocates at least additional_len
bytes if needed.
Reserves capacity for at least additional_len
more bytes to be inserted in the given
script. The script may reserve more space to speculatively avoid frequent reallocations.
After calling reserve
, capacity will be greater than or equal to
self.len() + additional_len
. Does nothing if capacity is already sufficient.
Panics
Panics if the new capacity exceeds isize::MAX bytes
.
sourcepub fn reserve_exact(&mut self, additional_len: usize)
pub fn reserve_exact(&mut self, additional_len: usize)
Pre-allocates exactly additional_len
bytes if needed.
Unlike reserve
, this will not deliberately over-allocate to speculatively avoid frequent
allocations. After calling reserve_exact
, capacity will be greater than or equal to
self.len() + additional
. Does nothing if the capacity is already sufficient.
Note that the allocator may give the collection more space than it requests. Therefore,
capacity can not be relied upon to be precisely minimal. Prefer reserve
if future insertions are expected.
Panics
Panics if the new capacity exceeds isize::MAX bytes
.
sourcepub fn as_mut_script(&mut self) -> &mut Script
pub fn as_mut_script(&mut self) -> &mut Script
Returns a mutable reference to unsized script.
sourcepub fn new_p2pkh(pubkey_hash: &PubkeyHash) -> Self
pub fn new_p2pkh(pubkey_hash: &PubkeyHash) -> Self
Generates P2PKH-type of scriptPubkey.
sourcepub fn new_p2sh(script_hash: &ScriptHash) -> Self
pub fn new_p2sh(script_hash: &ScriptHash) -> Self
Generates P2SH-type of scriptPubkey with a given hash of the redeem script.
sourcepub fn new_p2wpkh(pubkey_hash: &WPubkeyHash) -> Self
pub fn new_p2wpkh(pubkey_hash: &WPubkeyHash) -> Self
Generates P2WPKH-type of scriptPubkey.
sourcepub fn new_p2wsh(script_hash: &WScriptHash) -> Self
pub fn new_p2wsh(script_hash: &WScriptHash) -> Self
Generates P2WSH-type of scriptPubkey with a given hash of the redeem script.
sourcepub fn new_p2tr<C: Verification>(
secp: &Secp256k1<C>,
internal_key: UntweakedPublicKey,
merkle_root: Option<TapNodeHash>
) -> Self
pub fn new_p2tr<C: Verification>( secp: &Secp256k1<C>, internal_key: UntweakedPublicKey, merkle_root: Option<TapNodeHash> ) -> Self
Generates P2TR for script spending path using an internal public key and some optional script tree merkle root.
sourcepub fn new_p2tr_tweaked(output_key: TweakedPublicKey) -> Self
pub fn new_p2tr_tweaked(output_key: TweakedPublicKey) -> Self
Generates P2TR for key spending path for a known TweakedPublicKey
.
sourcepub fn new_witness_program(witness_program: &WitnessProgram) -> Self
pub fn new_witness_program(witness_program: &WitnessProgram) -> Self
Generates P2WSH-type of scriptPubkey with a given WitnessProgram
.
sourcepub fn p2wpkh_script_code(wpkh: WPubkeyHash) -> ScriptBuf
pub fn p2wpkh_script_code(wpkh: WPubkeyHash) -> ScriptBuf
Creates the script code used for spending a P2WPKH output.
The scriptCode
is described in BIP143.
sourcepub fn new_op_return<T: AsRef<PushBytes>>(data: T) -> Self
pub fn new_op_return<T: AsRef<PushBytes>>(data: T) -> Self
Generates OP_RETURN-type of scriptPubkey for the given data.
sourcepub fn from_hex(s: &str) -> Result<Self, HexToBytesError>
pub fn from_hex(s: &str) -> Result<Self, HexToBytesError>
Creates a ScriptBuf
from a hex string.
sourcepub fn from_bytes(bytes: Vec<u8>) -> Self
pub fn from_bytes(bytes: Vec<u8>) -> Self
Converts byte vector into script.
This method doesn’t (re)allocate.
sourcepub fn into_bytes(self) -> Vec<u8> ⓘ
pub fn into_bytes(self) -> Vec<u8> ⓘ
Converts the script into a byte vector.
This method doesn’t (re)allocate.
sourcepub fn push_opcode(&mut self, data: Opcode)
pub fn push_opcode(&mut self, data: Opcode)
Adds a single opcode to the script.
sourcepub fn push_slice<T: AsRef<PushBytes>>(&mut self, data: T)
pub fn push_slice<T: AsRef<PushBytes>>(&mut self, data: T)
Adds instructions to push some arbitrary data onto the stack.
sourcepub fn push_instruction(&mut self, instruction: Instruction<'_>)
pub fn push_instruction(&mut self, instruction: Instruction<'_>)
Add a single instruction to the script.
Panics
The method panics if the instruction is a data push with length greater or equal to 0x100000000.
sourcepub fn push_instruction_no_opt(&mut self, instruction: Instruction<'_>)
pub fn push_instruction_no_opt(&mut self, instruction: Instruction<'_>)
Like push_instruction, but avoids calling reserve
to not re-check the length.
sourcepub fn scan_and_push_verify(&mut self)
pub fn scan_and_push_verify(&mut self)
Adds an OP_VERIFY
to the script or replaces the last opcode with VERIFY form.
Some opcodes such as OP_CHECKSIG
have a verify variant that works as if VERIFY
was
in the script right after. To save space this function appends VERIFY
only if
the most-recently-added opcode does not have an alternate VERIFY
form. If it does
the last opcode is replaced. E.g., OP_CHECKSIG
will become OP_CHECKSIGVERIFY
.
Note that existing OP_*VERIFY
opcodes do not lead to the instruction being ignored
because OP_VERIFY
consumes an item from the stack so ignoring them would change the
semantics.
This function needs to iterate over the script to find the last instruction. Prefer
Builder
if you’re creating the script from scratch or if you want to push OP_VERIFY
multiple times.
sourcepub fn into_boxed_script(self) -> Box<Script>
pub fn into_boxed_script(self) -> Box<Script>
Converts this ScriptBuf
into a boxed Script
.
This method reallocates if the capacity is greater than length of the script but should not
when they are equal. If you know beforehand that you need to create a script of exact size
use reserve_exact
before adding data to the script so that the
reallocation can be avoided.
Methods from Deref<Target = Script>§
sourcepub fn as_mut_bytes(&mut self) -> &mut [u8] ⓘ
pub fn as_mut_bytes(&mut self) -> &mut [u8] ⓘ
Returns the script data as a mutable byte slice.
sourcepub fn script_hash(&self) -> ScriptHash
pub fn script_hash(&self) -> ScriptHash
Returns 160-bit hash of the script.
sourcepub fn wscript_hash(&self) -> WScriptHash
pub fn wscript_hash(&self) -> WScriptHash
Returns 256-bit hash of the script for P2WSH outputs.
sourcepub fn tapscript_leaf_hash(&self) -> TapLeafHash
pub fn tapscript_leaf_hash(&self) -> TapLeafHash
Computes leaf hash of tapscript.
sourcepub fn to_p2wsh(&self) -> ScriptBuf
pub fn to_p2wsh(&self) -> ScriptBuf
Computes the P2WSH output corresponding to this witnessScript (aka the “witness redeem script”).
sourcepub fn to_p2tr<C: Verification>(
&self,
secp: &Secp256k1<C>,
internal_key: UntweakedPublicKey
) -> ScriptBuf
pub fn to_p2tr<C: Verification>( &self, secp: &Secp256k1<C>, internal_key: UntweakedPublicKey ) -> ScriptBuf
Computes P2TR output with a given internal key and a single script spending path equal to the current script, assuming that the script is a Tapscript.
sourcepub fn witness_version(&self) -> Option<WitnessVersion>
pub fn witness_version(&self) -> Option<WitnessVersion>
Returns witness version of the script, if any, assuming the script is a scriptPubkey
.
Returns
The witness version if this script is found to conform to the SegWit rules:
A scriptPubKey (or redeemScript as defined in BIP16/P2SH) that consists of a 1-byte push opcode (for 0 to 16) followed by a data push between 2 and 40 bytes gets a new special meaning. The value of the first push is called the “version byte”. The following byte vector pushed is called the “witness program”.
sourcepub fn is_push_only(&self) -> bool
pub fn is_push_only(&self) -> bool
Checks whether a script is push only.
Note: OP_RESERVED
(0x50
) and all the OP_PUSHNUM operations
are considered push operations.
sourcepub fn is_p2pk(&self) -> bool
pub fn is_p2pk(&self) -> bool
Checks whether a script pubkey is a P2PK output.
You can obtain the public key, if its valid,
by calling p2pk_public_key()
sourcepub fn p2pk_public_key(&self) -> Option<PublicKey>
pub fn p2pk_public_key(&self) -> Option<PublicKey>
Returns the public key if this script is P2PK with a valid public key.
This may return None
even when is_p2pk()
returns true.
This happens when the public key is invalid (e.g. the point not being on the curve).
In this situation the script is unspendable.
sourcepub fn is_multisig(&self) -> bool
pub fn is_multisig(&self) -> bool
Checks whether a script pubkey is a bare multisig output.
In a bare multisig pubkey script the keys are not hashed, the script is of the form:
2 <pubkey1> <pubkey2> <pubkey3> 3 OP_CHECKMULTISIG
sourcepub fn is_witness_program(&self) -> bool
pub fn is_witness_program(&self) -> bool
Checks whether a script pubkey is a Segregated Witness (segwit) program.
sourcepub fn is_op_return(&self) -> bool
pub fn is_op_return(&self) -> bool
Check if this is an OP_RETURN output.
sourcepub fn is_provably_unspendable(&self) -> bool
👎Deprecated since 0.32.0: The method has potentially confusing semantics and is going to be removed, you might want is_op_return
pub fn is_provably_unspendable(&self) -> bool
is_op_return
Checks whether a script is trivially known to have no satisfying input.
This method has potentially confusing semantics and an unclear purpose, so it’s going to be
removed. Use is_op_return
if you want OP_RETURN
semantics.
sourcepub fn to_p2sh(&self) -> ScriptBuf
pub fn to_p2sh(&self) -> ScriptBuf
Computes the P2SH output corresponding to this redeem script.
sourcepub fn p2wpkh_script_code(&self) -> Option<ScriptBuf>
pub fn p2wpkh_script_code(&self) -> Option<ScriptBuf>
Returns the script code used for spending a P2WPKH output if this script is a script pubkey
for a P2WPKH output. The scriptCode
is described in BIP143.
sourcepub fn redeem_script(&self) -> Option<&Script>
pub fn redeem_script(&self) -> Option<&Script>
Get redeemScript following BIP16 rules regarding P2SH spending.
This does not guarantee that this represents a P2SH input Script
.
It merely gets the last push of the script. Use
Script::is_p2sh
on the
scriptPubKey to check whether it is actually a P2SH script.
sourcepub fn dust_value(&self) -> Amount
👎Deprecated since 0.32.0: use minimal_non_dust and friends
pub fn dust_value(&self) -> Amount
Returns the minimum value an output with this script should have in order to be broadcastable on today’s Bitcoin network.
sourcepub fn minimal_non_dust(&self) -> Amount
pub fn minimal_non_dust(&self) -> Amount
Returns the minimum value an output with this script should have in order to be broadcastable on today’s Bitcoin network.
Dust depends on the -dustrelayfee value of the Bitcoin Core node you are broadcasting to. This function uses the default value of 0.00003 BTC/kB (3 sat/vByte).
To use a custom value, use minimal_non_dust_custom
.
sourcepub fn minimal_non_dust_custom(&self, dust_relay_fee: FeeRate) -> Amount
pub fn minimal_non_dust_custom(&self, dust_relay_fee: FeeRate) -> Amount
Returns the minimum value an output with this script should have in order to be broadcastable on today’s Bitcoin network.
Dust depends on the -dustrelayfee value of the Bitcoin Core node you are broadcasting to. This function lets you set the fee rate used in dust calculation.
The current default value in Bitcoin Core (as of v26) is 3 sat/vByte.
To use the default Bitcoin Core value, use minimal_non_dust
.
sourcepub fn count_sigops(&self) -> usize
pub fn count_sigops(&self) -> usize
Counts the sigops for this Script using accurate counting.
In Bitcoin Core, there are two ways to count sigops, “accurate” and “legacy”. This method uses “accurate” counting. This means that OP_CHECKMULTISIG and its verify variant count for N sigops where N is the number of pubkeys used in the multisig. However, it will count for 20 sigops if CHECKMULTISIG is not preceded by an OP_PUSHNUM from 1 - 16 (this would be an invalid script)
Bitcoin Core uses accurate counting for sigops contained within redeemScripts (P2SH) and witnessScripts (P2WSH) only. It uses legacy for sigops in scriptSigs and scriptPubkeys.
(Note: taproot scripts don’t count toward the sigop count of the block, nor do they have CHECKMULTISIG operations. This function does not count OP_CHECKSIGADD, so do not use this to try and estimate if a taproot script goes over the sigop budget.)
sourcepub fn count_sigops_legacy(&self) -> usize
pub fn count_sigops_legacy(&self) -> usize
Counts the sigops for this Script using legacy counting.
In Bitcoin Core, there are two ways to count sigops, “accurate” and “legacy”. This method uses “legacy” counting. This means that OP_CHECKMULTISIG and its verify variant count for 20 sigops.
Bitcoin Core uses legacy counting for sigops contained within scriptSigs and scriptPubkeys. It uses accurate for redeemScripts (P2SH) and witnessScripts (P2WSH).
(Note: taproot scripts don’t count toward the sigop count of the block, nor do they have CHECKMULTISIG operations. This function does not count OP_CHECKSIGADD, so do not use this to try and estimate if a taproot script goes over the sigop budget.)
sourcepub fn instructions(&self) -> Instructions<'_> ⓘ
pub fn instructions(&self) -> Instructions<'_> ⓘ
Iterates over the script instructions.
Each returned item is a nested enum covering opcodes, datapushes and errors.
At most one error will be returned and then the iterator will end. To instead iterate over
the script as sequence of bytes call the bytes
method.
To force minimal pushes, use instructions_minimal
.
sourcepub fn instructions_minimal(&self) -> Instructions<'_> ⓘ
pub fn instructions_minimal(&self) -> Instructions<'_> ⓘ
Iterates over the script instructions while enforcing minimal pushes.
This is similar to instructions
but an error is returned if a push
is not minimal.
sourcepub fn instruction_indices(&self) -> InstructionIndices<'_> ⓘ
pub fn instruction_indices(&self) -> InstructionIndices<'_> ⓘ
Iterates over the script instructions and their indices.
Unless the script contains an error, the returned item consists of an index pointing to the position in the script where the instruction begins and the decoded instruction - either an opcode or data push.
To force minimal pushes, use Self::instruction_indices_minimal
.
sourcepub fn instruction_indices_minimal(&self) -> InstructionIndices<'_> ⓘ
pub fn instruction_indices_minimal(&self) -> InstructionIndices<'_> ⓘ
Iterates over the script instructions and their indices while enforcing minimal pushes.
This is similar to instruction_indices
but an error is
returned if a push is not minimal.
sourcepub fn fmt_asm(&self, f: &mut dyn Write) -> Result
pub fn fmt_asm(&self, f: &mut dyn Write) -> Result
Writes the human-readable assembly representation of the script to the formatter.
sourcepub fn to_asm_string(&self) -> String
pub fn to_asm_string(&self) -> String
Returns the human-readable assembly representation of the script.
sourcepub fn to_hex_string(&self) -> String
pub fn to_hex_string(&self) -> String
Formats the script as lower-case hex.
This is a more convenient and performant way to write format!("{:x}", script)
.
For better performance you should generally prefer displaying the script but if String
is
required (this is common in tests) this method can be used.
sourcepub fn first_opcode(&self) -> Option<Opcode>
pub fn first_opcode(&self) -> Option<Opcode>
Returns the first opcode of the script (if there is any).
sourcepub fn verify(
&self,
index: usize,
amount: Amount,
spending_tx: &[u8]
) -> Result<(), BitcoinconsensusError>
pub fn verify( &self, index: usize, amount: Amount, spending_tx: &[u8] ) -> Result<(), BitcoinconsensusError>
Verifies spend of an input script.
Shorthand for Self::verify_with_flags
with flag bitcoinconsensus::VERIFY_ALL
.
Parameters
index
- The input index in spending which is spending this transaction.amount
- The amount this script guards.spending_tx
- The transaction that attempts to spend the output holding this script.
sourcepub fn verify_with_flags<F: Into<u32>>(
&self,
index: usize,
amount: Amount,
spending_tx: &[u8],
flags: F
) -> Result<(), BitcoinconsensusError>
pub fn verify_with_flags<F: Into<u32>>( &self, index: usize, amount: Amount, spending_tx: &[u8], flags: F ) -> Result<(), BitcoinconsensusError>
Verifies spend of an input script.
Parameters
index
- The input index in spending which is spending this transaction.amount
- The amount this script guards.spending_tx
- The transaction that attempts to spend the output holding this script.flags
- Verification flags, seebitcoinconsensus::VERIFY_ALL
and similar.
Trait Implementations§
source§impl BorrowMut<Script> for ScriptBuf
impl BorrowMut<Script> for ScriptBuf
source§fn borrow_mut(&mut self) -> &mut Script
fn borrow_mut(&mut self) -> &mut Script
source§impl<'de> Deserialize<'de> for ScriptBuf
impl<'de> Deserialize<'de> for ScriptBuf
source§fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where D: Deserializer<'de>,
source§impl<'a> Extend<Instruction<'a>> for ScriptBuf
impl<'a> Extend<Instruction<'a>> for ScriptBuf
source§fn extend<T>(&mut self, iter: T)where
T: IntoIterator<Item = Instruction<'a>>,
fn extend<T>(&mut self, iter: T)where T: IntoIterator<Item = Instruction<'a>>,
source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)source§impl From<&ScriptBuf> for ScriptHash
impl From<&ScriptBuf> for ScriptHash
source§fn from(script: &ScriptBuf) -> ScriptHash
fn from(script: &ScriptBuf) -> ScriptHash
source§impl From<&ScriptBuf> for WScriptHash
impl From<&ScriptBuf> for WScriptHash
source§fn from(script: &ScriptBuf) -> WScriptHash
fn from(script: &ScriptBuf) -> WScriptHash
source§impl From<ScriptBuf> for ScriptHash
impl From<ScriptBuf> for ScriptHash
source§fn from(script: ScriptBuf) -> ScriptHash
fn from(script: ScriptBuf) -> ScriptHash
source§impl From<ScriptBuf> for WScriptHash
impl From<ScriptBuf> for WScriptHash
source§fn from(script: ScriptBuf) -> WScriptHash
fn from(script: ScriptBuf) -> WScriptHash
source§impl<'a> FromIterator<Instruction<'a>> for ScriptBuf
impl<'a> FromIterator<Instruction<'a>> for ScriptBuf
source§fn from_iter<T>(iter: T) -> Selfwhere
T: IntoIterator<Item = Instruction<'a>>,
fn from_iter<T>(iter: T) -> Selfwhere T: IntoIterator<Item = Instruction<'a>>,
source§impl Ord for ScriptBuf
impl Ord for ScriptBuf
source§impl PartialEq<Script> for ScriptBuf
impl PartialEq<Script> for ScriptBuf
source§impl PartialEq<ScriptBuf> for Script
impl PartialEq<ScriptBuf> for Script
source§impl PartialEq<ScriptBuf> for ScriptBuf
impl PartialEq<ScriptBuf> for ScriptBuf
source§impl PartialOrd<Script> for ScriptBuf
impl PartialOrd<Script> for ScriptBuf
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
self
and other
) and is used by the <=
operator. Read moresource§impl PartialOrd<ScriptBuf> for Script
impl PartialOrd<ScriptBuf> for Script
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
self
and other
) and is used by the <=
operator. Read moresource§impl PartialOrd<ScriptBuf> for ScriptBuf
impl PartialOrd<ScriptBuf> for ScriptBuf
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
self
and other
) and is used by the <=
operator. Read more