Struct bdk_chain::tx_graph::TxGraph

source ·
pub struct TxGraph<A = ()> { /* private fields */ }
Expand description

A graph of transactions and spends.

See the module-level documentation for more.

Implementations§

source§

impl<A> TxGraph<A>

source

pub fn all_txouts(&self) -> impl Iterator<Item = (OutPoint, &TxOut)>

Iterate over all tx outputs known by TxGraph.

This includes txouts of both full transactions as well as floating transactions.

source

pub fn floating_txouts(&self) -> impl Iterator<Item = (OutPoint, &TxOut)>

Iterate over floating txouts known by TxGraph.

Floating txouts are txouts that do not have the residing full transaction contained in the graph.

source

pub fn full_txs(&self) -> impl Iterator<Item = TxNode<'_, Arc<Transaction>, A>>

Iterate over all full transactions in the graph.

source

pub fn get_tx(&self, txid: Txid) -> Option<Arc<Transaction>>

Get a transaction by txid. This only returns Some for full transactions.

Refer to get_txout for getting a specific TxOut.

source

pub fn get_tx_node(&self, txid: Txid) -> Option<TxNode<'_, Arc<Transaction>, A>>

Get a transaction node by txid. This only returns Some for full transactions.

source

pub fn get_txout(&self, outpoint: OutPoint) -> Option<&TxOut>

Obtains a single tx output (if any) at the specified outpoint.

source

pub fn tx_outputs(&self, txid: Txid) -> Option<BTreeMap<u32, &TxOut>>

Returns known outputs of a given txid.

Returns a BTreeMap of vout to output of the provided txid.

source

pub fn calculate_fee(&self, tx: &Transaction) -> Result<u64, CalculateFeeError>

Calculates the fee of a given transaction. Returns 0 if tx is a coinbase transaction. Returns OK(_) if we have all the TxOuts being spent by tx in the graph (either as the full transactions or individual txouts).

To calculate the fee for a Transaction that depends on foreign TxOut values you must first manually insert the foreign TxOuts into the tx graph using the insert_txout function. Only insert TxOuts you trust the values for!

Note tx does not have to be in the graph for this to work.

source

pub fn outspends(&self, outpoint: OutPoint) -> &HashSet<Txid>

The transactions spending from this output.

TxGraph allows conflicting transactions within the graph. Obviously the transactions in the returned set will never be in the same active-chain.

source

pub fn tx_spends( &self, txid: Txid ) -> impl DoubleEndedIterator<Item = (u32, &HashSet<Txid>)> + '_

Iterates over the transactions spending from txid.

The iterator item is a union of (vout, txid-set) where:

  • vout is the provided txid’s outpoint that is being spent
  • txid-set is the set of txids spending the vout.
source§

impl<A: Clone + Ord> TxGraph<A>

source

pub fn walk_ancestors<'g, T, F, O>( &'g self, tx: T, walk_map: F ) -> TxAncestors<'g, A, F>
where T: Into<Arc<Transaction>>, F: FnMut(usize, Arc<Transaction>) -> Option<O> + 'g,

Creates an iterator that filters and maps ancestor transactions.

The iterator starts with the ancestors of the supplied tx (ancestor transactions of tx are transactions spent by tx). The supplied transaction is excluded from the iterator.

The supplied closure takes in two inputs (depth, ancestor_tx):

  • depth is the distance between the starting Transaction and the ancestor_tx. I.e., if the Transaction is spending an output of the ancestor_tx then depth will be 1.
  • ancestor_tx is the Transaction’s ancestor which we are considering to walk.

The supplied closure returns an Option<T>, allowing the caller to map each Transaction it visits and decide whether to visit ancestors.

source

pub fn walk_descendants<'g, F, O>( &'g self, txid: Txid, walk_map: F ) -> TxDescendants<'_, A, F>
where F: FnMut(usize, Txid) -> Option<O> + 'g,

Creates an iterator that filters and maps descendants from the starting txid.

The supplied closure takes in two inputs (depth, descendant_txid):

  • depth is the distance between the starting txid and the descendant_txid. I.e., if the descendant is spending an output of the starting txid then depth will be 1.
  • descendant_txid is the descendant’s txid which we are considering to walk.

The supplied closure returns an Option<T>, allowing the caller to map each node it visits and decide whether to visit descendants.

source§

impl<A> TxGraph<A>

source

pub fn walk_conflicts<'g, F, O>( &'g self, tx: &'g Transaction, walk_map: F ) -> TxDescendants<'_, A, F>
where F: FnMut(usize, Txid) -> Option<O> + 'g,

Creates an iterator that both filters and maps conflicting transactions (this includes descendants of directly-conflicting transactions, which are also considered conflicts).

Refer to Self::walk_descendants for walk_map usage.

source

pub fn direct_conflicts<'g>( &'g self, tx: &'g Transaction ) -> impl Iterator<Item = (usize, Txid)> + '_

Given a transaction, return an iterator of txids that directly conflict with the given transaction’s inputs (spends). The conflicting txids are returned with the given transaction’s vin (in which it conflicts).

Note that this only returns directly conflicting txids and won’t include:

  • descendants of conflicting transactions (which are technically also conflicting)
  • transactions conflicting with the given transaction’s ancestors
source

pub fn all_anchors(&self) -> &BTreeSet<(A, Txid)>

Get all transaction anchors known by TxGraph.

source

pub fn is_empty(&self) -> bool

Whether the graph has any transactions or outputs in it.

source§

impl<A: Clone + Ord> TxGraph<A>

source

pub fn map_anchors<A2: Clone + Ord, F>(self, f: F) -> TxGraph<A2>
where F: FnMut(A) -> A2,

Transform the TxGraph to have Anchors of another type.

This takes in a closure of signature FnMut(A) -> A2 which is called for each Anchor to transform it.

source

pub fn new(txs: impl IntoIterator<Item = Transaction>) -> Self

Construct a new TxGraph from a list of transactions.

source

pub fn insert_txout(&mut self, outpoint: OutPoint, txout: TxOut) -> ChangeSet<A>

Inserts the given TxOut at OutPoint.

Inserting floating txouts are useful for determining fee/feerate of transactions we care about.

The ChangeSet result will be empty if the outpoint (or a full transaction containing the outpoint) already existed in self.

source

pub fn insert_tx<T: Into<Arc<Transaction>>>(&mut self, tx: T) -> ChangeSet<A>

Inserts the given transaction into TxGraph.

The ChangeSet returned will be empty if tx already exists.

source

pub fn batch_insert_unconfirmed( &mut self, txs: impl IntoIterator<Item = (Transaction, u64)> ) -> ChangeSet<A>

Batch insert unconfirmed transactions.

Items of txs are tuples containing the transaction and a last seen timestamp. The last seen communicates when the transaction is last seen in mempool which is used for conflict-resolution (refer to TxGraph::insert_seen_at for details).

source

pub fn insert_anchor(&mut self, txid: Txid, anchor: A) -> ChangeSet<A>

Inserts the given anchor into TxGraph.

The ChangeSet returned will be empty if graph already knows that txid exists in anchor.

source

pub fn insert_seen_at(&mut self, txid: Txid, seen_at: u64) -> ChangeSet<A>

Inserts the given seen_at for txid into TxGraph.

Note that TxGraph only keeps track of the latest seen_at. To batch update all unconfirmed transactions with the latest seen_at, see update_last_seen_unconfirmed.

source

pub fn update_last_seen_unconfirmed(&mut self, seen_at: u64) -> ChangeSet<A>

Update the last seen time for all unconfirmed transactions.

This method updates the last seen unconfirmed time for this TxGraph by inserting the given seen_at for every transaction not yet anchored to a confirmed block, and returns the ChangeSet after applying all updates to self.

This is useful for keeping track of the latest time a transaction was seen unconfirmed, which is important for evaluating transaction conflicts in the same TxGraph. For details of how TxGraph resolves conflicts, see the docs for try_get_chain_position.

A normal use of this method is to call it with the current system time. Although block headers contain a timestamp, using the header time would be less effective at tracking mempool transactions, because it can drift from actual clock time, plus we may want to update a transaction’s last seen time repeatedly between blocks.

§Example
let now = std::time::SystemTime::now()
    .duration_since(UNIX_EPOCH)
    .expect("valid duration")
    .as_secs();
let changeset = tx_graph.update_last_seen_unconfirmed(now);
assert!(!changeset.last_seen.is_empty());

Note that TxGraph only keeps track of the latest seen_at, so the given time must by strictly greater than what is currently stored for a transaction to have an effect. To insert a last seen time for a single txid, see insert_seen_at.

source

pub fn apply_update(&mut self, update: TxGraph<A>) -> ChangeSet<A>

Extends this graph with another so that self becomes the union of the two sets of transactions.

The returned ChangeSet is the set difference between update and self (transactions that exist in update but not in self).

source

pub fn initial_changeset(&self) -> ChangeSet<A>

Determines the ChangeSet between self and an empty TxGraph.

source

pub fn apply_changeset(&mut self, changeset: ChangeSet<A>)

Applies ChangeSet to TxGraph.

source§

impl<A: Anchor> TxGraph<A>

source

pub fn try_get_chain_position<C: ChainOracle>( &self, chain: &C, chain_tip: BlockId, txid: Txid ) -> Result<Option<ChainPosition<&A>>, C::Error>

Get the position of the transaction in chain with tip chain_tip.

Chain data is fetched from chain, a ChainOracle implementation.

This method returns Ok(None) if the transaction is not found in the chain, and no longer belongs in the mempool. The following factors are used to approximate whether an unconfirmed transaction exists in the mempool (not evicted):

  1. Unconfirmed transactions that conflict with confirmed transactions are evicted.
  2. Unconfirmed transactions that spend from transactions that are evicted, are also evicted.
  3. Given two conflicting unconfirmed transactions, the transaction with the lower last_seen_unconfirmed parameter is evicted. A transaction’s last_seen_unconfirmed parameter is the max of all it’s descendants’ last_seen_unconfirmed parameters. If the final last_seen_unconfirmeds are the same, the transaction with the lower txid (by lexicographical order) is evicted.
§Error

An error will occur if the ChainOracle implementation (chain) fails. If the ChainOracle is infallible, get_chain_position can be used instead.

source

pub fn get_chain_position<C: ChainOracle<Error = Infallible>>( &self, chain: &C, chain_tip: BlockId, txid: Txid ) -> Option<ChainPosition<&A>>

Get the position of the transaction in chain with tip chain_tip.

This is the infallible version of try_get_chain_position.

source

pub fn try_get_chain_spend<C: ChainOracle>( &self, chain: &C, chain_tip: BlockId, outpoint: OutPoint ) -> Result<Option<(ChainPosition<&A>, Txid)>, C::Error>

Get the txid of the spending transaction and where the spending transaction is observed in the chain of chain_tip.

If no in-chain transaction spends outpoint, None will be returned.

§Error

An error will occur only if the ChainOracle implementation (chain) fails.

If the ChainOracle is infallible, get_chain_spend can be used instead.

source

pub fn get_chain_spend<C: ChainOracle<Error = Infallible>>( &self, chain: &C, static_block: BlockId, outpoint: OutPoint ) -> Option<(ChainPosition<&A>, Txid)>

Get the txid of the spending transaction and where the spending transaction is observed in the chain of chain_tip.

This is the infallible version of try_get_chain_spend

source

pub fn try_list_chain_txs<'a, C: ChainOracle + 'a>( &'a self, chain: &'a C, chain_tip: BlockId ) -> impl Iterator<Item = Result<CanonicalTx<'a, Arc<Transaction>, A>, C::Error>>

List graph transactions that are in chain with chain_tip.

Each transaction is represented as a CanonicalTx that contains where the transaction is observed in-chain, and the TxNode.

§Error

If the ChainOracle implementation (chain) fails, an error will be returned with the returned item.

If the ChainOracle is infallible, list_chain_txs can be used instead.

source

pub fn list_chain_txs<'a, C: ChainOracle + 'a>( &'a self, chain: &'a C, chain_tip: BlockId ) -> impl Iterator<Item = CanonicalTx<'a, Arc<Transaction>, A>>

List graph transactions that are in chain with chain_tip.

This is the infallible version of try_list_chain_txs.

source

pub fn try_filter_chain_txouts<'a, C: ChainOracle + 'a, OI: Clone + 'a>( &'a self, chain: &'a C, chain_tip: BlockId, outpoints: impl IntoIterator<Item = (OI, OutPoint)> + 'a ) -> impl Iterator<Item = Result<(OI, FullTxOut<A>), C::Error>> + 'a

Get a filtered list of outputs from the given outpoints that are in chain with chain_tip.

outpoints is a list of outpoints we are interested in, coupled with an outpoint identifier (OI) for convenience. If OI is not necessary, the caller can use (), or Iterator::enumerate over a list of OutPoints.

Floating outputs (i.e., outputs for which we don’t have the full transaction in the graph) are ignored.

§Error

An Iterator::Item can be an Err if the ChainOracle implementation (chain) fails.

If the ChainOracle implementation is infallible, filter_chain_txouts can be used instead.

source

pub fn filter_chain_txouts<'a, C: ChainOracle<Error = Infallible> + 'a, OI: Clone + 'a>( &'a self, chain: &'a C, chain_tip: BlockId, outpoints: impl IntoIterator<Item = (OI, OutPoint)> + 'a ) -> impl Iterator<Item = (OI, FullTxOut<A>)> + 'a

Get a filtered list of outputs from the given outpoints that are in chain with chain_tip.

This is the infallible version of try_filter_chain_txouts.

source

pub fn try_filter_chain_unspents<'a, C: ChainOracle + 'a, OI: Clone + 'a>( &'a self, chain: &'a C, chain_tip: BlockId, outpoints: impl IntoIterator<Item = (OI, OutPoint)> + 'a ) -> impl Iterator<Item = Result<(OI, FullTxOut<A>), C::Error>> + 'a

Get a filtered list of unspent outputs (UTXOs) from the given outpoints that are in chain with chain_tip.

outpoints is a list of outpoints we are interested in, coupled with an outpoint identifier (OI) for convenience. If OI is not necessary, the caller can use (), or Iterator::enumerate over a list of OutPoints.

Floating outputs are ignored.

§Error

An Iterator::Item can be an Err if the ChainOracle implementation (chain) fails.

If the ChainOracle implementation is infallible, filter_chain_unspents can be used instead.

source

pub fn filter_chain_unspents<'a, C: ChainOracle<Error = Infallible> + 'a, OI: Clone + 'a>( &'a self, chain: &'a C, chain_tip: BlockId, txouts: impl IntoIterator<Item = (OI, OutPoint)> + 'a ) -> impl Iterator<Item = (OI, FullTxOut<A>)> + 'a

Get a filtered list of unspent outputs (UTXOs) from the given outpoints that are in chain with chain_tip.

This is the infallible version of try_filter_chain_unspents.

source

pub fn try_balance<C: ChainOracle, OI: Clone>( &self, chain: &C, chain_tip: BlockId, outpoints: impl IntoIterator<Item = (OI, OutPoint)>, trust_predicate: impl FnMut(&OI, &Script) -> bool ) -> Result<Balance, C::Error>

Get the total balance of outpoints that are in chain of chain_tip.

The output of trust_predicate should return true for scripts that we trust.

outpoints is a list of outpoints we are interested in, coupled with an outpoint identifier (OI) for convenience. If OI is not necessary, the caller can use (), or Iterator::enumerate over a list of OutPoints.

If the provided ChainOracle implementation (chain) is infallible, balance can be used instead.

source

pub fn balance<C: ChainOracle<Error = Infallible>, OI: Clone>( &self, chain: &C, chain_tip: BlockId, outpoints: impl IntoIterator<Item = (OI, OutPoint)>, trust_predicate: impl FnMut(&OI, &Script) -> bool ) -> Balance

Get the total balance of outpoints that are in chain of chain_tip.

This is the infallible version of try_balance.

Trait Implementations§

source§

impl<A> AsRef<TxGraph<A>> for TxGraph<A>

source§

fn as_ref(&self) -> &TxGraph<A>

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

impl<A: Clone> Clone for TxGraph<A>

source§

fn clone(&self) -> TxGraph<A>

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<A: Debug> Debug for TxGraph<A>

source§

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

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

impl<A> Default for TxGraph<A>

source§

fn default() -> Self

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

impl<A: PartialEq> PartialEq for TxGraph<A>

source§

fn eq(&self, other: &TxGraph<A>) -> 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<A> StructuralPartialEq for TxGraph<A>

Auto Trait Implementations§

§

impl<A> Freeze for TxGraph<A>

§

impl<A> RefUnwindSafe for TxGraph<A>
where A: RefUnwindSafe,

§

impl<A> Send for TxGraph<A>
where A: Send,

§

impl<A> Sync for TxGraph<A>
where A: Sync,

§

impl<A> Unpin for TxGraph<A>

§

impl<A> UnwindSafe for TxGraph<A>
where A: RefUnwindSafe,

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

§

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

§

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

§

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.