Skip to content

Commit 1196405

Browse files
committed
refactor(chain): Reorganize TxGraph::insert_anchor logic for clarity
1 parent 4706315 commit 1196405

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

crates/chain/src/tx_graph.rs

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -634,20 +634,25 @@ impl<A: Anchor> TxGraph<A> {
634634
/// The [`ChangeSet`] returned will be empty if graph already knows that `txid` exists in
635635
/// `anchor`.
636636
pub fn insert_anchor(&mut self, txid: Txid, anchor: A) -> ChangeSet<A> {
637+
// These two variables are used to determine how to modify the `txid`'s entry in
638+
// `txs_by_highest_conf_heights`.
639+
// We want to remove `(old_top_h?, txid)` and insert `(new_top_h?, txid)`.
637640
let mut old_top_h = None;
638641
let mut new_top_h = anchor.confirmation_height_upper_bound();
639642

640643
let is_changed = match self.anchors.entry(txid) {
641644
hash_map::Entry::Occupied(mut e) => {
642-
fn top_anchor_height<A: Anchor>(anchors: &BTreeSet<A>) -> Option<u32> {
643-
anchors
644-
.iter()
645-
.last()
646-
.map(Anchor::confirmation_height_upper_bound)
645+
old_top_h = e
646+
.get()
647+
.iter()
648+
.last()
649+
.map(Anchor::confirmation_height_upper_bound);
650+
if let Some(old_top_h) = old_top_h {
651+
if old_top_h > new_top_h {
652+
new_top_h = old_top_h;
653+
}
647654
}
648-
old_top_h = top_anchor_height(e.get());
649655
let is_changed = e.get_mut().insert(anchor.clone());
650-
new_top_h = top_anchor_height(e.get()).expect("must have anchor");
651656
is_changed
652657
}
653658
hash_map::Entry::Vacant(e) => {
@@ -658,7 +663,12 @@ impl<A: Anchor> TxGraph<A> {
658663

659664
let mut changeset = ChangeSet::<A>::default();
660665
if is_changed {
661-
if old_top_h != Some(new_top_h) {
666+
let new_top_is_changed = match old_top_h {
667+
None => true,
668+
Some(old_top_h) if old_top_h != new_top_h => true,
669+
_ => false,
670+
};
671+
if new_top_is_changed {
662672
if let Some(prev_top_h) = old_top_h {
663673
self.txs_by_highest_conf_heights.remove(&(prev_top_h, txid));
664674
}

0 commit comments

Comments
 (0)