Skip to content

Commit c9dd821

Browse files
committed
feat(tx_graph): Add method update_last_seen_unconfirmed
That accepts a `u64` as param representing the latest timestamp and internally calls `insert_seen_at` for all transactions in graph that aren't yet anchored in a confirmed block.
1 parent b5557dc commit c9dd821

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

crates/chain/src/tx_graph.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -549,6 +549,32 @@ impl<A: Clone + Ord> TxGraph<A> {
549549
self.apply_update(update)
550550
}
551551

552+
/// Update the last seen unconfirmed time for all unanchored transactions.
553+
///
554+
/// Returns the [`ChangeSet`] after applying any updates to `self`. Note that
555+
/// [`TxGraph`] only keeps track of the latest `seen_at`.
556+
pub fn update_last_seen_unconfirmed(&mut self, seen_at: u64) -> ChangeSet<A> {
557+
let mut changeset = ChangeSet::default();
558+
let unanchored_txs: Vec<Txid> = self
559+
.txs
560+
.iter()
561+
.filter_map(
562+
|(&txid, (_, anchors, _))| {
563+
if anchors.is_empty() {
564+
Some(txid)
565+
} else {
566+
None
567+
}
568+
},
569+
)
570+
.collect();
571+
572+
for txid in unanchored_txs {
573+
changeset.append(self.insert_seen_at(txid, seen_at));
574+
}
575+
changeset
576+
}
577+
552578
/// Extends this graph with another so that `self` becomes the union of the two sets of
553579
/// transactions.
554580
///

crates/chain/tests/test_tx_graph.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1048,6 +1048,34 @@ fn test_changeset_last_seen_append() {
10481048
}
10491049
}
10501050

1051+
#[test]
1052+
fn update_last_seen_unconfirmed() {
1053+
let mut graph = TxGraph::<()>::default();
1054+
let tx = new_tx(0);
1055+
let txid = tx.txid();
1056+
1057+
// insert a new tx
1058+
// initially we have a last_seen of 0, and no anchors
1059+
let _ = graph.insert_tx(tx);
1060+
let tx = graph.full_txs().next().unwrap();
1061+
assert_eq!(tx.last_seen_unconfirmed, 0);
1062+
assert!(tx.anchors.is_empty());
1063+
1064+
// higher timestamp should update last seen
1065+
let changeset = graph.update_last_seen_unconfirmed(2);
1066+
assert_eq!(changeset.last_seen.get(&txid).unwrap(), &2);
1067+
1068+
// lower timestamp has no effect
1069+
let changeset = graph.update_last_seen_unconfirmed(1);
1070+
assert!(changeset.last_seen.is_empty());
1071+
1072+
// once anchored, last seen is not updated
1073+
let _ = graph.insert_anchor(txid, ());
1074+
let changeset = graph.update_last_seen_unconfirmed(4);
1075+
assert!(changeset.is_empty());
1076+
assert_eq!(graph.full_txs().next().unwrap().last_seen_unconfirmed, 2);
1077+
}
1078+
10511079
#[test]
10521080
fn test_missing_blocks() {
10531081
/// An anchor implementation for testing, made up of `(the_anchor_block, random_data)`.

0 commit comments

Comments
 (0)