pub struct Script(/* private fields */);
Expand description

Bitcoin script slice.

See also the groestlcoin::blockdata::script module.

Script is a script slice, the most primitive script type. It’s usually seen in its borrowed form &Script. It is always encoded as a series of bytes representing the opcodes and data pushes.

§Validity

Script does not have any validity invariants - it’s essentially just a marked slice of bytes. This is similar to Path vs OsStr where they are trivially cast-able to each-other and Path doesn’t guarantee being a usable FS path but having a newtype still has value because of added methods, readability and basic type checking.

Although at least data pushes could be checked not to overflow the script, bad scripts are allowed to be in a transaction (outputs just become unspendable) and there even are such transactions in the chain. Thus we must allow such scripts to be placed in the transaction.

§Slicing safety

Slicing is similar to how str works: some ranges may be incorrect and indexing by usize is not supported. However, as opposed to std, we have no way of checking correctness without causing linear complexity so there are no panics on invalid ranges! If you supply an invalid range, you’ll get a garbled script.

The range is considered valid if it’s at a boundary of instruction. Care must be taken especially with push operations because you could get a reference to arbitrary attacker-supplied bytes that look like a valid script.

It is recommended to use .instructions() method to get an iterator over script instructions and work with that instead.

§Memory safety

The type is #[repr(transparent)] for internal purposes only! No consumer crate may rely on the represenation of the struct!

§References

§Bitcoin Core References

Implementations§

source§

impl Script

source

pub fn new() -> &'static Script

Creates a new empty script.

source

pub fn from_bytes(bytes: &[u8]) -> &Script

Treat byte slice as Script

source

pub fn from_bytes_mut(bytes: &mut [u8]) -> &mut Script

Treat mutable byte slice as 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 builder() -> Builder

Creates a new script builder

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

👎Deprecated since 0.31.0: use to_p2wsh instead

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

source

pub fn to_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

👎Deprecated since 0.31.0: use to_p2tr instead

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

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

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_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

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

👎Deprecated since 0.31.0: use is_p2wsh instead

Checks whether a script pubkey is a P2WSH output.

source

pub fn is_p2wsh(&self) -> bool

Checks whether a script pubkey is a P2WSH output.

source

pub fn is_v0_p2wpkh(&self) -> bool

👎Deprecated since 0.31.0: use is_p2wpkh instead

Checks whether a script pubkey is a P2WPKH output.

source

pub fn is_p2wpkh(&self) -> bool

Checks whether a script pubkey is a P2WPKH output.

source

pub fn is_v1_p2tr(&self) -> bool

👎Deprecated since 0.31.0: use is_p2tr instead

Checks whether a script pubkey is a P2TR output.

source

pub fn is_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 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 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 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 preceeded 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.)

source

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

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 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<Opcode>

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

source

pub fn into_script_buf(self: Box<Self>) -> ScriptBuf

Converts a Box<Script> into a ScriptBuf without copying or allocating.

source§

impl Script

source

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

Available on crate feature groestlcoinconsensus only.

Verifies spend of an input script.

Shorthand for Self::verify_with_flags with flag groestlcoinconsensus::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<(), BitcoinconsensusError>

Available on crate feature groestlcoinconsensus 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 groestlcoinconsensus::VERIFY_ALL and similar.

Trait Implementations§

source§

impl AsMut<[u8]> for Script

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 Script

source§

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

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 Script

source§

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

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

impl AsRef<Script> for Script

source§

fn as_ref(&self) -> &Script

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 Debug for Script

source§

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

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

impl<'de> Deserialize<'de> for &'de Script

Available on crate feature serde only.

Can only deserialize borrowed bytes.

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 Script

source§

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

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

impl Encodable for Script

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> From<&'a Script> for Arc<Script>

Available on non-rust_v_1_60 or target_has_atomic="ptr" only.

Note: This will fail to compile on old Rust for targets that don’t support atomics

source§

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

Converts to this type from the input type.
source§

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

source§

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

Converts to this type from the input type.
source§

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

source§

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

Converts to this type from the input type.
source§

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

source§

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

Converts to this type from the input type.
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<&Script> for ScriptHash

source§

fn from(script: &Script) -> ScriptHash

Converts to this type from the input type.
source§

impl From<&Script> for WScriptHash

source§

fn from(script: &Script) -> WScriptHash

Converts to this type from the input type.
source§

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

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 Hash for Script

source§

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

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

impl Index<(Bound<usize>, Bound<usize>)> for Script

Script subslicing operation - read slicing safety!

§

type Output = Script

The returned type after indexing.
source§

fn index(&self, index: (Bound<usize>, Bound<usize>)) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
source§

impl Index<Range<usize>> for Script

Script subslicing operation - read slicing safety!

§

type Output = Script

The returned type after indexing.
source§

fn index(&self, index: Range<usize>) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
source§

impl Index<RangeFrom<usize>> for Script

Script subslicing operation - read slicing safety!

§

type Output = Script

The returned type after indexing.
source§

fn index(&self, index: RangeFrom<usize>) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
source§

impl Index<RangeFull> for Script

Script subslicing operation - read slicing safety!

§

type Output = Script

The returned type after indexing.
source§

fn index(&self, index: RangeFull) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
source§

impl Index<RangeInclusive<usize>> for Script

Script subslicing operation - read slicing safety!

§

type Output = Script

The returned type after indexing.
source§

fn index(&self, index: RangeInclusive<usize>) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
source§

impl Index<RangeTo<usize>> for Script

Script subslicing operation - read slicing safety!

§

type Output = Script

The returned type after indexing.
source§

fn index(&self, index: RangeTo<usize>) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
source§

impl Index<RangeToInclusive<usize>> for Script

Script subslicing operation - read slicing safety!

§

type Output = Script

The returned type after indexing.
source§

fn index(&self, index: RangeToInclusive<usize>) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
source§

impl LowerHex for Script

source§

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

Formats the value using the given formatter.
source§

impl Ord for Script

source§

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

This method returns an Ordering between self and other. 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 for Script

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 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 for Script

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 Serialize for Script

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 ToOwned for Script

§

type Owned = ScriptBuf

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> Self::Owned

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

fn clone_into(&self, target: &mut Self::Owned)

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

impl UpperHex for Script

source§

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

Formats the value using the given formatter.
source§

impl Eq for Script

source§

impl StructuralPartialEq for Script

Auto Trait Implementations§

§

impl RefUnwindSafe for Script

§

impl Send for Script

§

impl !Sized for Script

§

impl Sync for Script

§

impl Unpin for Script

§

impl UnwindSafe for Script

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. Read more
source§

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

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more