Skip to main content

ScriptBuf

Struct ScriptBuf 

Source
pub struct ScriptBuf<T>(/* 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.

§Hexadecimal strings

Scripts are consensus encoded with a length prefix and as a result of this in some places in the ecosystem one will encounter hex strings that include the prefix while in other places the prefix is excluded. To support parsing and formatting scripts as hex we provide a bunch of different APIs and trait implementations. Please see [examples/script.rs] for a thorough example of all the APIs.

§Panics

ScriptBuf is backed by Vec and inherits its panic behavior. This means that attempting to construct scripts larger than isize::MAX bytes will panic.

Implementations§

Source§

impl<T> ScriptBuf<T>

Source

pub const fn new() -> Self

Constructs a new empty script.

Source

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

Converts byte vector into script.

This method doesn’t (re)allocate. bytes is just the script bytes not consensus encoding (i.e no length prefix).

Source

pub fn from_hex_prefixed(s: &str) -> Result<Self, FromHexError>

Constructs a new ScriptBuf from a hex string.

The input string is expected to be consensus encoded i.e., includes the length prefix.

§Errors
  • If s cannot be parsed into a vector.
  • If the parsed bytes cannot be decoded as a valid script (incl.the length prefix).
Source

pub fn from_hex_no_length_prefix( s: &str, ) -> Result<Self, DecodeVariableLengthBytesError>

Constructs a new ScriptBuf from a hex string.

This is not consensus encoding. If your hex string is a consensus encoded script then use ScriptBuf::from_hex_prefixed.

There is no script decoding error path because what ever is in the hex input string is assumed to be the script. This means if you pass a consensus encoded hex string into this function there will be no error and the script will not be what you expect.

§Errors

Errors if s cannot be parsed into a vector.

Source

pub fn as_script(&self) -> &Script<T>

Returns a reference to unsized script.

Source

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

Returns a mutable reference to unsized script.

Source

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

Converts the script into a byte vector.

This method doesn’t (re)allocate.

§Returns

Just the script bytes not consensus encoding (which includes a length prefix).

Source

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

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.

Source

pub fn with_capacity(capacity: usize) -> Self

Constructs a new empty script with at least the specified 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 cannot 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 capacity(&self) -> usize

Returns the number of bytes available for writing without reallocation.

It is guaranteed that script.capacity() >= script.len() always holds.

Source

pub fn reserved_len_for_slice(len: usize) -> usize

Returns the encoded length for pushing a slice of bytes.

Source

pub fn push_opcode(&mut self, opcode: Opcode)

Adds a single opcode to the script.

Source

pub fn push_int(&mut self, n: i32) -> Result<(), Error>

Adds instructions to push an integer onto the stack.

§Errors

Returns Error::NumericOverflow when n is outside the minimally encodable range.

Source

pub fn push_int_unchecked(&mut self, n: i64)

Adds instructions to push an unchecked integer onto the stack.

Source

pub fn push_int_non_minimal(&mut self, data: i64)

Adds instructions to push an integer without numeric-opcode optimization.

§Panics

Panics only if the internally encoded script integer somehow exceeds the PushBytes limit.

Source

pub fn push_slice<D: AsRef<[u8]>>(&mut self, data: D)

Adds instructions to push some arbitrary data onto the stack.

Source

pub fn push_slice_non_minimal<D: AsRef<[u8]>>(&mut self, data: D)

Adds instructions to push arbitrary data without minimal-push optimization.

§Panics

Panics only if data exceeds the maximum size supported by PushBytes.

Source

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

Adds a single instruction.

Source

pub fn scan_and_push_verify(&mut self)

Adds an OP_VERIFY or rewrites the last opcode to its VERIFY form when possible.

Methods from Deref<Target = Script<T>>§

Source

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

Returns the script data as a byte slice.

This is just the script bytes not consensus encoding (which includes a length prefix).

Source

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

Returns the script data as a mutable byte slice.

This is just the script bytes not consensus encoding (which includes a length prefix).

Source

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

Returns a copy of the script data.

This is just the script bytes not consensus encoding (which includes a length prefix).

Source

pub fn to_hex_string_prefixed(&self) -> String

Consensus encodes the script as lower-case hex.

Consensus encoding includes a length prefix. To hex encode without the length prefix use to_hex_string_no_length_prefix.

Source

pub fn to_hex_string_no_length_prefix(&self) -> String

Encodes the script as lower-case hex.

This is not consensus encoding. The returned hex string will not include the length prefix. See to_hex_string_prefixed.

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 instructions(&self) -> Instructions<'_>

Iterates over decoded instructions.

Source

pub fn instructions_minimal(&self) -> Instructions<'_>

Iterates over decoded instructions while enforcing minimal pushes.

Source

pub fn count_sigops(&self) -> usize

Counts signature-check operations using accurate multisig counting.

This is the counting mode used by the node for redeem scripts and witness scripts. OP_CHECKSIGADD is not counted by Tidecoin consensus.

Source

pub fn count_sigops_legacy(&self) -> usize

Counts signature-check operations using legacy multisig counting.

This is the counting mode used by the node for scriptSigs and scriptPubKeys in context-free block sanity checks.

Source

pub fn instruction_indices(&self) -> InstructionIndices<'_>

Iterates over decoded instructions together with their byte indices.

Source

pub fn instruction_indices_minimal(&self) -> InstructionIndices<'_>

Iterates over decoded instructions and indices while enforcing minimal pushes.

Source

pub fn last_opcode(&self) -> Option<Opcode>

Returns the last opcode if the final instruction is an opcode.

Source

pub fn last_pushdata(&self) -> Option<&PushBytes>

Returns the last pushed byte slice if the final instruction is a data push.

Trait Implementations§

Source§

impl<'a, T> Arbitrary<'a> for ScriptBuf<T>

Available on crate feature arbitrary only.
Source§

fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self>

Generate an arbitrary value of Self from the given unstructured data. Read more
Source§

fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self, Error>

Generate an arbitrary value of Self from the entirety of the given unstructured data. Read more
Source§

fn size_hint(depth: usize) -> (usize, Option<usize>)

Get a size hint for how many bytes out of an Unstructured this type needs to construct itself. Read more
Source§

fn try_size_hint( depth: usize, ) -> Result<(usize, Option<usize>), MaxRecursionReached>

Get a size hint for how many bytes out of an Unstructured this type needs to construct itself. Read more
Source§

impl<T> AsMut<Script<T>> for ScriptBuf<T>

Source§

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

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

impl<T> AsMut<[u8]> for ScriptBuf<T>

Source§

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

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

impl<T> AsRef<Script<T>> for ScriptBuf<T>

Source§

fn as_ref(&self) -> &Script<T>

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

impl<T> AsRef<[u8]> for ScriptBuf<T>

Source§

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

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

impl<T> Borrow<Script<T>> for ScriptBuf<T>

Source§

fn borrow(&self) -> &Script<T>

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<Script<T>> for ScriptBuf<T>

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<T: Clone> Clone for ScriptBuf<T>

Source§

fn clone(&self) -> ScriptBuf<T>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<T> Debug for ScriptBuf<T>

Source§

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

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

impl<T> Decodable for ScriptBuf<T>

Source§

type Decoder = ScriptBufDecoder<T>

Associated decoder for the type.
Source§

fn decoder() -> Self::Decoder

Constructs a “default decoder” for the type.
Source§

impl<T> Default for ScriptBuf<T>

Source§

fn default() -> Self

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

impl<T> Deref for ScriptBuf<T>

Source§

type Target = Script<T>

The resulting type after dereferencing.
Source§

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

Dereferences the value.
Source§

impl<T> DerefMut for ScriptBuf<T>

Source§

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

Mutably dereferences the value.
Source§

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

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<T> Display for ScriptBuf<T>

Source§

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

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

impl<T> Encodable for ScriptBuf<T>

Source§

type Encoder<'e> = ScriptEncoder<'e> where Self: 'e

The encoder associated with this type. Conceptually, the encoder is like an iterator which yields byte slices.
Source§

fn encoder(&self) -> Self::Encoder<'_>

Constructs a “default encoder” for the type.
Source§

impl<T: Eq> Eq for ScriptBuf<T>

Source§

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

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, T> From<&'a Script<T>> for ScriptBuf<T>

Source§

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

Converts to this type from the input type.
Source§

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

Source§

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

Converts to this type from the input type.
Source§

impl<T> From<ScriptBuf<T>> for Box<Script<T>>

Source§

fn from(v: ScriptBuf<T>) -> Self

Converts to this type from the input type.
Source§

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

Source§

fn from(value: ScriptBuf<T>) -> Self

Converts to this type from the input type.
Source§

impl<T> From<ScriptBuf<T>> for Vec<u8>

Source§

fn from(v: ScriptBuf<T>) -> Self

Converts to this type from the input type.
Source§

impl<T> From<Vec<u8>> for ScriptBuf<T>

Source§

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

Converts to this type from the input type.
Source§

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

Source§

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

Creates a value from an iterator. Read more
Source§

impl<T: Hash> Hash for ScriptBuf<T>

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<T> LowerHex for ScriptBuf<T>

Available on crate feature hex only.
Source§

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

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

impl<T: Ord> Ord for ScriptBuf<T>

Source§

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

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

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

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

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

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

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

impl<T: PartialEq> PartialEq for ScriptBuf<T>

Source§

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

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

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

Inequality operator !=. Read more
Source§

impl<T: PartialEq> PartialEq<Script<T>> for ScriptBuf<T>

Source§

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

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

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

Inequality operator !=. Read more
Source§

impl<T: PartialEq> PartialEq<ScriptBuf<T>> for Script<T>

Source§

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

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

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

Inequality operator !=. Read more
Source§

impl<T: PartialOrd> PartialOrd for ScriptBuf<T>

Source§

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

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<T: PartialOrd> PartialOrd<Script<T>> for ScriptBuf<T>

Source§

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

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<T: PartialOrd> PartialOrd<ScriptBuf<T>> for Script<T>

Source§

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

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<T> Serialize for ScriptBuf<T>

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<T: PartialEq> StructuralPartialEq for ScriptBuf<T>

Source§

impl<T: ScriptHashableTag> TryFrom<&ScriptBuf<T>> for ScriptHash

Source§

type Error = RedeemScriptSizeError

The type returned in the event of a conversion error.
Source§

fn try_from(redeem_script: &ScriptBuf<T>) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<&ScriptBuf<WitnessScriptTag>> for WScriptHash

Source§

type Error = WitnessScriptSizeError

The type returned in the event of a conversion error.
Source§

fn try_from(witness_script: &WitnessScriptBuf) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl<T: ScriptHashableTag> TryFrom<ScriptBuf<T>> for ScriptHash

Source§

type Error = RedeemScriptSizeError

The type returned in the event of a conversion error.
Source§

fn try_from(redeem_script: ScriptBuf<T>) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<ScriptBuf<WitnessScriptTag>> for WScriptHash

Source§

type Error = WitnessScriptSizeError

The type returned in the event of a conversion error.
Source§

fn try_from(witness_script: WitnessScriptBuf) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl<T> UpperHex for ScriptBuf<T>

Available on crate feature hex only.
Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T> Freeze for ScriptBuf<T>

§

impl<T> RefUnwindSafe for ScriptBuf<T>
where T: RefUnwindSafe,

§

impl<T> Send for ScriptBuf<T>
where T: Send,

§

impl<T> Sync for ScriptBuf<T>
where T: Sync,

§

impl<T> Unpin for ScriptBuf<T>
where T: Unpin,

§

impl<T> UnsafeUnpin for ScriptBuf<T>

§

impl<T> UnwindSafe for ScriptBuf<T>
where T: UnwindSafe,

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

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

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

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

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<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

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 T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

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

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

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

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

Performs the conversion.
Source§

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

Source§

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

The type returned in the event of a conversion error.
Source§

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

Performs the conversion.