1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
use std::{
    fmt,
    str::{self, FromStr},
};

use bitcoin::{self, Script};

use super::{checksum::verify_checksum, Bare, Pkh, Sh, Wpkh, Wsh};
use {expression, DescriptorTrait, Error, MiniscriptKey, Satisfier, ToPublicKey};

/// Script descriptor
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PreTaprootDescriptor<Pk: MiniscriptKey> {
    /// Bare descriptor
    Bare(Bare<Pk>),
    /// Pay-to-PubKey-Hash
    Pkh(Pkh<Pk>),
    /// Pay-to-Witness-PubKey-Hash
    Wpkh(Wpkh<Pk>),
    /// Pay-to-ScriptHash(includes nested wsh/wpkh/sorted multi)
    Sh(Sh<Pk>),
    /// Pay-to-Witness-ScriptHash with Segwitv0 context
    Wsh(Wsh<Pk>),
}

impl<Pk: MiniscriptKey> DescriptorTrait<Pk> for PreTaprootDescriptor<Pk> {
    /// Whether the descriptor is safe
    /// Checks whether all the spend paths in the descriptor are possible
    /// on the bitcoin network under the current standardness and consensus rules
    /// Also checks whether the descriptor requires signauture on all spend paths
    /// And whether the script is malleable.
    /// In general, all the guarantees of miniscript hold only for safe scripts.
    /// All the analysis guarantees of miniscript only hold safe scripts.
    /// The signer may not be able to find satisfactions even if one exists
    fn sanity_check(&self) -> Result<(), Error> {
        match *self {
            PreTaprootDescriptor::Bare(ref bare) => bare.sanity_check(),
            PreTaprootDescriptor::Pkh(ref pkh) => pkh.sanity_check(),
            PreTaprootDescriptor::Wpkh(ref wpkh) => wpkh.sanity_check(),
            PreTaprootDescriptor::Wsh(ref wsh) => wsh.sanity_check(),
            PreTaprootDescriptor::Sh(ref sh) => sh.sanity_check(),
        }
    }
    /// Computes the Bitcoin address of the descriptor, if one exists
    fn address(&self, network: bitcoin::Network) -> Result<bitcoin::Address, Error>
    where
        Pk: ToPublicKey,
    {
        match *self {
            PreTaprootDescriptor::Bare(ref bare) => bare.address(network),
            PreTaprootDescriptor::Pkh(ref pkh) => pkh.address(network),
            PreTaprootDescriptor::Wpkh(ref wpkh) => wpkh.address(network),
            PreTaprootDescriptor::Wsh(ref wsh) => wsh.address(network),
            PreTaprootDescriptor::Sh(ref sh) => sh.address(network),
        }
    }

    /// Computes the scriptpubkey of the descriptor
    fn script_pubkey(&self) -> Script
    where
        Pk: ToPublicKey,
    {
        match *self {
            PreTaprootDescriptor::Bare(ref bare) => bare.script_pubkey(),
            PreTaprootDescriptor::Pkh(ref pkh) => pkh.script_pubkey(),
            PreTaprootDescriptor::Wpkh(ref wpkh) => wpkh.script_pubkey(),
            PreTaprootDescriptor::Wsh(ref wsh) => wsh.script_pubkey(),
            PreTaprootDescriptor::Sh(ref sh) => sh.script_pubkey(),
        }
    }

    /// Computes the scriptSig that will be in place for an unsigned
    /// input spending an output with this descriptor. For pre-segwit
    /// descriptors, which use the scriptSig for signatures, this
    /// returns the empty script.
    ///
    /// This is used in Segwit transactions to produce an unsigned
    /// transaction whose txid will not change during signing (since
    /// only the witness data will change).
    fn unsigned_script_sig(&self) -> Script
    where
        Pk: ToPublicKey,
    {
        match *self {
            PreTaprootDescriptor::Bare(ref bare) => bare.unsigned_script_sig(),
            PreTaprootDescriptor::Pkh(ref pkh) => pkh.unsigned_script_sig(),
            PreTaprootDescriptor::Wpkh(ref wpkh) => wpkh.unsigned_script_sig(),
            PreTaprootDescriptor::Wsh(ref wsh) => wsh.unsigned_script_sig(),
            PreTaprootDescriptor::Sh(ref sh) => sh.unsigned_script_sig(),
        }
    }

    /// Computes the "witness script" of the descriptor, i.e. the underlying
    /// script before any hashing is done. For `Bare`, `Pkh` and `Wpkh` this
    /// is the scriptPubkey; for `ShWpkh` and `Sh` this is the redeemScript;
    /// for the others it is the witness script.
    /// Errors:
    /// - When the descriptor is Tr
    fn explicit_script(&self) -> Result<Script, Error>
    where
        Pk: ToPublicKey,
    {
        match *self {
            PreTaprootDescriptor::Bare(ref bare) => bare.explicit_script(),
            PreTaprootDescriptor::Pkh(ref pkh) => pkh.explicit_script(),
            PreTaprootDescriptor::Wpkh(ref wpkh) => wpkh.explicit_script(),
            PreTaprootDescriptor::Wsh(ref wsh) => wsh.explicit_script(),
            PreTaprootDescriptor::Sh(ref sh) => sh.explicit_script(),
        }
    }

    /// Returns satisfying non-malleable witness and scriptSig to spend an
    /// output controlled by the given descriptor if it possible to
    /// construct one using the satisfier S.
    fn get_satisfaction<S>(&self, satisfier: S) -> Result<(Vec<Vec<u8>>, Script), Error>
    where
        Pk: ToPublicKey,
        S: Satisfier<Pk>,
    {
        match *self {
            PreTaprootDescriptor::Bare(ref bare) => bare.get_satisfaction(satisfier),
            PreTaprootDescriptor::Pkh(ref pkh) => pkh.get_satisfaction(satisfier),
            PreTaprootDescriptor::Wpkh(ref wpkh) => wpkh.get_satisfaction(satisfier),
            PreTaprootDescriptor::Wsh(ref wsh) => wsh.get_satisfaction(satisfier),
            PreTaprootDescriptor::Sh(ref sh) => sh.get_satisfaction(satisfier),
        }
    }

    /// Returns a possilbly mallable satisfying non-malleable witness and scriptSig to spend an
    /// output controlled by the given descriptor if it possible to
    /// construct one using the satisfier S.
    fn get_satisfaction_mall<S>(&self, satisfier: S) -> Result<(Vec<Vec<u8>>, Script), Error>
    where
        Pk: ToPublicKey,
        S: Satisfier<Pk>,
    {
        match *self {
            PreTaprootDescriptor::Bare(ref bare) => bare.get_satisfaction_mall(satisfier),
            PreTaprootDescriptor::Pkh(ref pkh) => pkh.get_satisfaction_mall(satisfier),
            PreTaprootDescriptor::Wpkh(ref wpkh) => wpkh.get_satisfaction_mall(satisfier),
            PreTaprootDescriptor::Wsh(ref wsh) => wsh.get_satisfaction_mall(satisfier),
            PreTaprootDescriptor::Sh(ref sh) => sh.get_satisfaction_mall(satisfier),
        }
    }

    /// Computes an upper bound on the weight of a satisfying witness to the
    /// transaction. Assumes all signatures are 73 bytes, including push opcode
    /// and sighash suffix. Includes the weight of the VarInts encoding the
    /// scriptSig and witness stack length.
    fn max_satisfaction_weight(&self) -> Result<usize, Error> {
        match *self {
            PreTaprootDescriptor::Bare(ref bare) => bare.max_satisfaction_weight(),
            PreTaprootDescriptor::Pkh(ref pkh) => pkh.max_satisfaction_weight(),
            PreTaprootDescriptor::Wpkh(ref wpkh) => wpkh.max_satisfaction_weight(),
            PreTaprootDescriptor::Wsh(ref wsh) => wsh.max_satisfaction_weight(),
            PreTaprootDescriptor::Sh(ref sh) => sh.max_satisfaction_weight(),
        }
    }

    /// Get the `scriptCode` of a transaction output.
    ///
    /// The `scriptCode` is the Script of the previous transaction output being serialized in the
    /// sighash when evaluating a `CHECKSIG` & co. OP code.
    /// Returns Error for Tr descriptors
    fn script_code(&self) -> Result<Script, Error>
    where
        Pk: ToPublicKey,
    {
        match *self {
            PreTaprootDescriptor::Bare(ref bare) => bare.script_code(),
            PreTaprootDescriptor::Pkh(ref pkh) => pkh.script_code(),
            PreTaprootDescriptor::Wpkh(ref wpkh) => wpkh.script_code(),
            PreTaprootDescriptor::Wsh(ref wsh) => wsh.script_code(),
            PreTaprootDescriptor::Sh(ref sh) => sh.script_code(),
        }
    }
}

impl<Pk> expression::FromTree for PreTaprootDescriptor<Pk>
where
    Pk: MiniscriptKey + str::FromStr,
    Pk::Hash: str::FromStr,
    <Pk as FromStr>::Err: ToString,
    <<Pk as MiniscriptKey>::Hash as FromStr>::Err: ToString,
{
    /// Parse an expression tree into a descriptor
    fn from_tree(top: &expression::Tree) -> Result<PreTaprootDescriptor<Pk>, Error> {
        Ok(match (top.name, top.args.len() as u32) {
            ("pkh", 1) => PreTaprootDescriptor::Pkh(Pkh::from_tree(top)?),
            ("wpkh", 1) => PreTaprootDescriptor::Wpkh(Wpkh::from_tree(top)?),
            ("sh", 1) => PreTaprootDescriptor::Sh(Sh::from_tree(top)?),
            ("wsh", 1) => PreTaprootDescriptor::Wsh(Wsh::from_tree(top)?),
            _ => PreTaprootDescriptor::Bare(Bare::from_tree(top)?),
        })
    }
}

impl<Pk> FromStr for PreTaprootDescriptor<Pk>
where
    Pk: MiniscriptKey + str::FromStr,
    Pk::Hash: str::FromStr,
    <Pk as FromStr>::Err: ToString,
    <<Pk as MiniscriptKey>::Hash as FromStr>::Err: ToString,
{
    type Err = Error;

    fn from_str(s: &str) -> Result<PreTaprootDescriptor<Pk>, Error> {
        let desc_str = verify_checksum(s)?;
        let top = expression::Tree::from_str(desc_str)?;
        expression::FromTree::from_tree(&top)
    }
}

impl<Pk: MiniscriptKey> fmt::Debug for PreTaprootDescriptor<Pk> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            PreTaprootDescriptor::Bare(ref sub) => write!(f, "{:?}", sub),
            PreTaprootDescriptor::Pkh(ref pkh) => write!(f, "{:?}", pkh),
            PreTaprootDescriptor::Wpkh(ref wpkh) => write!(f, "{:?}", wpkh),
            PreTaprootDescriptor::Sh(ref sub) => write!(f, "{:?}", sub),
            PreTaprootDescriptor::Wsh(ref sub) => write!(f, "{:?}", sub),
        }
    }
}

impl<Pk: MiniscriptKey> fmt::Display for PreTaprootDescriptor<Pk> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            PreTaprootDescriptor::Bare(ref sub) => write!(f, "{}", sub),
            PreTaprootDescriptor::Pkh(ref pkh) => write!(f, "{}", pkh),
            PreTaprootDescriptor::Wpkh(ref wpkh) => write!(f, "{}", wpkh),
            PreTaprootDescriptor::Sh(ref sub) => write!(f, "{}", sub),
            PreTaprootDescriptor::Wsh(ref sub) => write!(f, "{}", sub),
        }
    }
}

serde_string_impl_pk!(PreTaprootDescriptor, "a pre-taproot script descriptor");

// Have the trait in a separate module to avoid conflicts
pub(crate) mod traits {
    use bitcoin::Script;

    use {
        descriptor::{Pkh, Sh, Wpkh, Wsh},
        DescriptorTrait, MiniscriptKey, ToPublicKey,
    };

    use super::PreTaprootDescriptor;

    /// A general trait for Pre taproot bitcoin descriptor.
    /// Similar to [`DescriptorTrait`], but `explicit_script` and `script_code` methods cannot fail
    pub trait PreTaprootDescriptorTrait<Pk: MiniscriptKey>: DescriptorTrait<Pk> {
        /// Same as [`DescriptorTrait::explicit_script`], but a non failing version.
        /// All PreTaproot descriptors have a unique explicit script
        fn explicit_script(&self) -> Script
        where
            Pk: ToPublicKey,
        {
            // This expect can technically be avoided if we implement this for types, but
            // having this expect saves lots of LoC because of default implementation
            <Self as DescriptorTrait<Pk>>::explicit_script(&self)
                .expect("Pre taproot descriptor have explicit script")
        }

        /// Same as [`DescriptorTrait::script_code`], but a non failing version.
        /// All PreTaproot descriptors have a script code
        fn script_code(&self) -> Script
        where
            Pk: ToPublicKey,
        {
            <Self as DescriptorTrait<Pk>>::script_code(&self)
                .expect("Pre taproot descriptor have non-failing script code")
        }
    }

    impl<Pk: MiniscriptKey> PreTaprootDescriptorTrait<Pk> for Pkh<Pk> {}

    impl<Pk: MiniscriptKey> PreTaprootDescriptorTrait<Pk> for Sh<Pk> {}

    impl<Pk: MiniscriptKey> PreTaprootDescriptorTrait<Pk> for Wpkh<Pk> {}

    impl<Pk: MiniscriptKey> PreTaprootDescriptorTrait<Pk> for Wsh<Pk> {}

    impl<Pk: MiniscriptKey> PreTaprootDescriptorTrait<Pk> for PreTaprootDescriptor<Pk> {}
}