Skip to content

Commit 6112ced

Browse files
Add P2Tr compiler
Introduce a `compiler_tr` API for compiling a policy to a Tr Descriptor.
1 parent 685a4dc commit 6112ced

File tree

3 files changed

+94
-16
lines changed

3 files changed

+94
-16
lines changed

src/policy/compiler.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ type PolicyCache<Pk, Ctx> =
3636

3737
///Ordered f64 for comparison
3838
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
39-
struct OrdF64(f64);
39+
pub(crate) struct OrdF64(pub f64);
4040

4141
impl Eq for OrdF64 {}
4242
impl Ord for OrdF64 {

src/policy/concrete.rs

Lines changed: 65 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,13 @@ use {
2525
crate::descriptor::TapTree,
2626
crate::miniscript::ScriptContext,
2727
crate::policy::compiler::CompilerError,
28+
crate::policy::compiler::OrdF64,
2829
crate::policy::{compiler, Concrete, Liftable, Semantic},
2930
crate::Descriptor,
3031
crate::Miniscript,
3132
crate::Tap,
32-
std::collections::HashMap,
33+
std::cmp::Reverse,
34+
std::collections::{BinaryHeap, HashMap},
3335
std::sync::Arc,
3436
};
3537

@@ -173,15 +175,23 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
173175
}
174176
}
175177

178+
/// Compile [`Policy::Or`] and [`Policy::Threshold`] according to odds
176179
#[cfg(feature = "compiler")]
177-
fn compile_leaf_taptree(&self) -> Result<TapTree<Pk>, Error> {
178-
let compilation = self.compile::<Tap>().unwrap();
179-
Ok(TapTree::Leaf(Arc::new(compilation)))
180+
fn compile_tr_policy(&self) -> Result<TapTree<Pk>, Error> {
181+
let leaf_compilations: Vec<_> = self
182+
.to_tapleaf_prob_vec(1.0)
183+
.into_iter()
184+
.filter(|x| x.1 != Policy::Unsatisfiable)
185+
.map(|(prob, ref policy)| (OrdF64(prob), compiler::best_compilation(policy).unwrap()))
186+
.collect();
187+
let taptree = with_huffman_tree::<Pk>(leaf_compilations).unwrap();
188+
Ok(taptree)
180189
}
181190

182-
/// Extract the Taproot internal_key from policy tree.
191+
/// Extract the internal_key from policy tree.
183192
#[cfg(feature = "compiler")]
184193
fn extract_key(self, unspendable_key: Option<Pk>) -> Result<(Pk, Policy<Pk>), Error> {
194+
// Making sure the borrow ends before you move the value.
185195
let mut internal_key: Option<Pk> = None;
186196
{
187197
let mut prob = 0.;
@@ -222,11 +232,28 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
222232
}
223233
}
224234

225-
/// Compile the [`Tr`] descriptor into optimized [`TapTree`] implementation
235+
/// Compile the [`Policy`] into a [`Tr`][`Descriptor::Tr`] Descriptor.
236+
///
237+
/// ### TapTree compilation
238+
///
239+
/// The policy tree constructed by root-level disjunctions over [`Or`][`Policy::Or`] and
240+
/// [`Thresh`][`Policy::Threshold`](1, ..) which is flattened into a vector (with respective
241+
/// probabilities derived from odds) of policies.
242+
/// For example, the policy `thresh(1,or(pk(A),pk(B)),and(or(pk(C),pk(D)),pk(E)))` gives the vector
243+
/// `[pk(A),pk(B),and(or(pk(C),pk(D)),pk(E)))]`. Each policy in the vector is compiled into
244+
/// the respective miniscripts. A Huffman Tree is created from this vector which optimizes over
245+
/// the probabilitity of satisfaction for the respective branch in the TapTree.
246+
// TODO: We might require other compile errors for Taproot.
226247
#[cfg(feature = "compiler")]
227248
pub fn compile_tr(&self, unspendable_key: Option<Pk>) -> Result<Descriptor<Pk>, Error> {
228249
let (internal_key, policy) = self.clone().extract_key(unspendable_key)?;
229-
let tree = Descriptor::new_tr(internal_key, Some(policy.compile_leaf_taptree()?))?;
250+
let tree = Descriptor::new_tr(
251+
internal_key,
252+
match policy {
253+
Policy::Trivial => None,
254+
policy => Some(policy.compile_tr_policy()?),
255+
},
256+
)?;
230257
Ok(tree)
231258
}
232259

@@ -771,3 +798,34 @@ where
771798
Policy::from_tree_prob(top, false).map(|(_, result)| result)
772799
}
773800
}
801+
802+
/// Create a Huffman Tree from compiled [Miniscript] nodes
803+
#[cfg(feature = "compiler")]
804+
fn with_huffman_tree<Pk: MiniscriptKey>(
805+
ms: Vec<(OrdF64, Miniscript<Pk, Tap>)>,
806+
) -> Result<TapTree<Pk>, Error> {
807+
let mut node_weights = BinaryHeap::<(Reverse<OrdF64>, TapTree<Pk>)>::new();
808+
for (prob, script) in ms {
809+
node_weights.push((Reverse(prob), TapTree::Leaf(Arc::new(script))));
810+
}
811+
if node_weights.is_empty() {
812+
return Err(errstr("Empty Miniscript compilation"));
813+
}
814+
while node_weights.len() > 1 {
815+
let (p1, s1) = node_weights.pop().expect("len must atleast be two");
816+
let (p2, s2) = node_weights.pop().expect("len must atleast be two");
817+
818+
let p = (p1.0).0 + (p2.0).0;
819+
node_weights.push((
820+
Reverse(OrdF64(p)),
821+
TapTree::Tree(Arc::from(s1), Arc::from(s2)),
822+
));
823+
}
824+
825+
debug_assert!(node_weights.len() == 1);
826+
let node = node_weights
827+
.pop()
828+
.expect("huffman tree algorithm is broken")
829+
.1;
830+
Ok(node)
831+
}

src/policy/mod.rs

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -368,15 +368,35 @@ mod tests {
368368

369369
#[test]
370370
#[cfg(feature = "compiler")]
371-
fn single_leaf_tr_compile() {
372-
let unspendable_key: String = "z".to_string();
373-
let policy: Concrete<String> = policy_str!("thresh(2,pk(A),pk(B),pk(C),pk(D))");
374-
let descriptor = policy.compile_tr(Some(unspendable_key.clone())).unwrap();
371+
fn taproot_compile() {
372+
// Trivial single-node compilation
373+
let unspendable_key: String = "UNSPENDABLE".to_string();
374+
{
375+
let policy: Concrete<String> = policy_str!("thresh(2,pk(A),pk(B),pk(C),pk(D))");
376+
let descriptor = policy.compile_tr(Some(unspendable_key.clone())).unwrap();
375377

376-
let ms_compilation: Miniscript<String, Tap> = ms_str!("multi_a(2,A,B,C,D)");
377-
let tree: TapTree<String> = TapTree::Leaf(Arc::new(ms_compilation));
378-
let expected_descriptor = Descriptor::new_tr(unspendable_key, Some(tree)).unwrap();
378+
let ms_compilation: Miniscript<String, Tap> = ms_str!("multi_a(2,A,B,C,D)");
379+
let tree: TapTree<String> = TapTree::Leaf(Arc::new(ms_compilation));
380+
let expected_descriptor =
381+
Descriptor::new_tr(unspendable_key.clone(), Some(tree)).unwrap();
382+
assert_eq!(descriptor, expected_descriptor);
383+
}
384+
385+
// Trivial multi-node compilation
386+
{
387+
let policy: Concrete<String> = policy_str!("or(and(pk(A),pk(B)),and(pk(C),pk(D)))");
388+
let descriptor = policy.compile_tr(Some(unspendable_key.clone())).unwrap();
379389

380-
assert_eq!(descriptor, expected_descriptor);
390+
let left_ms_compilation: Arc<Miniscript<String, Tap>> =
391+
Arc::new(ms_str!("and_v(v:pk(C),pk(D))"));
392+
let right_ms_compilation: Arc<Miniscript<String, Tap>> =
393+
Arc::new(ms_str!("and_v(v:pk(A),pk(B))"));
394+
let left_node: Arc<TapTree<String>> = Arc::from(TapTree::Leaf(left_ms_compilation));
395+
let right_node: Arc<TapTree<String>> = Arc::from(TapTree::Leaf(right_ms_compilation));
396+
let tree: TapTree<String> = TapTree::Tree(left_node, right_node);
397+
let expected_descriptor =
398+
Descriptor::new_tr(unspendable_key.clone(), Some(tree)).unwrap();
399+
assert_eq!(descriptor, expected_descriptor);
400+
}
381401
}
382402
}

0 commit comments

Comments
 (0)