Skip to main content

elements_miniscript/descriptor/
tr.rs

1// SPDX-License-Identifier: CC0-1.0
2use 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/// A Taproot Tree representation.
29// Hidden leaves are not yet supported in descriptor spec. Conceptually, it should
30// be simple to integrate those here, but it is best to wait on core for the exact syntax.
31#[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
32#[non_exhaustive]
33pub enum TapTree<Pk: MiniscriptKey, Ext: Extension = NoExt> {
34    /// A taproot tree structure
35    Tree(Arc<TapTree<Pk, Ext>>, Arc<TapTree<Pk, Ext>>),
36    /// A taproot leaf denoting a spending condition
37    // A new leaf version would require a new Context, therefore there is no point
38    // in adding a LeafVersion with Leaf type here. All Miniscripts right now
39    // are of Leafversion::default
40    Leaf(Arc<Miniscript<Pk, Tap, Ext>>),
41    /// A taproot leaf denoting a spending condition in terms of Simplicity
42    #[cfg(feature = "simplicity")]
43    SimplicityLeaf(Arc<simplicity::Policy<Pk>>),
44}
45
46/// A taproot descriptor
47pub struct Tr<Pk: MiniscriptKey, Ext: Extension = NoExt> {
48    /// A taproot internal key
49    internal_key: Pk,
50    /// Optional Taproot Tree with spending conditions
51    tree: Option<TapTree<Pk, Ext>>,
52    /// Optional spending information associated with the descriptor
53    /// This will be [`None`] when the descriptor is not derived.
54    /// This information will be cached automatically when it is required
55    //
56    // The inner `Arc` here is because Rust does not allow us to return a reference
57    // to the contents of the `Option` from inside a `MutexGuard`. There is no outer
58    // `Arc` because when this structure is cloned, we create a whole new mutex.
59    spend_info: Mutex<Option<Arc<TaprootSpendInfo>>>,
60}
61
62impl<Pk: MiniscriptKey, Ext: Extension> Clone for Tr<Pk, Ext> {
63    fn clone(&self) -> Self {
64        // When cloning, construct a new Mutex so that distinct clones don't
65        // cause blocking between each other. We clone only the internal `Arc`,
66        // so the clone is always cheap (in both time and space)
67        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    // Helper function to compute height
114    // TODO: Instead of computing this every time we add a new leaf, we should
115    // add height as a separate field in taptree
116    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    /// Iterates over all miniscripts in DFS walk order compatible with the
128    /// PSBT requirements (BIP 371).
129    pub fn iter(&self) -> TapTreeIter<'_, Pk, Ext> {
130        TapTreeIter {
131            stack: vec![(0, self)],
132        }
133    }
134
135    // Helper function to translate keys
136    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    // Helper function to translate extensions
174    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    /// Create a new [`Tr`] descriptor from internal key and [`TapTree`]
217    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    /// Obtain the internal key of [`Tr`] descriptor
232    pub fn internal_key(&self) -> &Pk {
233        &self.internal_key
234    }
235
236    /// Obtain the [`TapTree`] of the [`Tr`] descriptor
237    pub fn taptree(&self) -> &Option<TapTree<Pk, Ext>> {
238        &self.tree
239    }
240
241    /// Iterate over all scripts in merkle tree. If there is no script path, the iterator
242    /// yields [`None`]
243    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    /// Compute the [`TaprootSpendInfo`] associated with this descriptor if spend data is `None`.
251    ///
252    /// If spend data is already computed (i.e it is not `None`), this does not recompute it.
253    ///
254    /// [`TaprootSpendInfo`] is only required for spending via the script paths.
255    pub fn spend_info(&self) -> Arc<TaprootSpendInfo>
256    where
257        Pk: ToPublicKey,
258        Ext: ParseableExt,
259    {
260        // If the value is already cache, read it
261        // read only panics if the lock is poisoned (meaning other thread having a lock panicked)
262        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        // Get a new secp context
269        // This would be cheap operation after static context support from upstream
270        let secp = secp256k1_zkp::Secp256k1::verification_only();
271        // Key spend path with no merkle root
272        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            // Assert builder cannot error here because we have a well formed descriptor
282            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    /// Checks whether the descriptor is safe.
293    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                // TODO: Add sanity check for Simplicity policies
298                #[cfg(feature = "simplicity")]
299                TapLeafScript::Simplicity(..) => {},
300            }
301        }
302        Ok(())
303    }
304
305    /// Computes an upper bound on the difference between a non-satisfied
306    /// `TxIn`'s `segwit_weight` and a satisfied `TxIn`'s `segwit_weight`
307    ///
308    /// Assumes all Schnorr signatures are 66 bytes, including push opcode and
309    /// sighash suffix.
310    ///
311    /// # Errors
312    /// When the descriptor is impossible to safisfy (ex: sh(OP_FALSE)).
313    pub fn max_weight_to_satisfy(&self) -> Result<usize, Error> {
314        let tree = match self.taptree() {
315            None => {
316                // key spend path
317                // item: varint(sig+sigHash) + <sig(64)+sigHash(1)>
318                let item_sig_size = 1 + 65;
319                // 1 stack item
320                let stack_varint_diff = varint_len(1) - varint_len(0);
321
322                return Ok(stack_varint_diff + item_sig_size);
323            }
324            // script path spend..
325            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                // stack varint difference (+1 for ctrl block, witness script already included)
336                let stack_varint_diff = varint_len(max_sat_elems + 1) - varint_len(0);
337
338                Some(
339                    stack_varint_diff +
340                    // size of elements to satisfy script
341                    max_sat_size +
342                    // second to last element: script
343                    varint_len(script_size) +
344                    script_size +
345                    // last element: control block
346                    varint_len(control_block_size) +
347                    control_block_size,
348                )
349            })
350            .max()
351            .ok_or(Error::ImpossibleSatisfaction)
352    }
353
354    /// Computes an upper bound on the weight of a satisfying witness to the
355    /// transaction.
356    ///
357    /// Assumes all ec-signatures are 73 bytes, including push opcode and
358    /// sighash suffix. Includes the weight of the VarInts encoding the
359    /// scriptSig and witness stack length.
360    ///
361    /// # Errors
362    /// When the descriptor is impossible to safisfy (ex: sh(OP_FALSE)).
363    #[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            // key spend path:
367            // scriptSigLen(4) + stackLen(1) + stack[Sig]Len(1) + stack[Sig](65)
368            None => return Ok(4 + 1 + 1 + 65),
369            // script path spend..
370            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                    // scriptSig len byte
381                    4 +
382                    // witness field stack len (+2 for control block & script)
383                    varint_len(max_sat_elems + 2) +
384                    // size of elements to satisfy script
385                    max_sat_size +
386                    // second to last element: script
387                    varint_len(script_size) +
388                    script_size +
389                    // last element: control block
390                    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    /// Obtains the corresponding script pubkey for this descriptor.
401    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    /// Obtains the corresponding address for this descriptor.
411    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    /// Returns satisfying non-malleable witness and scriptSig with minimum
421    /// weight to spend an output controlled by the given descriptor if it is
422    /// possible to construct one using the `satisfier`.
423    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 /* allow_mall */)
428    }
429
430    /// Returns satisfying, possibly malleable, witness and scriptSig with
431    /// minimum weight to spend an output controlled by the given descriptor if
432    /// it is possible to construct one using the `satisfier`.
433    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 /* allow_mall */)
438    }
439}
440
441/// Script at a tap leaf.
442#[derive(Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
443#[non_exhaustive]
444pub enum TapLeafScript<'a, Pk: MiniscriptKey, Ext: Extension> {
445    /// Miniscript leaf
446    Miniscript(&'a Miniscript<Pk, Tap, Ext>),
447    /// Simplicity leaf
448    #[cfg(feature = "simplicity")]
449    Simplicity(&'a simplicity::Policy<Pk>)
450}
451
452impl<'a, Pk: MiniscriptKey, Ext: Extension> TapLeafScript<'a, Pk, Ext> {
453    /// Get the Miniscript at the leaf, if it exists.
454    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    /// Get the Simplicity policy at the leaf, if it exists.
463    #[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    /// Return the version of the leaf.
472    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    /// Return the byte size of the encoded leaf script (witness script).
481    pub fn script_size(&self) -> usize {
482        match self {
483            TapLeafScript::Miniscript(ms) => ms.script_size(),
484            // Simplicity's witness script is always a 32-byte CMR
485            #[cfg(feature = "simplicity")]
486            TapLeafScript::Simplicity(..) => 32,
487        }
488    }
489
490    /// Return the maximum number of witness elements used to satisfied the leaf script,
491    /// including the witness script itself.
492    pub fn max_satisfaction_witness_elements(&self) -> Result<usize, Error> {
493        match self {
494            TapLeafScript::Miniscript(ms) => ms.max_satisfaction_witness_elements(),
495            // Simplicity always has one witness element plus leaf script:
496            // (1) Encoded program+witness
497            // (2) CMR program
498            // The third element is the control block, which is not counted by this method.
499            #[cfg(feature = "simplicity")]
500            TapLeafScript::Simplicity(..) => Ok(2),
501        }
502    }
503
504    /// Return the maximum byte size of a satisfying witness.
505    pub fn max_satisfaction_size(&self) -> Result<usize, Error> {
506        match self {
507            TapLeafScript::Miniscript(ms) => ms.max_satisfaction_size(),
508            // There is currently no way to bound the Simplicity witness size without producing one
509            // We mark the witness size as malleable since it depends on the chosen spending path
510            // TODO: Add method to simplicity::Policy and use it here
511            #[cfg(feature = "simplicity")]
512            TapLeafScript::Simplicity(..) => Err(Error::AnalysisError(crate::AnalysisError::Malleable))
513        }
514    }
515
516    /// Return an iterator over the plain public keys (and not key hash values) of the leaf script.
517    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    /// Encode the leaf script as Bitcoin script (witness script).
528    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    /// Attempt to produce a malleable satisfying witness for the leaf script.
539    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            // There doesn't (yet?) exist a malleable satisfaction of Simplicity policy
543            #[cfg(feature = "simplicity")]
544            TapLeafScript::Simplicity(..) => self.satisfy(satisfier),
545        }
546    }
547
548    /// Attempt to produce a non-malleable satisfying witness for the leaf script.
549    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/// Iterator over the leaves of a tap tree.
564///
565/// Each leaf consists is a pair of (depth, script).
566/// The leaves are yielded in a depth-first walk.
567///
568/// For example, this tree:
569///                                     - N0 -
570///                                    /     \\
571///                                   N1      N2
572///                                  /  \    /  \\
573///                                 A    B  C   N3
574///                                            /  \\
575///                                           D    E
576/// would yield (2, A), (2, B), (2,C), (3, D), (3, E).
577///
578#[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    // Helper function to parse taproot script path
615    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
718// Helper function to parse string into miniscript tree form
719fn 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        // use str::split_once() method to refactor this when compiler version bumps up
735        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        // No comma or trailing comma found
774        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
880// Helper function to compute the len of control block at a given depth
881fn control_block_len(depth: usize) -> usize {
882    TAPROOT_CONTROL_BASE_SIZE + depth * TAPROOT_CONTROL_NODE_SIZE
883}
884
885// Helper function to get a script spend satisfaction
886// try script spend
887fn 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    // First try the key spend path
899    if let Some(sig) = satisfier.lookup_tap_key_spend_sig() {
900        Ok((vec![sig.to_vec()], Script::new()))
901    } else {
902        // Since we have the complete descriptor we can ignore the satisfier. We don't use the control block
903        // map (lookup_control_block) from the satisfier here.
904        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, // No witness for this script in tr descriptor, look for next one
910                }
911            } else {
912                match script.satisfy(&satisfier) {
913                    Ok(wit) => wit,
914                    Err(..) => continue, // No witness for this script in tr descriptor, look for next one
915                }
916            };
917            // Compute the final witness size
918            // Control block len + script len + witnesssize + varint(wit.len + 2)
919            // The extra +2 elements are control block and script itself
920            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()); // Push the leaf script
933                                                      // There can be multiple control blocks for a (script, ver) pair
934                                                      // Find the smallest one amongst those
935                wit.push(control_block.serialize());
936                // Finally, save the minimum
937                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), // Could not satisfy all miniscripts inside Tr
944        }
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        // Note the last ac12 only has ac and fails the predicate
970        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        // Key spend only
990        verify_from_str("eltr(internal)#0aen4jhp", "internal", &[]);
991
992        // Miniscript key spend
993        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            // Simplicity key spend
1002            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            // Mixed Miniscript and Simplicity
1009            verify_from_str(
1010                "eltr(internal,{pk(a),sim{pk(a)}})#7vmfhpaj", "internal",
1011                &[TapLeafScript::Miniscript(&ms), TapLeafScript::Simplicity(&sim)]
1012            );
1013        }
1014    }
1015}