Struct bitcoin::Transaction
pub struct Transaction {
pub version: i32,
pub lock_time: LockTime,
pub input: Vec<TxIn, Global>,
pub output: Vec<TxOut, Global>,
}
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: i32
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, Global>
List of transaction inputs.
output: Vec<TxOut, Global>
List of transaction outputs.
Implementations§
§impl Transaction
impl Transaction
pub fn ntxid(&self) -> Hash
pub fn 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
pub fn 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::wtxid()
.
pub fn wtxid(&self) -> Wtxid
pub fn 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 encode_signing_data_to<Write, U>(
&self,
writer: Write,
input_index: usize,
script_pubkey: &Script,
sighash_type: U
) -> EncodeSigningDataResult<Error>where
Write: Write,
U: Into<u32>,
👎Deprecated since 0.30.0: Use SighashCache::legacy_encode_signing_data_to instead
pub fn encode_signing_data_to<Write, U>( &self, writer: Write, input_index: usize, script_pubkey: &Script, sighash_type: U ) -> EncodeSigningDataResult<Error>where Write: Write, U: Into<u32>,
Encodes the signing data from which a signature hash for a given input index with a given sighash flag can be computed.
To actually produce a scriptSig, this hash needs to be run through an ECDSA signer, the
[EcdsaSighashType
] appended to the resulting sig, and a script written around this, but
this is the general (and hard) part.
The sighash_type
supports an arbitrary u32
value, instead of just [EcdsaSighashType
],
because internally 4 bytes are being hashed, even though only the lowest byte is appended to
signature in a transaction.
Warning
- Does NOT attempt to support OP_CODESEPARATOR. In general this would require evaluating
script_pubkey
to determine which separators get evaluated and which don’t, which we don’t have the information to determine. - Does NOT handle the sighash single bug (see “Returns” section)
Returns
This function can’t handle the SIGHASH_SINGLE bug internally, so it returns [EncodeSigningDataResult
]
that must be handled by the caller (see [EncodeSigningDataResult::is_sighash_single_bug
]).
Panics
If input_index
is out of bounds (greater than or equal to self.input.len()
).
pub fn signature_hash(
&self,
input_index: usize,
script_pubkey: &Script,
sighash_u32: u32
) -> LegacySighash
👎Deprecated since 0.30.0: Use SighashCache::legacy_signature_hash instead
pub fn signature_hash( &self, input_index: usize, script_pubkey: &Script, sighash_u32: u32 ) -> LegacySighash
Computes a signature hash for a given input index with a given sighash flag.
To actually produce a scriptSig, this hash needs to be run through an ECDSA signer, the
[EcdsaSighashType
] appended to the resulting sig, and a script written around this, but
this is the general (and hard) part.
The sighash_type
supports an arbitrary u32
value, instead of just [EcdsaSighashType
],
because internally 4 bytes are being hashed, even though only the lowest byte is appended to
signature in a transaction.
This function correctly handles the sighash single bug by returning the ‘one array’. The
sighash single bug becomes exploitable when one tries to sign a transaction with
SIGHASH_SINGLE
and there is not a corresponding output with the same index as the input.
Warning
Does NOT attempt to support OP_CODESEPARATOR. In general this would require evaluating
script_pubkey
to determine which separators get evaluated and which don’t, which we don’t
have the information to determine.
Panics
If input_index
is out of bounds (greater than or equal to self.input.len()
).
pub fn weight(&self) -> Weight
pub fn weight(&self) -> Weight
Returns the “weight” of this transaction, as defined by BIP141.
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 size(&self) -> usize
pub fn size(&self) -> usize
Returns the regular byte-wise consensus-serialized size of this transaction.
pub fn vsize(&self) -> usize
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.
pub fn strippedsize(&self) -> usize
pub fn strippedsize(&self) -> usize
Returns the size of this transaction excluding the witness data.
pub fn is_coin_base(&self) -> bool
pub fn is_coin_base(&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
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
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
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>
pub fn script_pubkey_lens(&self) -> impl Iterator<Item = usize>
Returns an iterator over lengths of script_pubkey
s 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.
Trait Implementations§
§impl AsRef<Transaction> for PrefilledTransaction
impl AsRef<Transaction> for PrefilledTransaction
§fn as_ref(&self) -> &Transaction
fn as_ref(&self) -> &Transaction
§impl Clone for Transaction
impl Clone for Transaction
§fn clone(&self) -> Transaction
fn clone(&self) -> Transaction
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read more§impl Debug for Transaction
impl Debug for Transaction
§impl Decodable for Transaction
impl Decodable for Transaction
§impl<'de> Deserialize<'de> for Transaction
impl<'de> Deserialize<'de> for Transaction
§fn deserialize<__D>(
__deserializer: __D
) -> Result<Transaction, <__D as Deserializer<'de>>::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>( __deserializer: __D ) -> Result<Transaction, <__D as Deserializer<'de>>::Error>where __D: Deserializer<'de>,
§impl Encodable for Transaction
impl Encodable for Transaction
§impl From<&Transaction> for Txid
impl From<&Transaction> for Txid
§fn from(tx: &Transaction) -> Txid
fn from(tx: &Transaction) -> Txid
§impl From<&Transaction> for Wtxid
impl From<&Transaction> for Wtxid
§fn from(tx: &Transaction) -> Wtxid
fn from(tx: &Transaction) -> Wtxid
§impl From<Transaction> for Txid
impl From<Transaction> for Txid
§fn from(tx: Transaction) -> Txid
fn from(tx: Transaction) -> Txid
§impl From<Transaction> for Wtxid
impl From<Transaction> for Wtxid
§fn from(tx: Transaction) -> Wtxid
fn from(tx: Transaction) -> Wtxid
§impl Hash for Transaction
impl Hash for Transaction
§impl Ord for Transaction
impl Ord for Transaction
§impl PartialEq<Transaction> for Transaction
impl PartialEq<Transaction> for Transaction
§fn eq(&self, other: &Transaction) -> bool
fn eq(&self, other: &Transaction) -> bool
self
and other
values to be equal, and is used
by ==
.§impl PartialOrd<Transaction> for Transaction
impl PartialOrd<Transaction> for Transaction
§fn partial_cmp(&self, other: &Transaction) -> Option<Ordering>
fn partial_cmp(&self, other: &Transaction) -> Option<Ordering>
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§impl<C> Queryable<C> for Transactionwhere
C: RpcApi,
impl<C> Queryable<C> for Transactionwhere C: RpcApi,
§fn query(
rpc: &C,
id: &<Transaction as Queryable<C>>::Id
) -> Result<Transaction, Error>
fn query( rpc: &C, id: &<Transaction as Queryable<C>>::Id ) -> Result<Transaction, Error>
rpc
and convert to Self
.§impl<'a> RawTx for &'a Transaction
impl<'a> RawTx for &'a Transaction
§impl Serialize for Transaction
impl Serialize for Transaction
§fn serialize<__S>(
&self,
__serializer: __S
) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>where
__S: Serializer,
fn serialize<__S>( &self, __serializer: __S ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>where __S: Serializer,
source§impl TransactionExt for Transaction
impl TransactionExt for Transaction
source§fn get_op_return(&self) -> Option<H256>
fn get_op_return(&self) -> Option<H256>
Extract the hash from the OP_RETURN uxto, if present
source§fn get_op_return_bytes(&self) -> Option<[u8; 34]>
fn get_op_return_bytes(&self) -> Option<[u8; 34]>
Extract the bytes of the OP_RETURN uxto, if present
source§fn get_payment_amount_to(&self, dest: Payload) -> Option<u64>
fn get_payment_amount_to(&self, dest: Payload) -> Option<u64>
Get the amount of btc that self sent to dest
, if any
source§fn extract_output_addresses(&self) -> Vec<Payload> ⓘ
fn extract_output_addresses(&self) -> Vec<Payload> ⓘ
return the addresses that are used as outputs with non-zero value in this transaction
impl Eq for Transaction
impl StructuralEq for Transaction
impl StructuralPartialEq for Transaction
Auto Trait Implementations§
impl RefUnwindSafe for Transaction
impl Send for Transaction
impl Sync for Transaction
impl Unpin for Transaction
impl UnwindSafe for Transaction
Blanket Implementations§
§impl<T> Conv for T
impl<T> Conv for T
source§impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,
source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key
and return true
if they are equal.§impl<T> FmtForward for T
impl<T> FmtForward for T
§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where Self: Binary,
self
to use its Binary
implementation when Debug
-formatted.§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where Self: Display,
self
to use its Display
implementation when
Debug
-formatted.§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where Self: LowerExp,
self
to use its LowerExp
implementation when
Debug
-formatted.§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where Self: LowerHex,
self
to use its LowerHex
implementation when
Debug
-formatted.§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where Self: Octal,
self
to use its Octal
implementation when Debug
-formatted.§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where Self: Pointer,
self
to use its Pointer
implementation when
Debug
-formatted.§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where Self: UpperExp,
self
to use its UpperExp
implementation when
Debug
-formatted.§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where Self: UpperHex,
self
to use its UpperHex
implementation when
Debug
-formatted.§fn fmt_list(self) -> FmtList<Self>where
&'a Self: for<'a> IntoIterator,
fn fmt_list(self) -> FmtList<Self>where &'a Self: for<'a> IntoIterator,
source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere T: ?Sized,
§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere Self: Sized,
§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere R: 'a,
self
and passes that borrow into the pipe function. Read more§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere R: 'a,
self
and passes that borrow into the pipe function. Read more§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> Rwhere
Self: Borrow<B>,
B: 'a + ?Sized,
R: 'a,
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> Rwhere Self: Borrow<B>, B: 'a + ?Sized, R: 'a,
§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R
) -> Rwhere
Self: BorrowMut<B>,
B: 'a + ?Sized,
R: 'a,
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R ) -> Rwhere Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,
§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> Rwhere
Self: AsRef<U>,
U: 'a + ?Sized,
R: 'a,
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> Rwhere Self: AsRef<U>, U: 'a + ?Sized, R: 'a,
self
, then passes self.as_ref()
into the pipe function.§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> Rwhere
Self: AsMut<U>,
U: 'a + ?Sized,
R: 'a,
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> Rwhere Self: AsMut<U>, U: 'a + ?Sized, R: 'a,
self
, then passes self.as_mut()
into the pipe
function.§impl<T> Tap for T
impl<T> Tap for T
§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Selfwhere Self: Borrow<B>, B: ?Sized,
Borrow<B>
of a value. Read more§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere Self: BorrowMut<B>, B: ?Sized,
BorrowMut<B>
of a value. Read more§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Selfwhere Self: AsRef<R>, R: ?Sized,
AsRef<R>
view of a value. Read more§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere Self: AsMut<R>, R: ?Sized,
AsMut<R>
view of a value. Read more§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Selfwhere
Self: Deref<Target = T>,
T: ?Sized,
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Selfwhere Self: Deref<Target = T>, T: ?Sized,
Deref::Target
of a value. Read more§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Selfwhere
Self: DerefMut<Target = T> + Deref,
T: ?Sized,
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Selfwhere Self: DerefMut<Target = T> + Deref, T: ?Sized,
Deref::Target
of a value. Read more§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap()
only in debug builds, and is erased in release builds.§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut()
only in debug builds, and is erased in release
builds.§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Selfwhere Self: Borrow<B>, B: ?Sized,
.tap_borrow()
only in debug builds, and is erased in release
builds.§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere Self: BorrowMut<B>, B: ?Sized,
.tap_borrow_mut()
only in debug builds, and is erased in release
builds.§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Selfwhere Self: AsRef<R>, R: ?Sized,
.tap_ref()
only in debug builds, and is erased in release
builds.§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere Self: AsMut<R>, R: ?Sized,
.tap_ref_mut()
only in debug builds, and is erased in release
builds.§impl<T> TryConv for T
impl<T> TryConv for T
§impl<S, T> UncheckedInto<T> for Swhere
T: UncheckedFrom<S>,
impl<S, T> UncheckedInto<T> for Swhere T: UncheckedFrom<S>,
§fn unchecked_into(self) -> T
fn unchecked_into(self) -> T
unchecked_from
.