Skip to content

Commit 0d7d146

Browse files
Add taproot compiler default version
The `compile_tr` method added here uses the heuristic as specified in the docs and provides better cost guarantees than the `compile_tr_private` method.
1 parent 4fd9281 commit 0d7d146

File tree

3 files changed

+279
-0
lines changed

3 files changed

+279
-0
lines changed

src/policy/compiler.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1140,6 +1140,20 @@ pub fn best_compilation<Pk: MiniscriptKey, Ctx: ScriptContext>(
11401140
}
11411141
}
11421142

1143+
/// Obtain the best compilation of for p=1.0 and q=0, along with the satisfaction cost for the script
1144+
pub(crate) fn best_compilation_sat<Pk: MiniscriptKey, Ctx: ScriptContext>(
1145+
policy: &Concrete<Pk>,
1146+
) -> Result<(Arc<Miniscript<Pk, Ctx>>, f64), CompilerError> {
1147+
let mut policy_cache = PolicyCache::<Pk, Ctx>::new();
1148+
let x: AstElemExt<Pk, Ctx> = best_t(&mut policy_cache, policy, 1.0, None)?;
1149+
if !x.ms.ty.mall.safe {
1150+
Err(CompilerError::TopLevelNonSafe)
1151+
} else if !x.ms.ty.mall.non_malleable {
1152+
Err(CompilerError::ImpossibleNonMalleableCompilation)
1153+
} else {
1154+
Ok((x.ms, x.comp_ext_data.sat_cost))
1155+
}
1156+
}
11431157
/// Obtain the best B expression with given sat and dissat
11441158
fn best_t<Pk, Ctx>(
11451159
policy_cache: &mut PolicyCache<Pk, Ctx>,

src/policy/concrete.rs

Lines changed: 236 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ use {
3232
crate::Miniscript,
3333
crate::Tap,
3434
core::cmp::Reverse,
35+
std::collections::BTreeMap,
36+
std::collections::{BinaryHeap, HashMap},
3537
sync::Arc,
3638
};
3739

@@ -42,6 +44,14 @@ use crate::miniscript::types::extra_props::TimelockInfo;
4244
use crate::prelude::*;
4345
use crate::{errstr, Error, ForEach, ForEachKey, MiniscriptKey};
4446

47+
/// [`TapTree`] -> ([`Policy`], satisfaction cost) cache
48+
#[cfg(feature = "compiler")]
49+
type PolicyTapCache<Pk> = BTreeMap<TapTree<Pk>, (Policy<Pk>, f64)>;
50+
51+
/// [`Miniscript`] -> leaf probability in policy cache
52+
#[cfg(feature = "compiler")]
53+
type MsTapCache<Pk> = BTreeMap<TapTree<Pk>, f64>;
54+
4555
/// Concrete policy which corresponds directly to a Miniscript structure,
4656
/// and whose disjunctions are annotated with satisfaction probabilities
4757
/// to assist the compiler
@@ -285,6 +295,69 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
285295
}
286296
}
287297

298+
/// Compile [`Policy`] into a [`TapTree Descriptor`][`Descriptor::Tr`]
299+
///
300+
///
301+
/// This follows the heuristic as described in [`with_huffman_tree_eff`]
302+
#[cfg(feature = "compiler")]
303+
pub fn compile_tr(&self, unspendable_key: Option<Pk>) -> Result<Descriptor<Pk>, Error> {
304+
self.is_valid()?; // Check for validity
305+
match self.is_safe_nonmalleable() {
306+
(false, _) => Err(Error::from(CompilerError::TopLevelNonSafe)),
307+
(_, false) => Err(Error::from(
308+
CompilerError::ImpossibleNonMalleableCompilation,
309+
)),
310+
_ => {
311+
let (internal_key, policy) = self.clone().extract_key(unspendable_key)?;
312+
let tree = Descriptor::new_tr(
313+
internal_key,
314+
match policy {
315+
Policy::Trivial => None,
316+
policy => {
317+
let mut policy_cache = PolicyTapCache::<Pk>::new();
318+
let mut ms_cache = MsTapCache::<Pk>::new();
319+
// Obtain the policy compilations and populate the respective caches for
320+
// creating the huffman tree later on
321+
let vec_policies: Vec<_> = policy.to_tapleaf_prob_vec(1.0);
322+
let mut leaf_compilations: Vec<Arc<Miniscript<Pk, Tap>>> = vec![];
323+
for (prob, pol) in vec_policies {
324+
// policy corresponding to the key (replaced by unsatisfiable) is skipped
325+
if pol == Policy::Unsatisfiable {
326+
continue;
327+
}
328+
let compilation = compiler::best_compilation_sat::<Pk, Tap>(&pol)?;
329+
compilation.0.sanity_check()?;
330+
let leaf_comp = TapTree::Leaf(compilation.0.clone());
331+
policy_cache.insert(
332+
TapTree::Leaf(Arc::clone(&compilation.0)),
333+
(pol.clone(), compilation.1), // (policy, sat_cost)
334+
);
335+
// In case we hit duplication compilations for sub-policies, we add
336+
// their respective probabilities without pushing the node back again.
337+
match ms_cache.get(&leaf_comp) {
338+
Some(p) => {
339+
ms_cache.insert(leaf_comp, p + prob);
340+
}
341+
None => {
342+
ms_cache.insert(leaf_comp, prob);
343+
leaf_compilations.push(compilation.0);
344+
}
345+
};
346+
}
347+
let taptree = with_huffman_tree_eff(
348+
leaf_compilations,
349+
&mut policy_cache,
350+
&mut ms_cache,
351+
)?;
352+
Some(taptree)
353+
}
354+
},
355+
)?;
356+
Ok(tree)
357+
}
358+
}
359+
}
360+
288361
/// Compile the descriptor into an optimized `Miniscript` representation
289362
#[cfg(feature = "compiler")]
290363
pub fn compile<Ctx: ScriptContext>(&self) -> Result<Miniscript<Pk, Ctx>, CompilerError> {
@@ -827,6 +900,50 @@ where
827900
}
828901
}
829902

903+
/// Average satisfaction cost for [`TapTree`] with the leaf [`Miniscript`] nodes at some depth having
904+
/// probabilities corresponding to the (sub)policies they're compiled from.
905+
///
906+
/// Average satisfaction cost for [`TapTree`] over script-spend paths is probability times
907+
/// the size of control block at depth + the script size.
908+
#[cfg(feature = "compiler")]
909+
fn at_depth_taptree_cost<Pk: MiniscriptKey>(
910+
tr: &TapTree<Pk>,
911+
ms_cache: &MsTapCache<Pk>,
912+
policy_cache: &PolicyTapCache<Pk>,
913+
depth: u32,
914+
) -> f64 {
915+
match *tr {
916+
TapTree::Tree(ref l, ref r) => {
917+
at_depth_taptree_cost(l, ms_cache, policy_cache, depth + 1)
918+
+ at_depth_taptree_cost(r, ms_cache, policy_cache, depth + 1)
919+
}
920+
TapTree::Leaf(ref ms) => {
921+
let prob = ms_cache
922+
.get(&TapTree::Leaf(Arc::clone(ms)))
923+
.expect("Probability should exist for the given ms");
924+
let sat_cost = policy_cache
925+
.get(&TapTree::Leaf(Arc::clone(ms)))
926+
.expect("Cost should exist for the given ms")
927+
.1;
928+
prob * (ms.script_size() as f64 + sat_cost + 32.0 * depth as f64)
929+
}
930+
}
931+
}
932+
933+
/// Average net satisfaction cost for [`TapTree`] with the leaf [`Miniscript`] nodes having
934+
/// probabilities corresponding to the (sub)policies they're compiled from.
935+
///
936+
/// Average satisfaction cost for [`TapTree`] over script-spend paths is probability times
937+
/// the size of control block + the script size.
938+
#[cfg(feature = "compiler")]
939+
fn taptree_cost<Pk: MiniscriptKey>(
940+
tr: &TapTree<Pk>,
941+
ms_cache: &MsTapCache<Pk>,
942+
policy_cache: &PolicyTapCache<Pk>,
943+
) -> f64 {
944+
at_depth_taptree_cost(tr, ms_cache, policy_cache, 0)
945+
}
946+
830947
/// Create a Huffman Tree from compiled [Miniscript] nodes
831948
#[cfg(feature = "compiler")]
832949
fn with_huffman_tree<Pk: MiniscriptKey>(
@@ -857,3 +974,122 @@ fn with_huffman_tree<Pk: MiniscriptKey>(
857974
.1;
858975
Ok(node)
859976
}
977+
978+
/// Create a [`TapTree`] from the a list of [`Miniscript`]s having corresponding satisfaction
979+
/// cost and probability.
980+
///
981+
/// Given that satisfaction probability and cost for each script is known, constructing the
982+
/// [`TapTree`] as a huffman tree over the net cost (as defined in [`taptree_cost`]) is
983+
/// the optimal one.
984+
/// For finding the optimal policy to taptree compilation, we are required to search
985+
/// exhaustively over all policies which have the same leaf policies. Owing to the exponential
986+
/// blow-up for such a method, we use a heuristic where we augment the merge to check if the
987+
/// compilation of a new (sub)policy into a [`TapTree::Leaf`] with the policy corresponding to
988+
/// the nodes as children is better than [`TapTree::Tree`] with the nodes as children.
989+
///
990+
/// # Assumption
991+
///
992+
/// We have no two duplicate policies/ compilations in the given list.
993+
/// In any other case, we'd need to re-engineer the node-merging algorithm here to gracefully
994+
/// handle duplicate intermediate policies/ miniscript compilations by dis-disambiguating them.
995+
#[cfg(feature = "compiler")]
996+
fn with_huffman_tree_eff<Pk: MiniscriptKey>(
997+
ms: Vec<Arc<Miniscript<Pk, Tap>>>,
998+
policy_cache: &mut PolicyTapCache<Pk>,
999+
ms_cache: &mut MsTapCache<Pk>,
1000+
) -> Result<TapTree<Pk>, Error> {
1001+
let mut node_weights = BinaryHeap::<(Reverse<OrdF64>, OrdF64, TapTree<Pk>)>::new(); // (cost, branch_prob, tree)
1002+
// Populate the heap with each `ms` as a TapLeaf, and the respective cost fields
1003+
for script in ms {
1004+
let wt = OrdF64(taptree_cost(
1005+
&TapTree::Leaf(Arc::clone(&script)),
1006+
ms_cache,
1007+
policy_cache,
1008+
));
1009+
let prob = OrdF64(
1010+
*ms_cache
1011+
.get(&TapTree::Leaf(Arc::clone(&script)))
1012+
.expect("Probability should exist for the given ms"),
1013+
);
1014+
node_weights.push((Reverse(wt), prob, TapTree::Leaf(Arc::clone(&script))));
1015+
}
1016+
if node_weights.is_empty() {
1017+
return Err(errstr("Empty Miniscript compilation"));
1018+
}
1019+
while node_weights.len() > 1 {
1020+
// Obtain the two least-weighted nodes from the heap for merging
1021+
let (_prev_cost1, p1, ms1) = node_weights.pop().expect("len must atleast be two");
1022+
let (_prev_cost2, p2, ms2) = node_weights.pop().expect("len must atleast be two");
1023+
1024+
// Retrieve the respective policies
1025+
let (left_pol, _c1) = policy_cache
1026+
.get(&ms1)
1027+
.ok_or_else(|| errstr("No corresponding policy found"))?
1028+
.clone();
1029+
1030+
let (right_pol, _c2) = policy_cache
1031+
.get(&ms2)
1032+
.ok_or_else(|| errstr("No corresponding policy found"))?
1033+
.clone();
1034+
1035+
// Create a parent policy with the respective node TapTrees as children (with odds
1036+
// weighted approximately in ratio to their probabilities)
1037+
let parent_policy = Policy::Or(vec![
1038+
((p1.0 * 1e4).round() as usize, left_pol),
1039+
((p2.0 * 1e4).round() as usize, right_pol),
1040+
]);
1041+
1042+
// Obtain compilation for the parent policy
1043+
let (parent_compilation, parent_sat_cost) =
1044+
compiler::best_compilation_sat::<Pk, Tap>(&parent_policy)?;
1045+
parent_compilation.sanity_check()?;
1046+
1047+
// Probability of the parent node being satisfied equals the probability of either
1048+
// nodes to be satisfied. Since we weight the odds appropriately, the children nodes
1049+
// still have approximately the same probabilities
1050+
let p = p1.0 + p2.0;
1051+
// Inserting parent policy's weights (sat_cost and probability) for later usage, assuming
1052+
// we don't hit duplicate policy/ compilation here.
1053+
ms_cache.insert(TapTree::Leaf(Arc::clone(&parent_compilation)), p);
1054+
policy_cache.insert(
1055+
TapTree::Leaf(Arc::clone(&parent_compilation)),
1056+
(parent_policy.clone(), parent_sat_cost),
1057+
);
1058+
1059+
let parent_cost = OrdF64(taptree_cost(
1060+
&TapTree::Leaf(Arc::clone(&parent_compilation)),
1061+
ms_cache,
1062+
policy_cache,
1063+
));
1064+
let children_cost = OrdF64(
1065+
taptree_cost(&ms1, ms_cache, policy_cache) + taptree_cost(&ms2, ms_cache, policy_cache),
1066+
);
1067+
1068+
// Merge the children nodes into either TapLeaf of the parent compilation or
1069+
// TapTree children nodes accordingly
1070+
node_weights.push(if parent_cost > children_cost {
1071+
ms_cache.insert(
1072+
TapTree::Tree(Arc::from(ms1.clone()), Arc::from(ms2.clone())),
1073+
p,
1074+
);
1075+
policy_cache.insert(
1076+
TapTree::Tree(Arc::from(ms1.clone()), Arc::from(ms2.clone())),
1077+
(parent_policy, parent_sat_cost),
1078+
);
1079+
(
1080+
Reverse(children_cost),
1081+
OrdF64(p),
1082+
TapTree::Tree(Arc::from(ms1), Arc::from(ms2)),
1083+
)
1084+
} else {
1085+
let node = TapTree::Leaf(Arc::from(parent_compilation));
1086+
(Reverse(parent_cost), OrdF64(p), node)
1087+
});
1088+
}
1089+
debug_assert!(node_weights.len() == 1);
1090+
let node = node_weights
1091+
.pop()
1092+
.expect("huffman tree algorithm is broken")
1093+
.2;
1094+
Ok(node)
1095+
}

src/policy/mod.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,8 @@ mod tests {
237237
use super::super::miniscript::context::Segwitv0;
238238
use super::super::miniscript::Miniscript;
239239
use super::{Concrete, Liftable, Semantic};
240+
#[cfg(feature = "compiler")]
241+
use crate::descriptor::Tr;
240242
use crate::prelude::*;
241243
use crate::DummyKey;
242244
#[cfg(feature = "compiler")]
@@ -492,5 +494,32 @@ mod tests {
492494
let expected_descriptor = Descriptor::new_tr("E".to_string(), Some(tree)).unwrap();
493495
assert_eq!(descriptor, expected_descriptor);
494496
}
497+
498+
// private and optimized compilation for a given policy
499+
{
500+
let policy = policy_str!(
501+
"thresh(1,or(1@pk(A),1@pk(B)),or(1@pk(C),1@or(1@and(pk(E),pk(F)),1@pk(D))))"
502+
);
503+
let priv_desc = policy
504+
.clone()
505+
.compile_tr_private(Some(unspendable_key.clone()))
506+
.unwrap();
507+
let priv_expected_desc = Descriptor::Tr(
508+
Tr::<String>::from_str("tr(A,{{and_v(v:pk(E),pk(F)),pk(D)},{pk(C),pk(B)}})")
509+
.unwrap(),
510+
);
511+
512+
assert_eq!(priv_desc, priv_expected_desc);
513+
514+
let opt_desc = policy
515+
.clone()
516+
.compile_tr(Some(unspendable_key.clone()))
517+
.unwrap();
518+
let opt_expected_desc = Descriptor::Tr(
519+
Tr::<String>::from_str("tr(A,{{pk(D),pk(C)},{pk(B),and_v(v:pk(E),pk(F))}})")
520+
.unwrap(),
521+
);
522+
assert_eq!(opt_desc, opt_expected_desc);
523+
}
495524
}
496525
}

0 commit comments

Comments
 (0)