parse/parse.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//! Example: Parsing a descriptor from a string
16
17extern crate bitcoin;
18extern crate sapio_miniscript as miniscript;
19
20use miniscript::{descriptor::DescriptorType, Descriptor, DescriptorTrait};
21use std::str::FromStr;
22
23fn main() {
24 let my_descriptor = miniscript::Descriptor::<bitcoin::PublicKey>::from_str(
25 "wsh(c:pk_k(020202020202020202020202020202020202020202020202020202020202020202))",
26 )
27 .unwrap();
28
29 // Check whether the descriptor is safe
30 // This checks whether all spend paths are accessible in bitcoin network.
31 // It maybe possible that some of the spend require more than 100 elements in Wsh scripts
32 // Or they contain a combination of timelock and heightlock.
33 assert!(my_descriptor.sanity_check().is_ok());
34
35 // Compute the script pubkey. As mentioned in the documentation, script_pubkey only fails
36 // for Tr descriptors that don't have some pre-computed data
37 assert_eq!(
38 format!("{:x}", my_descriptor.script_pubkey()),
39 "0020daef16dd7c946a3e735a6e43310cb2ce33dfd14a04f76bf8241a16654cb2f0f9"
40 );
41
42 // Another way to compute script pubkey
43 // We can also compute the type of descriptor
44 let desc_type = my_descriptor.desc_type();
45 assert_eq!(desc_type, DescriptorType::Wsh);
46 // Since we know the type of descriptor, we can get the Wsh struct from Descriptor
47 // This allows us to call infallible methods for getting script pubkey
48 if let Descriptor::Wsh(wsh) = &my_descriptor {
49 assert_eq!(
50 format!("{:x}", wsh.spk()),
51 "0020daef16dd7c946a3e735a6e43310cb2ce33dfd14a04f76bf8241a16654cb2f0f9"
52 );
53 } else {
54 // We checked for the descriptor type earlier
55 }
56
57 // Get the inner script inside the descriptor
58 assert_eq!(
59 format!(
60 "{:x}",
61 my_descriptor
62 .explicit_script()
63 .expect("Wsh descriptors have inner scripts")
64 ),
65 "21020202020202020202020202020202020202020202020202020202020202020202ac"
66 );
67
68 let desc = miniscript::Descriptor::<bitcoin::PublicKey>::from_str(
69 "sh(wsh(c:pk_k(020202020202020202020202020202020202020202020202020202020202020202)))",
70 )
71 .unwrap();
72
73 assert!(desc.desc_type() == DescriptorType::ShWsh);
74}