@@ -13,7 +13,7 @@ use {Error, MiniscriptKey};
13
13
/// A Taproot Tree representation.
14
14
// Hidden leaves are not yet supported in descriptor spec. Conceptually, it should
15
15
// be simple to integrate those here, but it is best to wait on core for the exact syntax.
16
- #[ derive( Clone , Ord , PartialOrd , Eq , PartialEq , Hash ) ]
16
+ #[ derive( Clone , Ord , PartialOrd , Eq , PartialEq , Hash , Debug ) ]
17
17
pub enum TapTree < Pk : MiniscriptKey > {
18
18
/// A taproot tree structure
19
19
Tree ( Arc < TapTree < Pk > > , Arc < TapTree < Pk > > ) ,
@@ -42,6 +42,11 @@ impl<Pk: MiniscriptKey> TapTree<Pk> {
42
42
TapTree :: Leaf ( _) => 1 ,
43
43
}
44
44
}
45
+
46
+ /// Iterate over all miniscripts
47
+ pub fn iter ( & self ) -> TapTreeIter < Pk > {
48
+ TapTreeIter { stack : vec ! [ self ] }
49
+ }
45
50
}
46
51
47
52
impl < Pk : MiniscriptKey > fmt:: Display for TapTree < Pk > {
@@ -82,6 +87,43 @@ impl<Pk: MiniscriptKey> Tr<Pk> {
82
87
pub fn taptree ( & self ) -> & Option < TapTree < Pk > > {
83
88
& self . tree
84
89
}
90
+
91
+ /// Iterate over all scripts in merkle tree. If there is no script path, the iterator
92
+ /// yields [`None`]
93
+ pub fn iter_scripts ( & self ) -> TapTreeIter < Pk > {
94
+ match self . tree {
95
+ Some ( ref t) => t. iter ( ) ,
96
+ None => TapTreeIter { stack : vec ! [ ] } ,
97
+ }
98
+ }
99
+ }
100
+
101
+ /// Iterator for Taproot structures
102
+ /// Yields the miniscript in a depth first walk
103
+ #[ derive( Debug , Clone ) ]
104
+ pub struct TapTreeIter < ' a , Pk : MiniscriptKey > where Pk : ' a {
105
+ stack : Vec < & ' a TapTree < Pk > > ,
106
+ }
107
+
108
+ impl < ' a , Pk > Iterator for TapTreeIter < ' a , Pk >
109
+ where
110
+ Pk : MiniscriptKey + ' a ,
111
+ {
112
+ type Item = & ' a Miniscript < Pk , Tap > ;
113
+
114
+ fn next ( & mut self ) -> Option < Self :: Item > {
115
+ while !self . stack . is_empty ( ) {
116
+ let last = self . stack . pop ( ) . expect ( "Size checked above" ) ;
117
+ match & * last {
118
+ TapTree :: Tree ( l, r) => {
119
+ self . stack . push ( & r) ;
120
+ self . stack . push ( & l) ;
121
+ }
122
+ TapTree :: Leaf ( ref ms) => return Some ( ms) ,
123
+ }
124
+ }
125
+ None
126
+ }
85
127
}
86
128
87
129
impl < Pk : MiniscriptKey > FromTree for Tr < Pk >
0 commit comments