Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions crates/chain/src/chain_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,19 @@ impl<A: Anchor> ChainPosition<A> {
ChainPosition::Unconfirmed { .. } => None,
}
}

/// Number of blocks mined on top of this position's confirmation block, given `tip`.
///
/// Returns `None` if unconfirmed, or if the confirmation height is above `tip`.
pub fn blocks_since_conf(&self, tip: u32) -> Option<u32> {
let height = self.confirmation_height_upper_bound()?;

if height > tip {
return None;
}

Some(tip - height)
}
}

/// Ordering for `ChainPosition`:
Expand Down Expand Up @@ -335,4 +348,29 @@ mod test {
]
);
}

#[test]
fn test_blocks_since_conf() {
let confirmed_at = |height: u32| ChainPosition::Confirmed {
anchor: ConfirmationBlockTime {
confirmation_time: 0,
block_id: BlockId {
height,
..Default::default()
},
},
transitively: None,
};

assert_eq!(confirmed_at(100).blocks_since_conf(100), Some(0));
assert_eq!(confirmed_at(99).blocks_since_conf(100), Some(1));
assert_eq!(confirmed_at(90).blocks_since_conf(100), Some(10));
assert_eq!(confirmed_at(101).blocks_since_conf(100), None);

let unconfirmed = ChainPosition::<ConfirmationBlockTime>::Unconfirmed {
first_seen: Some(1),
last_seen: Some(2),
};
assert_eq!(unconfirmed.blocks_since_conf(100), None);
}
}