• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

bitcoindevkit / bdk / 5973044273

25 Aug 2023 07:19AM UTC coverage: 78.684% (-0.03%) from 78.711%
5973044273

Pull #1092

github

web-flow
Merge c75358437 into 6125062a5
Pull Request #1092: Use `apply_update` instead of `determine_changeset` + `apply_changeset` around the code

4 of 4 new or added lines in 1 file covered. (100.0%)

8025 of 10199 relevant lines covered (78.68%)

5028.66 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.97
/crates/chain/src/tx_graph.rs
1
//! Module for structures that store and traverse transactions.
2
//!
3
//! [`TxGraph`] is a monotone structure that inserts transactions and indexes the spends. The
4
//! [`ChangeSet`] structure reports changes of [`TxGraph`] but can also be applied to a
5
//! [`TxGraph`] as well. Lastly, [`TxDescendants`] is an [`Iterator`] that traverses descendants of
6
//! a given transaction.
7
//!
8
//! Conflicting transactions are allowed to coexist within a [`TxGraph`]. This is useful for
9
//! identifying and traversing conflicts and descendants of a given transaction.
10
//!
11
//! # Applying changes
12
//!
13
//! Methods that apply changes to [`TxGraph`] will return [`ChangeSet`].
14
//! [`ChangeSet`] can be applied back to a [`TxGraph`] or be used to inform persistent storage
15
//! of the changes to [`TxGraph`].
16
//!
17
//! ```
18
//! # use bdk_chain::BlockId;
19
//! # use bdk_chain::tx_graph::TxGraph;
20
//! # use bdk_chain::example_utils::*;
21
//! # use bitcoin::Transaction;
22
//! # let tx_a = tx_from_hex(RAW_TX_1);
23
//! let mut graph: TxGraph = TxGraph::default();
24
//! let mut another_graph: TxGraph = TxGraph::default();
25
//!
26
//! // insert a transaction
27
//! let changeset = graph.insert_tx(tx_a);
28
//!
29
//! // the resulting changeset can be applied to another tx graph
30
//! another_graph.apply_changeset(changeset);
31
//! ```
32
//!
33
//! A [`TxGraph`] can also be updated with another [`TxGraph`].
34
//!
35
//! ```
36
//! # use bdk_chain::BlockId;
37
//! # use bdk_chain::tx_graph::TxGraph;
38
//! # use bdk_chain::example_utils::*;
39
//! # use bitcoin::Transaction;
40
//! # let tx_a = tx_from_hex(RAW_TX_1);
41
//! # let tx_b = tx_from_hex(RAW_TX_2);
42
//! let mut graph: TxGraph = TxGraph::default();
43
//! let update = TxGraph::new(vec![tx_a, tx_b]);
44
//!
45
//! // apply the update graph
46
//! let changeset = graph.apply_update(update.clone());
47
//!
48
//! // if we apply it again, the resulting changeset will be empty
49
//! let changeset = graph.apply_update(update);
50
//! assert!(changeset.is_empty());
51
//! ```
52

53
use crate::{
54
    collections::*, keychain::Balance, local_chain::LocalChain, Anchor, Append, BlockId,
55
    ChainOracle, ChainPosition, ForEachTxOut, FullTxOut,
56
};
57
use alloc::vec::Vec;
58
use bitcoin::{OutPoint, Script, Transaction, TxOut, Txid};
59
use core::{
60
    convert::Infallible,
61
    ops::{Deref, RangeInclusive},
62
};
63

64
/// A graph of transactions and spends.
65
///
66
/// See the [module-level documentation] for more.
67
///
68
/// [module-level documentation]: crate::tx_graph
69
#[derive(Clone, Debug, PartialEq)]
2✔
70
pub struct TxGraph<A = ()> {
71
    // all transactions that the graph is aware of in format: `(tx_node, tx_anchors, tx_last_seen)`
72
    txs: HashMap<Txid, (TxNodeInternal, BTreeSet<A>, u64)>,
73
    spends: BTreeMap<OutPoint, HashSet<Txid>>,
74
    anchors: BTreeSet<(A, Txid)>,
75

76
    // This atrocity exists so that `TxGraph::outspends()` can return a reference.
77
    // FIXME: This can be removed once `HashSet::new` is a const fn.
78
    empty_outspends: HashSet<Txid>,
79
}
80

81
impl<A> Default for TxGraph<A> {
82
    fn default() -> Self {
730✔
83
        Self {
730✔
84
            txs: Default::default(),
730✔
85
            spends: Default::default(),
730✔
86
            anchors: Default::default(),
730✔
87
            empty_outspends: Default::default(),
730✔
88
        }
730✔
89
    }
730✔
90
}
91

92
/// An outward-facing view of a (transaction) node in the [`TxGraph`].
93
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
×
94
pub struct TxNode<'a, T, A> {
95
    /// Txid of the transaction.
96
    pub txid: Txid,
97
    /// A partial or full representation of the transaction.
98
    pub tx: &'a T,
99
    /// The blocks that the transaction is "anchored" in.
100
    pub anchors: &'a BTreeSet<A>,
101
    /// The last-seen unix timestamp of the transaction as unconfirmed.
102
    pub last_seen_unconfirmed: u64,
103
}
104

105
impl<'a, T, A> Deref for TxNode<'a, T, A> {
106
    type Target = T;
107

108
    fn deref(&self) -> &Self::Target {
×
109
        self.tx
×
110
    }
×
111
}
112

113
/// Internal representation of a transaction node of a [`TxGraph`].
114
///
115
/// This can either be a whole transaction, or a partial transaction (where we only have select
116
/// outputs).
117
#[derive(Clone, Debug, PartialEq)]
6✔
118
enum TxNodeInternal {
119
    Whole(Transaction),
120
    Partial(BTreeMap<u32, TxOut>),
121
}
122

123
impl Default for TxNodeInternal {
124
    fn default() -> Self {
546✔
125
        Self::Partial(BTreeMap::new())
546✔
126
    }
546✔
127
}
128

129
/// An outwards-facing view of a transaction that is part of the *best chain*'s history.
130
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
×
131
pub struct CanonicalTx<'a, T, A> {
132
    /// How the transaction is observed as (confirmed or unconfirmed).
133
    pub chain_position: ChainPosition<&'a A>,
134
    /// The transaction node (as part of the graph).
135
    pub tx_node: TxNode<'a, T, A>,
136
}
137

138
impl<A> TxGraph<A> {
139
    /// Iterate over all tx outputs known by [`TxGraph`].
140
    ///
141
    /// This includes txouts of both full transactions as well as floating transactions.
142
    pub fn all_txouts(&self) -> impl Iterator<Item = (OutPoint, &TxOut)> {
1✔
143
        self.txs.iter().flat_map(|(txid, (tx, _, _))| match tx {
3✔
144
            TxNodeInternal::Whole(tx) => tx
1✔
145
                .output
1✔
146
                .iter()
1✔
147
                .enumerate()
1✔
148
                .map(|(vout, txout)| (OutPoint::new(*txid, vout as _), txout))
1✔
149
                .collect::<Vec<_>>(),
1✔
150
            TxNodeInternal::Partial(txouts) => txouts
2✔
151
                .iter()
2✔
152
                .map(|(vout, txout)| (OutPoint::new(*txid, *vout as _), txout))
3✔
153
                .collect::<Vec<_>>(),
2✔
154
        })
3✔
155
    }
1✔
156

157
    /// Iterate over floating txouts known by [`TxGraph`].
158
    ///
159
    /// Floating txouts are txouts that do not have the residing full transaction contained in the
160
    /// graph.
161
    pub fn floating_txouts(&self) -> impl Iterator<Item = (OutPoint, &TxOut)> {
1✔
162
        self.txs
1✔
163
            .iter()
1✔
164
            .filter_map(|(txid, (tx_node, _, _))| match tx_node {
3✔
165
                TxNodeInternal::Whole(_) => None,
1✔
166
                TxNodeInternal::Partial(txouts) => Some(
2✔
167
                    txouts
2✔
168
                        .iter()
2✔
169
                        .map(|(&vout, txout)| (OutPoint::new(*txid, vout), txout)),
3✔
170
                ),
2✔
171
            })
3✔
172
            .flatten()
1✔
173
    }
1✔
174

175
    /// Iterate over all full transactions in the graph.
176
    pub fn full_txs(&self) -> impl Iterator<Item = TxNode<'_, Transaction, A>> {
8✔
177
        self.txs
8✔
178
            .iter()
8✔
179
            .filter_map(|(&txid, (tx, anchors, last_seen))| match tx {
10✔
180
                TxNodeInternal::Whole(tx) => Some(TxNode {
8✔
181
                    txid,
8✔
182
                    tx,
8✔
183
                    anchors,
8✔
184
                    last_seen_unconfirmed: *last_seen,
8✔
185
                }),
8✔
186
                TxNodeInternal::Partial(_) => None,
2✔
187
            })
10✔
188
    }
8✔
189

190
    /// Get a transaction by txid. This only returns `Some` for full transactions.
191
    ///
192
    /// Refer to [`get_txout`] for getting a specific [`TxOut`].
193
    ///
194
    /// [`get_txout`]: Self::get_txout
195
    pub fn get_tx(&self, txid: Txid) -> Option<&Transaction> {
468✔
196
        self.get_tx_node(txid).map(|n| n.tx)
468✔
197
    }
468✔
198

199
    /// Get a transaction node by txid. This only returns `Some` for full transactions.
200
    pub fn get_tx_node(&self, txid: Txid) -> Option<TxNode<'_, Transaction, A>> {
729✔
201
        match &self.txs.get(&txid)? {
729✔
202
            (TxNodeInternal::Whole(tx), anchors, last_seen) => Some(TxNode {
560✔
203
                txid,
560✔
204
                tx,
560✔
205
                anchors,
560✔
206
                last_seen_unconfirmed: *last_seen,
560✔
207
            }),
560✔
208
            _ => None,
×
209
        }
210
    }
729✔
211

212
    /// Obtains a single tx output (if any) at the specified outpoint.
213
    pub fn get_txout(&self, outpoint: OutPoint) -> Option<&TxOut> {
156✔
214
        match &self.txs.get(&outpoint.txid)?.0 {
156✔
215
            TxNodeInternal::Whole(tx) => tx.output.get(outpoint.vout as usize),
154✔
216
            TxNodeInternal::Partial(txouts) => txouts.get(&outpoint.vout),
1✔
217
        }
218
    }
156✔
219

220
    /// Returns known outputs of a given `txid`.
221
    ///
222
    /// Returns a [`BTreeMap`] of vout to output of the provided `txid`.
223
    pub fn tx_outputs(&self, txid: Txid) -> Option<BTreeMap<u32, &TxOut>> {
2✔
224
        Some(match &self.txs.get(&txid)?.0 {
2✔
225
            TxNodeInternal::Whole(tx) => tx
1✔
226
                .output
1✔
227
                .iter()
1✔
228
                .enumerate()
1✔
229
                .map(|(vout, txout)| (vout as u32, txout))
1✔
230
                .collect::<BTreeMap<_, _>>(),
1✔
231
            TxNodeInternal::Partial(txouts) => txouts
1✔
232
                .iter()
1✔
233
                .map(|(vout, txout)| (*vout, txout))
2✔
234
                .collect::<BTreeMap<_, _>>(),
1✔
235
        })
236
    }
2✔
237

238
    /// Calculates the fee of a given transaction. Returns 0 if `tx` is a coinbase transaction.
239
    /// Returns `Some(_)` if we have all the `TxOut`s being spent by `tx` in the graph (either as
240
    /// the full transactions or individual txouts). If the returned value is negative, then the
241
    /// transaction is invalid according to the graph.
242
    ///
243
    /// Returns `None` if we're missing an input for the tx in the graph.
244
    ///
245
    /// Note `tx` does not have to be in the graph for this to work.
246
    pub fn calculate_fee(&self, tx: &Transaction) -> Option<i64> {
21✔
247
        if tx.is_coin_base() {
21✔
248
            return Some(0);
1✔
249
        }
20✔
250
        let inputs_sum = tx
20✔
251
            .input
20✔
252
            .iter()
20✔
253
            .map(|txin| {
26✔
254
                self.get_txout(txin.previous_output)
26✔
255
                    .map(|txout| txout.value as i64)
26✔
256
            })
26✔
257
            .sum::<Option<i64>>()?;
20✔
258

259
        let outputs_sum = tx
19✔
260
            .output
19✔
261
            .iter()
19✔
262
            .map(|txout| txout.value as i64)
29✔
263
            .sum::<i64>();
19✔
264

19✔
265
        Some(inputs_sum - outputs_sum)
19✔
266
    }
21✔
267

268
    /// The transactions spending from this output.
269
    ///
270
    /// `TxGraph` allows conflicting transactions within the graph. Obviously the transactions in
271
    /// the returned set will never be in the same active-chain.
272
    pub fn outspends(&self, outpoint: OutPoint) -> &HashSet<Txid> {
4✔
273
        self.spends.get(&outpoint).unwrap_or(&self.empty_outspends)
4✔
274
    }
4✔
275

276
    /// Iterates over the transactions spending from `txid`.
277
    ///
278
    /// The iterator item is a union of `(vout, txid-set)` where:
279
    ///
280
    /// - `vout` is the provided `txid`'s outpoint that is being spent
281
    /// - `txid-set` is the set of txids spending the `vout`.
282
    pub fn tx_spends(
1✔
283
        &self,
1✔
284
        txid: Txid,
1✔
285
    ) -> impl DoubleEndedIterator<Item = (u32, &HashSet<Txid>)> + '_ {
1✔
286
        let start = OutPoint { txid, vout: 0 };
1✔
287
        let end = OutPoint {
1✔
288
            txid,
1✔
289
            vout: u32::MAX,
1✔
290
        };
1✔
291
        self.spends
1✔
292
            .range(start..=end)
1✔
293
            .map(|(outpoint, spends)| (outpoint.vout, spends))
1✔
294
    }
1✔
295

296
    /// Creates an iterator that filters and maps descendants from the starting `txid`.
297
    ///
298
    /// The supplied closure takes in two inputs `(depth, descendant_txid)`:
299
    ///
300
    /// * `depth` is the distance between the starting `txid` and the `descendant_txid`. I.e., if the
301
    ///     descendant is spending an output of the starting `txid`; the `depth` will be 1.
302
    /// * `descendant_txid` is the descendant's txid which we are considering to walk.
303
    ///
304
    /// The supplied closure returns an `Option<T>`, allowing the caller to map each node it vists
305
    /// and decide whether to visit descendants.
306
    pub fn walk_descendants<'g, F, O>(&'g self, txid: Txid, walk_map: F) -> TxDescendants<A, F>
1✔
307
    where
1✔
308
        F: FnMut(usize, Txid) -> Option<O> + 'g,
1✔
309
    {
1✔
310
        TxDescendants::new_exclude_root(self, txid, walk_map)
1✔
311
    }
1✔
312

313
    /// Creates an iterator that both filters and maps conflicting transactions (this includes
314
    /// descendants of directly-conflicting transactions, which are also considered conflicts).
315
    ///
316
    /// Refer to [`Self::walk_descendants`] for `walk_map` usage.
317
    pub fn walk_conflicts<'g, F, O>(
165✔
318
        &'g self,
165✔
319
        tx: &'g Transaction,
165✔
320
        walk_map: F,
165✔
321
    ) -> TxDescendants<A, F>
165✔
322
    where
165✔
323
        F: FnMut(usize, Txid) -> Option<O> + 'g,
165✔
324
    {
165✔
325
        let txids = self.direct_conflicts_of_tx(tx).map(|(_, txid)| txid);
165✔
326
        TxDescendants::from_multiple_include_root(self, txids, walk_map)
165✔
327
    }
165✔
328

329
    /// Given a transaction, return an iterator of txids that directly conflict with the given
330
    /// transaction's inputs (spends). The conflicting txids are returned with the given
331
    /// transaction's vin (in which it conflicts).
332
    ///
333
    /// Note that this only returns directly conflicting txids and does not include descendants of
334
    /// those txids (which are technically also conflicting).
335
    pub fn direct_conflicts_of_tx<'g>(
165✔
336
        &'g self,
165✔
337
        tx: &'g Transaction,
165✔
338
    ) -> impl Iterator<Item = (usize, Txid)> + '_ {
165✔
339
        let txid = tx.txid();
165✔
340
        tx.input
165✔
341
            .iter()
165✔
342
            .enumerate()
165✔
343
            .filter_map(move |(vin, txin)| self.spends.get(&txin.previous_output).zip(Some(vin)))
165✔
344
            .flat_map(|(spends, vin)| core::iter::repeat(vin).zip(spends.iter().cloned()))
165✔
345
            .filter(move |(_, conflicting_txid)| *conflicting_txid != txid)
169✔
346
    }
165✔
347

348
    /// Get all transaction anchors known by [`TxGraph`].
349
    pub fn all_anchors(&self) -> &BTreeSet<(A, Txid)> {
×
350
        &self.anchors
×
351
    }
×
352

353
    /// Whether the graph has any transactions or outputs in it.
354
    pub fn is_empty(&self) -> bool {
×
355
        self.txs.is_empty()
×
356
    }
×
357
}
358

359
impl<A: Clone + Ord> TxGraph<A> {
360
    /// Construct a new [`TxGraph`] from a list of transactions.
361
    pub fn new(txs: impl IntoIterator<Item = Transaction>) -> Self {
×
362
        let mut new = Self::default();
×
363
        for tx in txs.into_iter() {
×
364
            let _ = new.insert_tx(tx);
×
365
        }
×
366
        new
×
367
    }
×
368

369
    /// Inserts the given [`TxOut`] at [`OutPoint`].
370
    ///
371
    /// Inserting floating txouts are useful for determining fee/feerate of transactions we care
372
    /// about.
373
    ///
374
    /// The [`ChangeSet`] result will be empty if the `outpoint` (or a full transaction containing
375
    /// the `outpoint`) already existed in `self`.
376
    ///
377
    /// [`apply_changeset`]: Self::apply_changeset
378
    pub fn insert_txout(&mut self, outpoint: OutPoint, txout: TxOut) -> ChangeSet<A> {
8✔
379
        let mut update = Self::default();
8✔
380
        update.txs.insert(
8✔
381
            outpoint.txid,
8✔
382
            (
8✔
383
                TxNodeInternal::Partial([(outpoint.vout, txout)].into()),
8✔
384
                BTreeSet::new(),
8✔
385
                0,
8✔
386
            ),
8✔
387
        );
8✔
388
        self.apply_update(update)
8✔
389
    }
8✔
390

391
    /// Inserts the given transaction into [`TxGraph`].
392
    ///
393
    /// The [`ChangeSet`] returned will be empty if `tx` already exists.
394
    pub fn insert_tx(&mut self, tx: Transaction) -> ChangeSet<A> {
204✔
395
        let mut update = Self::default();
204✔
396
        update
204✔
397
            .txs
204✔
398
            .insert(tx.txid(), (TxNodeInternal::Whole(tx), BTreeSet::new(), 0));
204✔
399
        self.apply_update(update)
204✔
400
    }
204✔
401

402
    /// Inserts the given `anchor` into [`TxGraph`].
403
    ///
404
    /// The [`ChangeSet`] returned will be empty if graph already knows that `txid` exists in
405
    /// `anchor`.
406
    pub fn insert_anchor(&mut self, txid: Txid, anchor: A) -> ChangeSet<A> {
159✔
407
        let mut update = Self::default();
159✔
408
        update.anchors.insert((anchor, txid));
159✔
409
        self.apply_update(update)
159✔
410
    }
159✔
411

412
    /// Inserts the given `seen_at` for `txid` into [`TxGraph`].
413
    ///
414
    /// Note that [`TxGraph`] only keeps track of the lastest `seen_at`.
415
    pub fn insert_seen_at(&mut self, txid: Txid, seen_at: u64) -> ChangeSet<A> {
28✔
416
        let mut update = Self::default();
28✔
417
        let (_, _, update_last_seen) = update.txs.entry(txid).or_default();
28✔
418
        *update_last_seen = seen_at;
28✔
419
        self.apply_update(update)
28✔
420
    }
28✔
421

422
    /// Extends this graph with another so that `self` becomes the union of the two sets of
423
    /// transactions.
424
    ///
425
    /// The returned [`ChangeSet`] is the set difference between `update` and `self` (transactions that
426
    /// exist in `update` but not in `self`).
427
    pub fn apply_update(&mut self, update: TxGraph<A>) -> ChangeSet<A> {
569✔
428
        let changeset = self.determine_changeset(update);
569✔
429
        self.apply_changeset(changeset.clone());
569✔
430
        changeset
569✔
431
    }
569✔
432

433
    /// Determines the [`ChangeSet`] between `self` and an empty [`TxGraph`].
434
    pub fn initial_changeset(&self) -> ChangeSet<A> {
2✔
435
        Self::default().determine_changeset(self.clone())
2✔
436
    }
2✔
437

438
    /// Applies [`ChangeSet`] to [`TxGraph`].
439
    pub fn apply_changeset(&mut self, changeset: ChangeSet<A>) {
707✔
440
        for tx in changeset.txs {
1,082✔
441
            let txid = tx.txid();
374✔
442

374✔
443
            tx.input
374✔
444
                .iter()
374✔
445
                .map(|txin| txin.previous_output)
374✔
446
                // coinbase spends are not to be counted
374✔
447
                .filter(|outpoint| !outpoint.is_null())
374✔
448
                // record spend as this tx has spent this outpoint
374✔
449
                .for_each(|outpoint| {
374✔
450
                    self.spends.entry(outpoint).or_default().insert(txid);
70✔
451
                });
374✔
452

374✔
453
            match self.txs.get_mut(&txid) {
374✔
454
                Some((tx_node @ TxNodeInternal::Partial(_), _, _)) => {
1✔
455
                    *tx_node = TxNodeInternal::Whole(tx);
1✔
456
                }
1✔
457
                Some((TxNodeInternal::Whole(tx), _, _)) => {
1✔
458
                    debug_assert_eq!(
459
                        tx.txid(),
1✔
460
                        txid,
461
                        "tx should produce txid that is same as key"
×
462
                    );
463
                }
464
                None => {
373✔
465
                    self.txs
373✔
466
                        .insert(txid, (TxNodeInternal::Whole(tx), BTreeSet::new(), 0));
373✔
467
                }
373✔
468
            }
469
        }
470

471
        for (outpoint, txout) in changeset.txouts {
715✔
472
            let tx_entry = self
7✔
473
                .txs
7✔
474
                .entry(outpoint.txid)
7✔
475
                .or_insert_with(Default::default);
7✔
476

7✔
477
            match tx_entry {
7✔
478
                (TxNodeInternal::Whole(_), _, _) => { /* do nothing since we already have full tx */
×
479
                }
×
480
                (TxNodeInternal::Partial(txouts), _, _) => {
7✔
481
                    txouts.insert(outpoint.vout, txout);
7✔
482
                }
7✔
483
            }
484
        }
485

486
        for (anchor, txid) in changeset.anchors {
1,012✔
487
            if self.anchors.insert((anchor.clone(), txid)) {
304✔
488
                let (_, anchors, _) = self.txs.entry(txid).or_insert_with(Default::default);
302✔
489
                anchors.insert(anchor);
302✔
490
            }
302✔
491
        }
492

493
        for (txid, new_last_seen) in changeset.last_seen {
717✔
494
            let (_, _, last_seen) = self.txs.entry(txid).or_insert_with(Default::default);
9✔
495
            if new_last_seen > *last_seen {
9✔
496
                *last_seen = new_last_seen;
8✔
497
            }
8✔
498
        }
499
    }
708✔
500

501
    /// Previews the resultant [`ChangeSet`] when [`Self`] is updated against the `update` graph.
502
    ///
503
    /// The [`ChangeSet`] would be the set difference between `update` and `self` (transactions that
504
    /// exist in `update` but not in `self`).
505
    pub(crate) fn determine_changeset(&self, update: TxGraph<A>) -> ChangeSet<A> {
571✔
506
        let mut changeset = ChangeSet::default();
571✔
507

508
        for (&txid, (update_tx_node, _, update_last_seen)) in &update.txs {
988✔
509
            let prev_last_seen: u64 = match (self.txs.get(&txid), update_tx_node) {
418✔
510
                (None, TxNodeInternal::Whole(update_tx)) => {
377✔
511
                    changeset.txs.insert(update_tx.clone());
377✔
512
                    0
377✔
513
                }
514
                (None, TxNodeInternal::Partial(update_txos)) => {
7✔
515
                    changeset.txouts.extend(
7✔
516
                        update_txos
7✔
517
                            .iter()
7✔
518
                            .map(|(&vout, txo)| (OutPoint::new(txid, vout), txo.clone())),
8✔
519
                    );
7✔
520
                    0
7✔
521
                }
522
                (Some((TxNodeInternal::Whole(_), _, last_seen)), _) => *last_seen,
29✔
523
                (
524
                    Some((TxNodeInternal::Partial(_), _, last_seen)),
1✔
525
                    TxNodeInternal::Whole(update_tx),
1✔
526
                ) => {
1✔
527
                    changeset.txs.insert(update_tx.clone());
1✔
528
                    *last_seen
1✔
529
                }
530
                (
531
                    Some((TxNodeInternal::Partial(txos), _, last_seen)),
3✔
532
                    TxNodeInternal::Partial(update_txos),
3✔
533
                ) => {
3✔
534
                    changeset.txouts.extend(
3✔
535
                        update_txos
3✔
536
                            .iter()
3✔
537
                            .filter(|(vout, _)| !txos.contains_key(*vout))
3✔
538
                            .map(|(&vout, txo)| (OutPoint::new(txid, vout), txo.clone())),
3✔
539
                    );
3✔
540
                    *last_seen
3✔
541
                }
542
            };
543

544
            if *update_last_seen > prev_last_seen {
417✔
545
                changeset.last_seen.insert(txid, *update_last_seen);
9✔
546
            }
408✔
547
        }
548

549
        changeset.anchors = update.anchors.difference(&self.anchors).cloned().collect();
570✔
550

570✔
551
        changeset
570✔
552
    }
570✔
553
}
554

555
impl<A: Anchor> TxGraph<A> {
556
    /// Find missing block heights of `chain`.
557
    ///
558
    /// This works by scanning through anchors, and seeing whether the anchor block of the anchor
559
    /// exists in the [`LocalChain`]. The returned iterator does not output duplicate heights.
560
    pub fn missing_heights<'a>(&'a self, chain: &'a LocalChain) -> impl Iterator<Item = u32> + 'a {
7✔
561
        // Map of txids to skip.
7✔
562
        //
7✔
563
        // Usually, if a height of a tx anchor is missing from the chain, we would want to return
7✔
564
        // this height in the iterator. The exception is when the tx is confirmed in chain. All the
7✔
565
        // other missing-height anchors of this tx can be skipped.
7✔
566
        //
7✔
567
        // * Some(true)  => skip all anchors of this txid
7✔
568
        // * Some(false) => do not skip anchors of this txid
7✔
569
        // * None        => we do not know whether we can skip this txid
7✔
570
        let mut txids_to_skip = HashMap::<Txid, bool>::new();
7✔
571

7✔
572
        // Keeps track of the last height emitted so we don't double up.
7✔
573
        let mut last_height_emitted = Option::<u32>::None;
7✔
574

7✔
575
        self.anchors
7✔
576
            .iter()
7✔
577
            .filter(move |(_, txid)| {
14✔
578
                let skip = *txids_to_skip.entry(*txid).or_insert_with(|| {
14✔
579
                    let tx_anchors = match self.txs.get(txid) {
9✔
580
                        Some((_, anchors, _)) => anchors,
9✔
581
                        None => return true,
×
582
                    };
583
                    let mut has_missing_height = false;
9✔
584
                    for anchor_block in tx_anchors.iter().map(Anchor::anchor_block) {
14✔
585
                        match chain.blocks().get(&anchor_block.height) {
14✔
586
                            None => {
587
                                has_missing_height = true;
8✔
588
                                continue;
8✔
589
                            }
590
                            Some(chain_hash) => {
6✔
591
                                if chain_hash == &anchor_block.hash {
6✔
592
                                    return true;
2✔
593
                                }
4✔
594
                            }
595
                        }
596
                    }
597
                    !has_missing_height
7✔
598
                });
14✔
599
                #[cfg(feature = "std")]
600
                debug_assert!({
601
                    println!("txid={} skip={}", txid, skip);
14✔
602
                    true
14✔
603
                });
604
                !skip
14✔
605
            })
14✔
606
            .filter_map(move |(a, _)| {
8✔
607
                let anchor_block = a.anchor_block();
8✔
608
                if Some(anchor_block.height) != last_height_emitted
8✔
609
                    && !chain.blocks().contains_key(&anchor_block.height)
6✔
610
                {
611
                    last_height_emitted = Some(anchor_block.height);
5✔
612
                    Some(anchor_block.height)
5✔
613
                } else {
614
                    None
3✔
615
                }
616
            })
8✔
617
    }
7✔
618

619
    /// Get the position of the transaction in `chain` with tip `chain_tip`.
620
    ///
621
    /// If the given transaction of `txid` does not exist in the chain of `chain_tip`, `None` is
622
    /// returned.
623
    ///
624
    /// # Error
625
    ///
626
    /// An error will occur if the [`ChainOracle`] implementation (`chain`) fails. If the
627
    /// [`ChainOracle`] is infallible, [`get_chain_position`] can be used instead.
628
    ///
629
    /// [`get_chain_position`]: Self::get_chain_position
630
    pub fn try_get_chain_position<C: ChainOracle>(
759✔
631
        &self,
759✔
632
        chain: &C,
759✔
633
        chain_tip: BlockId,
759✔
634
        txid: Txid,
759✔
635
    ) -> Result<Option<ChainPosition<&A>>, C::Error> {
759✔
636
        let (tx_node, anchors, last_seen) = match self.txs.get(&txid) {
759✔
637
            Some(v) => v,
756✔
638
            None => return Ok(None),
3✔
639
        };
640

641
        for anchor in anchors {
780✔
642
            match chain.is_block_in_chain(anchor.anchor_block(), chain_tip)? {
616✔
643
                Some(true) => return Ok(Some(ChainPosition::Confirmed(anchor))),
592✔
644
                _ => continue,
24✔
645
            }
646
        }
647

648
        // The tx is not anchored to a block which is in the best chain, let's check whether we can
649
        // ignore it by checking conflicts!
650
        let tx = match tx_node {
164✔
651
            TxNodeInternal::Whole(tx) => tx,
164✔
652
            TxNodeInternal::Partial(_) => {
653
                // Partial transactions (outputs only) cannot have conflicts.
654
                return Ok(None);
×
655
            }
656
        };
657

658
        // If a conflicting tx is in the best chain, or has `last_seen` higher than this tx, then
659
        // this tx cannot exist in the best chain
660
        for conflicting_tx in self.walk_conflicts(tx, |_, txid| self.get_tx_node(txid)) {
164✔
661
            for block in conflicting_tx.anchors.iter().map(A::anchor_block) {
4✔
662
                if chain.is_block_in_chain(block, chain_tip)? == Some(true) {
1✔
663
                    // conflicting tx is in best chain, so the current tx cannot be in best chain!
664
                    return Ok(None);
1✔
665
                }
×
666
            }
667
            if conflicting_tx.last_seen_unconfirmed > *last_seen {
3✔
668
                return Ok(None);
1✔
669
            }
2✔
670
        }
671

672
        Ok(Some(ChainPosition::Unconfirmed(*last_seen)))
162✔
673
    }
759✔
674

675
    /// Get the position of the transaction in `chain` with tip `chain_tip`.
676
    ///
677
    /// This is the infallible version of [`try_get_chain_position`].
678
    ///
679
    /// [`try_get_chain_position`]: Self::try_get_chain_position
680
    pub fn get_chain_position<C: ChainOracle<Error = Infallible>>(
208✔
681
        &self,
208✔
682
        chain: &C,
208✔
683
        chain_tip: BlockId,
208✔
684
        txid: Txid,
208✔
685
    ) -> Option<ChainPosition<&A>> {
208✔
686
        self.try_get_chain_position(chain, chain_tip, txid)
208✔
687
            .expect("error is infallible")
208✔
688
    }
208✔
689

690
    /// Get the txid of the spending transaction and where the spending transaction is observed in
691
    /// the `chain` of `chain_tip`.
692
    ///
693
    /// If no in-chain transaction spends `outpoint`, `None` will be returned.
694
    ///
695
    /// # Error
696
    ///
697
    /// An error will occur only if the [`ChainOracle`] implementation (`chain`) fails.
698
    ///
699
    /// If the [`ChainOracle`] is infallible, [`get_chain_spend`] can be used instead.
700
    ///
701
    /// [`get_chain_spend`]: Self::get_chain_spend
702
    pub fn try_get_chain_spend<C: ChainOracle>(
257✔
703
        &self,
257✔
704
        chain: &C,
257✔
705
        chain_tip: BlockId,
257✔
706
        outpoint: OutPoint,
257✔
707
    ) -> Result<Option<(ChainPosition<&A>, Txid)>, C::Error> {
257✔
708
        if self
257✔
709
            .try_get_chain_position(chain, chain_tip, outpoint.txid)?
257✔
710
            .is_none()
257✔
711
        {
712
            return Ok(None);
×
713
        }
257✔
714
        if let Some(spends) = self.spends.get(&outpoint) {
257✔
715
            for &txid in spends {
34✔
716
                if let Some(observed_at) = self.try_get_chain_position(chain, chain_tip, txid)? {
34✔
717
                    return Ok(Some((observed_at, txid)));
34✔
718
                }
×
719
            }
720
        }
223✔
721
        Ok(None)
223✔
722
    }
257✔
723

724
    /// Get the txid of the spending transaction and where the spending transaction is observed in
725
    /// the `chain` of `chain_tip`.
726
    ///
727
    /// This is the infallible version of [`try_get_chain_spend`]
728
    ///
729
    /// [`try_get_chain_spend`]: Self::try_get_chain_spend
730
    pub fn get_chain_spend<C: ChainOracle<Error = Infallible>>(
4✔
731
        &self,
4✔
732
        chain: &C,
4✔
733
        static_block: BlockId,
4✔
734
        outpoint: OutPoint,
4✔
735
    ) -> Option<(ChainPosition<&A>, Txid)> {
4✔
736
        self.try_get_chain_spend(chain, static_block, outpoint)
4✔
737
            .expect("error is infallible")
4✔
738
    }
4✔
739

740
    /// List graph transactions that are in `chain` with `chain_tip`.
741
    ///
742
    /// Each transaction is represented as a [`CanonicalTx`] that contains where the transaction is
743
    /// observed in-chain, and the [`TxNode`].
744
    ///
745
    /// # Error
746
    ///
747
    /// If the [`ChainOracle`] implementation (`chain`) fails, an error will be returned with the
748
    /// returned item.
749
    ///
750
    /// If the [`ChainOracle`] is infallible, [`list_chain_txs`] can be used instead.
751
    ///
752
    /// [`list_chain_txs`]: Self::list_chain_txs
753
    pub fn try_list_chain_txs<'a, C: ChainOracle + 'a>(
7✔
754
        &'a self,
7✔
755
        chain: &'a C,
7✔
756
        chain_tip: BlockId,
7✔
757
    ) -> impl Iterator<Item = Result<CanonicalTx<'a, Transaction, A>, C::Error>> {
7✔
758
        self.full_txs().filter_map(move |tx| {
7✔
759
            self.try_get_chain_position(chain, chain_tip, tx.txid)
7✔
760
                .map(|v| {
7✔
761
                    v.map(|observed_in| CanonicalTx {
7✔
762
                        chain_position: observed_in,
7✔
763
                        tx_node: tx,
7✔
764
                    })
7✔
765
                })
7✔
766
                .transpose()
7✔
767
        })
7✔
768
    }
7✔
769

770
    /// List graph transactions that are in `chain` with `chain_tip`.
771
    ///
772
    /// This is the infallible version of [`try_list_chain_txs`].
773
    ///
774
    /// [`try_list_chain_txs`]: Self::try_list_chain_txs
775
    pub fn list_chain_txs<'a, C: ChainOracle + 'a>(
7✔
776
        &'a self,
7✔
777
        chain: &'a C,
7✔
778
        chain_tip: BlockId,
7✔
779
    ) -> impl Iterator<Item = CanonicalTx<'a, Transaction, A>> {
7✔
780
        self.try_list_chain_txs(chain, chain_tip)
7✔
781
            .map(|r| r.expect("oracle is infallible"))
7✔
782
    }
7✔
783

784
    /// Get a filtered list of outputs from the given `outpoints` that are in `chain` with
785
    /// `chain_tip`.
786
    ///
787
    /// `outpoints` is a list of outpoints we are interested in, coupled with an outpoint identifier
788
    /// (`OI`) for convenience. If `OI` is not necessary, the caller can use `()`, or
789
    /// [`Iterator::enumerate`] over a list of [`OutPoint`]s.
790
    ///
791
    /// Floating outputs are ignored.
792
    ///
793
    /// # Error
794
    ///
795
    /// An [`Iterator::Item`] can be an [`Err`] if the [`ChainOracle`] implementation (`chain`)
796
    /// fails.
797
    ///
798
    /// If the [`ChainOracle`] implementation is infallible, [`filter_chain_txouts`] can be used
799
    /// instead.
800
    ///
801
    /// [`filter_chain_txouts`]: Self::filter_chain_txouts
802
    pub fn try_filter_chain_txouts<'a, C: ChainOracle + 'a, OI: Clone + 'a>(
164✔
803
        &'a self,
164✔
804
        chain: &'a C,
164✔
805
        chain_tip: BlockId,
164✔
806
        outpoints: impl IntoIterator<Item = (OI, OutPoint)> + 'a,
164✔
807
    ) -> impl Iterator<Item = Result<(OI, FullTxOut<A>), C::Error>> + 'a {
164✔
808
        outpoints
164✔
809
            .into_iter()
164✔
810
            .map(
164✔
811
                move |(spk_i, op)| -> Result<Option<(OI, FullTxOut<_>)>, C::Error> {
164✔
812
                    let tx_node = match self.get_tx_node(op.txid) {
253✔
813
                        Some(n) => n,
253✔
814
                        None => return Ok(None),
×
815
                    };
816

817
                    let txout = match tx_node.tx.output.get(op.vout as usize) {
253✔
818
                        Some(txout) => txout.clone(),
253✔
819
                        None => return Ok(None),
×
820
                    };
821

822
                    let chain_position =
253✔
823
                        match self.try_get_chain_position(chain, chain_tip, op.txid)? {
253✔
824
                            Some(pos) => pos.cloned(),
253✔
825
                            None => return Ok(None),
×
826
                        };
827

828
                    let spent_by = self
253✔
829
                        .try_get_chain_spend(chain, chain_tip, op)?
253✔
830
                        .map(|(a, txid)| (a.cloned(), txid));
253✔
831

253✔
832
                    Ok(Some((
253✔
833
                        spk_i,
253✔
834
                        FullTxOut {
253✔
835
                            outpoint: op,
253✔
836
                            txout,
253✔
837
                            chain_position,
253✔
838
                            spent_by,
253✔
839
                            is_on_coinbase: tx_node.tx.is_coin_base(),
253✔
840
                        },
253✔
841
                    )))
253✔
842
                },
253✔
843
            )
164✔
844
            .filter_map(Result::transpose)
164✔
845
    }
164✔
846

847
    /// Get a filtered list of outputs from the given `outpoints` that are in `chain` with
848
    /// `chain_tip`.
849
    ///
850
    /// This is the infallible version of [`try_filter_chain_txouts`].
851
    ///
852
    /// [`try_filter_chain_txouts`]: Self::try_filter_chain_txouts
853
    pub fn filter_chain_txouts<'a, C: ChainOracle<Error = Infallible> + 'a, OI: Clone + 'a>(
5✔
854
        &'a self,
5✔
855
        chain: &'a C,
5✔
856
        chain_tip: BlockId,
5✔
857
        outpoints: impl IntoIterator<Item = (OI, OutPoint)> + 'a,
5✔
858
    ) -> impl Iterator<Item = (OI, FullTxOut<A>)> + 'a {
5✔
859
        self.try_filter_chain_txouts(chain, chain_tip, outpoints)
5✔
860
            .map(|r| r.expect("oracle is infallible"))
25✔
861
    }
5✔
862

863
    /// Get a filtered list of unspent outputs (UTXOs) from the given `outpoints` that are in
864
    /// `chain` with `chain_tip`.
865
    ///
866
    /// `outpoints` is a list of outpoints we are interested in, coupled with an outpoint identifier
867
    /// (`OI`) for convenience. If `OI` is not necessary, the caller can use `()`, or
868
    /// [`Iterator::enumerate`] over a list of [`OutPoint`]s.
869
    ///
870
    /// Floating outputs are ignored.
871
    ///
872
    /// # Error
873
    ///
874
    /// An [`Iterator::Item`] can be an [`Err`] if the [`ChainOracle`] implementation (`chain`)
875
    /// fails.
876
    ///
877
    /// If the [`ChainOracle`] implementation is infallible, [`filter_chain_unspents`] can be used
878
    /// instead.
879
    ///
880
    /// [`filter_chain_unspents`]: Self::filter_chain_unspents
881
    pub fn try_filter_chain_unspents<'a, C: ChainOracle + 'a, OI: Clone + 'a>(
159✔
882
        &'a self,
159✔
883
        chain: &'a C,
159✔
884
        chain_tip: BlockId,
159✔
885
        outpoints: impl IntoIterator<Item = (OI, OutPoint)> + 'a,
159✔
886
    ) -> impl Iterator<Item = Result<(OI, FullTxOut<A>), C::Error>> + 'a {
159✔
887
        self.try_filter_chain_txouts(chain, chain_tip, outpoints)
159✔
888
            .filter(|r| match r {
228✔
889
                // keep unspents, drop spents
890
                Ok((_, full_txo)) => full_txo.spent_by.is_none(),
228✔
891
                // keep errors
892
                Err(_) => true,
×
893
            })
228✔
894
    }
159✔
895

896
    /// Get a filtered list of unspent outputs (UTXOs) from the given `outpoints` that are in
897
    /// `chain` with `chain_tip`.
898
    ///
899
    /// This is the infallible version of [`try_filter_chain_unspents`].
900
    ///
901
    /// [`try_filter_chain_unspents`]: Self::try_filter_chain_unspents
902
    pub fn filter_chain_unspents<'a, C: ChainOracle<Error = Infallible> + 'a, OI: Clone + 'a>(
151✔
903
        &'a self,
151✔
904
        chain: &'a C,
151✔
905
        chain_tip: BlockId,
151✔
906
        txouts: impl IntoIterator<Item = (OI, OutPoint)> + 'a,
151✔
907
    ) -> impl Iterator<Item = (OI, FullTxOut<A>)> + 'a {
151✔
908
        self.try_filter_chain_unspents(chain, chain_tip, txouts)
151✔
909
            .map(|r| r.expect("oracle is infallible"))
180✔
910
    }
151✔
911

912
    /// Get the total balance of `outpoints` that are in `chain` of `chain_tip`.
913
    ///
914
    /// The output of `trust_predicate` should return `true` for scripts that we trust.
915
    ///
916
    /// `outpoints` is a list of outpoints we are interested in, coupled with an outpoint identifier
917
    /// (`OI`) for convenience. If `OI` is not necessary, the caller can use `()`, or
918
    /// [`Iterator::enumerate`] over a list of [`OutPoint`]s.
919
    ///
920
    /// If the provided [`ChainOracle`] implementation (`chain`) is infallible, [`balance`] can be
921
    /// used instead.
922
    ///
923
    /// [`balance`]: Self::balance
924
    pub fn try_balance<C: ChainOracle, OI: Clone>(
8✔
925
        &self,
8✔
926
        chain: &C,
8✔
927
        chain_tip: BlockId,
8✔
928
        outpoints: impl IntoIterator<Item = (OI, OutPoint)>,
8✔
929
        mut trust_predicate: impl FnMut(&OI, &Script) -> bool,
8✔
930
    ) -> Result<Balance, C::Error> {
8✔
931
        let mut immature = 0;
8✔
932
        let mut trusted_pending = 0;
8✔
933
        let mut untrusted_pending = 0;
8✔
934
        let mut confirmed = 0;
8✔
935

936
        for res in self.try_filter_chain_unspents(chain, chain_tip, outpoints) {
23✔
937
            let (spk_i, txout) = res?;
23✔
938

939
            match &txout.chain_position {
23✔
940
                ChainPosition::Confirmed(_) => {
941
                    if txout.is_confirmed_and_spendable(chain_tip.height) {
11✔
942
                        confirmed += txout.txout.value;
6✔
943
                    } else if !txout.is_mature(chain_tip.height) {
6✔
944
                        immature += txout.txout.value;
5✔
945
                    }
5✔
946
                }
947
                ChainPosition::Unconfirmed(_) => {
948
                    if trust_predicate(&spk_i, &txout.txout.script_pubkey) {
12✔
949
                        trusted_pending += txout.txout.value;
7✔
950
                    } else {
7✔
951
                        untrusted_pending += txout.txout.value;
5✔
952
                    }
5✔
953
                }
954
            }
955
        }
956

957
        Ok(Balance {
8✔
958
            immature,
8✔
959
            trusted_pending,
8✔
960
            untrusted_pending,
8✔
961
            confirmed,
8✔
962
        })
8✔
963
    }
8✔
964

965
    /// Get the total balance of `outpoints` that are in `chain` of `chain_tip`.
966
    ///
967
    /// This is the infallible version of [`try_balance`].
968
    ///
969
    /// [`try_balance`]: Self::try_balance
970
    pub fn balance<C: ChainOracle<Error = Infallible>, OI: Clone>(
8✔
971
        &self,
8✔
972
        chain: &C,
8✔
973
        chain_tip: BlockId,
8✔
974
        outpoints: impl IntoIterator<Item = (OI, OutPoint)>,
8✔
975
        trust_predicate: impl FnMut(&OI, &Script) -> bool,
8✔
976
    ) -> Balance {
8✔
977
        self.try_balance(chain, chain_tip, outpoints, trust_predicate)
8✔
978
            .expect("oracle is infallible")
8✔
979
    }
8✔
980
}
981

982
/// A structure that represents changes to a [`TxGraph`].
983
///
984
/// Since [`TxGraph`] is monotone "changeset" can only contain transactions to be added and
985
/// not removed.
986
///
987
/// Refer to [module-level documentation] for more.
988
///
989
/// [module-level documentation]: crate::tx_graph
990
#[derive(Debug, Clone, PartialEq)]
569✔
991
#[cfg_attr(
992
    feature = "serde",
993
    derive(serde::Deserialize, serde::Serialize),
×
994
    serde(
995
        crate = "serde_crate",
996
        bound(
997
            deserialize = "A: Ord + serde::Deserialize<'de>",
998
            serialize = "A: Ord + serde::Serialize",
999
        )
1000
    )
1001
)]
1002
#[must_use]
1003
pub struct ChangeSet<A = ()> {
1004
    /// Added transactions.
1005
    pub txs: BTreeSet<Transaction>,
1006
    /// Added txouts.
1007
    pub txouts: BTreeMap<OutPoint, TxOut>,
1008
    /// Added anchors.
1009
    pub anchors: BTreeSet<(A, Txid)>,
1010
    /// Added last-seen unix timestamps of transactions.
1011
    pub last_seen: BTreeMap<Txid, u64>,
1012
}
1013

1014
impl<A> Default for ChangeSet<A> {
1015
    fn default() -> Self {
2,080✔
1016
        Self {
2,080✔
1017
            txs: Default::default(),
2,080✔
1018
            txouts: Default::default(),
2,080✔
1019
            anchors: Default::default(),
2,080✔
1020
            last_seen: Default::default(),
2,080✔
1021
        }
2,080✔
1022
    }
2,080✔
1023
}
1024

1025
impl<A> ChangeSet<A> {
1026
    /// Returns true if the [`ChangeSet`] is empty (no transactions or txouts).
1027
    pub fn is_empty(&self) -> bool {
374✔
1028
        self.txs.is_empty() && self.txouts.is_empty()
374✔
1029
    }
374✔
1030

1031
    /// Iterates over all outpoints contained within [`ChangeSet`].
1032
    pub fn txouts(&self) -> impl Iterator<Item = (OutPoint, &TxOut)> {
×
1033
        self.txs
×
1034
            .iter()
×
1035
            .flat_map(|tx| {
×
1036
                tx.output
×
1037
                    .iter()
×
1038
                    .enumerate()
×
1039
                    .map(move |(vout, txout)| (OutPoint::new(tx.txid(), vout as _), txout))
×
1040
            })
×
1041
            .chain(self.txouts.iter().map(|(op, txout)| (*op, txout)))
×
1042
    }
×
1043
}
1044

1045
impl<A: Ord> Append for ChangeSet<A> {
1046
    fn append(&mut self, mut other: Self) {
630✔
1047
        self.txs.append(&mut other.txs);
630✔
1048
        self.txouts.append(&mut other.txouts);
630✔
1049
        self.anchors.append(&mut other.anchors);
630✔
1050

630✔
1051
        // last_seen timestamps should only increase
630✔
1052
        self.last_seen.extend(
630✔
1053
            other
630✔
1054
                .last_seen
630✔
1055
                .into_iter()
630✔
1056
                .filter(|(txid, update_ls)| self.last_seen.get(txid) < Some(update_ls))
630✔
1057
                .collect::<Vec<_>>(),
630✔
1058
        );
630✔
1059
    }
630✔
1060

1061
    fn is_empty(&self) -> bool {
×
1062
        self.txs.is_empty()
×
1063
            && self.txouts.is_empty()
×
1064
            && self.anchors.is_empty()
×
1065
            && self.last_seen.is_empty()
×
1066
    }
×
1067
}
1068

1069
impl<A> AsRef<TxGraph<A>> for TxGraph<A> {
1070
    fn as_ref(&self) -> &TxGraph<A> {
×
1071
        self
×
1072
    }
×
1073
}
1074

1075
impl<A> ForEachTxOut for ChangeSet<A> {
1076
    fn for_each_txout(&self, f: impl FnMut((OutPoint, &TxOut))) {
×
1077
        self.txouts().for_each(f)
×
1078
    }
×
1079
}
1080

1081
impl<A> ForEachTxOut for TxGraph<A> {
1082
    fn for_each_txout(&self, f: impl FnMut((OutPoint, &TxOut))) {
×
1083
        self.all_txouts().for_each(f)
×
1084
    }
×
1085
}
1086

1087
/// An iterator that traverses transaction descendants.
1088
///
1089
/// This `struct` is created by the [`walk_descendants`] method of [`TxGraph`].
1090
///
1091
/// [`walk_descendants`]: TxGraph::walk_descendants
1092
pub struct TxDescendants<'g, A, F> {
1093
    graph: &'g TxGraph<A>,
1094
    visited: HashSet<Txid>,
1095
    stack: Vec<(usize, Txid)>,
1096
    filter_map: F,
1097
}
1098

1099
impl<'g, A, F> TxDescendants<'g, A, F> {
1100
    /// Creates a `TxDescendants` that includes the starting `txid` when iterating.
1101
    #[allow(unused)]
1102
    pub(crate) fn new_include_root(graph: &'g TxGraph<A>, txid: Txid, filter_map: F) -> Self {
×
1103
        Self {
×
1104
            graph,
×
1105
            visited: Default::default(),
×
1106
            stack: [(0, txid)].into(),
×
1107
            filter_map,
×
1108
        }
×
1109
    }
×
1110

1111
    /// Creates a `TxDescendants` that excludes the starting `txid` when iterating.
1112
    pub(crate) fn new_exclude_root(graph: &'g TxGraph<A>, txid: Txid, filter_map: F) -> Self {
1✔
1113
        let mut descendants = Self {
1✔
1114
            graph,
1✔
1115
            visited: Default::default(),
1✔
1116
            stack: Default::default(),
1✔
1117
            filter_map,
1✔
1118
        };
1✔
1119
        descendants.populate_stack(1, txid);
1✔
1120
        descendants
1✔
1121
    }
1✔
1122

1123
    /// Creates a `TxDescendants` from multiple starting transactions that include the starting
1124
    /// `txid`s when iterating.
1125
    pub(crate) fn from_multiple_include_root<I>(
165✔
1126
        graph: &'g TxGraph<A>,
165✔
1127
        txids: I,
165✔
1128
        filter_map: F,
165✔
1129
    ) -> Self
165✔
1130
    where
165✔
1131
        I: IntoIterator<Item = Txid>,
165✔
1132
    {
165✔
1133
        Self {
165✔
1134
            graph,
165✔
1135
            visited: Default::default(),
165✔
1136
            stack: txids.into_iter().map(|txid| (0, txid)).collect(),
165✔
1137
            filter_map,
165✔
1138
        }
165✔
1139
    }
165✔
1140

1141
    /// Creates a `TxDescendants` from multiple starting transactions that excludes the starting
1142
    /// `txid`s when iterating.
1143
    #[allow(unused)]
1144
    pub(crate) fn from_multiple_exclude_root<I>(
×
1145
        graph: &'g TxGraph<A>,
×
1146
        txids: I,
×
1147
        filter_map: F,
×
1148
    ) -> Self
×
1149
    where
×
1150
        I: IntoIterator<Item = Txid>,
×
1151
    {
×
1152
        let mut descendants = Self {
×
1153
            graph,
×
1154
            visited: Default::default(),
×
1155
            stack: Default::default(),
×
1156
            filter_map,
×
1157
        };
×
1158
        for txid in txids {
×
1159
            descendants.populate_stack(1, txid);
×
1160
        }
×
1161
        descendants
×
1162
    }
×
1163
}
1164

1165
impl<'g, A, F> TxDescendants<'g, A, F> {
1166
    fn populate_stack(&mut self, depth: usize, txid: Txid) {
14✔
1167
        let spend_paths = self
14✔
1168
            .graph
14✔
1169
            .spends
14✔
1170
            .range(tx_outpoint_range(txid))
14✔
1171
            .flat_map(|(_, spends)| spends)
14✔
1172
            .map(|&txid| (depth, txid));
14✔
1173
        self.stack.extend(spend_paths);
14✔
1174
    }
14✔
1175
}
1176

1177
impl<'g, A, F, O> Iterator for TxDescendants<'g, A, F>
1178
where
1179
    F: FnMut(usize, Txid) -> Option<O>,
1180
{
1181
    type Item = O;
1182

1183
    fn next(&mut self) -> Option<Self::Item> {
177✔
1184
        let (op_spends, txid, item) = loop {
13✔
1185
            // we have exhausted all paths when stack is empty
1186
            let (op_spends, txid) = self.stack.pop()?;
178✔
1187
            // we do not want to visit the same transaction twice
1188
            if self.visited.insert(txid) {
14✔
1189
                // ignore paths when user filters them out
1190
                if let Some(item) = (self.filter_map)(op_spends, txid) {
13✔
1191
                    break (op_spends, txid, item);
13✔
1192
                }
×
1193
            }
1✔
1194
        };
1195

1196
        self.populate_stack(op_spends + 1, txid);
13✔
1197
        Some(item)
13✔
1198
    }
177✔
1199
}
1200

1201
fn tx_outpoint_range(txid: Txid) -> RangeInclusive<OutPoint> {
182✔
1202
    OutPoint::new(txid, u32::MIN)..=OutPoint::new(txid, u32::MAX)
182✔
1203
}
182✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc