bdk_chain::bitcoin::blockdata::transaction

Struct Transaction

pub struct Transaction {
    pub version: Version,
    pub lock_time: LockTime,
    pub input: Vec<TxIn>,
    pub output: Vec<TxOut>,
}
Expand description

Bitcoin transaction.

An authenticated movement of coins.

See Bitcoin Wiki: Transaction for more information.

§Bitcoin Core References

§Serialization notes

If any inputs have nonempty witnesses, the entire transaction is serialized in the post-BIP141 Segwit format which includes a list of witnesses. If all inputs have empty witnesses, the transaction is serialized in the pre-BIP141 format.

There is one major exception to this: to avoid deserialization ambiguity, if the transaction has no inputs, it is serialized in the BIP141 style. Be aware that this differs from the transaction format in PSBT, which never uses BIP141. (Ordinarily there is no conflict, since in PSBT transactions are always unsigned and therefore their inputs have empty witnesses.)

The specific ambiguity is that Segwit uses the flag bytes 0001 where an old serializer would read the number of transaction inputs. The old serializer would interpret this as “no inputs, one output”, which means the transaction is invalid, and simply reject it. Segwit further specifies that this encoding should only be used when some input has a nonempty witness; that is, witness-less transactions should be encoded in the traditional format.

However, in protocols where transactions may legitimately have 0 inputs, e.g. when parties are cooperatively funding a transaction, the “00 means Segwit” heuristic does not work. Since Segwit requires such a transaction be encoded in the original transaction format (since it has no inputs and therefore no input witnesses), a traditionally encoded transaction may have the 0001 Segwit flag in it, which confuses most Segwit parsers including the one in Bitcoin Core.

We therefore deviate from the spec by always using the Segwit witness encoding for 0-input transactions, which results in unambiguously parseable transactions.

§A note on ordering

This type implements Ord, even though it contains a locktime, which is not itself Ord. This was done to simplify applications that may need to hold transactions inside a sorted container. We have ordered the locktimes based on their representation as a u32, which is not a semantically meaningful order, and therefore the ordering on Transaction itself is not semantically meaningful either.

The ordering is, however, consistent with the ordering present in this library before this change, so users should not notice any breakage (here) when transitioning from 0.29 to 0.30.

Fields§

§version: Version

The protocol version, is currently expected to be 1 or 2 (BIP 68).

§lock_time: LockTime

Block height or timestamp. Transaction cannot be included in a block until this height/time.

§Relevant BIPs
§input: Vec<TxIn>

List of transaction inputs.

§output: Vec<TxOut>

List of transaction outputs.

Implementations§

§

impl Transaction

pub const MAX_STANDARD_WEIGHT: Weight = _

Maximum transaction weight for Bitcoin Core 25.0.

pub fn ntxid(&self) -> Hash

👎Deprecated since 0.31.0: ntxid has been renamed to compute_ntxid to note that it’s computationally expensive. use compute_ntxid() instead.

Computes a “normalized TXID” which does not include any signatures.

This method is deprecated. Use compute_ntxid instead.

pub fn compute_ntxid(&self) -> Hash

Computes a “normalized TXID” which does not include any signatures.

This gives a way to identify a transaction that is “the same” as another in the sense of having same inputs and outputs.

pub fn txid(&self) -> Txid

👎Deprecated since 0.31.0: txid has been renamed to compute_txid to note that it’s computationally expensive. use compute_txid() instead.

Computes the Txid.

This method is deprecated. Use compute_txid instead.

pub fn compute_txid(&self) -> Txid

Computes the Txid.

Hashes the transaction excluding the segwit data (i.e. the marker, flag bytes, and the witness fields themselves). For non-segwit transactions which do not have any segwit data, this will be equal to Transaction::compute_wtxid().

pub fn wtxid(&self) -> Wtxid

👎Deprecated since 0.31.0: wtxid has been renamed to compute_wtxid to note that it’s computationally expensive. use compute_wtxid() instead.

Computes the segwit version of the transaction id.

This method is deprecated. Use compute_wtxid instead.

pub fn compute_wtxid(&self) -> Wtxid

Computes the segwit version of the transaction id.

Hashes the transaction including all segwit data (i.e. the marker, flag bytes, and the witness fields themselves). For non-segwit transactions which do not have any segwit data, this will be equal to Transaction::txid().

pub fn weight(&self) -> Weight

Returns the weight of this transaction, as defined by BIP-141.

Transaction weight is defined as Base transaction size * 3 + Total transaction size (ie. the same method as calculating Block weight from Base size and Total size).

For transactions with an empty witness, this is simply the consensus-serialized size times four. For transactions with a witness, this is the non-witness consensus-serialized size multiplied by three plus the with-witness consensus-serialized size.

For transactions with no inputs, this function will return a value 2 less than the actual weight of the serialized transaction. The reason is that zero-input transactions, post-segwit, cannot be unambiguously serialized; we make a choice that adds two extra bytes. For more details see BIP 141 which uses a “input count” of 0x00 as a marker for a Segwit-encoded transaction.

If you need to use 0-input transactions, we strongly recommend you do so using the PSBT API. The unsigned transaction encoded within PSBT is always a non-segwit transaction and can therefore avoid this ambiguity.

pub fn base_size(&self) -> usize

Returns the base transaction size.

Base transaction size is the size of the transaction serialised with the witness data stripped.

pub fn total_size(&self) -> usize

Returns the total transaction size.

Total transaction size is the transaction size in bytes serialized as described in BIP144, including base data and witness data.

pub fn vsize(&self) -> usize

Returns the “virtual size” (vsize) of this transaction.

Will be ceil(weight / 4.0). Note this implements the virtual size as per BIP141, which is different to what is implemented in Bitcoin Core. The computation should be the same for any remotely sane transaction, and a standardness-rule-correct version is available in the policy module.

Virtual transaction size is defined as Transaction weight / 4 (rounded up to the next integer).

pub fn is_coinbase(&self) -> bool

Checks if this is a coinbase transaction.

The first transaction in the block distributes the mining reward and is called the coinbase transaction. It is impossible to check if the transaction is first in the block, so this function checks the structure of the transaction instead - the previous output must be all-zeros (creates satoshis “out of thin air”).

pub fn is_explicitly_rbf(&self) -> bool

Returns true if the transaction itself opted in to be BIP-125-replaceable (RBF).

§Warning

Incorrectly relying on RBF may lead to monetary loss!

This does not cover the case where a transaction becomes replaceable due to ancestors being RBF. Please note that transactions may be replaced even if they do not include the RBF signal: https://bitcoinops.org/en/newsletters/2022/10/19/#transaction-replacement-option.

pub fn is_absolute_timelock_satisfied(&self, height: Height, time: Time) -> bool

Returns true if this Transaction’s absolute timelock is satisfied at height/time.

§Returns

By definition if the lock time is not enabled the transaction’s absolute timelock is considered to be satisfied i.e., there are no timelock constraints restricting this transaction from being mined immediately.

pub fn is_lock_time_enabled(&self) -> bool

Returns true if this transactions nLockTime is enabled (BIP-65).

pub fn script_pubkey_lens(&self) -> impl Iterator<Item = usize>

Returns an iterator over lengths of script_pubkeys in the outputs.

This is useful in combination with predict_weight if you have the transaction already constructed with a dummy value in the fee output which you’ll adjust after calculating the weight.

pub fn total_sigop_cost<S>(&self, spent: S) -> usize
where S: FnMut(&OutPoint) -> Option<TxOut>,

Counts the total number of sigops.

This value is for pre-taproot transactions only.

In taproot, a different mechanism is used. Instead of having a global per-block limit, there is a per-transaction-input limit, proportional to the size of that input. ref: https://bitcoin.stackexchange.com/questions/117356/what-is-sigop-signature-operation#117359

The spent parameter is a closure/function that looks up the output being spent by each input It takes in an OutPoint and returns a TxOut. If you can’t provide this, a placeholder of |_| None can be used. Without access to the previous TxOut, any sigops in a redeemScript (P2SH) as well as any segwit sigops will not be counted for that input.

pub fn tx_in(&self, input_index: usize) -> Result<&TxIn, InputsIndexError>

Returns a reference to the input at input_index if it exists.

pub fn tx_out(&self, output_index: usize) -> Result<&TxOut, OutputsIndexError>

Returns a reference to the output at output_index if it exists.

Trait Implementations§

§

impl AsRef<Transaction> for PrefilledTransaction

§

fn as_ref(&self) -> &Transaction

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

impl Clone for Transaction

§

fn clone(&self) -> Transaction

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
§

impl Debug for Transaction

§

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

Formats the value using the given formatter. Read more
§

impl Decodable for Transaction

§

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

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

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

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

impl<'de> Deserialize<'de> for Transaction

§

fn deserialize<__D>( __deserializer: __D, ) -> Result<Transaction, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,

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

impl Encodable for Transaction

§

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

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

impl From<&Transaction> for Txid

§

fn from(tx: &Transaction) -> Txid

Converts to this type from the input type.
§

impl From<&Transaction> for Wtxid

§

fn from(tx: &Transaction) -> Wtxid

Converts to this type from the input type.
§

impl From<Transaction> for Txid

§

fn from(tx: Transaction) -> Txid

Converts to this type from the input type.
§

impl From<Transaction> for Wtxid

§

fn from(tx: Transaction) -> Wtxid

Converts to this type from the input type.
§

impl Hash for Transaction

§

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

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
§

impl Ord for Transaction

§

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

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

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

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

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

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

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

Restrict a value to a certain interval. Read more
§

impl PartialEq for Transaction

§

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

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

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

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

impl PartialOrd for Transaction

§

fn partial_cmp(&self, other: &Transaction) -> 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

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

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

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

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

impl Serialize for Transaction

§

fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
§

impl Eq for Transaction

§

impl StructuralPartialEq for Transaction

Auto Trait Implementations§

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, dst: *mut u8)

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

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
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<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, 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.
§

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

§

fn vzip(self) -> V

Source§

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