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> {
540 match self {
541 TapLeafScript::Miniscript(ms) => ms.satisfy_malleable(satisfier),
542 #[cfg(feature = "simplicity")]
544 TapLeafScript::Simplicity(..) => self.satisfy(satisfier),
545 }
546 }
547
548 pub fn satisfy<S: Satisfier<Pk>>(&self, satisfier: S) -> Result<Vec<Vec<u8>>, Error> {
550 match self {
551 TapLeafScript::Miniscript(ms) => ms.satisfy(satisfier),
552 #[cfg(feature = "simplicity")]
553 TapLeafScript::Simplicity(sim) => {
554 let satisfier = crate::simplicity::SatisfierWrapper::new(satisfier);
555 let program = sim.satisfy(&satisfier).map_err(|_| Error::CouldNotSatisfy)?;
556 let (program_bytes, witness_bytes) = program.encode_to_vec();
557 Ok(vec![program_bytes, witness_bytes])
558 }
559 }
560 }
561}
562
563#[derive(Debug, Clone)]
579pub struct TapTreeIter<'a, Pk: MiniscriptKey, Ext: Extension> {
580 stack: Vec<(usize, &'a TapTree<Pk, Ext>)>,
581}
582
583impl<'a, Pk, Ext> Iterator for TapTreeIter<'a, Pk, Ext>
584where
585 Pk: MiniscriptKey + 'a,
586 Ext: Extension,
587{
588 type Item = (usize, TapLeafScript<'a, Pk, Ext>);
589
590 fn next(&mut self) -> Option<Self::Item> {
591 while let Some((depth, last)) = self.stack.pop() {
592 match *last {
593 TapTree::Tree(ref l, ref r) => {
594 self.stack.push((depth + 1, r));
595 self.stack.push((depth + 1, l));
596 }
597 TapTree::Leaf(ref ms) => {
598 return Some((depth, TapLeafScript::Miniscript(ms)))
599 },
600 #[cfg(feature = "simplicity")]
601 TapTree::SimplicityLeaf(ref sim) => {
602 return Some((depth, TapLeafScript::Simplicity(sim)))
603 }
604 }
605 }
606 None
607 }
608}
609
610#[rustfmt::skip]
611impl_block_str!(
612 Tr<Pk, Ext>,
613 => Ext; Extension,
614 fn parse_tr_script_spend(tree: &expression::Tree,) -> Result<TapTree<Pk, Ext>, Error> {
616 match tree {
617 #[cfg(feature = "simplicity")]
618 expression::Tree { name, args } if *name == "sim" && args.len() == 1 => {
619 let policy = crate::simplicity::PolicyWrapper::<Pk>::from_str(args[0].name)?;
620 Ok(TapTree::SimplicityLeaf(Arc::new(policy.0)))
621 }
622 expression::Tree { name, args } if !name.is_empty() && args.is_empty() => {
623 let script = Miniscript::<Pk, Tap, Ext>::from_str(name)?;
624 Ok(TapTree::Leaf(Arc::new(script)))
625 }
626 expression::Tree { name, args } if name.is_empty() && args.len() == 2 => {
627 let left = Self::parse_tr_script_spend(&args[0])?;
628 let right = Self::parse_tr_script_spend(&args[1])?;
629 Ok(TapTree::Tree(Arc::new(left), Arc::new(right)))
630 }
631 _ => Err(Error::Unexpected(
632 "unknown format for script spending paths while parsing taproot descriptor"
633 .to_string(),
634 )),
635 }
636 }
637);
638
639impl_from_tree!(
640 Tr<Pk, Ext>,
641 => Ext; Extension,
642 fn from_tree(top: &expression::Tree) -> Result<Self, Error> {
643 if top.name == "eltr" {
644 match top.args.len() {
645 1 => {
646 let key = &top.args[0];
647 if !key.args.is_empty() {
648 return Err(Error::Unexpected(format!(
649 "#{} script associated with `key-path` while parsing taproot descriptor",
650 key.args.len()
651 )));
652 }
653 Tr::new(expression::terminal(key, Pk::from_str)?, None)
654 }
655 2 => {
656 let key = &top.args[0];
657 if !key.args.is_empty() {
658 return Err(Error::Unexpected(format!(
659 "#{} script associated with `key-path` while parsing taproot descriptor",
660 key.args.len()
661 )));
662 }
663 let tree = &top.args[1];
664 let ret = Self::parse_tr_script_spend(tree)?;
665 Tr::new(expression::terminal(key, Pk::from_str)?, Some(ret))
666 }
667 _ => {
668 Err(Error::Unexpected(format!(
669 "{}[#{} args] while parsing taproot descriptor",
670 top.name,
671 top.args.len()
672 )))
673 }
674 }
675 } else {
676 Err(Error::Unexpected(format!(
677 "{}[#{} args] while parsing taproot descriptor",
678 top.name,
679 top.args.len()
680 )))
681 }
682 }
683);
684
685impl_from_str!(
686 Tr<Pk, Ext>,
687 => Ext; Extension,
688 type Err = Error;,
689 fn from_str(s: &str) -> Result<Self, Self::Err> {
690 let desc_str = verify_checksum(s)?;
691 let top = parse_tr_tree(desc_str)?;
692 Self::from_tree(&top)
693 }
694);
695
696impl<Pk: MiniscriptKey, Ext: Extension> fmt::Debug for Tr<Pk, Ext> {
697 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
698 match self.tree {
699 Some(ref s) => write!(f, "tr({:?},{:?})", self.internal_key, s),
700 None => write!(f, "tr({:?})", self.internal_key),
701 }
702 }
703}
704
705impl<Pk: MiniscriptKey, Ext: Extension> fmt::Display for Tr<Pk, Ext> {
706 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
707 use fmt::Write;
708 let mut wrapped_f = checksum::Formatter::new(f);
709 let key = &self.internal_key;
710 match self.tree {
711 Some(ref s) => write!(wrapped_f, "{}tr({},{})", ELMTS_STR, key, s)?,
712 None => write!(wrapped_f, "{}tr({})", ELMTS_STR, key)?,
713 }
714 wrapped_f.write_checksum_if_not_alt()
715 }
716}
717
718fn parse_tr_tree(s: &str) -> Result<expression::Tree<'_>, Error> {
720 check_valid_chars(s)?;
721
722 if s.len() > 5 && &s[..5] == "eltr(" && s.as_bytes()[s.len() - 1] == b')' {
723 let rest = &s[5..s.len() - 1];
724 if !rest.contains(',') {
725 let internal_key = expression::Tree {
726 name: rest,
727 args: vec![],
728 };
729 return Ok(expression::Tree {
730 name: "eltr",
731 args: vec![internal_key],
732 });
733 }
734 let (key, script) = split_once(rest, ',')
736 .ok_or_else(|| Error::BadDescriptor("invalid taproot descriptor".to_string()))?;
737
738 let internal_key = expression::Tree {
739 name: key,
740 args: vec![],
741 };
742 if script.is_empty() {
743 return Ok(expression::Tree {
744 name: "eltr",
745 args: vec![internal_key],
746 });
747 }
748 let (tree, rest) = expression::Tree::from_slice_delim(script, 1, '{')?;
749 if rest.is_empty() {
750 Ok(expression::Tree {
751 name: "eltr",
752 args: vec![internal_key, tree],
753 })
754 } else {
755 Err(errstr(rest))
756 }
757 } else {
758 Err(Error::Unexpected("invalid taproot descriptor".to_string()))
759 }
760}
761
762fn split_once(inp: &str, delim: char) -> Option<(&str, &str)> {
763 if inp.is_empty() {
764 None
765 } else {
766 let mut found = inp.len();
767 for (idx, ch) in inp.chars().enumerate() {
768 if ch == delim {
769 found = idx;
770 break;
771 }
772 }
773 if found >= inp.len() - 1 {
775 Some((inp, ""))
776 } else {
777 Some((&inp[..found], &inp[found + 1..]))
778 }
779 }
780}
781
782impl<Pk: MiniscriptKey, Ext: Extension> Liftable<Pk> for TapTree<Pk, Ext> {
783 fn lift(&self) -> Result<Policy<Pk>, Error> {
784 fn lift_helper<Pk: MiniscriptKey, Ext: Extension>(
785 s: &TapTree<Pk, Ext>,
786 ) -> Result<Policy<Pk>, Error> {
787 match s {
788 TapTree::Tree(ref l, ref r) => {
789 Ok(Policy::Threshold(1, vec![lift_helper(l)?, lift_helper(r)?]))
790 }
791 TapTree::Leaf(ref leaf) => leaf.lift(),
792 #[cfg(feature = "simplicity")]
793 TapTree::SimplicityLeaf(..) => panic!("FIXME: Cannot lift Simplicity policy to Miniscript semantic policy"),
794 }
795 }
796
797 let pol = lift_helper(self)?;
798 Ok(pol.normalized())
799 }
800}
801
802impl<Pk: MiniscriptKey, Ext: Extension> Liftable<Pk> for Tr<Pk, Ext> {
803 fn lift(&self) -> Result<Policy<Pk>, Error> {
804 match &self.tree {
805 Some(root) => Ok(Policy::Threshold(
806 1,
807 vec![Policy::Key(self.internal_key.clone()), root.lift()?],
808 )),
809 None => Ok(Policy::Key(self.internal_key.clone())),
810 }
811 }
812}
813
814impl<Pk: MiniscriptKey, Ext: Extension> ForEachKey<Pk> for Tr<Pk, Ext> {
815 fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool
816 where
817 Pk: 'a,
818 {
819 let script_keys_res = self
820 .iter_scripts()
821 .all(|(_d, script)| {
822 match script {
823 TapLeafScript::Miniscript(ms) => ms.for_each_key(&mut pred),
824 #[cfg(feature = "simplicity")]
825 TapLeafScript::Simplicity(sim) => crate::simplicity::for_each_key(sim, &mut pred),
826 }
827 });
828 script_keys_res && pred(&self.internal_key)
829 }
830}
831
832impl<P, Q, Ext> TranslatePk<P, Q> for Tr<P, Ext>
833where
834 P: MiniscriptKey,
835 Q: MiniscriptKey,
836 Ext: Extension,
837{
838 type Output = Tr<Q, Ext>;
839
840 fn translate_pk<T, E>(&self, translate: &mut T) -> Result<Self::Output, E>
841 where
842 T: Translator<P, Q, E>,
843 {
844 let translate_desc = Tr {
845 internal_key: translate.pk(&self.internal_key)?,
846 tree: match &self.tree {
847 Some(tree) => Some(tree.translate_helper(translate)?),
848 None => None,
849 },
850 spend_info: Mutex::new(None),
851 };
852 Ok(translate_desc)
853 }
854}
855
856impl<PExt, QExt, Pk> TranslateExt<PExt, QExt> for Tr<Pk, PExt>
857where
858 PExt: Extension + TranslateExt<PExt, QExt, Output = QExt>,
859 QExt: Extension,
860 Pk: MiniscriptKey,
861{
862 type Output = Tr<Pk, QExt>;
863
864 fn translate_ext<T, E>(&self, translator: &mut T) -> Result<Self::Output, E>
865 where
866 T: crate::ExtTranslator<PExt, QExt, E>,
867 {
868 let translate_desc = Tr {
869 internal_key: self.internal_key.clone(),
870 tree: match &self.tree {
871 Some(tree) => Some(tree.translate_ext_helper(translator)?),
872 None => None,
873 },
874 spend_info: Mutex::new(None),
875 };
876 Ok(translate_desc)
877 }
878}
879
880fn control_block_len(depth: usize) -> usize {
882 TAPROOT_CONTROL_BASE_SIZE + depth * TAPROOT_CONTROL_NODE_SIZE
883}
884
885fn best_tap_spend<Pk, S, Ext>(
888 desc: &Tr<Pk, Ext>,
889 satisfier: S,
890 allow_mall: bool,
891) -> Result<(Vec<Vec<u8>>, Script), Error>
892where
893 Pk: ToPublicKey,
894 S: Satisfier<Pk>,
895 Ext: ParseableExt,
896{
897 let spend_info = desc.spend_info();
898 if let Some(sig) = satisfier.lookup_tap_key_spend_sig() {
900 Ok((vec![sig.to_vec()], Script::new()))
901 } else {
902 let (mut min_wit, mut min_wit_len) = (None, None);
905 for (depth, script) in desc.iter_scripts() {
906 let mut wit = if allow_mall {
907 match script.satisfy_malleable(&satisfier) {
908 Ok(wit) => wit,
909 Err(..) => continue, }
911 } else {
912 match script.satisfy(&satisfier) {
913 Ok(wit) => wit,
914 Err(..) => continue, }
916 };
917 let wit_size = witness_size(&wit)
921 + control_block_len(depth)
922 + script.script_size()
923 + varint_len(script.script_size());
924
925 if min_wit_len.is_some() && Some(wit_size) > min_wit_len {
926 continue;
927 } else {
928 let leaf_script = (script.encode(), script.version());
929 let control_block = spend_info
930 .control_block(&leaf_script)
931 .expect("Control block must exist in script map for every known leaf");
932 wit.push(leaf_script.0.into_bytes()); wit.push(control_block.serialize());
936 min_wit = Some(wit);
938 min_wit_len = Some(wit_size);
939 }
940 }
941 match min_wit {
942 Some(wit) => Ok((wit, Script::new())),
943 None => Err(Error::CouldNotSatisfy), }
945 }
946}
947
948#[cfg(test)]
949mod tests {
950 use super::*;
951 use crate::{ForEachKey, NoExt};
952
953 #[test]
954 fn test_for_each() {
955 let desc = "eltr(acc0, {
956 multi_a(3, acc10, acc11, acc12), {
957 and_v(
958 v:multi_a(2, acc10, acc11, acc12),
959 after(10)
960 ),
961 and_v(
962 v:multi_a(1, acc10, acc11, ac12),
963 after(100)
964 )
965 }
966 })";
967 let desc = desc.replace(&[' ', '\n'][..], "");
968 let tr = Tr::<String, NoExt>::from_str(&desc).unwrap();
969 assert!(!tr.for_each_key(|k| k.starts_with("acc")));
971 }
972
973 fn verify_from_str(desc_str: &str, internal_key: &str, scripts: &[TapLeafScript<String, NoExt>]) {
974 let desc = Tr::<String, NoExt>::from_str(desc_str).unwrap();
975 assert_eq!(desc_str, &desc.to_string());
976 assert_eq!(internal_key, &desc.internal_key);
977
978 let desc_scripts: Vec<_> = desc.iter_scripts().collect();
979 assert_eq!(scripts.len(), scripts.len());
980
981 for i in 0..scripts.len() {
982 let script = &scripts[i];
983 assert_eq!(script, &desc_scripts[i].1);
984 }
985 }
986
987 #[test]
988 fn tr_from_str() {
989 verify_from_str("eltr(internal)#0aen4jhp", "internal", &[]);
991
992 let ms = Miniscript::<String, Tap>::from_str("pk(a)").unwrap();
994 verify_from_str(
995 "eltr(internal,pk(a))#vadmk9gd", "internal",
996 &[TapLeafScript::Miniscript(&ms)]
997 );
998
999 #[cfg(feature = "simplicity")]
1000 {
1001 let sim = simplicity::Policy::Key("a".to_string());
1003 verify_from_str(
1004 "eltr(internal,sim{pk(a)})#duhmnzmm", "internal",
1005 &[TapLeafScript::Simplicity(&sim)]
1006 );
1007
1008 verify_from_str(
1010 "eltr(internal,{pk(a),sim{pk(a)}})#7vmfhpaj", "internal",
1011 &[TapLeafScript::Miniscript(&ms), TapLeafScript::Simplicity(&sim)]
1012 );
1013 }
1014 }
1015}