miniscript_debug/miniscript/
mod.rs

1// Miniscript
2// Written in 2019 by
3//     Andrew Poelstra <apoelstra@wpsoftware.net>
4//
5// To the extent possible under law, the author(s) have dedicated all
6// copyright and related and neighboring rights to this software to
7// the public domain worldwide. This software is distributed without
8// any warranty.
9//
10// You should have received a copy of the CC0 Public Domain Dedication
11// along with this software.
12// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
13//
14
15//! # Abstract Syntax Tree
16//!
17//! Defines a variety of data structures for describing Miniscript, a subset of
18//! Bitcoin Script which can be efficiently parsed and serialized from Script,
19//! and from which it is easy to extract data needed to construct witnesses.
20//!
21//! Users of the library in general will only need to use the structures exposed
22//! from the top level of this module; however for people wanting to do advanced
23//! things, the submodules are public as well which provide visibility into the
24//! components of the AST.
25//!
26
27use core::marker::PhantomData;
28use core::{fmt, hash, str};
29
30use bitcoin::blockdata::script;
31use bitcoin::util::taproot::{LeafVersion, TapLeafHash};
32
33use self::analyzable::ExtParams;
34pub use self::context::{BareCtx, Legacy, Segwitv0, Tap};
35use crate::prelude::*;
36
37pub mod analyzable;
38pub mod astelem;
39pub(crate) mod context;
40pub mod decode;
41pub mod hash256;
42pub mod iter;
43pub mod lex;
44pub mod limits;
45pub mod satisfy;
46pub mod types;
47
48use core::cmp;
49
50use sync::Arc;
51
52use self::lex::{lex, TokenIter};
53use self::types::Property;
54pub use crate::miniscript::context::ScriptContext;
55use crate::miniscript::decode::Terminal;
56use crate::miniscript::types::extra_props::ExtData;
57use crate::miniscript::types::Type;
58use crate::{expression, Error, ForEachKey, MiniscriptKey, ToPublicKey, TranslatePk, Translator};
59#[cfg(test)]
60mod ms_tests;
61
62/// Top-level script AST type
63#[derive(Clone)]
64pub struct Miniscript<Pk: MiniscriptKey, Ctx: ScriptContext> {
65    ///A node in the Abstract Syntax Tree(
66    pub node: Terminal<Pk, Ctx>,
67    ///The correctness and malleability type information for the AST node
68    pub ty: types::Type,
69    ///Additional information helpful for extra analysis.
70    pub ext: types::extra_props::ExtData,
71    /// Context PhantomData. Only accessible inside this crate
72    pub(crate) phantom: PhantomData<Ctx>,
73}
74
75/// `PartialOrd` of `Miniscript` must depend only on node and not the type information.
76/// The type information and extra_properties can be deterministically determined
77/// by the ast.
78impl<Pk: MiniscriptKey, Ctx: ScriptContext> PartialOrd for Miniscript<Pk, Ctx> {
79    fn partial_cmp(&self, other: &Miniscript<Pk, Ctx>) -> Option<cmp::Ordering> {
80        Some(self.node.cmp(&other.node))
81    }
82}
83
84/// `Ord` of `Miniscript` must depend only on node and not the type information.
85/// The type information and extra_properties can be deterministically determined
86/// by the ast.
87impl<Pk: MiniscriptKey, Ctx: ScriptContext> Ord for Miniscript<Pk, Ctx> {
88    fn cmp(&self, other: &Miniscript<Pk, Ctx>) -> cmp::Ordering {
89        self.node.cmp(&other.node)
90    }
91}
92
93/// `PartialEq` of `Miniscript` must depend only on node and not the type information.
94/// The type information and extra_properties can be deterministically determined
95/// by the ast.
96impl<Pk: MiniscriptKey, Ctx: ScriptContext> PartialEq for Miniscript<Pk, Ctx> {
97    fn eq(&self, other: &Miniscript<Pk, Ctx>) -> bool {
98        self.node.eq(&other.node)
99    }
100}
101
102/// `Eq` of `Miniscript` must depend only on node and not the type information.
103/// The type information and extra_properties can be deterministically determined
104/// by the ast.
105impl<Pk: MiniscriptKey, Ctx: ScriptContext> Eq for Miniscript<Pk, Ctx> {}
106
107impl<Pk: MiniscriptKey, Ctx: ScriptContext> fmt::Debug for Miniscript<Pk, Ctx> {
108    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109        write!(f, "{:?}", self.node)
110    }
111}
112
113impl<Pk: MiniscriptKey, Ctx: ScriptContext> hash::Hash for Miniscript<Pk, Ctx> {
114    fn hash<H: hash::Hasher>(&self, state: &mut H) {
115        self.node.hash(state);
116    }
117}
118
119impl<Pk: MiniscriptKey, Ctx: ScriptContext> Miniscript<Pk, Ctx> {
120    /// Add type information(Type and Extdata) to Miniscript based on
121    /// `AstElem` fragment. Dependent on display and clone because of Error
122    /// Display code of type_check.
123    pub fn from_ast(t: Terminal<Pk, Ctx>) -> Result<Miniscript<Pk, Ctx>, Error> {
124        Ok(Miniscript {
125            ty: Type::type_check(&t, |_| None)?,
126            ext: ExtData::type_check(&t, |_| None)?,
127            node: t,
128            phantom: PhantomData,
129        })
130    }
131}
132
133impl<Pk: MiniscriptKey, Ctx: ScriptContext> fmt::Display for Miniscript<Pk, Ctx> {
134    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
135        write!(f, "{}", self.node)
136    }
137}
138
139impl<Pk: MiniscriptKey, Ctx: ScriptContext> Miniscript<Pk, Ctx> {
140    /// Extracts the `AstElem` representing the root of the miniscript
141    pub fn into_inner(self) -> Terminal<Pk, Ctx> {
142        self.node
143    }
144
145    /// Get a reference to the inner `AstElem` representing the root of miniscript
146    pub fn as_inner(&self) -> &Terminal<Pk, Ctx> {
147        &self.node
148    }
149}
150
151impl<Ctx: ScriptContext> Miniscript<Ctx::Key, Ctx> {
152    /// Attempt to parse an insane(scripts don't clear sanity checks)
153    /// script into a Miniscript representation.
154    /// Use this to parse scripts with repeated pubkeys, timelock mixing, malleable
155    /// scripts without sig or scripts that can exceed resource limits.
156    /// Some of the analysis guarantees of miniscript are lost when dealing with
157    /// insane scripts. In general, in a multi-party setting users should only
158    /// accept sane scripts.
159    pub fn parse_insane(script: &script::Script) -> Result<Miniscript<Ctx::Key, Ctx>, Error> {
160        Miniscript::parse_with_ext(script, &ExtParams::insane())
161    }
162
163    /// Attempt to parse an miniscript with extra features that not yet specified in the spec.
164    /// Users should not use this function unless they scripts can/will change in the future.
165    /// Currently, this function supports the following features:
166    ///     - Parsing all insane scripts
167    ///     - Parsing miniscripts with raw pubkey hashes
168    ///
169    /// Allowed extra features can be specified by the ext [`ExtParams`] argument.
170    pub fn parse_with_ext(
171        script: &script::Script,
172        ext: &ExtParams,
173    ) -> Result<Miniscript<Ctx::Key, Ctx>, Error> {
174        let tokens = lex(script)?;
175        let mut iter = TokenIter::new(tokens);
176
177        let top = decode::parse(&mut iter)?;
178        Ctx::check_global_validity(&top)?;
179        let type_check = types::Type::type_check(&top.node, |_| None)?;
180        if type_check.corr.base != types::Base::B {
181            return Err(Error::NonTopLevel(format!("{:?}", top)));
182        };
183        if let Some(leading) = iter.next() {
184            Err(Error::Trailing(leading.to_string()))
185        } else {
186            top.ext_check(ext)?;
187            Ok(top)
188        }
189    }
190
191    /// Attempt to parse a Script into Miniscript representation.
192    ///
193    /// This function will fail parsing for scripts that do not clear the
194    /// [`Miniscript::sanity_check`] checks. Use [`Miniscript::parse_insane`] to
195    /// parse such scripts.
196    ///
197    /// ## Decode/Parse a miniscript from script hex
198    ///
199    /// ```rust
200    /// use miniscript::{Miniscript, Segwitv0, Tap};
201    /// use miniscript::bitcoin::secp256k1::XOnlyPublicKey;
202    /// use miniscript::bitcoin::hashes::hex::FromHex;
203    ///
204    /// type Segwitv0Script = Miniscript<bitcoin::PublicKey, Segwitv0>;
205    /// type TapScript = Miniscript<XOnlyPublicKey, Tap>;
206    ///
207    /// // parse x-only miniscript in Taproot context
208    /// let tapscript_ms = TapScript::parse(&bitcoin::Script::from(Vec::<u8>::from_hex(
209    ///     "202788ee41e76f4f3af603da5bc8fa22997bc0344bb0f95666ba6aaff0242baa99ac",
210    /// ).expect("Even length hex")))
211    ///     .expect("Xonly keys are valid only in taproot context");
212    /// // tapscript fails decoding when we use them with compressed keys
213    /// let err = TapScript::parse(&bitcoin::Script::from(Vec::<u8>::from_hex(
214    ///     "21022788ee41e76f4f3af603da5bc8fa22997bc0344bb0f95666ba6aaff0242baa99ac",
215    /// ).expect("Even length hex")))
216    ///     .expect_err("Compressed keys cannot be used in Taproot context");
217    /// // Segwitv0 succeeds decoding with full keys.
218    /// Segwitv0Script::parse(&bitcoin::Script::from(Vec::<u8>::from_hex(
219    ///     "21022788ee41e76f4f3af603da5bc8fa22997bc0344bb0f95666ba6aaff0242baa99ac",
220    /// ).expect("Even length hex")))
221    ///     .expect("Compressed keys are allowed in Segwit context");
222    ///
223    /// ```
224    pub fn parse(script: &script::Script) -> Result<Miniscript<Ctx::Key, Ctx>, Error> {
225        let ms = Self::parse_with_ext(script, &ExtParams::sane())?;
226        Ok(ms)
227    }
228}
229
230impl<Pk, Ctx> Miniscript<Pk, Ctx>
231where
232    Pk: MiniscriptKey,
233    Ctx: ScriptContext,
234{
235    /// Encode as a Bitcoin script
236    pub fn encode(&self) -> script::Script
237    where
238        Pk: ToPublicKey,
239    {
240        self.node.encode(script::Builder::new()).into_script()
241    }
242
243    /// Size, in bytes of the script-pubkey. If this Miniscript is used outside
244    /// of segwit (e.g. in a bare or P2SH descriptor), this quantity should be
245    /// multiplied by 4 to compute the weight.
246    ///
247    /// In general, it is not recommended to use this function directly, but
248    /// to instead call the corresponding function on a `Descriptor`, which
249    /// will handle the segwit/non-segwit technicalities for you.
250    pub fn script_size(&self) -> usize {
251        self.node.script_size()
252    }
253}
254
255impl<Pk: MiniscriptKey, Ctx: ScriptContext> Miniscript<Pk, Ctx> {
256    /// Maximum number of witness elements used to satisfy the Miniscript
257    /// fragment, including the witness script itself. Used to estimate
258    /// the weight of the `VarInt` that specifies this number in a serialized
259    /// transaction.
260    ///
261    /// This function may returns Error when the Miniscript is
262    /// impossible to satisfy
263    pub fn max_satisfaction_witness_elements(&self) -> Result<usize, Error> {
264        self.ext
265            .stack_elem_count_sat
266            .map(|x| x + 1)
267            .ok_or(Error::ImpossibleSatisfaction)
268    }
269
270    /// Maximum size, in bytes, of a satisfying witness. For Segwit outputs
271    /// `one_cost` should be set to 2, since the number `1` requires two
272    /// bytes to encode. For non-segwit outputs `one_cost` should be set to
273    /// 1, since `OP_1` is available in scriptSigs.
274    ///
275    /// In general, it is not recommended to use this function directly, but
276    /// to instead call the corresponding function on a `Descriptor`, which
277    /// will handle the segwit/non-segwit technicalities for you.
278    ///
279    /// All signatures are assumed to be 73 bytes in size, including the
280    /// length prefix (segwit) or push opcode (pre-segwit) and sighash
281    /// postfix.
282    pub fn max_satisfaction_size(&self) -> Result<usize, Error> {
283        Ctx::max_satisfaction_size(self).ok_or(Error::ImpossibleSatisfaction)
284    }
285}
286
287impl<Pk: MiniscriptKey, Ctx: ScriptContext> ForEachKey<Pk> for Miniscript<Pk, Ctx> {
288    fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool
289    where
290        Pk: 'a,
291    {
292        self.real_for_each_key(&mut pred)
293    }
294}
295
296impl<Pk, Q, Ctx> TranslatePk<Pk, Q> for Miniscript<Pk, Ctx>
297where
298    Pk: MiniscriptKey,
299    Q: MiniscriptKey,
300    Ctx: ScriptContext,
301{
302    type Output = Miniscript<Q, Ctx>;
303
304    /// Translates a struct from one generic to another where the translation
305    /// for Pk is provided by [`Translator`]
306    fn translate_pk<T, E>(&self, translate: &mut T) -> Result<Self::Output, E>
307    where
308        T: Translator<Pk, Q, E>,
309    {
310        self.real_translate_pk(translate)
311    }
312}
313
314impl<Pk: MiniscriptKey, Ctx: ScriptContext> Miniscript<Pk, Ctx> {
315    fn real_for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, pred: &mut F) -> bool
316    where
317        Pk: 'a,
318    {
319        self.node.real_for_each_key(pred)
320    }
321
322    pub(super) fn real_translate_pk<Q, CtxQ, T, FuncError>(
323        &self,
324        t: &mut T,
325    ) -> Result<Miniscript<Q, CtxQ>, FuncError>
326    where
327        Q: MiniscriptKey,
328        CtxQ: ScriptContext,
329        T: Translator<Pk, Q, FuncError>,
330    {
331        let inner = self.node.real_translate_pk(t)?;
332        let ms = Miniscript {
333            //directly copying the type and ext is safe because translating public
334            //key should not change any properties
335            ty: self.ty,
336            ext: self.ext,
337            node: inner,
338            phantom: PhantomData,
339        };
340        Ok(ms)
341    }
342}
343
344impl_block_str!(
345    ;Ctx; ScriptContext,
346    Miniscript<Pk, Ctx>,
347    /// Attempt to parse an insane(scripts don't clear sanity checks)
348    /// from string into a Miniscript representation.
349    /// Use this to parse scripts with repeated pubkeys, timelock mixing, malleable
350    /// scripts without sig or scripts that can exceed resource limits.
351    /// Some of the analysis guarantees of miniscript are lost when dealing with
352    /// insane scripts. In general, in a multi-party setting users should only
353    /// accept sane scripts.
354    pub fn from_str_insane(s: &str,) -> Result<Miniscript<Pk, Ctx>, Error>
355    {
356        Miniscript::from_str_ext(s, &ExtParams::insane())
357    }
358);
359
360impl_block_str!(
361    ;Ctx; ScriptContext,
362    Miniscript<Pk, Ctx>,
363    /// Attempt to parse an Miniscripts that don't follow the spec.
364    /// Use this to parse scripts with repeated pubkeys, timelock mixing, malleable
365    /// scripts, raw pubkey hashes without sig or scripts that can exceed resource limits.
366    ///
367    /// Use [`ExtParams`] builder to specify the types of non-sane rules to allow while parsing.
368    pub fn from_str_ext(s: &str, ext: &ExtParams,) -> Result<Miniscript<Pk, Ctx>, Error>
369    {
370        // This checks for invalid ASCII chars
371        let top = expression::Tree::from_str(s)?;
372        let ms: Miniscript<Pk, Ctx> = expression::FromTree::from_tree(&top)?;
373        ms.ext_check(ext)?;
374
375        if ms.ty.corr.base != types::Base::B {
376            Err(Error::NonTopLevel(format!("{:?}", ms)))
377        } else {
378            Ok(ms)
379        }
380    }
381);
382
383impl<Pk: MiniscriptKey, Ctx: ScriptContext> Miniscript<Pk, Ctx> {
384    /// Attempt to produce non-malleable satisfying witness for the
385    /// witness script represented by the parse tree
386    pub fn satisfy<S: satisfy::Satisfier<Pk>>(&self, satisfier: S) -> Result<Vec<Vec<u8>>, Error>
387    where
388        Pk: ToPublicKey,
389    {
390        // Only satisfactions for default versions (0xc0) are allowed.
391        let leaf_hash = TapLeafHash::from_script(&self.encode(), LeafVersion::TapScript);
392        match satisfy::Satisfaction::satisfy(&self.node, &satisfier, self.ty.mall.safe, &leaf_hash)
393            .stack
394        {
395            satisfy::Witness::Stack(stack) => {
396                Ctx::check_witness::<Pk>(&stack)?;
397                Ok(stack)
398            }
399            satisfy::Witness::Unavailable | satisfy::Witness::Impossible => {
400                Err(Error::CouldNotSatisfy)
401            }
402        }
403    }
404
405    /// Attempt to produce a malleable satisfying witness for the
406    /// witness script represented by the parse tree
407    pub fn satisfy_malleable<S: satisfy::Satisfier<Pk>>(
408        &self,
409        satisfier: S,
410    ) -> Result<Vec<Vec<u8>>, Error>
411    where
412        Pk: ToPublicKey,
413    {
414        let leaf_hash = TapLeafHash::from_script(&self.encode(), LeafVersion::TapScript);
415        match satisfy::Satisfaction::satisfy_mall(
416            &self.node,
417            &satisfier,
418            self.ty.mall.safe,
419            &leaf_hash,
420        )
421        .stack
422        {
423            satisfy::Witness::Stack(stack) => {
424                Ctx::check_witness::<Pk>(&stack)?;
425                Ok(stack)
426            }
427            satisfy::Witness::Unavailable | satisfy::Witness::Impossible => {
428                Err(Error::CouldNotSatisfy)
429            }
430        }
431    }
432}
433
434impl_from_tree!(
435    ;Ctx; ScriptContext,
436    Arc<Miniscript<Pk, Ctx>>,
437    fn from_tree(top: &expression::Tree) -> Result<Arc<Miniscript<Pk, Ctx>>, Error> {
438        Ok(Arc::new(expression::FromTree::from_tree(top)?))
439    }
440);
441
442impl_from_tree!(
443    ;Ctx; ScriptContext,
444    Miniscript<Pk, Ctx>,
445    /// Parse an expression tree into a Miniscript. As a general rule, this
446    /// should not be called directly; rather go through the descriptor API.
447    fn from_tree(top: &expression::Tree) -> Result<Miniscript<Pk, Ctx>, Error> {
448        let inner: Terminal<Pk, Ctx> = expression::FromTree::from_tree(top)?;
449        Ok(Miniscript {
450            ty: Type::type_check(&inner, |_| None)?,
451            ext: ExtData::type_check(&inner, |_| None)?,
452            node: inner,
453            phantom: PhantomData,
454        })
455    }
456);
457
458impl_from_str!(
459    ;Ctx; ScriptContext,
460    Miniscript<Pk, Ctx>,
461    type Err = Error;,
462    /// Parse a Miniscript from string and perform sanity checks
463    /// See [Miniscript::from_str_insane] to parse scripts from string that
464    /// do not clear the [Miniscript::sanity_check] checks.
465    fn from_str(s: &str) -> Result<Miniscript<Pk, Ctx>, Error> {
466        let ms = Self::from_str_ext(s, &ExtParams::sane())?;
467        Ok(ms)
468    }
469);
470
471serde_string_impl_pk!(Miniscript, "a miniscript", Ctx; ScriptContext);
472
473#[cfg(test)]
474mod tests {
475
476    use core::marker::PhantomData;
477    use core::str;
478    use core::str::FromStr;
479
480    use bitcoin::hashes::{hash160, sha256, Hash};
481    use bitcoin::secp256k1::XOnlyPublicKey;
482    use bitcoin::util::taproot::TapLeafHash;
483    use bitcoin::{self, secp256k1, Sequence};
484    use sync::Arc;
485
486    use super::{Miniscript, ScriptContext, Segwitv0, Tap};
487    use crate::miniscript::types::{self, ExtData, Property, Type};
488    use crate::miniscript::Terminal;
489    use crate::policy::Liftable;
490    use crate::prelude::*;
491    use crate::test_utils::{StrKeyTranslator, StrXOnlyKeyTranslator};
492    use crate::{hex_script, DummyKey, ExtParams, Satisfier, ToPublicKey, TranslatePk};
493
494    type Segwitv0Script = Miniscript<bitcoin::PublicKey, Segwitv0>;
495    type Tapscript = Miniscript<bitcoin::secp256k1::XOnlyPublicKey, Tap>;
496
497    fn pubkeys(n: usize) -> Vec<bitcoin::PublicKey> {
498        let mut ret = Vec::with_capacity(n);
499        let secp = secp256k1::Secp256k1::new();
500        let mut sk = [0; 32];
501        for i in 1..n + 1 {
502            sk[0] = i as u8;
503            sk[1] = (i >> 8) as u8;
504            sk[2] = (i >> 16) as u8;
505
506            let pk = bitcoin::PublicKey {
507                inner: secp256k1::PublicKey::from_secret_key(
508                    &secp,
509                    &secp256k1::SecretKey::from_slice(&sk[..]).expect("secret key"),
510                ),
511                compressed: true,
512            };
513            ret.push(pk);
514        }
515        ret
516    }
517
518    fn string_rtt<Ctx: ScriptContext>(
519        script: Miniscript<bitcoin::PublicKey, Ctx>,
520        expected_debug: &str,
521        expected_display: &str,
522    ) {
523        assert_eq!(script.ty.corr.base, types::Base::B);
524        let debug = format!("{:?}", script);
525        let display = format!("{}", script);
526        if let Some(expected) = expected_debug.into() {
527            assert_eq!(debug, expected);
528        }
529        if let Some(expected) = expected_display.into() {
530            assert_eq!(display, expected);
531        }
532        let roundtrip = Miniscript::from_str(&display).expect("parse string serialization");
533        assert_eq!(roundtrip, script);
534    }
535
536    fn string_display_debug_test<Ctx: ScriptContext>(
537        script: Miniscript<bitcoin::PublicKey, Ctx>,
538        expected_debug: &str,
539        expected_display: &str,
540    ) {
541        assert_eq!(script.ty.corr.base, types::Base::B);
542        let debug = format!("{:?}", script);
543        let display = format!("{}", script);
544        if let Some(expected) = expected_debug.into() {
545            assert_eq!(debug, expected);
546        }
547        if let Some(expected) = expected_display.into() {
548            assert_eq!(display, expected);
549        }
550    }
551
552    fn dummy_string_rtt<Ctx: ScriptContext>(
553        script: Miniscript<DummyKey, Ctx>,
554        expected_debug: &str,
555        expected_display: &str,
556    ) {
557        assert_eq!(script.ty.corr.base, types::Base::B);
558        let debug = format!("{:?}", script);
559        let display = format!("{}", script);
560        if let Some(expected) = expected_debug.into() {
561            assert_eq!(debug, expected);
562        }
563        if let Some(expected) = expected_display.into() {
564            assert_eq!(display, expected);
565        }
566        let roundtrip = Miniscript::from_str(&display).expect("parse string serialization");
567        assert_eq!(roundtrip, script);
568    }
569
570    fn script_rtt<Str1: Into<Option<&'static str>>>(script: Segwitv0Script, expected_hex: Str1) {
571        assert_eq!(script.ty.corr.base, types::Base::B);
572        let bitcoin_script = script.encode();
573        assert_eq!(bitcoin_script.len(), script.script_size());
574        if let Some(expected) = expected_hex.into() {
575            assert_eq!(format!("{:x}", bitcoin_script), expected);
576        }
577        // Parse scripts with all extensions
578        let roundtrip = Segwitv0Script::parse_with_ext(&bitcoin_script, &ExtParams::allow_all())
579            .expect("parse string serialization");
580        assert_eq!(roundtrip, script);
581    }
582
583    fn roundtrip(tree: &Segwitv0Script, s: &str) {
584        assert_eq!(tree.ty.corr.base, types::Base::B);
585        let ser = tree.encode();
586        assert_eq!(ser.len(), tree.script_size());
587        assert_eq!(ser.to_string(), s);
588        let deser = Segwitv0Script::parse_insane(&ser).expect("deserialize result of serialize");
589        assert_eq!(*tree, deser);
590    }
591
592    fn ms_attributes_test(
593        ms: &str,
594        expected_hex: &str,
595        valid: bool,
596        non_mal: bool,
597        need_sig: bool,
598        ops: usize,
599        _stack: usize,
600    ) {
601        let ms: Result<Segwitv0Script, _> = Miniscript::from_str_insane(ms);
602        match (ms, valid) {
603            (Ok(ms), true) => {
604                assert_eq!(format!("{:x}", ms.encode()), expected_hex);
605                assert_eq!(ms.ty.mall.non_malleable, non_mal);
606                assert_eq!(ms.ty.mall.safe, need_sig);
607                assert_eq!(ms.ext.ops.op_count().unwrap(), ops);
608            }
609            (Err(_), false) => return,
610            _ => unreachable!(),
611        }
612    }
613
614    #[test]
615    fn all_attribute_tests() {
616        ms_attributes_test(
617            "lltvln:after(1231488000)",
618            "6300676300676300670400046749b1926869516868",
619            true,
620            true,
621            false,
622            12,
623            3,
624        );
625        ms_attributes_test("uuj:and_v(v:multi(2,03d01115d548e7561b15c38f004d734633687cf4419620095bc5b0f47070afe85a,025601570cb47f238d2b0286db4a990fa0f3ba28d1a319f5e7cf55c2a2444da7cc),after(1231488000))", "6363829263522103d01115d548e7561b15c38f004d734633687cf4419620095bc5b0f47070afe85a21025601570cb47f238d2b0286db4a990fa0f3ba28d1a319f5e7cf55c2a2444da7cc52af0400046749b168670068670068", true, true, true, 14, 5);
626        ms_attributes_test("or_b(un:multi(2,03daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729,024ce119c96e2fa357200b559b2f7dd5a5f02d5290aff74b03f3e471b273211c97),al:older(16))", "63522103daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee872921024ce119c96e2fa357200b559b2f7dd5a5f02d5290aff74b03f3e471b273211c9752ae926700686b63006760b2686c9b", true, false, false, 14, 5);
627        ms_attributes_test(
628            "j:and_v(vdv:after(1567547623),older(2016))",
629            "829263766304e7e06e5db169686902e007b268",
630            true,
631            true,
632            false,
633            11,
634            1,
635        );
636        ms_attributes_test("t:and_v(vu:hash256(131772552c01444cd81360818376a040b7c3b2b7b0a53550ee3edde216cec61b),v:sha256(ec4916dd28fc4c10d78e287ca5d9cc51ee1ae73cbfde08c6b37324cbfaac8bc5))", "6382012088aa20131772552c01444cd81360818376a040b7c3b2b7b0a53550ee3edde216cec61b876700686982012088a820ec4916dd28fc4c10d78e287ca5d9cc51ee1ae73cbfde08c6b37324cbfaac8bc58851", true, true, false, 12, 3);
637        ms_attributes_test("t:andor(multi(3,02d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e,03fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a1460297556,02e493dbf1c10d80f3581e4904930b1404cc6c13900ee0758474fa94abe8c4cd13),v:older(4194305),v:sha256(9267d3dbed802941483f1afa2a6bc68de5f653128aca9bf1461c5d0a3ad36ed2))", "532102d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e2103fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a14602975562102e493dbf1c10d80f3581e4904930b1404cc6c13900ee0758474fa94abe8c4cd1353ae6482012088a8209267d3dbed802941483f1afa2a6bc68de5f653128aca9bf1461c5d0a3ad36ed2886703010040b2696851", true, true, false, 13, 5);
638        ms_attributes_test("or_d(multi(1,02f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9),or_b(multi(3,022f01e5e15cca351daff3843fb70f3c2f0a1bdd05e5af888a67784ef3e10a2a01,032fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f,03d01115d548e7561b15c38f004d734633687cf4419620095bc5b0f47070afe85a),su:after(500000)))", "512102f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f951ae73645321022f01e5e15cca351daff3843fb70f3c2f0a1bdd05e5af888a67784ef3e10a2a0121032fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f2103d01115d548e7561b15c38f004d734633687cf4419620095bc5b0f47070afe85a53ae7c630320a107b16700689b68", true, true, false, 15, 7);
639        ms_attributes_test("or_d(sha256(38df1c1f64a24a77b23393bca50dff872e31edc4f3b5aa3b90ad0b82f4f089b6),and_n(un:after(499999999),older(4194305)))", "82012088a82038df1c1f64a24a77b23393bca50dff872e31edc4f3b5aa3b90ad0b82f4f089b68773646304ff64cd1db19267006864006703010040b26868", true, false, false, 16, 1);
640        ms_attributes_test("and_v(or_i(v:multi(2,02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5,03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb),v:multi(2,03e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a,025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc)),sha256(d1ec675902ef1633427ca360b290b0b3045a0d9058ddb5e648b4c3c3224c5c68))", "63522102c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee52103774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb52af67522103e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a21025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc52af6882012088a820d1ec675902ef1633427ca360b290b0b3045a0d9058ddb5e648b4c3c3224c5c6887", true, true, true, 11, 5);
641        ms_attributes_test("j:and_b(multi(2,0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798,024ce119c96e2fa357200b559b2f7dd5a5f02d5290aff74b03f3e471b273211c97),s:or_i(older(1),older(4252898)))", "82926352210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179821024ce119c96e2fa357200b559b2f7dd5a5f02d5290aff74b03f3e471b273211c9752ae7c6351b26703e2e440b2689a68", true, false, true, 14, 4);
642        ms_attributes_test("and_b(older(16),s:or_d(sha256(e38990d0c7fc009880a9c07c23842e886c6bbdc964ce6bdd5817ad357335ee6f),n:after(1567547623)))", "60b27c82012088a820e38990d0c7fc009880a9c07c23842e886c6bbdc964ce6bdd5817ad357335ee6f87736404e7e06e5db192689a", true, false, false, 12, 1);
643        ms_attributes_test("j:and_v(v:hash160(20195b5a3d650c17f0f29f91c33f8f6335193d07),or_d(sha256(96de8fc8c256fa1e1556d41af431cace7dca68707c78dd88c3acab8b17164c47),older(16)))", "82926382012088a91420195b5a3d650c17f0f29f91c33f8f6335193d078882012088a82096de8fc8c256fa1e1556d41af431cace7dca68707c78dd88c3acab8b17164c4787736460b26868", true, false, false, 16, 2);
644        ms_attributes_test("and_b(hash256(32ba476771d01e37807990ead8719f08af494723de1d228f2c2c07cc0aa40bac),a:and_b(hash256(131772552c01444cd81360818376a040b7c3b2b7b0a53550ee3edde216cec61b),a:older(1)))", "82012088aa2032ba476771d01e37807990ead8719f08af494723de1d228f2c2c07cc0aa40bac876b82012088aa20131772552c01444cd81360818376a040b7c3b2b7b0a53550ee3edde216cec61b876b51b26c9a6c9a", true, true, false, 15, 2);
645        ms_attributes_test("thresh(2,multi(2,03a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00),a:multi(1,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00),ac:pk_k(022f01e5e15cca351daff3843fb70f3c2f0a1bdd05e5af888a67784ef3e10a2a01))", "522103a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c721036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a0052ae6b5121036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a0051ae6c936b21022f01e5e15cca351daff3843fb70f3c2f0a1bdd05e5af888a67784ef3e10a2a01ac6c935287", true, true, true, 13, 6);
646        ms_attributes_test("and_n(sha256(d1ec675902ef1633427ca360b290b0b3045a0d9058ddb5e648b4c3c3224c5c68),t:or_i(v:older(4252898),v:older(144)))", "82012088a820d1ec675902ef1633427ca360b290b0b3045a0d9058ddb5e648b4c3c3224c5c68876400676303e2e440b26967029000b269685168", true, false, false, 14, 2);
647        ms_attributes_test("or_d(nd:and_v(v:older(4252898),v:older(4252898)),sha256(38df1c1f64a24a77b23393bca50dff872e31edc4f3b5aa3b90ad0b82f4f089b6))", "766303e2e440b26903e2e440b2696892736482012088a82038df1c1f64a24a77b23393bca50dff872e31edc4f3b5aa3b90ad0b82f4f089b68768", true, false, false, 15, 2);
648        ms_attributes_test("c:and_v(or_c(sha256(9267d3dbed802941483f1afa2a6bc68de5f653128aca9bf1461c5d0a3ad36ed2),v:multi(1,02c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db)),pk_k(03acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe))", "82012088a8209267d3dbed802941483f1afa2a6bc68de5f653128aca9bf1461c5d0a3ad36ed28764512102c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db51af682103acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbeac", true, false, true, 9, 2);
649        ms_attributes_test("c:and_v(or_c(multi(2,036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a00,02352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5),v:ripemd160(1b0f3c404d12075c68c938f9f60ebea4f74941a0)),pk_k(03fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a1460297556))", "5221036d2b085e9e382ed10b69fc311a03f8641ccfff21574de0927513a49d9a688a002102352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d552ae6482012088a6141b0f3c404d12075c68c938f9f60ebea4f74941a088682103fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a1460297556ac", true, true, true, 10, 5);
650        ms_attributes_test("and_v(andor(hash256(8a35d9ca92a48eaade6f53a64985e9e2afeb74dcf8acb4c3721e0dc7e4294b25),v:hash256(939894f70e6c3a25da75da0cc2071b4076d9b006563cf635986ada2e93c0d735),v:older(50000)),after(499999999))", "82012088aa208a35d9ca92a48eaade6f53a64985e9e2afeb74dcf8acb4c3721e0dc7e4294b2587640350c300b2696782012088aa20939894f70e6c3a25da75da0cc2071b4076d9b006563cf635986ada2e93c0d735886804ff64cd1db1", true, false, false, 14, 2);
651        ms_attributes_test("andor(hash256(5f8d30e655a7ba0d7596bb3ddfb1d2d20390d23b1845000e1e118b3be1b3f040),j:and_v(v:hash160(3a2bff0da9d96868e66abc4427bea4691cf61ccd),older(4194305)),ripemd160(44d90e2d3714c8663b632fcf0f9d5f22192cc4c8))", "82012088aa205f8d30e655a7ba0d7596bb3ddfb1d2d20390d23b1845000e1e118b3be1b3f040876482012088a61444d90e2d3714c8663b632fcf0f9d5f22192cc4c8876782926382012088a9143a2bff0da9d96868e66abc4427bea4691cf61ccd8803010040b26868", true, false, false, 20, 2);
652        ms_attributes_test("or_i(c:and_v(v:after(500000),pk_k(02c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5)),sha256(d9147961436944f43cd99d28b2bbddbf452ef872b30c8279e255e7daafc7f946))", "630320a107b1692102c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5ac6782012088a820d9147961436944f43cd99d28b2bbddbf452ef872b30c8279e255e7daafc7f9468768", true, true, false, 10, 2);
653        ms_attributes_test("thresh(2,c:pk_h(03daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729),s:sha256(e38990d0c7fc009880a9c07c23842e886c6bbdc964ce6bdd5817ad357335ee6f),a:hash160(dd69735817e0e3f6f826a9238dc2e291184f0131))", "76a91420d637c1a6404d2227f3561fdbaff5a680dba64888ac7c82012088a820e38990d0c7fc009880a9c07c23842e886c6bbdc964ce6bdd5817ad357335ee6f87936b82012088a914dd69735817e0e3f6f826a9238dc2e291184f0131876c935287", true, false, false, 18, 4);
654        ms_attributes_test("and_n(sha256(9267d3dbed802941483f1afa2a6bc68de5f653128aca9bf1461c5d0a3ad36ed2),uc:and_v(v:older(144),pk_k(03fe72c435413d33d48ac09c9161ba8b09683215439d62b7940502bda8b202e6ce)))", "82012088a8209267d3dbed802941483f1afa2a6bc68de5f653128aca9bf1461c5d0a3ad36ed28764006763029000b2692103fe72c435413d33d48ac09c9161ba8b09683215439d62b7940502bda8b202e6ceac67006868", true, false, true, 13, 3);
655        ms_attributes_test("and_n(c:pk_k(03daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729),and_b(l:older(4252898),a:older(16)))", "2103daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729ac64006763006703e2e440b2686b60b26c9a68", true, true, true, 12, 2);
656        ms_attributes_test("c:or_i(and_v(v:older(16),pk_h(03daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729)),pk_h(02352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5))", "6360b26976a91420d637c1a6404d2227f3561fdbaff5a680dba648886776a9148f9dff39a81ee4abcbad2ad8bafff090415a2be88868ac", true, true, true, 12, 3);
657        ms_attributes_test("or_d(c:pk_h(02352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5),andor(c:pk_k(024ce119c96e2fa357200b559b2f7dd5a5f02d5290aff74b03f3e471b273211c97),older(2016),after(1567547623)))", "76a9148f9dff39a81ee4abcbad2ad8bafff090415a2be888ac736421024ce119c96e2fa357200b559b2f7dd5a5f02d5290aff74b03f3e471b273211c97ac6404e7e06e5db16702e007b26868", true, true, false, 13, 3);
658        ms_attributes_test("c:andor(ripemd160(6ad07d21fd5dfc646f0b30577045ce201616b9ba),pk_h(03daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729),and_v(v:hash256(8a35d9ca92a48eaade6f53a64985e9e2afeb74dcf8acb4c3721e0dc7e4294b25),pk_h(02352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5)))", "82012088a6146ad07d21fd5dfc646f0b30577045ce201616b9ba876482012088aa208a35d9ca92a48eaade6f53a64985e9e2afeb74dcf8acb4c3721e0dc7e4294b258876a9148f9dff39a81ee4abcbad2ad8bafff090415a2be8886776a91420d637c1a6404d2227f3561fdbaff5a680dba6488868ac", true, false, true, 18, 3);
659        ms_attributes_test("c:andor(u:ripemd160(6ad07d21fd5dfc646f0b30577045ce201616b9ba),pk_h(03daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729),or_i(pk_h(024ce119c96e2fa357200b559b2f7dd5a5f02d5290aff74b03f3e471b273211c97),pk_h(02352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5)))", "6382012088a6146ad07d21fd5dfc646f0b30577045ce201616b9ba87670068646376a914385defb0ed10fe95817943ed37b4984f8f4255d6886776a9148f9dff39a81ee4abcbad2ad8bafff090415a2be888686776a91420d637c1a6404d2227f3561fdbaff5a680dba6488868ac", true, false, true, 23, 4);
660        ms_attributes_test("c:or_i(andor(c:pk_h(02352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5),pk_h(024ce119c96e2fa357200b559b2f7dd5a5f02d5290aff74b03f3e471b273211c97),pk_h(03daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729)),pk_k(03fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a1460297556))", "6376a9148f9dff39a81ee4abcbad2ad8bafff090415a2be888ac6476a91420d637c1a6404d2227f3561fdbaff5a680dba648886776a914385defb0ed10fe95817943ed37b4984f8f4255d68868672103fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a146029755668ac", true, true, true, 17, 5);
661    }
662
663    #[test]
664    fn basic() {
665        let pk = bitcoin::PublicKey::from_str(
666            "\
667             020202020202020202020202020202020202020202020202020202020202020202\
668             ",
669        )
670        .unwrap();
671        let hash = hash160::Hash::from_inner([17; 20]);
672
673        let pkk_ms: Miniscript<DummyKey, Segwitv0> = Miniscript {
674            node: Terminal::Check(Arc::new(Miniscript {
675                node: Terminal::PkK(DummyKey),
676                ty: Type::from_pk_k::<Segwitv0>(),
677                ext: types::extra_props::ExtData::from_pk_k::<Segwitv0>(),
678                phantom: PhantomData,
679            })),
680            ty: Type::cast_check(Type::from_pk_k::<Segwitv0>()).unwrap(),
681            ext: ExtData::cast_check(ExtData::from_pk_k::<Segwitv0>()).unwrap(),
682            phantom: PhantomData,
683        };
684        dummy_string_rtt(pkk_ms, "[B/onduesm]c:[K/onduesm]pk_k(DummyKey)", "pk()");
685
686        let pkh_ms: Miniscript<DummyKey, Segwitv0> = Miniscript {
687            node: Terminal::Check(Arc::new(Miniscript {
688                node: Terminal::PkH(DummyKey),
689                ty: Type::from_pk_h::<Segwitv0>(),
690                ext: types::extra_props::ExtData::from_pk_h::<Segwitv0>(),
691                phantom: PhantomData,
692            })),
693            ty: Type::cast_check(Type::from_pk_h::<Segwitv0>()).unwrap(),
694            ext: ExtData::cast_check(ExtData::from_pk_h::<Segwitv0>()).unwrap(),
695            phantom: PhantomData,
696        };
697
698        let expected_debug = "[B/nduesm]c:[K/nduesm]pk_h(DummyKey)";
699        let expected_display = "pkh()";
700
701        assert_eq!(pkh_ms.ty.corr.base, types::Base::B);
702        let debug = format!("{:?}", pkh_ms);
703        let display = format!("{}", pkh_ms);
704        if let Some(expected) = expected_debug.into() {
705            assert_eq!(debug, expected);
706        }
707        if let Some(expected) = expected_display.into() {
708            assert_eq!(display, expected);
709        }
710
711        let pkk_ms: Segwitv0Script = Miniscript {
712            node: Terminal::Check(Arc::new(Miniscript {
713                node: Terminal::PkK(pk),
714                ty: Type::from_pk_k::<Segwitv0>(),
715                ext: types::extra_props::ExtData::from_pk_k::<Segwitv0>(),
716                phantom: PhantomData,
717            })),
718            ty: Type::cast_check(Type::from_pk_k::<Segwitv0>()).unwrap(),
719            ext: ExtData::cast_check(ExtData::from_pk_k::<Segwitv0>()).unwrap(),
720            phantom: PhantomData,
721        };
722
723        script_rtt(
724            pkk_ms,
725            "21020202020202020202020202020202020202020202020202020202020\
726             202020202ac",
727        );
728
729        let pkh_ms: Segwitv0Script = Miniscript {
730            node: Terminal::Check(Arc::new(Miniscript {
731                node: Terminal::RawPkH(hash),
732                ty: Type::from_pk_h::<Segwitv0>(),
733                ext: types::extra_props::ExtData::from_pk_h::<Segwitv0>(),
734                phantom: PhantomData,
735            })),
736            ty: Type::cast_check(Type::from_pk_h::<Segwitv0>()).unwrap(),
737            ext: ExtData::cast_check(ExtData::from_pk_h::<Segwitv0>()).unwrap(),
738            phantom: PhantomData,
739        };
740
741        script_rtt(pkh_ms, "76a914111111111111111111111111111111111111111188ac");
742    }
743
744    #[test]
745    fn true_false() {
746        roundtrip(&ms_str!("1"), "Script(OP_PUSHNUM_1)");
747        roundtrip(
748            &ms_str!("tv:1"),
749            "Script(OP_PUSHNUM_1 OP_VERIFY OP_PUSHNUM_1)",
750        );
751        roundtrip(&ms_str!("0"), "Script(OP_0)");
752        roundtrip(
753            &ms_str!("andor(0,1,0)"),
754            "Script(OP_0 OP_NOTIF OP_0 OP_ELSE OP_PUSHNUM_1 OP_ENDIF)",
755        );
756
757        assert!(Segwitv0Script::from_str("1()").is_err());
758        assert!(Segwitv0Script::from_str("tv:1()").is_err());
759    }
760
761    #[test]
762    fn verify_parse() {
763        let ms = "and_v(v:hash160(20195b5a3d650c17f0f29f91c33f8f6335193d07),or_d(sha256(96de8fc8c256fa1e1556d41af431cace7dca68707c78dd88c3acab8b17164c47),older(16)))";
764        let ms: Segwitv0Script = Miniscript::from_str_insane(ms).unwrap();
765        assert_eq!(ms, Segwitv0Script::parse_insane(&ms.encode()).unwrap());
766
767        let ms = "and_v(v:sha256(96de8fc8c256fa1e1556d41af431cace7dca68707c78dd88c3acab8b17164c47),or_d(sha256(96de8fc8c256fa1e1556d41af431cace7dca68707c78dd88c3acab8b17164c47),older(16)))";
768        let ms: Segwitv0Script = Miniscript::from_str_insane(ms).unwrap();
769        assert_eq!(ms, Segwitv0Script::parse_insane(&ms.encode()).unwrap());
770
771        let ms = "and_v(v:ripemd160(20195b5a3d650c17f0f29f91c33f8f6335193d07),or_d(sha256(96de8fc8c256fa1e1556d41af431cace7dca68707c78dd88c3acab8b17164c47),older(16)))";
772        let ms: Segwitv0Script = Miniscript::from_str_insane(ms).unwrap();
773        assert_eq!(ms, Segwitv0Script::parse_insane(&ms.encode()).unwrap());
774
775        let ms = "and_v(v:hash256(96de8fc8c256fa1e1556d41af431cace7dca68707c78dd88c3acab8b17164c47),or_d(sha256(96de8fc8c256fa1e1556d41af431cace7dca68707c78dd88c3acab8b17164c47),older(16)))";
776        let ms: Segwitv0Script = Miniscript::from_str_insane(ms).unwrap();
777        assert_eq!(ms, Segwitv0Script::parse_insane(&ms.encode()).unwrap());
778    }
779
780    #[test]
781    fn pk_alias() {
782        let pubkey = pubkeys(1)[0];
783
784        let script: Segwitv0Script = ms_str!("c:pk_k({})", pubkey.to_string());
785
786        string_rtt(
787            script,
788            "[B/onduesm]c:[K/onduesm]pk_k(PublicKey { compressed: true, inner: PublicKey(aa4c32e50fb34a95a372940ae3654b692ea35294748c3dd2c08b29f87ba9288c8294efcb73dc719e45b91c45f084e77aebc07c1ff3ed8f37935130a36304a340) })",
789            "pk(028c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa)"
790        );
791
792        let script: Segwitv0Script = ms_str!("pk({})", pubkey.to_string());
793
794        string_rtt(
795            script,
796            "[B/onduesm]c:[K/onduesm]pk_k(PublicKey { compressed: true, inner: PublicKey(aa4c32e50fb34a95a372940ae3654b692ea35294748c3dd2c08b29f87ba9288c8294efcb73dc719e45b91c45f084e77aebc07c1ff3ed8f37935130a36304a340) })",
797            "pk(028c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa)"
798        );
799
800        let script: Segwitv0Script = ms_str!("tv:pk({})", pubkey.to_string());
801
802        string_rtt(
803            script,
804            "[B/onufsm]t[V/onfsm]v[B/onduesm]c:[K/onduesm]pk_k(PublicKey { compressed: true, inner: PublicKey(aa4c32e50fb34a95a372940ae3654b692ea35294748c3dd2c08b29f87ba9288c8294efcb73dc719e45b91c45f084e77aebc07c1ff3ed8f37935130a36304a340) })",
805            "tv:pk(028c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa)"
806        );
807
808        let script: Segwitv0Script = ms_str!("c:pk_h({})", pubkey.to_string());
809
810        string_display_debug_test(
811            script,
812            "[B/nduesm]c:[K/nduesm]pk_h(PublicKey { compressed: true, inner: PublicKey(aa4c32e50fb34a95a372940ae3654b692ea35294748c3dd2c08b29f87ba9288c8294efcb73dc719e45b91c45f084e77aebc07c1ff3ed8f37935130a36304a340) })",
813            "pkh(028c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa)",
814        );
815
816        let script: Segwitv0Script = ms_str!("pkh({})", pubkey.to_string());
817
818        string_display_debug_test(
819            script,
820            "[B/nduesm]c:[K/nduesm]pk_h(PublicKey { compressed: true, inner: PublicKey(aa4c32e50fb34a95a372940ae3654b692ea35294748c3dd2c08b29f87ba9288c8294efcb73dc719e45b91c45f084e77aebc07c1ff3ed8f37935130a36304a340) })",
821            "pkh(028c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa)",
822        );
823
824        let script: Segwitv0Script = ms_str!("tv:pkh({})", pubkey.to_string());
825
826        string_display_debug_test(
827            script,
828            "[B/nufsm]t[V/nfsm]v[B/nduesm]c:[K/nduesm]pk_h(PublicKey { compressed: true, inner: PublicKey(aa4c32e50fb34a95a372940ae3654b692ea35294748c3dd2c08b29f87ba9288c8294efcb73dc719e45b91c45f084e77aebc07c1ff3ed8f37935130a36304a340) })",
829            "tv:pkh(028c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa)",
830        );
831    }
832
833    #[test]
834    fn serialize() {
835        let keys = pubkeys(6);
836
837        let tree: &Segwitv0Script = &ms_str!("c:pk_h({})", keys[5]);
838        assert_eq!(tree.ty.corr.base, types::Base::B);
839        let ser = tree.encode();
840        let s = "\
841             Script(OP_DUP OP_HASH160 OP_PUSHBYTES_20 \
842             7e5a2a6a7610ca4ea78bd65a087bd75b1870e319 \
843             OP_EQUALVERIFY OP_CHECKSIG)\
844             ";
845        assert_eq!(ser.len(), tree.script_size());
846        assert_eq!(ser.to_string(), s);
847
848        roundtrip(
849            &ms_str!("pk({})", keys[0]),
850            "Script(OP_PUSHBYTES_33 028c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa OP_CHECKSIG)"
851        );
852        roundtrip(
853            &ms_str!("multi(3,{},{},{},{},{})", keys[0], keys[1], keys[2], keys[3], keys[4]),
854            "Script(OP_PUSHNUM_3 OP_PUSHBYTES_33 028c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa OP_PUSHBYTES_33 03ab1ac1872a38a2f196bed5a6047f0da2c8130fe8de49fc4d5dfb201f7611d8e2 OP_PUSHBYTES_33 039729247032c0dfcf45b4841fcd72f6e9a2422631fc3466cf863e87154754dd40 OP_PUSHBYTES_33 032564fe9b5beef82d3703a607253f31ef8ea1b365772df434226aee642651b3fa OP_PUSHBYTES_33 0289637f97580a796e050791ad5a2f27af1803645d95df021a3c2d82eb8c2ca7ff OP_PUSHNUM_5 OP_CHECKMULTISIG)"
855        );
856
857        // Liquid policy
858        roundtrip(
859            &ms_str!("or_d(multi(2,{},{}),and_v(v:multi(2,{},{}),older(10000)))",
860                      keys[0].to_string(),
861                      keys[1].to_string(),
862                      keys[3].to_string(),
863                      keys[4].to_string()),
864            "Script(OP_PUSHNUM_2 OP_PUSHBYTES_33 028c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa \
865                                  OP_PUSHBYTES_33 03ab1ac1872a38a2f196bed5a6047f0da2c8130fe8de49fc4d5dfb201f7611d8e2 \
866                                  OP_PUSHNUM_2 OP_CHECKMULTISIG \
867                     OP_IFDUP OP_NOTIF \
868                         OP_PUSHNUM_2 OP_PUSHBYTES_33 032564fe9b5beef82d3703a607253f31ef8ea1b365772df434226aee642651b3fa \
869                                      OP_PUSHBYTES_33 0289637f97580a796e050791ad5a2f27af1803645d95df021a3c2d82eb8c2ca7ff \
870                                      OP_PUSHNUM_2 OP_CHECKMULTISIGVERIFY \
871                         OP_PUSHBYTES_2 1027 OP_CSV \
872                     OP_ENDIF)"
873        );
874
875        let miniscript: Segwitv0Script = ms_str!(
876            "or_d(multi(3,{},{},{}),and_v(v:multi(2,{},{}),older(10000)))",
877            keys[0].to_string(),
878            keys[1].to_string(),
879            keys[2].to_string(),
880            keys[3].to_string(),
881            keys[4].to_string(),
882        );
883
884        let mut abs = miniscript.lift().unwrap();
885        assert_eq!(abs.n_keys(), 5);
886        assert_eq!(abs.minimum_n_keys(), Some(2));
887        abs = abs.at_age(Sequence::from_height(10000));
888        assert_eq!(abs.n_keys(), 5);
889        assert_eq!(abs.minimum_n_keys(), Some(2));
890        abs = abs.at_age(Sequence::from_height(9999));
891        assert_eq!(abs.n_keys(), 3);
892        assert_eq!(abs.minimum_n_keys(), Some(3));
893        abs = abs.at_age(Sequence::ZERO);
894        assert_eq!(abs.n_keys(), 3);
895        assert_eq!(abs.minimum_n_keys(), Some(3));
896
897        roundtrip(&ms_str!("older(921)"), "Script(OP_PUSHBYTES_2 9903 OP_CSV)");
898
899        roundtrip(
900            &ms_str!("sha256({})",sha256::Hash::hash(&[])),
901            "Script(OP_SIZE OP_PUSHBYTES_1 20 OP_EQUALVERIFY OP_SHA256 OP_PUSHBYTES_32 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 OP_EQUAL)"
902        );
903
904        roundtrip(
905            &ms_str!(
906                "multi(3,{},{},{},{},{})",
907                keys[0],
908                keys[1],
909                keys[2],
910                keys[3],
911                keys[4]
912            ),
913            "Script(OP_PUSHNUM_3 \
914             OP_PUSHBYTES_33 028c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa \
915             OP_PUSHBYTES_33 03ab1ac1872a38a2f196bed5a6047f0da2c8130fe8de49fc4d5dfb201f7611d8e2 \
916             OP_PUSHBYTES_33 039729247032c0dfcf45b4841fcd72f6e9a2422631fc3466cf863e87154754dd40 \
917             OP_PUSHBYTES_33 032564fe9b5beef82d3703a607253f31ef8ea1b365772df434226aee642651b3fa \
918             OP_PUSHBYTES_33 0289637f97580a796e050791ad5a2f27af1803645d95df021a3c2d82eb8c2ca7ff \
919             OP_PUSHNUM_5 OP_CHECKMULTISIG)",
920        );
921
922        roundtrip(
923            &ms_str!(
924                "t:and_v(\
925                     vu:hash256(131772552c01444cd81360818376a040b7c3b2b7b0a53550ee3edde216cec61b),\
926                     v:sha256(ec4916dd28fc4c10d78e287ca5d9cc51ee1ae73cbfde08c6b37324cbfaac8bc5)\
927                 )"),
928            "Script(OP_IF OP_SIZE OP_PUSHBYTES_1 20 OP_EQUALVERIFY OP_HASH256 OP_PUSHBYTES_32 131772552c01444cd81360818376a040b7c3b2b7b0a53550ee3edde216cec61b OP_EQUAL OP_ELSE OP_0 OP_ENDIF OP_VERIFY OP_SIZE OP_PUSHBYTES_1 20 OP_EQUALVERIFY OP_SHA256 OP_PUSHBYTES_32 ec4916dd28fc4c10d78e287ca5d9cc51ee1ae73cbfde08c6b37324cbfaac8bc5 OP_EQUALVERIFY OP_PUSHNUM_1)"
929        );
930        roundtrip(
931            &ms_str!("and_n(pk(03daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729),and_b(l:older(4252898),a:older(16)))"),
932            "Script(OP_PUSHBYTES_33 03daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729 OP_CHECKSIG OP_NOTIF OP_0 OP_ELSE OP_IF OP_0 OP_ELSE OP_PUSHBYTES_3 e2e440 OP_CSV OP_ENDIF OP_TOALTSTACK OP_PUSHNUM_16 OP_CSV OP_FROMALTSTACK OP_BOOLAND OP_ENDIF)"
933        );
934        roundtrip(
935            &ms_str!(
936                "t:andor(multi(\
937                    3,\
938                    02d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e,\
939                    03fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a1460297556,\
940                    02e493dbf1c10d80f3581e4904930b1404cc6c13900ee0758474fa94abe8c4cd13\
941                 ),\
942                 v:older(4194305),\
943                 v:sha256(9267d3dbed802941483f1afa2a6bc68de5f653128aca9bf1461c5d0a3ad36ed2)\
944                 )"),
945            "Script(OP_PUSHNUM_3 OP_PUSHBYTES_33 02d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e \
946             OP_PUSHBYTES_33 03fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a1460297556 \
947             OP_PUSHBYTES_33 02e493dbf1c10d80f3581e4904930b1404cc6c13900ee0758474fa94abe8c4cd13 \
948             OP_PUSHNUM_3 OP_CHECKMULTISIG OP_NOTIF OP_SIZE OP_PUSHBYTES_1 20 OP_EQUALVERIFY OP_SHA256 \
949             OP_PUSHBYTES_32 9267d3dbed802941483f1afa2a6bc68de5f653128aca9bf1461c5d0a3ad36ed2 OP_EQUALVERIFY \
950             OP_ELSE OP_PUSHBYTES_3 010040 OP_CSV OP_VERIFY OP_ENDIF OP_PUSHNUM_1)"
951        );
952        roundtrip(
953            &ms_str!(
954                "t:and_v(\
955                    vu:hash256(131772552c01444cd81360818376a040b7c3b2b7b0a53550ee3edde216cec61b),\
956                    v:sha256(ec4916dd28fc4c10d78e287ca5d9cc51ee1ae73cbfde08c6b37324cbfaac8bc5)\
957                 )"),
958            "Script(\
959             OP_IF OP_SIZE OP_PUSHBYTES_1 20 OP_EQUALVERIFY OP_HASH256 OP_PUSHBYTES_32 131772552c01444cd81360818376a040b7c3b2b7b0a53550ee3edde216cec61b OP_EQUAL \
960             OP_ELSE OP_0 OP_ENDIF OP_VERIFY OP_SIZE OP_PUSHBYTES_1 20 OP_EQUALVERIFY OP_SHA256 OP_PUSHBYTES_32 ec4916dd28fc4c10d78e287ca5d9cc51ee1ae73cbfde08c6b37324cbfaac8bc5 OP_EQUALVERIFY \
961             OP_PUSHNUM_1\
962             )"
963        );
964
965        // Thresh bug with equal verify roundtrip
966        roundtrip(
967            &ms_str!("tv:thresh(1,pk(02d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e))", ),
968            "Script(OP_PUSHBYTES_33 02d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e OP_CHECKSIG OP_PUSHNUM_1 OP_EQUALVERIFY OP_PUSHNUM_1)",
969        );
970    }
971
972    #[test]
973    fn deserialize() {
974        // Most of these came from fuzzing, hence the increasing lengths
975        assert!(Segwitv0Script::parse_insane(&hex_script("")).is_err()); // empty
976        assert!(Segwitv0Script::parse_insane(&hex_script("00")).is_ok()); // FALSE
977        assert!(Segwitv0Script::parse_insane(&hex_script("51")).is_ok()); // TRUE
978        assert!(Segwitv0Script::parse_insane(&hex_script("69")).is_err()); // VERIFY
979        assert!(Segwitv0Script::parse_insane(&hex_script("0000")).is_err()); //and_v(FALSE,FALSE)
980        assert!(Segwitv0Script::parse_insane(&hex_script("1001")).is_err()); // incomplete push
981        assert!(Segwitv0Script::parse_insane(&hex_script("03990300b2")).is_err()); // non-minimal #
982        assert!(Segwitv0Script::parse_insane(&hex_script("8559b2")).is_err()); // leading bytes
983        assert!(Segwitv0Script::parse_insane(&hex_script("4c0169b2")).is_err()); // non-minimal push
984        assert!(Segwitv0Script::parse_insane(&hex_script("0000af0000ae85")).is_err()); // OR not BOOLOR
985
986        // misc fuzzer problems
987        assert!(Segwitv0Script::parse_insane(&hex_script("0000000000af")).is_err());
988        assert!(Segwitv0Script::parse_insane(&hex_script("04009a2970af00")).is_err()); // giant CMS key num
989        assert!(Segwitv0Script::parse_insane(&hex_script(
990            "2102ffffffffffffffefefefefefefefefefefef394c0fe5b711179e124008584753ac6900"
991        ))
992        .is_err());
993    }
994
995    #[test]
996    fn non_ascii() {
997        assert!(Segwitv0Script::from_str_insane("🌏")
998            .unwrap_err()
999            .to_string()
1000            .contains("unprintable character"));
1001    }
1002
1003    #[test]
1004    fn test_tapscript_rtt() {
1005        // Test x-only invalid under segwitc0 context
1006        let ms = Segwitv0Script::from_str_insane(&format!(
1007            "pk(2788ee41e76f4f3af603da5bc8fa22997bc0344bb0f95666ba6aaff0242baa99)"
1008        ));
1009        assert_eq!(
1010            ms.unwrap_err().to_string(),
1011            "unexpected «key hex decoding error»",
1012        );
1013        Tapscript::from_str_insane(&format!(
1014            "pk(2788ee41e76f4f3af603da5bc8fa22997bc0344bb0f95666ba6aaff0242baa99)"
1015        ))
1016        .unwrap();
1017
1018        // Now test that bitcoin::PublicKey works with Taproot context
1019        Miniscript::<bitcoin::PublicKey, Tap>::from_str_insane(&format!(
1020            "pk(022788ee41e76f4f3af603da5bc8fa22997bc0344bb0f95666ba6aaff0242baa99)"
1021        ))
1022        .unwrap();
1023
1024        // uncompressed keys should not be allowed
1025        Miniscript::<bitcoin::PublicKey, Tap>::from_str_insane(&format!(
1026            "pk(04eed24a081bf1b1e49e3300df4bebe04208ac7e516b6f3ea8eb6e094584267c13483f89dcf194132e12238cc5a34b6b286fc7990d68ed1db86b69ebd826c63b29)"
1027        ))
1028        .unwrap_err();
1029
1030        //---------------- test script <-> miniscript ---------------
1031        // Test parsing from scripts: x-only fails decoding in segwitv0 ctx
1032        Segwitv0Script::parse_insane(&hex_script(
1033            "202788ee41e76f4f3af603da5bc8fa22997bc0344bb0f95666ba6aaff0242baa99ac",
1034        ))
1035        .unwrap_err();
1036        // x-only succeeds in tap ctx
1037        Tapscript::parse_insane(&hex_script(
1038            "202788ee41e76f4f3af603da5bc8fa22997bc0344bb0f95666ba6aaff0242baa99ac",
1039        ))
1040        .unwrap();
1041        // tapscript fails decoding with compressed
1042        Tapscript::parse_insane(&hex_script(
1043            "21022788ee41e76f4f3af603da5bc8fa22997bc0344bb0f95666ba6aaff0242baa99ac",
1044        ))
1045        .unwrap_err();
1046        // Segwitv0 succeeds decoding with tapscript.
1047        Segwitv0Script::parse_insane(&hex_script(
1048            "21022788ee41e76f4f3af603da5bc8fa22997bc0344bb0f95666ba6aaff0242baa99ac",
1049        ))
1050        .unwrap();
1051
1052        // multi not allowed in tapscript
1053        Tapscript::from_str_insane(&format!(
1054            "multi(1,2788ee41e76f4f3af603da5bc8fa22997bc0344bb0f95666ba6aaff0242baa99)"
1055        ))
1056        .unwrap_err();
1057        // but allowed in segwit
1058        Segwitv0Script::from_str_insane(&format!(
1059            "multi(1,022788ee41e76f4f3af603da5bc8fa22997bc0344bb0f95666ba6aaff0242baa99)"
1060        ))
1061        .unwrap();
1062    }
1063
1064    #[test]
1065    fn multi_a_tests() {
1066        // Test from string tests
1067        type Segwitv0Ms = Miniscript<String, Segwitv0>;
1068        type TapMs = Miniscript<String, Tap>;
1069        let segwit_multi_a_ms = Segwitv0Ms::from_str_insane("multi_a(1,A,B,C)");
1070        assert_eq!(
1071            segwit_multi_a_ms.unwrap_err().to_string(),
1072            "Multi a(CHECKSIGADD) only allowed post tapscript"
1073        );
1074        let tap_multi_a_ms = TapMs::from_str_insane("multi_a(1,A,B,C)").unwrap();
1075        assert_eq!(tap_multi_a_ms.to_string(), "multi_a(1,A,B,C)");
1076
1077        // Test encode/decode and translation tests
1078        let tap_ms = tap_multi_a_ms
1079            .translate_pk(&mut StrXOnlyKeyTranslator::new())
1080            .unwrap();
1081        // script rtt test
1082        assert_eq!(
1083            Miniscript::<XOnlyPublicKey, Tap>::parse_insane(&tap_ms.encode()).unwrap(),
1084            tap_ms
1085        );
1086        assert_eq!(tap_ms.script_size(), 104);
1087        assert_eq!(tap_ms.encode().len(), tap_ms.script_size());
1088
1089        // Test satisfaction code
1090        struct SimpleSatisfier(secp256k1::schnorr::Signature);
1091
1092        // a simple satisfier that always outputs the same signature
1093        impl<Pk: ToPublicKey> Satisfier<Pk> for SimpleSatisfier {
1094            fn lookup_tap_leaf_script_sig(
1095                &self,
1096                _pk: &Pk,
1097                _h: &TapLeafHash,
1098            ) -> Option<bitcoin::SchnorrSig> {
1099                Some(bitcoin::SchnorrSig {
1100                    sig: self.0,
1101                    hash_ty: bitcoin::SchnorrSighashType::Default,
1102                })
1103            }
1104        }
1105
1106        let schnorr_sig = secp256k1::schnorr::Signature::from_str("84526253c27c7aef56c7b71a5cd25bebb66dddda437826defc5b2568bde81f0784526253c27c7aef56c7b71a5cd25bebb66dddda437826defc5b2568bde81f07").unwrap();
1107        let s = SimpleSatisfier(schnorr_sig);
1108
1109        let wit = tap_ms.satisfy(s).unwrap();
1110        assert_eq!(wit, vec![schnorr_sig.as_ref().to_vec(), vec![], vec![]]);
1111    }
1112
1113    #[test]
1114    fn decode_bug_cpp_review() {
1115        let ms = Miniscript::<String, Segwitv0>::from_str_insane(
1116            "and_b(1,s:and_v(v:older(9),c:pk_k(A)))",
1117        )
1118        .unwrap();
1119        let ms_trans = ms.translate_pk(&mut StrKeyTranslator::new()).unwrap();
1120        let enc = ms_trans.encode();
1121        let ms = Miniscript::<bitcoin::PublicKey, Segwitv0>::parse_insane(&enc).unwrap();
1122        assert_eq!(ms_trans.encode(), ms.encode());
1123    }
1124
1125    #[test]
1126    fn expr_features() {
1127        // test that parsing raw hash160 does not work with
1128        let hash160_str = "e9f171df53e04b270fa6271b42f66b0f4a99c5a2";
1129        let ms_str = &format!("c:expr_raw_pkh({})", hash160_str);
1130        type SegwitMs = Miniscript<bitcoin::PublicKey, Segwitv0>;
1131
1132        // Test that parsing raw hash160 from string does not work without extra features
1133        SegwitMs::from_str(ms_str).unwrap_err();
1134        SegwitMs::from_str_insane(ms_str).unwrap_err();
1135        let ms = SegwitMs::from_str_ext(ms_str, &ExtParams::allow_all()).unwrap();
1136
1137        let script = ms.encode();
1138        // The same test, but parsing from script
1139        SegwitMs::parse(&script).unwrap_err();
1140        SegwitMs::parse_insane(&script).unwrap_err();
1141        SegwitMs::parse_with_ext(&script, &ExtParams::allow_all()).unwrap();
1142    }
1143}