Struct bitcoin::ScriptBuf

source ·
pub struct ScriptBuf(_);
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

source

pub fn new() -> Self

Creates a new empty script.

source

pub fn with_capacity(capacity: usize) -> Self

Creates a new empty script with pre-allocated capacity.

source

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.

source

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.

source

pub fn as_script(&self) -> &Script

Returns a reference to unsized script.

source

pub fn as_mut_script(&mut self) -> &mut Script

Returns a mutable reference to unsized script.

source

pub fn builder() -> Builder

Creates a new script builder

source

pub fn new_p2pk(pubkey: &PublicKey) -> Self

Generates P2PK-type of scriptPubkey.

source

pub fn new_p2pkh(pubkey_hash: &PubkeyHash) -> Self

Generates P2PKH-type of scriptPubkey.

source

pub fn new_p2sh(script_hash: &ScriptHash) -> Self

Generates P2SH-type of scriptPubkey with a given hash of the redeem script.

source

pub fn new_v0_p2wpkh(pubkey_hash: &WPubkeyHash) -> Self

Generates P2WPKH-type of scriptPubkey.

source

pub fn new_v0_p2wsh(script_hash: &WScriptHash) -> Self

Generates P2WSH-type of scriptPubkey with a given hash of the redeem script.

source

pub fn new_v1_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.

source

pub fn new_v1_p2tr_tweaked(output_key: TweakedPublicKey) -> Self

Generates P2TR for key spending path for a known TweakedPublicKey.

source

pub fn new_witness_program(witness_program: &WitnessProgram) -> Self

Generates P2WSH-type of scriptPubkey with a given WitnessProgram.

source

pub fn new_op_return<T: AsRef<PushBytes>>(data: &T) -> Self

Generates OP_RETURN-type of scriptPubkey for the given data.

source

pub fn from_hex(s: &str) -> Result<Self, Error>

Creates a ScriptBuf from a hex string.

source

pub fn from_bytes(bytes: Vec<u8>) -> Self

Converts byte vector into script.

This method doesn’t (re)allocate.

source

pub fn into_bytes(self) -> Vec<u8>

Converts the script into a byte vector.

This method doesn’t (re)allocate.

source

pub fn to_p2sh(&self) -> ScriptBuf

Computes the P2SH output corresponding to this redeem script.

source

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.

source

pub fn push_opcode(&mut self, data: All)

Adds a single opcode to the script.

source

pub fn push_slice<T: AsRef<PushBytes>>(&mut self, data: T)

Adds instructions to push some arbitrary data onto the stack.

source

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.

source

pub fn push_instruction_no_opt(&mut self, instruction: Instruction<'_>)

Like push_instruction, but avoids calling reserve to not re-check the length.

source

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.

source

pub fn into_boxed_script(self) -> Box<Script>

Converts this ScriptBuf into a boxed Script.

This method reallocates if the capacity is greater than lenght 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>§

source

pub fn as_bytes(&self) -> &[u8]

Returns the script data as a byte slice.

source

pub fn as_mut_bytes(&mut self) -> &mut [u8]

Returns the script data as a mutable byte slice.

source

pub fn script_hash(&self) -> ScriptHash

Returns 160-bit hash of the script.

source

pub fn wscript_hash(&self) -> WScriptHash

Returns 256-bit hash of the script for P2WSH outputs.

source

pub fn tapscript_leaf_hash(&self) -> TapLeafHash

Computes leaf hash of tapscript.

source

pub fn len(&self) -> usize

Returns the length in bytes of the script.

source

pub fn is_empty(&self) -> bool

Returns whether the script is the empty script.

source

pub fn to_bytes(&self) -> Vec<u8>

Returns a copy of the script data.

source

pub fn bytes(&self) -> Bytes<'_>

Returns an iterator over script bytes.

source

pub fn to_v0_p2wsh(&self) -> ScriptBuf

Computes the P2WSH output corresponding to this witnessScript (aka the “witness redeem script”).

source

pub fn to_v1_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.

source

pub fn witness_version(&self) -> Option<WitnessVersion>

Returns witness version of the script, if any, assuming the script is a scriptPubkey.

source

pub fn is_p2sh(&self) -> bool

Checks whether a script pubkey is a P2SH output.

source

pub fn is_p2pkh(&self) -> bool

Checks whether a script pubkey is a P2PKH output.

source

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()

source

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). It also implies the script is unspendable.

source

pub fn is_witness_program(&self) -> bool

Checks whether a script pubkey is a Segregated Witness (segwit) program.

source

pub fn is_v0_p2wsh(&self) -> bool

Checks whether a script pubkey is a P2WSH output.

source

pub fn is_v0_p2wpkh(&self) -> bool

Checks whether a script pubkey is a P2WPKH output.

source

pub fn is_v1_p2tr(&self) -> bool

Checks whether a script pubkey is a P2TR output.

source

pub fn is_op_return(&self) -> bool

Check if this is an OP_RETURN output.

source

pub fn is_provably_unspendable(&self) -> bool

Checks whether a script can be proven to have no satisfying input.

source

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.

source

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.

source

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.

source

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.

source

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.

source

pub fn verify( &self, index: usize, amount: Amount, spending_tx: &[u8] ) -> Result<(), Error>

Available on crate feature bitcoinconsensus only.

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.
source

pub fn verify_with_flags<F: Into<u32>>( &self, index: usize, amount: Amount, spending_tx: &[u8], flags: F ) -> Result<(), Error>

Available on crate feature bitcoinconsensus only.

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, see bitcoinconsensus::VERIFY_ALL and similar.
source

pub fn fmt_asm(&self, f: &mut dyn Write) -> Result

Writes the assembly decoding of the script to the formatter.

source

pub fn to_asm_string(&self) -> String

Returns the assembly decoding of the script.

source

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 is can be used.

source

pub fn first_opcode(&self) -> Option<All>

Returns the first opcode of the script (if there is any).

Trait Implementations§

source§

impl AsMut<[u8]> for ScriptBuf

source§

fn as_mut(&mut self) -> &mut [u8]

Converts this type into a mutable reference of the (usually inferred) input type.
source§

impl AsMut<Script> for ScriptBuf

source§

fn as_mut(&mut self) -> &mut Script

Converts this type into a mutable reference of the (usually inferred) input type.
source§

impl AsRef<[u8]> for ScriptBuf

source§

fn as_ref(&self) -> &[u8]

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl AsRef<Script> for ScriptBuf

source§

fn as_ref(&self) -> &Script

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl Borrow<Script> for ScriptBuf

source§

fn borrow(&self) -> &Script

Immutably borrows from an owned value. Read more
source§

impl BorrowMut<Script> for ScriptBuf

source§

fn borrow_mut(&mut self) -> &mut Script

Mutably borrows from an owned value. Read more
source§

impl Clone for ScriptBuf

source§

fn clone(&self) -> ScriptBuf

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for ScriptBuf

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Decodable for ScriptBuf

source§

fn consensus_decode_from_finite_reader<R: Read + ?Sized>( r: &mut R ) -> Result<Self, Error>

Decode Self from a size-limited reader. Read more
source§

fn consensus_decode<R: Read + ?Sized>(reader: &mut R) -> Result<Self, Error>

Decode an object with a well-defined format. Read more
source§

impl Default for ScriptBuf

source§

fn default() -> ScriptBuf

Returns the “default value” for a type. Read more
source§

impl Deref for ScriptBuf

§

type Target = Script

The resulting type after dereferencing.
source§

fn deref(&self) -> &Self::Target

Dereferences the value.
source§

impl DerefMut for ScriptBuf

source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
source§

impl<'de> Deserialize<'de> for ScriptBuf

Available on crate feature serde only.
source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl Display for ScriptBuf

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Encodable for ScriptBuf

source§

fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, Error>

Encodes an object with a well-defined format. Read more
source§

impl<'a> Extend<Instruction<'a>> for ScriptBuf

source§

fn extend<T>(&mut self, iter: T)where T: IntoIterator<Item = Instruction<'a>>,

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<'a> From<&'a Script> for ScriptBuf

source§

fn from(value: &'a Script) -> Self

Converts to this type from the input type.
source§

impl From<&ScriptBuf> for ScriptHash

source§

fn from(script: &ScriptBuf) -> ScriptHash

Converts to this type from the input type.
source§

impl From<&ScriptBuf> for WScriptHash

source§

fn from(script: &ScriptBuf) -> WScriptHash

Converts to this type from the input type.
source§

impl From<Address<NetworkChecked>> for ScriptBuf

source§

fn from(a: Address) -> Self

Converts to this type from the input type.
source§

impl<'a> From<Cow<'a, Script>> for ScriptBuf

source§

fn from(value: Cow<'a, Script>) -> Self

Converts to this type from the input type.
source§

impl From<ScriptBuf> for Box<Script>

source§

fn from(v: ScriptBuf) -> Self

Converts to this type from the input type.
source§

impl From<ScriptBuf> for Cow<'_, Script>

source§

fn from(value: ScriptBuf) -> Self

Converts to this type from the input type.
source§

impl From<ScriptBuf> for ScriptHash

source§

fn from(script: ScriptBuf) -> ScriptHash

Converts to this type from the input type.
source§

impl From<ScriptBuf> for Vec<u8>

source§

fn from(v: ScriptBuf) -> Self

Converts to this type from the input type.
source§

impl From<ScriptBuf> for WScriptHash

source§

fn from(script: ScriptBuf) -> WScriptHash

Converts to this type from the input type.
source§

impl From<Vec<u8, Global>> for ScriptBuf

source§

fn from(v: Vec<u8>) -> Self

Converts to this type from the input type.
source§

impl<'a> FromIterator<Instruction<'a>> for ScriptBuf

source§

fn from_iter<T>(iter: T) -> Selfwhere T: IntoIterator<Item = Instruction<'a>>,

Creates a value from an iterator. Read more
source§

impl Hash for ScriptBuf

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl LowerHex for ScriptBuf

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter.
source§

impl Ord for ScriptBuf

source§

fn cmp(&self, other: &ScriptBuf) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Selfwhere Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Selfwhere Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Selfwhere Self: Sized + PartialOrd<Self>,

Restrict a value to a certain interval. Read more
source§

impl PartialEq<Script> for ScriptBuf

source§

fn eq(&self, other: &Script) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialEq<ScriptBuf> for Script

source§

fn eq(&self, other: &ScriptBuf) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialEq<ScriptBuf> for ScriptBuf

source§

fn eq(&self, other: &ScriptBuf) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd<Script> for ScriptBuf

source§

fn partial_cmp(&self, other: &Script) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl PartialOrd<ScriptBuf> for Script

source§

fn partial_cmp(&self, other: &ScriptBuf) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl PartialOrd<ScriptBuf> for ScriptBuf

source§

fn partial_cmp(&self, other: &ScriptBuf) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl Serialize for ScriptBuf

Available on crate feature serde only.
source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>where S: Serializer,

User-facing serialization for Script.

source§

impl UpperHex for ScriptBuf

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter.
source§

impl Eq for ScriptBuf

source§

impl StructuralEq for ScriptBuf

source§

impl StructuralPartialEq for ScriptBuf

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Base32Len for Twhere T: AsRef<[u8]>,

source§

fn base32_len(&self) -> usize

Calculate the base32 serialized length
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CheckBase32<Vec<u5, Global>> for Twhere T: AsRef<[u8]>,

§

type Err = Error

Error type if conversion fails
source§

fn check_base32( self ) -> Result<Vec<u5, Global>, <T as CheckBase32<Vec<u5, Global>>>::Err>

Check if all values are in range and return array-like struct of u5 values
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToBase32 for Twhere T: AsRef<[u8]>,

source§

fn write_base32<W>(&self, writer: &mut W) -> Result<(), <W as WriteBase32>::Err>where W: WriteBase32,

Encode as base32 and write it to the supplied writer Implementations shouldn’t allocate.
source§

fn to_base32(&self) -> Vec<u5, Global>

Convert Self to base32 vector
source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for Twhere T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V

source§

impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>,