1use std::cmp::{self, max};
3use std::str::FromStr;
4use std::sync::{Arc, Mutex};
5use std::{fmt, hash};
6
7use bitcoin_miniscript::expression::check_valid_chars;
8use elements::taproot::{
9 LeafVersion, TaprootBuilder, TaprootSpendInfo, TAPROOT_CONTROL_BASE_SIZE,
10 TAPROOT_CONTROL_MAX_NODE_COUNT, TAPROOT_CONTROL_NODE_SIZE,
11};
12use elements::{self, opcodes, secp256k1_zkp, Script};
13
14use super::checksum::verify_checksum;
15use super::ELMTS_STR;
16use crate::descriptor::checksum;
17use crate::expression::{self, FromTree};
18use crate::extensions::ParseableExt;
19use crate::miniscript::Miniscript;
20use crate::policy::semantic::Policy;
21use crate::policy::Liftable;
22use crate::util::{varint_len, witness_size};
23use crate::{
24 errstr, Error, Extension, ForEachKey, MiniscriptKey, NoExt, Satisfier, Tap, ToPublicKey,
25 TranslateExt, TranslatePk, Translator,
26};
27
28#[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
32#[non_exhaustive]
33pub enum TapTree<Pk: MiniscriptKey, Ext: Extension = NoExt> {
34 Tree(Arc<TapTree<Pk, Ext>>, Arc<TapTree<Pk, Ext>>),
36 Leaf(Arc<Miniscript<Pk, Tap, Ext>>),
41 #[cfg(feature = "simplicity")]
43 SimplicityLeaf(Arc<simplicity::Policy<Pk>>),
44}
45
46pub struct Tr<Pk: MiniscriptKey, Ext: Extension = NoExt> {
48 internal_key: Pk,
50 tree: Option<TapTree<Pk, Ext>>,
52 spend_info: Mutex<Option<Arc<TaprootSpendInfo>>>,
60}
61
62impl<Pk: MiniscriptKey, Ext: Extension> Clone for Tr<Pk, Ext> {
63 fn clone(&self) -> Self {
64 Self {
68 internal_key: self.internal_key.clone(),
69 tree: self.tree.clone(),
70 spend_info: Mutex::new(
71 self.spend_info
72 .lock()
73 .expect("Lock poisoned")
74 .as_ref()
75 .map(Arc::clone),
76 ),
77 }
78 }
79}
80
81impl<Pk: MiniscriptKey, Ext: Extension> PartialEq for Tr<Pk, Ext> {
82 fn eq(&self, other: &Self) -> bool {
83 self.internal_key == other.internal_key && self.tree == other.tree
84 }
85}
86
87impl<Pk: MiniscriptKey, Ext: Extension> Eq for Tr<Pk, Ext> {}
88
89impl<Pk: MiniscriptKey, Ext: Extension> PartialOrd for Tr<Pk, Ext> {
90 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
91 Some(self.cmp(other))
92 }
93}
94
95impl<Pk: MiniscriptKey, Ext: Extension> Ord for Tr<Pk, Ext> {
96 fn cmp(&self, other: &Self) -> cmp::Ordering {
97 match self.internal_key.cmp(&other.internal_key) {
98 cmp::Ordering::Equal => {}
99 ord => return ord,
100 }
101 self.tree.cmp(&other.tree)
102 }
103}
104
105impl<Pk: MiniscriptKey, Ext: Extension> hash::Hash for Tr<Pk, Ext> {
106 fn hash<H: hash::Hasher>(&self, state: &mut H) {
107 self.internal_key.hash(state);
108 self.tree.hash(state);
109 }
110}
111
112impl<Pk: MiniscriptKey, Ext: Extension> TapTree<Pk, Ext> {
113 fn taptree_height(&self) -> usize {
117 match *self {
118 TapTree::Tree(ref left_tree, ref right_tree) => {
119 1 + max(left_tree.taptree_height(), right_tree.taptree_height())
120 }
121 TapTree::Leaf(..) => 0,
122 #[cfg(feature = "simplicity")]
123 TapTree::SimplicityLeaf(..) => 0,
124 }
125 }
126
127 pub fn iter(&self) -> TapTreeIter<'_, Pk, Ext> {
130 TapTreeIter {
131 stack: vec![(0, self)],
132 }
133 }
134
135 fn translate_helper<T, Q, Error>(&self, t: &mut T) -> Result<TapTree<Q, Ext>, Error>
137 where
138 T: Translator<Pk, Q, Error>,
139 Q: MiniscriptKey,
140 Ext: Extension,
141 {
142 #[cfg(feature = "simplicity")]
143 struct SimTranslator<'a, T>(&'a mut T);
144
145 #[cfg(feature = "simplicity")]
146 impl<'a, Pk, T, Q, Error> simplicity::Translator<Pk, Q, Error> for SimTranslator<'a, T>
147 where
148 Pk: MiniscriptKey,
149 T: Translator<Pk, Q, Error>,
150 Q: MiniscriptKey,
151 {
152 fn pk(&mut self, pk: &Pk) -> Result<Q, Error> {
153 self.0.pk(pk)
154 }
155
156 fn sha256(&mut self, sha256: &Pk::Sha256) -> Result<Q::Sha256, Error> {
157 self.0.sha256(sha256)
158 }
159 }
160
161 let frag = match self {
162 TapTree::Tree(l, r) => TapTree::Tree(
163 Arc::new(l.translate_helper(t)?),
164 Arc::new(r.translate_helper(t)?),
165 ),
166 TapTree::Leaf(ms) => TapTree::Leaf(Arc::new(ms.translate_pk(t)?)),
167 #[cfg(feature = "simplicity")]
168 TapTree::SimplicityLeaf(sim) => TapTree::SimplicityLeaf(Arc::new(sim.translate(&mut SimTranslator(t))?))
169 };
170 Ok(frag)
171 }
172
173 fn translate_ext_helper<T, QExt, Error>(&self, t: &mut T) -> Result<TapTree<Pk, QExt>, Error>
175 where
176 T: crate::ExtTranslator<Ext, QExt, Error>,
177 QExt: Extension,
178 Ext: Extension + TranslateExt<Ext, QExt, Output = QExt>,
179 {
180 let frag = match self {
181 TapTree::Tree(l, r) => TapTree::Tree(
182 Arc::new(l.translate_ext_helper(t)?),
183 Arc::new(r.translate_ext_helper(t)?),
184 ),
185 TapTree::Leaf(ms) => TapTree::Leaf(Arc::new(ms.translate_ext(t)?)),
186 #[cfg(feature = "simplicity")]
187 TapTree::SimplicityLeaf(sim) => TapTree::SimplicityLeaf(Arc::clone(sim)),
188 };
189 Ok(frag)
190 }
191}
192
193impl<Pk: MiniscriptKey, Ext: Extension> fmt::Display for TapTree<Pk, Ext> {
194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195 match self {
196 TapTree::Tree(ref left, ref right) => write!(f, "{{{},{}}}", *left, *right),
197 TapTree::Leaf(ref script) => write!(f, "{}", *script),
198 #[cfg(feature = "simplicity")]
199 TapTree::SimplicityLeaf(ref policy) => write!(f, "sim{{{}}}", policy),
200 }
201 }
202}
203
204impl<Pk: MiniscriptKey, Ext: Extension> fmt::Debug for TapTree<Pk, Ext> {
205 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206 match self {
207 TapTree::Tree(ref left, ref right) => write!(f, "{{{:?},{:?}}}", *left, *right),
208 TapTree::Leaf(ref script) => write!(f, "{:?}", *script),
209 #[cfg(feature = "simplicity")]
210 TapTree::SimplicityLeaf(ref policy) => write!(f, "{:?}", policy),
211 }
212 }
213}
214
215impl<Pk: MiniscriptKey, Ext: Extension> Tr<Pk, Ext> {
216 pub fn new(internal_key: Pk, tree: Option<TapTree<Pk, Ext>>) -> Result<Self, Error> {
218 let nodes = tree.as_ref().map(|t| t.taptree_height()).unwrap_or(0);
219
220 if nodes <= TAPROOT_CONTROL_MAX_NODE_COUNT {
221 Ok(Self {
222 internal_key,
223 tree,
224 spend_info: Mutex::new(None),
225 })
226 } else {
227 Err(Error::MaxRecursiveDepthExceeded)
228 }
229 }
230
231 pub fn internal_key(&self) -> &Pk {
233 &self.internal_key
234 }
235
236 pub fn taptree(&self) -> &Option<TapTree<Pk, Ext>> {
238 &self.tree
239 }
240
241 pub fn iter_scripts(&self) -> TapTreeIter<'_, Pk, Ext> {
244 match self.tree {
245 Some(ref t) => t.iter(),
246 None => TapTreeIter { stack: vec![] },
247 }
248 }
249
250 pub fn spend_info(&self) -> Arc<TaprootSpendInfo>
256 where
257 Pk: ToPublicKey,
258 Ext: ParseableExt,
259 {
260 let read_lock = self.spend_info.lock().expect("Lock poisoned");
263 if let Some(ref spend_info) = *read_lock {
264 return Arc::clone(spend_info);
265 }
266 drop(read_lock);
267
268 let secp = secp256k1_zkp::Secp256k1::verification_only();
271 let data = if self.tree.is_none() {
273 TaprootSpendInfo::new_key_spend(&secp, self.internal_key.to_x_only_pubkey(), None)
274 } else {
275 let mut builder = TaprootBuilder::new();
276 for (depth, script) in self.iter_scripts() {
277 builder = builder
278 .add_leaf_with_ver(depth, script.encode(), script.version())
279 .expect("Computing spend data on a valid Tree should always succeed");
280 }
281 match builder.finalize(&secp, self.internal_key.to_x_only_pubkey()) {
283 Ok(data) => data,
284 Err(_) => unreachable!("We know the builder can be finalized"),
285 }
286 };
287 let spend_info = Arc::new(data);
288 *self.spend_info.lock().expect("Lock poisoned") = Some(Arc::clone(&spend_info));
289 spend_info
290 }
291
292 pub fn sanity_check(&self) -> Result<(), Error> {
294 for (_depth, script) in self.iter_scripts() {
295 match script {
296 TapLeafScript::Miniscript(ms) => ms.sanity_check()?,
297 #[cfg(feature = "simplicity")]
299 TapLeafScript::Simplicity(..) => {},
300 }
301 }
302 Ok(())
303 }
304
305 pub fn max_weight_to_satisfy(&self) -> Result<usize, Error> {
314 let tree = match self.taptree() {
315 None => {
316 let item_sig_size = 1 + 65;
319 let stack_varint_diff = varint_len(1) - varint_len(0);
321
322 return Ok(stack_varint_diff + item_sig_size);
323 }
324 Some(tree) => tree,
326 };
327
328 tree.iter()
329 .filter_map(|(depth, script)| {
330 let script_size = script.script_size();
331 let max_sat_elems = script.max_satisfaction_witness_elements().ok()?;
332 let max_sat_size = script.max_satisfaction_size().ok()?;
333 let control_block_size = control_block_len(depth);
334
335 let stack_varint_diff = varint_len(max_sat_elems + 1) - varint_len(0);
337
338 Some(
339 stack_varint_diff +
340 max_sat_size +
342 varint_len(script_size) +
344 script_size +
345 varint_len(control_block_size) +
347 control_block_size,
348 )
349 })
350 .max()
351 .ok_or(Error::ImpossibleSatisfaction)
352 }
353
354 #[deprecated(note = "use max_weight_to_satisfy instead")]
364 pub fn max_satisfaction_weight(&self) -> Result<usize, Error> {
365 let tree = match self.taptree() {
366 None => return Ok(4 + 1 + 1 + 65),
369 Some(tree) => tree,
371 };
372
373 tree.iter()
374 .filter_map(|(depth, script)| {
375 let script_size = script.script_size();
376 let max_sat_elems = script.max_satisfaction_witness_elements().ok()?;
377 let max_sat_size = script.max_satisfaction_size().ok()?;
378 let control_block_size = control_block_len(depth);
379 Some(
380 4 +
382 varint_len(max_sat_elems + 2) +
384 max_sat_size +
386 varint_len(script_size) +
388 script_size +
389 varint_len(control_block_size) +
391 control_block_size,
392 )
393 })
394 .max()
395 .ok_or(Error::ImpossibleSatisfaction)
396 }
397}
398
399impl<Pk: MiniscriptKey + ToPublicKey, Ext: ParseableExt> Tr<Pk, Ext> {
400 pub fn script_pubkey(&self) -> Script {
402 let output_key = self.spend_info().output_key();
403 let builder = elements::script::Builder::new();
404 builder
405 .push_opcode(opcodes::all::OP_PUSHNUM_1)
406 .push_slice(&output_key.as_inner().serialize())
407 .into_script()
408 }
409
410 pub fn address(
412 &self,
413 blinder: Option<secp256k1_zkp::PublicKey>,
414 params: &'static elements::AddressParams,
415 ) -> elements::Address {
416 let spend_info = self.spend_info();
417 elements::Address::p2tr_tweaked(spend_info.output_key(), blinder, params)
418 }
419
420 pub fn get_satisfaction<S>(&self, satisfier: S) -> Result<(Vec<Vec<u8>>, Script), Error>
424 where
425 S: Satisfier<Pk>,
426 {
427 best_tap_spend(self, satisfier, false )
428 }
429
430 pub fn get_satisfaction_mall<S>(&self, satisfier: S) -> Result<(Vec<Vec<u8>>, Script), Error>
434 where
435 S: Satisfier<Pk>,
436 {
437 best_tap_spend(self, satisfier, true )
438 }
439}
440
441#[derive(Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
443#[non_exhaustive]
444pub enum TapLeafScript<'a, Pk: MiniscriptKey, Ext: Extension> {
445 Miniscript(&'a Miniscript<Pk, Tap, Ext>),
447 #[cfg(feature = "simplicity")]
449 Simplicity(&'a simplicity::Policy<Pk>)
450}
451
452impl<'a, Pk: MiniscriptKey, Ext: Extension> TapLeafScript<'a, Pk, Ext> {
453 pub fn as_miniscript(&self) -> Option<&'a Miniscript<Pk, Tap, Ext>> {
455 match self {
456 TapLeafScript::Miniscript(ms) => Some(ms),
457 #[cfg(feature = "simplicity")]
458 _ => None,
459 }
460 }
461
462 #[cfg(feature = "simplicity")]
464 pub fn as_simplicity(&self) -> Option<&'a simplicity::Policy<Pk>> {
465 match self {
466 TapLeafScript::Simplicity(sim) => Some(sim),
467 _ => None,
468 }
469 }
470
471 pub fn version(&self) -> LeafVersion {
473 match self {
474 TapLeafScript::Miniscript(..) => LeafVersion::default(),
475 #[cfg(feature = "simplicity")]
476 TapLeafScript::Simplicity(..) => simplicity::leaf_version(),
477 }
478 }
479
480 pub fn script_size(&self) -> usize {
482 match self {
483 TapLeafScript::Miniscript(ms) => ms.script_size(),
484 #[cfg(feature = "simplicity")]
486 TapLeafScript::Simplicity(..) => 32,
487 }
488 }
489
490 pub fn max_satisfaction_witness_elements(&self) -> Result<usize, Error> {
493 match self {
494 TapLeafScript::Miniscript(ms) => ms.max_satisfaction_witness_elements(),
495 #[cfg(feature = "simplicity")]
500 TapLeafScript::Simplicity(..) => Ok(2),
501 }
502 }
503
504 pub fn max_satisfaction_size(&self) -> Result<usize, Error> {
506 match self {
507 TapLeafScript::Miniscript(ms) => ms.max_satisfaction_size(),
508 #[cfg(feature = "simplicity")]
512 TapLeafScript::Simplicity(..) => Err(Error::AnalysisError(crate::AnalysisError::Malleable))
513 }
514 }
515
516 pub fn iter_pk(&self) -> Box<dyn Iterator<Item=Pk> + 'a> {
518 match self {
519 TapLeafScript::Miniscript(ms) => Box::new(ms.iter_pk()),
520 #[cfg(feature = "simplicity")]
521 TapLeafScript::Simplicity(sim) => Box::new(sim.iter_pk()),
522 }
523 }
524}
525
526impl<'a, Pk: ToPublicKey, Ext: ParseableExt> TapLeafScript<'a, Pk, Ext> {
527 pub fn encode(&self) -> Script {
529 match self {
530 TapLeafScript::Miniscript(ms) => ms.encode(),
531 #[cfg(feature = "simplicity")]
532 TapLeafScript::Simplicity(sim) => {
533 Script::from(sim.cmr().as_ref().to_vec())
534 }
535 }
536 }
537
538 pub fn satisfy_malleable<S: Satisfier<Pk>>(&self, satisfier: S) -> Result<Vec<Vec<u8>>, Error> {
543 match self {
544 TapLeafScript::Miniscript(ms) => ms.satisfy_malleable(satisfier),
545 #[cfg(feature = "simplicity")]
547 TapLeafScript::Simplicity(..) => self.satisfy(satisfier),
548 }
549 }
550
551 pub fn satisfy<S: Satisfier<Pk>>(&self, satisfier: S) -> Result<Vec<Vec<u8>>, Error> {
556 match self {
557 TapLeafScript::Miniscript(ms) => ms.satisfy(satisfier),
558 #[cfg(feature = "simplicity")]
559 TapLeafScript::Simplicity(..) => {
560 Err(Error::CouldNotSatisfy)
563 }
564 }
565 }
566}
567
568#[derive(Debug, Clone)]
584pub struct TapTreeIter<'a, Pk: MiniscriptKey, Ext: Extension> {
585 stack: Vec<(usize, &'a TapTree<Pk, Ext>)>,
586}
587
588impl<'a, Pk, Ext> Iterator for TapTreeIter<'a, Pk, Ext>
589where
590 Pk: MiniscriptKey + 'a,
591 Ext: Extension,
592{
593 type Item = (usize, TapLeafScript<'a, Pk, Ext>);
594
595 fn next(&mut self) -> Option<Self::Item> {
596 while let Some((depth, last)) = self.stack.pop() {
597 match *last {
598 TapTree::Tree(ref l, ref r) => {
599 self.stack.push((depth + 1, r));
600 self.stack.push((depth + 1, l));
601 }
602 TapTree::Leaf(ref ms) => {
603 return Some((depth, TapLeafScript::Miniscript(ms)))
604 },
605 #[cfg(feature = "simplicity")]
606 TapTree::SimplicityLeaf(ref sim) => {
607 return Some((depth, TapLeafScript::Simplicity(sim)))
608 }
609 }
610 }
611 None
612 }
613}
614
615#[rustfmt::skip]
616impl_block_str!(
617 Tr<Pk, Ext>,
618 => Ext; Extension,
619 fn parse_tr_script_spend(tree: &expression::Tree,) -> Result<TapTree<Pk, Ext>, Error> {
621 match tree {
622 #[cfg(feature = "simplicity")]
623 expression::Tree { name, args } if *name == "sim" && args.len() == 1 => {
624 let policy = crate::simplicity::PolicyWrapper::<Pk>::from_str(args[0].name)?;
625 Ok(TapTree::SimplicityLeaf(Arc::new(policy.0)))
626 }
627 expression::Tree { name, args } if !name.is_empty() && args.is_empty() => {
628 let script = Miniscript::<Pk, Tap, Ext>::from_str(name)?;
629 Ok(TapTree::Leaf(Arc::new(script)))
630 }
631 expression::Tree { name, args } if name.is_empty() && args.len() == 2 => {
632 let left = Self::parse_tr_script_spend(&args[0])?;
633 let right = Self::parse_tr_script_spend(&args[1])?;
634 Ok(TapTree::Tree(Arc::new(left), Arc::new(right)))
635 }
636 _ => Err(Error::Unexpected(
637 "unknown format for script spending paths while parsing taproot descriptor"
638 .to_string(),
639 )),
640 }
641 }
642);
643
644impl_from_tree!(
645 Tr<Pk, Ext>,
646 => Ext; Extension,
647 fn from_tree(top: &expression::Tree) -> Result<Self, Error> {
648 if top.name == "eltr" {
649 match top.args.len() {
650 1 => {
651 let key = &top.args[0];
652 if !key.args.is_empty() {
653 return Err(Error::Unexpected(format!(
654 "#{} script associated with `key-path` while parsing taproot descriptor",
655 key.args.len()
656 )));
657 }
658 Tr::new(expression::terminal(key, Pk::from_str)?, None)
659 }
660 2 => {
661 let key = &top.args[0];
662 if !key.args.is_empty() {
663 return Err(Error::Unexpected(format!(
664 "#{} script associated with `key-path` while parsing taproot descriptor",
665 key.args.len()
666 )));
667 }
668 let tree = &top.args[1];
669 let ret = Self::parse_tr_script_spend(tree)?;
670 Tr::new(expression::terminal(key, Pk::from_str)?, Some(ret))
671 }
672 _ => {
673 Err(Error::Unexpected(format!(
674 "{}[#{} args] while parsing taproot descriptor",
675 top.name,
676 top.args.len()
677 )))
678 }
679 }
680 } else {
681 Err(Error::Unexpected(format!(
682 "{}[#{} args] while parsing taproot descriptor",
683 top.name,
684 top.args.len()
685 )))
686 }
687 }
688);
689
690impl_from_str!(
691 Tr<Pk, Ext>,
692 => Ext; Extension,
693 type Err = Error;,
694 fn from_str(s: &str) -> Result<Self, Self::Err> {
695 let desc_str = verify_checksum(s)?;
696 let top = parse_tr_tree(desc_str)?;
697 Self::from_tree(&top)
698 }
699);
700
701impl<Pk: MiniscriptKey, Ext: Extension> fmt::Debug for Tr<Pk, Ext> {
702 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
703 match self.tree {
704 Some(ref s) => write!(f, "tr({:?},{:?})", self.internal_key, s),
705 None => write!(f, "tr({:?})", self.internal_key),
706 }
707 }
708}
709
710impl<Pk: MiniscriptKey, Ext: Extension> fmt::Display for Tr<Pk, Ext> {
711 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
712 use fmt::Write;
713 let mut wrapped_f = checksum::Formatter::new(f);
714 let key = &self.internal_key;
715 match self.tree {
716 Some(ref s) => write!(wrapped_f, "{}tr({},{})", ELMTS_STR, key, s)?,
717 None => write!(wrapped_f, "{}tr({})", ELMTS_STR, key)?,
718 }
719 wrapped_f.write_checksum_if_not_alt()
720 }
721}
722
723fn parse_tr_tree(s: &str) -> Result<expression::Tree<'_>, Error> {
725 check_valid_chars(s)?;
726
727 if s.len() > 5 && &s[..5] == "eltr(" && s.as_bytes()[s.len() - 1] == b')' {
728 let rest = &s[5..s.len() - 1];
729 if !rest.contains(',') {
730 let internal_key = expression::Tree {
731 name: rest,
732 args: vec![],
733 };
734 return Ok(expression::Tree {
735 name: "eltr",
736 args: vec![internal_key],
737 });
738 }
739 let (key, script) = split_once(rest, ',')
741 .ok_or_else(|| Error::BadDescriptor("invalid taproot descriptor".to_string()))?;
742
743 let internal_key = expression::Tree {
744 name: key,
745 args: vec![],
746 };
747 if script.is_empty() {
748 return Ok(expression::Tree {
749 name: "eltr",
750 args: vec![internal_key],
751 });
752 }
753 let (tree, rest) = expression::Tree::from_slice_delim(script, 1, '{')?;
754 if rest.is_empty() {
755 Ok(expression::Tree {
756 name: "eltr",
757 args: vec![internal_key, tree],
758 })
759 } else {
760 Err(errstr(rest))
761 }
762 } else {
763 Err(Error::Unexpected("invalid taproot descriptor".to_string()))
764 }
765}
766
767fn split_once(inp: &str, delim: char) -> Option<(&str, &str)> {
768 if inp.is_empty() {
769 None
770 } else {
771 let mut found = inp.len();
772 for (idx, ch) in inp.chars().enumerate() {
773 if ch == delim {
774 found = idx;
775 break;
776 }
777 }
778 if found >= inp.len() - 1 {
780 Some((inp, ""))
781 } else {
782 Some((&inp[..found], &inp[found + 1..]))
783 }
784 }
785}
786
787impl<Pk: MiniscriptKey, Ext: Extension> Liftable<Pk> for TapTree<Pk, Ext> {
788 fn lift(&self) -> Result<Policy<Pk>, Error> {
789 fn lift_helper<Pk: MiniscriptKey, Ext: Extension>(
790 s: &TapTree<Pk, Ext>,
791 ) -> Result<Policy<Pk>, Error> {
792 match s {
793 TapTree::Tree(ref l, ref r) => {
794 Ok(Policy::Threshold(1, vec![lift_helper(l)?, lift_helper(r)?]))
795 }
796 TapTree::Leaf(ref leaf) => leaf.lift(),
797 #[cfg(feature = "simplicity")]
798 TapTree::SimplicityLeaf(..) => panic!("FIXME: Cannot lift Simplicity policy to Miniscript semantic policy"),
799 }
800 }
801
802 let pol = lift_helper(self)?;
803 Ok(pol.normalized())
804 }
805}
806
807impl<Pk: MiniscriptKey, Ext: Extension> Liftable<Pk> for Tr<Pk, Ext> {
808 fn lift(&self) -> Result<Policy<Pk>, Error> {
809 match &self.tree {
810 Some(root) => Ok(Policy::Threshold(
811 1,
812 vec![Policy::Key(self.internal_key.clone()), root.lift()?],
813 )),
814 None => Ok(Policy::Key(self.internal_key.clone())),
815 }
816 }
817}
818
819impl<Pk: MiniscriptKey, Ext: Extension> ForEachKey<Pk> for Tr<Pk, Ext> {
820 fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool
821 where
822 Pk: 'a,
823 {
824 let script_keys_res = self
825 .iter_scripts()
826 .all(|(_d, script)| {
827 match script {
828 TapLeafScript::Miniscript(ms) => ms.for_each_key(&mut pred),
829 #[cfg(feature = "simplicity")]
830 TapLeafScript::Simplicity(sim) => crate::simplicity::for_each_key(sim, &mut pred),
831 }
832 });
833 script_keys_res && pred(&self.internal_key)
834 }
835}
836
837impl<P, Q, Ext> TranslatePk<P, Q> for Tr<P, Ext>
838where
839 P: MiniscriptKey,
840 Q: MiniscriptKey,
841 Ext: Extension,
842{
843 type Output = Tr<Q, Ext>;
844
845 fn translate_pk<T, E>(&self, translate: &mut T) -> Result<Self::Output, E>
846 where
847 T: Translator<P, Q, E>,
848 {
849 let translate_desc = Tr {
850 internal_key: translate.pk(&self.internal_key)?,
851 tree: match &self.tree {
852 Some(tree) => Some(tree.translate_helper(translate)?),
853 None => None,
854 },
855 spend_info: Mutex::new(None),
856 };
857 Ok(translate_desc)
858 }
859}
860
861impl<PExt, QExt, Pk> TranslateExt<PExt, QExt> for Tr<Pk, PExt>
862where
863 PExt: Extension + TranslateExt<PExt, QExt, Output = QExt>,
864 QExt: Extension,
865 Pk: MiniscriptKey,
866{
867 type Output = Tr<Pk, QExt>;
868
869 fn translate_ext<T, E>(&self, translator: &mut T) -> Result<Self::Output, E>
870 where
871 T: crate::ExtTranslator<PExt, QExt, E>,
872 {
873 let translate_desc = Tr {
874 internal_key: self.internal_key.clone(),
875 tree: match &self.tree {
876 Some(tree) => Some(tree.translate_ext_helper(translator)?),
877 None => None,
878 },
879 spend_info: Mutex::new(None),
880 };
881 Ok(translate_desc)
882 }
883}
884
885fn control_block_len(depth: usize) -> usize {
887 TAPROOT_CONTROL_BASE_SIZE + depth * TAPROOT_CONTROL_NODE_SIZE
888}
889
890fn best_tap_spend<Pk, S, Ext>(
893 desc: &Tr<Pk, Ext>,
894 satisfier: S,
895 allow_mall: bool,
896) -> Result<(Vec<Vec<u8>>, Script), Error>
897where
898 Pk: ToPublicKey,
899 S: Satisfier<Pk>,
900 Ext: ParseableExt,
901{
902 let spend_info = desc.spend_info();
903 if let Some(sig) = satisfier.lookup_tap_key_spend_sig() {
905 Ok((vec![sig.to_vec()], Script::new()))
906 } else {
907 let (mut min_wit, mut min_wit_len) = (None, None);
910 for (depth, script) in desc.iter_scripts() {
911 let mut wit = if allow_mall {
912 match script.satisfy_malleable(&satisfier) {
913 Ok(wit) => wit,
914 Err(..) => continue, }
916 } else {
917 match script.satisfy(&satisfier) {
918 Ok(wit) => wit,
919 Err(..) => continue, }
921 };
922 let wit_size = witness_size(&wit)
926 + control_block_len(depth)
927 + script.script_size()
928 + varint_len(script.script_size());
929
930 if min_wit_len.is_some() && Some(wit_size) > min_wit_len {
931 continue;
932 } else {
933 let leaf_script = (script.encode(), script.version());
934 let control_block = spend_info
935 .control_block(&leaf_script)
936 .expect("Control block must exist in script map for every known leaf");
937 wit.push(leaf_script.0.into_bytes()); wit.push(control_block.serialize());
941 min_wit = Some(wit);
943 min_wit_len = Some(wit_size);
944 }
945 }
946 match min_wit {
947 Some(wit) => Ok((wit, Script::new())),
948 None => Err(Error::CouldNotSatisfy), }
950 }
951}
952
953#[cfg(test)]
954mod tests {
955 use super::*;
956 use crate::{ForEachKey, NoExt};
957
958 #[cfg(feature = "simplicity")]
959 #[test]
960 fn mixed_tree_satisfaction_skips_simplicity() {
961 let key = bitcoin::XOnlyPublicKey::from_str(
962 "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
963 )
964 .unwrap();
965 let ms =
966 Miniscript::<bitcoin::XOnlyPublicKey, Tap>::from_str(&format!("pk({})", key)).unwrap();
967 let script = ms.encode();
968 let leaf_hash =
969 elements::taproot::TapLeafHash::from_script(&script, LeafVersion::default());
970 let sig = elements::SchnorrSig {
971 sig: secp256k1_zkp::schnorr::Signature::from_slice(&[1; 64]).unwrap(),
972 hash_ty: elements::SchnorrSighashType::Default,
973 };
974 let mut satisfier = std::collections::HashMap::new();
975 satisfier.insert((key, leaf_hash), sig);
976
977 for tree in [
978 format!("{{pk({0}),sim{{pk({0})}}}}", key),
979 format!("{{sim{{pk({0})}},pk({0})}}", key),
980 ] {
981 let desc = Tr::<bitcoin::XOnlyPublicKey>::from_str(&format!("eltr({},{})", key, tree))
982 .unwrap();
983 let control_block = desc
984 .spend_info()
985 .control_block(&(script.clone(), LeafVersion::default()))
986 .unwrap();
987 let expected = (
988 vec![sig.to_vec(), script.to_bytes(), control_block.serialize()],
989 Script::new(),
990 );
991 assert_eq!(desc.get_satisfaction(&satisfier).unwrap(), expected);
992 assert_eq!(desc.get_satisfaction_mall(&satisfier).unwrap(), expected);
993 assert!(matches!(
994 desc.get_satisfaction(()),
995 Err(Error::CouldNotSatisfy)
996 ));
997 assert!(matches!(
998 desc.get_satisfaction_mall(()),
999 Err(Error::CouldNotSatisfy)
1000 ));
1001 }
1002 }
1003
1004 #[test]
1005 fn test_for_each() {
1006 let desc = "eltr(acc0, {
1007 multi_a(3, acc10, acc11, acc12), {
1008 and_v(
1009 v:multi_a(2, acc10, acc11, acc12),
1010 after(10)
1011 ),
1012 and_v(
1013 v:multi_a(1, acc10, acc11, ac12),
1014 after(100)
1015 )
1016 }
1017 })";
1018 let desc = desc.replace(&[' ', '\n'][..], "");
1019 let tr = Tr::<String, NoExt>::from_str(&desc).unwrap();
1020 assert!(!tr.for_each_key(|k| k.starts_with("acc")));
1022 }
1023
1024 fn verify_from_str(desc_str: &str, internal_key: &str, scripts: &[TapLeafScript<String, NoExt>]) {
1025 let desc = Tr::<String, NoExt>::from_str(desc_str).unwrap();
1026 assert_eq!(desc_str, &desc.to_string());
1027 assert_eq!(internal_key, &desc.internal_key);
1028
1029 let desc_scripts: Vec<_> = desc.iter_scripts().collect();
1030 assert_eq!(scripts.len(), scripts.len());
1031
1032 for i in 0..scripts.len() {
1033 let script = &scripts[i];
1034 assert_eq!(script, &desc_scripts[i].1);
1035 }
1036 }
1037
1038 #[test]
1039 fn tr_from_str() {
1040 verify_from_str("eltr(internal)#0aen4jhp", "internal", &[]);
1042
1043 let ms = Miniscript::<String, Tap>::from_str("pk(a)").unwrap();
1045 verify_from_str(
1046 "eltr(internal,pk(a))#vadmk9gd", "internal",
1047 &[TapLeafScript::Miniscript(&ms)]
1048 );
1049
1050 #[cfg(feature = "simplicity")]
1051 {
1052 let sim = simplicity::Policy::Key("a".to_string());
1054 verify_from_str(
1055 "eltr(internal,sim{pk(a)})#duhmnzmm", "internal",
1056 &[TapLeafScript::Simplicity(&sim)]
1057 );
1058
1059 verify_from_str(
1061 "eltr(internal,{pk(a),sim{pk(a)}})#7vmfhpaj", "internal",
1062 &[TapLeafScript::Miniscript(&ms), TapLeafScript::Simplicity(&sim)]
1063 );
1064 }
1065 }
1066}