Skip to content

Commit 4087b45

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 a4cb70b commit 4087b45

File tree

2 files changed

+223
-0
lines changed

2 files changed

+223
-0
lines changed

src/policy/compiler.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1115,6 +1115,20 @@ pub fn best_compilation<Pk: MiniscriptKey, Ctx: ScriptContext>(
11151115
}
11161116
}
11171117

1118+
/// Obtain the best compilation of for p=1.0 and q=0, along with the satisfaction cost for the script
1119+
pub(crate) fn best_compilation_sat<Pk: MiniscriptKey, Ctx: ScriptContext>(
1120+
policy: &Concrete<Pk>,
1121+
) -> Result<(Arc<Miniscript<Pk, Ctx>>, f64), CompilerError> {
1122+
let mut policy_cache = PolicyCache::<Pk, Ctx>::new();
1123+
let x: AstElemExt<Pk, Ctx> = best_t(&mut policy_cache, policy, 1.0, None)?;
1124+
if !x.ms.ty.mall.safe {
1125+
Err(CompilerError::TopLevelNonSafe)
1126+
} else if !x.ms.ty.mall.non_malleable {
1127+
Err(CompilerError::ImpossibleNonMalleableCompilation)
1128+
} else {
1129+
Ok((x.ms, x.comp_ext_data.sat_cost))
1130+
}
1131+
}
11181132
/// Obtain the best B expression with given sat and dissat
11191133
fn best_t<Pk, Ctx>(
11201134
policy_cache: &mut PolicyCache<Pk, Ctx>,

src/policy/concrete.rs

Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,19 @@ use {
3737
crate::Miniscript,
3838
crate::Tap,
3939
std::cmp::Reverse,
40+
std::collections::BTreeMap,
4041
std::collections::{BinaryHeap, HashMap},
4142
std::sync::Arc,
4243
};
4344

45+
/// [`TapTree`] -> ([`Policy`], satisfaction cost) cache
46+
#[cfg(feature = "compiler")]
47+
type PolicyTapCache<Pk> = BTreeMap<TapTree<Pk>, (Policy<Pk>, f64)>;
48+
49+
/// [`Miniscript`] -> leaf probability in policy cache
50+
#[cfg(feature = "compiler")]
51+
type MsTapCache<Pk> = BTreeMap<TapTree<Pk>, f64>;
52+
4453
/// Concrete policy which corresponds directly to a Miniscript structure,
4554
/// and whose disjunctions are annotated with satisfaction probabilities
4655
/// to assist the compiler
@@ -264,6 +273,62 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
264273
}
265274
}
266275

276+
/// Compile [`Policy`] into a [`TapTree Descriptor`][`Descriptor::Tr`]
277+
///
278+
///
279+
/// This follows the heuristic as described in [`with_huffman_tree_eff`]
280+
#[cfg(feature = "compiler")]
281+
pub fn compile_tr(&self, unspendable_key: Option<Pk>) -> Result<Descriptor<Pk>, Error> {
282+
self.is_valid()?; // Check for validity
283+
match self.is_safe_nonmalleable() {
284+
(false, _) => Err(Error::from(CompilerError::TopLevelNonSafe)),
285+
(_, false) => Err(Error::from(
286+
CompilerError::ImpossibleNonMalleableCompilation,
287+
)),
288+
_ => {
289+
let (internal_key, policy) = self.clone().extract_key(unspendable_key)?;
290+
let tree = Descriptor::new_tr(
291+
internal_key,
292+
match policy {
293+
Policy::Trivial => None,
294+
policy => {
295+
let mut policy_cache = PolicyTapCache::<Pk>::new();
296+
let mut ms_cache = MsTapCache::<Pk>::new();
297+
// Obtain the policy compilations and populate the respective caches for
298+
// creating the huffman tree later on
299+
let leaf_compilations: Vec<_> = policy
300+
.to_tapleaf_prob_vec(1.0)
301+
.into_iter()
302+
.filter(|x| x.1 != Policy::Unsatisfiable)
303+
.map(|(prob, ref pol)| {
304+
let compilation =
305+
compiler::best_compilation_sat::<Pk, Tap>(pol).unwrap();
306+
policy_cache.insert(
307+
TapTree::Leaf(Arc::clone(&compilation.0)),
308+
(pol.clone(), compilation.1), // (policy, sat_cost)
309+
);
310+
ms_cache.insert(
311+
TapTree::Leaf(Arc::from(compilation.0.clone())),
312+
prob,
313+
);
314+
compilation.0
315+
})
316+
.collect();
317+
let taptree = with_huffman_tree_eff(
318+
leaf_compilations,
319+
&mut policy_cache,
320+
&mut ms_cache,
321+
)
322+
.unwrap();
323+
Some(taptree)
324+
}
325+
},
326+
)?;
327+
Ok(tree)
328+
}
329+
}
330+
}
331+
267332
/// Compile the descriptor into an optimized `Miniscript` representation
268333
#[cfg(feature = "compiler")]
269334
pub fn compile<Ctx: ScriptContext>(&self) -> Result<Miniscript<Pk, Ctx>, CompilerError> {
@@ -815,6 +880,36 @@ where
815880
}
816881
}
817882

883+
/// Average satisfaction cost for [`TapTree`] with the leaf [`Miniscript`] nodes having
884+
/// probabilities corresponding to the (sub)policies they're compiled from.
885+
///
886+
/// Average satisfaction cost for [`TapTree`] over script-spend paths is probability times
887+
/// the size of control block + the script size.
888+
#[cfg(feature = "compiler")]
889+
fn taptree_cost<Pk: MiniscriptKey>(
890+
tr: &TapTree<Pk>,
891+
ms_cache: &MsTapCache<Pk>,
892+
policy_cache: &PolicyTapCache<Pk>,
893+
depth: u32,
894+
) -> f64 {
895+
match *tr {
896+
TapTree::Tree(ref l, ref r) => {
897+
taptree_cost(l, ms_cache, policy_cache, depth + 1)
898+
+ taptree_cost(r, ms_cache, policy_cache, depth + 1)
899+
}
900+
TapTree::Leaf(ref ms) => {
901+
let prob = ms_cache
902+
.get(&TapTree::Leaf(Arc::clone(ms)))
903+
.expect("Probability should exist for the given ms");
904+
let sat_cost = policy_cache
905+
.get(&TapTree::Leaf(Arc::clone(ms)))
906+
.expect("Cost should exist for the given ms")
907+
.1;
908+
prob * (ms.script_size() as f64 + sat_cost + 32.0 * depth as f64)
909+
}
910+
}
911+
}
912+
818913
/// Create a Huffman Tree from compiled [Miniscript] nodes
819914
#[cfg(feature = "compiler")]
820915
fn with_huffman_tree<Pk: MiniscriptKey>(
@@ -845,3 +940,117 @@ fn with_huffman_tree<Pk: MiniscriptKey>(
845940
.1;
846941
Ok(node)
847942
}
943+
944+
/// Create a [`TapTree`] from the a list of [`Miniscript`]s having corresponding satisfaction
945+
/// cost and probability.
946+
///
947+
/// Given that satisfaction probability and cost for each script is known, constructing the
948+
/// [`TapTree`] as a huffman tree over the net cost (as defined in [`taptree_cost`]) is
949+
/// the optimal one.
950+
/// For finding the optimal policy to taptree compilation, we are required to search
951+
/// exhaustively over all policies which have the same leaf policies. Owing to the exponential
952+
/// blow-up for such a method, we use a heuristic where we augment the merge to check if the
953+
/// compilation of a new (sub)policy into a [`TapTree::Leaf`] with the policy corresponding to
954+
/// the nodes as children is better than [`TapTree::Tree`] with the nodes as children.
955+
#[cfg(feature = "compiler")]
956+
fn with_huffman_tree_eff<Pk: MiniscriptKey>(
957+
ms: Vec<Arc<Miniscript<Pk, Tap>>>,
958+
policy_cache: &mut PolicyTapCache<Pk>,
959+
ms_cache: &mut MsTapCache<Pk>,
960+
) -> Result<TapTree<Pk>, Error> {
961+
let mut node_weights = BinaryHeap::<(Reverse<OrdF64>, OrdF64, TapTree<Pk>)>::new(); // (cost, branch_prob, tree)
962+
// Populate the heap with each `ms` as a TapLeaf, and the respective cost fields
963+
for script in ms {
964+
let wt = OrdF64(taptree_cost(
965+
&TapTree::Leaf(Arc::clone(&script)),
966+
ms_cache,
967+
policy_cache,
968+
0,
969+
));
970+
let prob = OrdF64(
971+
*ms_cache
972+
.get(&TapTree::Leaf(Arc::clone(&script)))
973+
.expect("Probability should exist for the given ms"),
974+
);
975+
node_weights.push((Reverse(wt), prob, TapTree::Leaf(Arc::clone(&script))));
976+
}
977+
if node_weights.is_empty() {
978+
return Err(errstr("Empty Miniscript compilation"));
979+
}
980+
while node_weights.len() > 1 {
981+
// Obtain the two least-weighted nodes from the heap for merging
982+
let (_prev_cost1, p1, ms1) = node_weights.pop().expect("len must atleast be two");
983+
let (_prev_cost2, p2, ms2) = node_weights.pop().expect("len must atleast be two");
984+
985+
// Retrieve the respective policies
986+
let (left_pol, _c1) = policy_cache
987+
.get(&ms1)
988+
.ok_or_else(|| errstr("No corresponding policy found"))?
989+
.clone();
990+
991+
let (right_pol, _c2) = policy_cache
992+
.get(&ms2)
993+
.ok_or_else(|| errstr("No corresponding policy found"))?
994+
.clone();
995+
996+
// Create a parent policy with the respective node TapTrees as children (with odds
997+
// weighted approximately in ratio to their probabilities)
998+
let parent_policy = Policy::Or(vec![
999+
((p1.0 * 1e4).round() as usize, left_pol),
1000+
((p2.0 * 1e4).round() as usize, right_pol),
1001+
]);
1002+
1003+
// Obtain compilation for the parent policy
1004+
let (parent_compilation, parent_sat_cost) =
1005+
compiler::best_compilation_sat::<Pk, Tap>(&parent_policy)?;
1006+
1007+
// Probability of the parent node being satisfied equals the probability of either
1008+
// nodes to be satisfied. Since we weight the odds appropriately, the children nodes
1009+
// still have approximately the same probabilities
1010+
let p = p1.0 + p2.0;
1011+
// Inserting parent policy's weights (sat_cost and probability) for later usage
1012+
ms_cache.insert(TapTree::Leaf(Arc::clone(&parent_compilation)), p);
1013+
policy_cache.insert(
1014+
TapTree::Leaf(Arc::clone(&parent_compilation)),
1015+
(parent_policy.clone(), parent_sat_cost),
1016+
);
1017+
1018+
let parent_cost = OrdF64(taptree_cost(
1019+
&TapTree::Leaf(Arc::clone(&parent_compilation)),
1020+
ms_cache,
1021+
policy_cache,
1022+
0,
1023+
));
1024+
let children_cost = OrdF64(
1025+
taptree_cost(&ms1, ms_cache, policy_cache, 0)
1026+
+ taptree_cost(&ms2, ms_cache, policy_cache, 0),
1027+
);
1028+
1029+
// Merge the children nodes into either TapLeaf of the parent compilation or
1030+
// TapTree children nodes accordingly
1031+
node_weights.push(if parent_cost > children_cost {
1032+
ms_cache.insert(
1033+
TapTree::Tree(Arc::from(ms1.clone()), Arc::from(ms2.clone())),
1034+
p,
1035+
);
1036+
policy_cache.insert(
1037+
TapTree::Tree(Arc::from(ms1.clone()), Arc::from(ms2.clone())),
1038+
(parent_policy, parent_sat_cost),
1039+
);
1040+
(
1041+
Reverse(children_cost),
1042+
OrdF64(p),
1043+
TapTree::Tree(Arc::from(ms1), Arc::from(ms2)),
1044+
)
1045+
} else {
1046+
let node = TapTree::Leaf(Arc::from(parent_compilation));
1047+
(Reverse(parent_cost), OrdF64(p), node)
1048+
});
1049+
}
1050+
debug_assert!(node_weights.len() == 1);
1051+
let node = node_weights
1052+
.pop()
1053+
.expect("huffman tree algorithm is broken")
1054+
.2;
1055+
Ok(node)
1056+
}

0 commit comments

Comments
 (0)