]> Untitled Git - bdk/commitdiff
[bdk_chain_redesign] Add tests for `TxGraph::relevant_heights`
author志宇 <hello@evanlinjin.me>
Wed, 19 Apr 2023 08:14:52 +0000 (16:14 +0800)
committer志宇 <hello@evanlinjin.me>
Wed, 19 Apr 2023 08:14:52 +0000 (16:14 +0800)
crates/chain/src/tx_graph.rs
crates/chain/tests/test_tx_graph.rs

index 5d06bbda658ca8964892ccf5608dfddb2e37a374..e16ae88d60adec6afc8fe5f7dd420a939ccff737 100644 (file)
@@ -602,7 +602,7 @@ impl<A: Clone + Ord> TxGraph<A> {
 
 impl<A: Anchor> TxGraph<A> {
     /// Get all heights that are relevant to the graph.
-    pub fn relevant_heights(&self) -> impl Iterator<Item = u32> + '_ {
+    pub fn relevant_heights(&self) -> impl DoubleEndedIterator<Item = u32> + '_ {
         let mut visited = HashSet::new();
         self.anchors
             .iter()
index 965bb25953d55b59c39eb8a3982435505b58694c..20b3e27ff93461fd1dd690c7a043d5432e2b31d6 100644 (file)
@@ -10,6 +10,7 @@ use bitcoin::{
     hashes::Hash, BlockHash, OutPoint, PackedLockTime, Script, Transaction, TxIn, TxOut, Txid,
 };
 use core::iter;
+use std::vec;
 
 #[test]
 fn insert_txouts() {
@@ -781,3 +782,70 @@ fn test_chain_spends() {
         .get_chain_position(&local_chain, tip, tx_2.txid())
         .is_none());
 }
+
+#[test]
+fn test_relevant_heights() {
+    let mut graph = TxGraph::<BlockId>::default();
+
+    let tx1 = common::new_tx(1);
+    let tx2 = common::new_tx(2);
+
+    let _ = graph.insert_tx(tx1.clone());
+    assert_eq!(
+        graph.relevant_heights().collect::<Vec<_>>(),
+        vec![],
+        "no anchors in graph"
+    );
+
+    let _ = graph.insert_anchor(
+        tx1.txid(),
+        BlockId {
+            height: 3,
+            hash: h!("3a"),
+        },
+    );
+    assert_eq!(
+        graph.relevant_heights().collect::<Vec<_>>(),
+        vec![3],
+        "one anchor at height 3"
+    );
+
+    let _ = graph.insert_anchor(
+        tx1.txid(),
+        BlockId {
+            height: 3,
+            hash: h!("3b"),
+        },
+    );
+    assert_eq!(
+        graph.relevant_heights().collect::<Vec<_>>(),
+        vec![3],
+        "introducing duplicate anchor at height 3, must not iterate over duplicate heights"
+    );
+
+    let _ = graph.insert_anchor(
+        tx1.txid(),
+        BlockId {
+            height: 4,
+            hash: h!("4a"),
+        },
+    );
+    assert_eq!(
+        graph.relevant_heights().collect::<Vec<_>>(),
+        vec![3, 4],
+        "anchors in height 3 and now 4"
+    );
+
+    let _ = graph.insert_anchor(
+        tx2.txid(),
+        BlockId {
+            height: 5,
+            hash: h!("5a"),
+        },
+    );
+    assert_eq!(
+        graph.relevant_heights().collect::<Vec<_>>(),
+        vec![3, 4, 5],
+        "anchor for non-existant tx is inserted at height 5, must still be in relevant heights",
+    );
+}