Struct TxGraph

Source
pub struct TxGraph<A = ConfirmationBlockTime> { /* 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 txs_with_no_anchor_or_last_seen( &self, ) -> impl Iterator<Item = TxNode<'_, Arc<Transaction>, A>>

Iterate over graph transactions with no anchors or last-seen.

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 get_last_evicted(&self, txid: Txid) -> Option<u64>

Get the last_evicted timestamp of the given txid.

Ideally, this would be included in TxNode, but that would be a breaking change.

Source

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

Calculates the fee of a given transaction. Returns Amount::ZERO 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, O>
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<'g, A, F, O>
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<'g, A, F, O>
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)> + 'g

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) -> &HashMap<Txid, BTreeSet<A>>

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: Anchor> TxGraph<A>

Source

pub fn map_anchors<A2: Anchor, 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>

Insert the given transaction into TxGraph.

The ChangeSet returned will be empty if no changes are made to the graph.

§Updating Existing Transactions

An unsigned transaction can be inserted first and have it’s witness fields updated with further transaction insertions (given that the newly introduced transaction shares the same txid as the original transaction).

The witnesses of the newly introduced transaction will be merged with the witnesses of the original transaction in a way where:

  • A non-empty witness has precedence over an empty witness.
  • A smaller witness has precedence over a larger witness.
  • If the witness sizes are the same, we prioritize the two witnesses with lexicographical order.
Source

pub fn batch_insert_unconfirmed<T: Into<Arc<Transaction>>>( &mut self, txs: impl IntoIterator<Item = (T, 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>

Updates the first-seen and last-seen timestamps for a given txid in the TxGraph.

This method records the time a transaction was observed by updating both:

  • the first-seen timestamp, which only changes if seen_at is earlier than the current value, and
  • the last-seen timestamp, which only changes if seen_at is later than the current value.

seen_at is a UNIX timestamp in seconds.

Returns a ChangeSet representing any changes applied.

Source

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

Inserts the given evicted_at for txid into TxGraph.

The evicted_at timestamp represents the last known time when the transaction was observed to be missing from the mempool. If txid was previously recorded with an earlier evicted_at value, it is updated only if the new value is greater.

Source

pub fn batch_insert_relevant_evicted_at( &mut self, evicted_ats: impl IntoIterator<Item = (Txid, u64)>, ) -> ChangeSet<A>

Batch inserts (txid, evicted_at) pairs into TxGraph for txids that the graph is tracking.

The evicted_at timestamp represents the last known time when the transaction was observed to be missing from the mempool. If txid was previously recorded with an earlier evicted_at value, it is updated only if the new value is greater.

Source

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

Extends this graph with the given update.

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_list_canonical_txs<'a, C: ChainOracle + 'a>( &'a self, chain: &'a C, chain_tip: BlockId, params: CanonicalizationParams, ) -> 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_canonical_txs can be used instead.

Source

pub fn list_canonical_txs<'a, C: ChainOracle<Error = Infallible> + 'a>( &'a self, chain: &'a C, chain_tip: BlockId, params: CanonicalizationParams, ) -> 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_canonical_txs.

Source

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

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 txids_by_descending_anchor_height( &self, ) -> impl ExactSizeIterator<Item = (u32, Txid)> + '_

List txids by descending anchor height order.

If multiple anchors exist for a txid, the highest anchor height will be used. Transactions without anchors are excluded.

Source

pub fn txids_by_descending_last_seen( &self, ) -> impl Iterator<Item = (u64, Txid)> + '_

List txids by descending last-seen order.

Transactions without last-seens are excluded. Transactions with a last-evicted timestamp equal or higher than it’s last-seen timestamp are excluded.

Source

pub fn canonical_iter<'a, C: ChainOracle>( &'a self, chain: &'a C, chain_tip: BlockId, params: CanonicalizationParams, ) -> CanonicalIter<'a, A, C>

Returns a CanonicalIter.

Source

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

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, params: CanonicalizationParams, 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, params: CanonicalizationParams, outpoints: impl IntoIterator<Item = (OI, OutPoint)>, trust_predicate: impl FnMut(&OI, ScriptBuf) -> 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, params: CanonicalizationParams, outpoints: impl IntoIterator<Item = (OI, OutPoint)>, trust_predicate: impl FnMut(&OI, ScriptBuf) -> bool, ) -> Balance

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

This is the infallible version of try_balance.

§Minimum confirmations

To filter for transactions with at least N confirmations, pass a chain_tip that is N - 1 blocks below the actual tip. This ensures that only transactions with at least N confirmations are counted as confirmed in the returned Balance.



let minimum_confirmations = 6;
let target_tip = chain
    .tip()
    .floor_below(minimum_confirmations - 1)
    .expect("checkpoint from local chain must have genesis");
let balance = graph.balance(
    &chain,
    target_tip.block_id(),
    CanonicalizationParams::default(),
    std::iter::once(((), OutPoint::new(txid, 0))),
    |_: &(), _| true,
);
assert_eq!(balance.confirmed, Amount::from_sat(42_000));
Source

pub fn try_list_expected_spk_txids<'a, C, I>( &'a self, chain: &'a C, chain_tip: BlockId, indexer: &'a impl AsRef<SpkTxOutIndex<I>>, spk_index_range: impl RangeBounds<I> + 'a, ) -> impl Iterator<Item = Result<(ScriptBuf, Txid), C::Error>> + 'a
where C: ChainOracle, I: Debug + Clone + Ord + 'a,

List txids that are expected to exist under the given spks.

This is used to fill SyncRequestBuilder::expected_spk_txids.

The spk index range can be constrained with range.

§Error

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

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

Source

pub fn list_expected_spk_txids<'a, C, I>( &'a self, chain: &'a C, chain_tip: BlockId, indexer: &'a impl AsRef<SpkTxOutIndex<I>>, spk_index_range: impl RangeBounds<I> + 'a, ) -> impl Iterator<Item = (ScriptBuf, Txid)> + 'a
where C: ChainOracle<Error = Infallible>, I: Debug + Clone + Ord + 'a,

List txids that are expected to exist under the given spks.

This is the infallible version of try_list_expected_spk_txids.

Source

pub fn from_changeset(changeset: ChangeSet<A>) -> Self

Construct a TxGraph from a changeset.

Trait Implementations§

Source§

impl<A, I> AsRef<TxGraph<A>> for IndexedTxGraph<A, I>

Source§

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

Converts this type into a shared reference of the (usually inferred) input type.
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 duplicate 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: Ord> From<TxGraph<A>> for TxUpdate<A>

Source§

fn from(graph: TxGraph<A>) -> Self

Converts to this type from the input type.
Source§

impl<A: Anchor> From<TxUpdate<A>> for TxGraph<A>

Source§

fn from(update: TxUpdate<A>) -> Self

Converts to this type from the input type.
Source§

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

Source§

fn eq(&self, other: &TxGraph<A>) -> 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.
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> 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> 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.
Source§

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

Source§

fn vzip(self) -> V