elements_miniscript/miniscript/
satisfy.rs

1// Written in 2018 by Andrew Poelstra <apoelstra@wpsoftware.net>
2// SPDX-License-Identifier: CC0-1.0
3
4//! # Satisfaction and Dissatisfaction
5//!
6//! Traits and implementations to support producing witnesses for Miniscript
7//! scriptpubkeys.
8//!
9
10use std::collections::{BTreeMap, HashMap};
11use std::sync::Arc;
12use std::{cmp, mem};
13
14use bitcoin::hashes::hash160;
15use bitcoin::secp256k1::XOnlyPublicKey;
16use elements::hashes::sha256d;
17use elements::secp256k1_zkp::schnorr;
18use elements::taproot::{ControlBlock, LeafVersion, TapLeafHash};
19use elements::{self, confidential, secp256k1_zkp, LockTime, OutPoint, Script, Sequence};
20
21use super::context::SigType;
22use crate::extensions::{CsfsMsg, ParseableExt};
23use crate::util::witness_size;
24use crate::{Miniscript, MiniscriptKey, ScriptContext, Terminal, ToPublicKey};
25
26/// Type alias for a signature/hashtype pair
27pub type ElementsSig = (secp256k1_zkp::ecdsa::Signature, elements::EcdsaSighashType);
28/// Type alias for 32 byte Preimage.
29pub type Preimage32 = [u8; 32];
30
31/// Convert to raw sig
32pub fn elementssig_to_rawsig(sig: &ElementsSig) -> Vec<u8> {
33    let ser_sig = sig.0.serialize_der();
34    let mut raw_sig = Vec::from(&ser_sig[..]);
35    raw_sig.push(sig.1 as u8);
36    raw_sig
37}
38
39/// Helper function to create ElementsSig from Rawsig
40/// Useful for downstream when implementing Satisfier.
41/// Returns underlying secp if the Signature is not of correct format
42pub fn elementssig_from_rawsig(rawsig: &[u8]) -> Result<ElementsSig, crate::interpreter::Error> {
43    let (flag, sig) = rawsig.split_last().unwrap();
44    let flag = elements::EcdsaSighashType::from_u32(*flag as u32);
45    let sig = secp256k1_zkp::ecdsa::Signature::from_der(sig)?;
46    Ok((sig, flag))
47}
48/// Trait describing a lookup table for signatures, hash preimages, etc.
49/// Every method has a default implementation that simply returns `None`
50/// on every query. Users are expected to override the methods that they
51/// have data for.
52pub trait Satisfier<Pk: MiniscriptKey + ToPublicKey> {
53    /// Given a public key, look up an ECDSA signature with that key
54    fn lookup_ecdsa_sig(&self, _: &Pk) -> Option<ElementsSig> {
55        None
56    }
57
58    /// Lookup the tap key spend sig
59    fn lookup_tap_key_spend_sig(&self) -> Option<elements::SchnorrSig> {
60        None
61    }
62
63    /// Given a public key and a associated leaf hash, look up an schnorr signature with that key
64    fn lookup_tap_leaf_script_sig(&self, _: &Pk, _: &TapLeafHash) -> Option<elements::SchnorrSig> {
65        None
66    }
67
68    /// Obtain a reference to the control block for a ver and script
69    fn lookup_tap_control_block_map(
70        &self,
71    ) -> Option<&BTreeMap<ControlBlock, (elements::Script, LeafVersion)>> {
72        None
73    }
74
75    /// Given a raw `Pkh`, lookup corresponding [`bitcoin::PublicKey`]
76    fn lookup_raw_pkh_pk(&self, _: &hash160::Hash) -> Option<bitcoin::PublicKey> {
77        None
78    }
79
80    /// Given a raw `Pkh`, lookup corresponding [`bitcoin::key::XOnlyPublicKey`]
81    fn lookup_raw_pkh_x_only_pk(&self, _: &hash160::Hash) -> Option<XOnlyPublicKey> {
82        None
83    }
84
85    /// Given a keyhash, look up the EC signature and the associated key
86    /// Even if signatures for public key Hashes are not available, the users
87    /// can use this map to provide pkh -> pk mapping which can be useful
88    /// for dissatisfying pkh.
89    fn lookup_raw_pkh_ecdsa_sig(
90        &self,
91        _: &hash160::Hash,
92    ) -> Option<(bitcoin::PublicKey, ElementsSig)> {
93        None
94    }
95
96    /// Given a keyhash, look up the schnorr signature and the associated key
97    /// Even if signatures for public key Hashes are not available, the users
98    /// can use this map to provide pkh -> pk mapping which can be useful
99    /// for dissatisfying pkh.
100    fn lookup_raw_pkh_tap_leaf_script_sig(
101        &self,
102        _: &(hash160::Hash, TapLeafHash),
103    ) -> Option<(XOnlyPublicKey, elements::SchnorrSig)> {
104        None
105    }
106
107    /// Given a SHA256 hash, look up its preimage
108    fn lookup_sha256(&self, _: &Pk::Sha256) -> Option<Preimage32> {
109        None
110    }
111
112    /// Given a HASH256 hash, look up its preimage
113    fn lookup_hash256(&self, _: &Pk::Hash256) -> Option<Preimage32> {
114        None
115    }
116
117    /// Given a RIPEMD160 hash, look up its preimage
118    fn lookup_ripemd160(&self, _: &Pk::Ripemd160) -> Option<Preimage32> {
119        None
120    }
121
122    /// Given a HASH160 hash, look up its preimage
123    fn lookup_hash160(&self, _: &Pk::Hash160) -> Option<Preimage32> {
124        None
125    }
126
127    /// Assert whether an relative locktime is satisfied
128    fn check_older(&self, _: Sequence) -> bool {
129        false
130    }
131
132    /// Assert whether a absolute locktime is satisfied
133    fn check_after(&self, _: LockTime) -> bool {
134        false
135    }
136
137    /// Introspection Data for Covenant support
138    /// #1 Version
139    fn lookup_nversion(&self) -> Option<u32> {
140        None
141    }
142
143    /// Item 2: hashprevouts
144    fn lookup_hashprevouts(&self) -> Option<sha256d::Hash> {
145        None
146    }
147
148    /// Item 3: hashsequence
149    fn lookup_hashsequence(&self) -> Option<sha256d::Hash> {
150        None
151    }
152
153    /// ELEMENTS EXTRA: Item 3b: hashsequence
154    fn lookup_hashissuances(&self) -> Option<sha256d::Hash> {
155        None
156    }
157
158    /// Item 4: outpoint
159    fn lookup_outpoint(&self) -> Option<OutPoint> {
160        None
161    }
162
163    /// Item 5: scriptcode
164    fn lookup_scriptcode(&self) -> Option<&Script> {
165        None
166    }
167
168    /// Item 6: value
169    fn lookup_value(&self) -> Option<confidential::Value> {
170        None
171    }
172
173    /// Item 7: sequence
174    fn lookup_nsequence(&self) -> Option<u32> {
175        None
176    }
177
178    /// Item 8: hashoutputs
179    fn lookup_outputs(&self) -> Option<&[elements::TxOut]> {
180        None
181    }
182
183    /// Item 9: nlocktime
184    fn lookup_nlocktime(&self) -> Option<u32> {
185        None
186    }
187
188    /// Item 10: sighash type as u32
189    fn lookup_sighashu32(&self) -> Option<u32> {
190        None
191    }
192
193    /// Lookup spending transaction. Required for introspection
194    // TODO: cleanup some of lookup_* methods as they are subsumed by this
195    fn lookup_tx(&self) -> Option<&elements::Transaction> {
196        None
197    }
198
199    /// Lookup spent txouts. Required for introspection
200    fn lookup_spent_utxos(&self) -> Option<&[elements::TxOut]> {
201        None
202    }
203
204    /// Lookup spent txouts. Required for introspection
205    fn lookup_curr_inp(&self) -> Option<usize> {
206        None
207    }
208
209    /// Lookup (msg, sig) for CSFS fragment
210    fn lookup_csfs_sig(&self, _pk: &XOnlyPublicKey, _msg: &CsfsMsg) -> Option<schnorr::Signature> {
211        None
212    }
213
214    /// Lookup price oracle signature
215    fn lookup_price_oracle_sig(
216        &self,
217        _pk: &XOnlyPublicKey,
218        _time: u64,
219    ) -> Option<(schnorr::Signature, i64, u64)> {
220        None
221    }
222}
223
224// Allow use of `()` as a "no conditions available" satisfier
225impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk> for () {}
226
227impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk> for Sequence {
228    fn check_older(&self, n: Sequence) -> bool {
229        if !self.is_relative_lock_time() {
230            return false;
231        }
232
233        // We need a relative lock time type in rust-bitcoin to clean this up.
234
235        /* If nSequence encodes a relative lock-time, this mask is
236         * applied to extract that lock-time from the sequence field. */
237        const SEQUENCE_LOCKTIME_MASK: u32 = 0x0000ffff;
238        const SEQUENCE_LOCKTIME_TYPE_FLAG: u32 = 0x00400000;
239
240        let mask = SEQUENCE_LOCKTIME_MASK | SEQUENCE_LOCKTIME_TYPE_FLAG;
241        let masked_n = n.to_consensus_u32() & mask;
242        let masked_seq = self.to_consensus_u32() & mask;
243        if masked_n < SEQUENCE_LOCKTIME_TYPE_FLAG && masked_seq >= SEQUENCE_LOCKTIME_TYPE_FLAG {
244            false
245        } else {
246            masked_n <= masked_seq
247        }
248    }
249}
250
251impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk> for LockTime {
252    fn check_after(&self, n: LockTime) -> bool {
253        use LockTime::*;
254
255        match (n, *self) {
256            (Blocks(n), Blocks(lock_time)) => n <= lock_time,
257            (Seconds(n), Seconds(lock_time)) => n <= lock_time,
258            _ => false, // Not the same units.
259        }
260    }
261}
262
263impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk> for HashMap<Pk, ElementsSig> {
264    fn lookup_ecdsa_sig(&self, key: &Pk) -> Option<ElementsSig> {
265        self.get(key).copied()
266    }
267}
268
269impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk>
270    for HashMap<(Pk, TapLeafHash), elements::SchnorrSig>
271{
272    fn lookup_tap_leaf_script_sig(
273        &self,
274        key: &Pk,
275        h: &TapLeafHash,
276    ) -> Option<elements::SchnorrSig> {
277        // Unfortunately, there is no way to get a &(a, b) from &a and &b without allocating
278        // If we change the signature the of lookup_tap_leaf_script_sig to accept a tuple. We would
279        // face the same problem while satisfying PkK.
280        // We use this signature to optimize for the psbt common use case.
281        self.get(&(key.clone(), *h)).copied()
282    }
283}
284
285impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk> for HashMap<hash160::Hash, (Pk, ElementsSig)>
286where
287    Pk: MiniscriptKey + ToPublicKey,
288{
289    fn lookup_ecdsa_sig(&self, key: &Pk) -> Option<ElementsSig> {
290        self.get(&key.to_pubkeyhash(SigType::Ecdsa)).map(|x| x.1)
291    }
292
293    fn lookup_raw_pkh_pk(&self, pk_hash: &hash160::Hash) -> Option<bitcoin::PublicKey> {
294        self.get(pk_hash).map(|x| x.0.to_public_key())
295    }
296
297    fn lookup_raw_pkh_ecdsa_sig(
298        &self,
299        pk_hash: &hash160::Hash,
300    ) -> Option<(bitcoin::PublicKey, ElementsSig)> {
301        self.get(pk_hash)
302            .map(|&(ref pk, sig)| (pk.to_public_key(), sig))
303    }
304}
305
306impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk>
307    for HashMap<(hash160::Hash, TapLeafHash), (Pk, elements::SchnorrSig)>
308where
309    Pk: MiniscriptKey + ToPublicKey,
310{
311    fn lookup_tap_leaf_script_sig(
312        &self,
313        key: &Pk,
314        h: &TapLeafHash,
315    ) -> Option<elements::SchnorrSig> {
316        self.get(&(key.to_pubkeyhash(SigType::Schnorr), *h))
317            .map(|x| x.1)
318    }
319
320    fn lookup_raw_pkh_tap_leaf_script_sig(
321        &self,
322        pk_hash: &(hash160::Hash, TapLeafHash),
323    ) -> Option<(XOnlyPublicKey, elements::SchnorrSig)> {
324        self.get(pk_hash)
325            .map(|&(ref pk, sig)| (pk.to_x_only_pubkey(), sig))
326    }
327}
328
329impl<'a, Pk: MiniscriptKey + ToPublicKey, S: Satisfier<Pk>> Satisfier<Pk> for &'a S {
330    fn lookup_ecdsa_sig(&self, p: &Pk) -> Option<ElementsSig> {
331        (**self).lookup_ecdsa_sig(p)
332    }
333
334    fn lookup_tap_leaf_script_sig(&self, p: &Pk, h: &TapLeafHash) -> Option<elements::SchnorrSig> {
335        (**self).lookup_tap_leaf_script_sig(p, h)
336    }
337
338    fn lookup_raw_pkh_pk(&self, pkh: &hash160::Hash) -> Option<bitcoin::PublicKey> {
339        (**self).lookup_raw_pkh_pk(pkh)
340    }
341
342    fn lookup_raw_pkh_x_only_pk(&self, pkh: &hash160::Hash) -> Option<XOnlyPublicKey> {
343        (**self).lookup_raw_pkh_x_only_pk(pkh)
344    }
345
346    fn lookup_raw_pkh_ecdsa_sig(
347        &self,
348        pkh: &hash160::Hash,
349    ) -> Option<(bitcoin::PublicKey, ElementsSig)> {
350        (**self).lookup_raw_pkh_ecdsa_sig(pkh)
351    }
352
353    fn lookup_tap_key_spend_sig(&self) -> Option<elements::SchnorrSig> {
354        (**self).lookup_tap_key_spend_sig()
355    }
356
357    fn lookup_raw_pkh_tap_leaf_script_sig(
358        &self,
359        pkh: &(hash160::Hash, TapLeafHash),
360    ) -> Option<(XOnlyPublicKey, elements::SchnorrSig)> {
361        (**self).lookup_raw_pkh_tap_leaf_script_sig(pkh)
362    }
363
364    fn lookup_tap_control_block_map(
365        &self,
366    ) -> Option<&BTreeMap<ControlBlock, (elements::Script, LeafVersion)>> {
367        (**self).lookup_tap_control_block_map()
368    }
369
370    fn lookup_sha256(&self, h: &Pk::Sha256) -> Option<Preimage32> {
371        (**self).lookup_sha256(h)
372    }
373
374    fn lookup_hash256(&self, h: &Pk::Hash256) -> Option<Preimage32> {
375        (**self).lookup_hash256(h)
376    }
377
378    fn lookup_ripemd160(&self, h: &Pk::Ripemd160) -> Option<Preimage32> {
379        (**self).lookup_ripemd160(h)
380    }
381
382    fn lookup_hash160(&self, h: &Pk::Hash160) -> Option<Preimage32> {
383        (**self).lookup_hash160(h)
384    }
385
386    fn check_older(&self, t: Sequence) -> bool {
387        (**self).check_older(t)
388    }
389
390    fn check_after(&self, n: LockTime) -> bool {
391        (**self).check_after(n)
392    }
393
394    fn lookup_nversion(&self) -> Option<u32> {
395        (**self).lookup_nversion()
396    }
397
398    fn lookup_hashprevouts(&self) -> Option<sha256d::Hash> {
399        (**self).lookup_hashprevouts()
400    }
401
402    fn lookup_hashsequence(&self) -> Option<sha256d::Hash> {
403        (**self).lookup_hashsequence()
404    }
405
406    fn lookup_hashissuances(&self) -> Option<sha256d::Hash> {
407        (**self).lookup_hashissuances()
408    }
409
410    fn lookup_outpoint(&self) -> Option<OutPoint> {
411        (**self).lookup_outpoint()
412    }
413
414    fn lookup_scriptcode(&self) -> Option<&Script> {
415        (**self).lookup_scriptcode()
416    }
417
418    fn lookup_value(&self) -> Option<confidential::Value> {
419        (**self).lookup_value()
420    }
421
422    fn lookup_nsequence(&self) -> Option<u32> {
423        (**self).lookup_nsequence()
424    }
425
426    fn lookup_outputs(&self) -> Option<&[elements::TxOut]> {
427        (**self).lookup_outputs()
428    }
429
430    fn lookup_nlocktime(&self) -> Option<u32> {
431        (**self).lookup_nlocktime()
432    }
433
434    fn lookup_sighashu32(&self) -> Option<u32> {
435        (**self).lookup_sighashu32()
436    }
437
438    fn lookup_spent_utxos(&self) -> Option<&[elements::TxOut]> {
439        (**self).lookup_spent_utxos()
440    }
441
442    fn lookup_tx(&self) -> Option<&elements::Transaction> {
443        (**self).lookup_tx()
444    }
445
446    fn lookup_curr_inp(&self) -> Option<usize> {
447        (**self).lookup_curr_inp()
448    }
449
450    fn lookup_csfs_sig(&self, pk: &XOnlyPublicKey, msg: &CsfsMsg) -> Option<schnorr::Signature> {
451        (**self).lookup_csfs_sig(pk, msg)
452    }
453
454    fn lookup_price_oracle_sig(
455        &self,
456        pk: &XOnlyPublicKey,
457        time: u64,
458    ) -> Option<(schnorr::Signature, i64, u64)> {
459        (**self).lookup_price_oracle_sig(pk, time)
460    }
461}
462
463impl<'a, Pk: MiniscriptKey + ToPublicKey, S: Satisfier<Pk>> Satisfier<Pk> for &'a mut S {
464    fn lookup_ecdsa_sig(&self, p: &Pk) -> Option<ElementsSig> {
465        (**self).lookup_ecdsa_sig(p)
466    }
467
468    fn lookup_tap_leaf_script_sig(&self, p: &Pk, h: &TapLeafHash) -> Option<elements::SchnorrSig> {
469        (**self).lookup_tap_leaf_script_sig(p, h)
470    }
471
472    fn lookup_tap_key_spend_sig(&self) -> Option<elements::SchnorrSig> {
473        (**self).lookup_tap_key_spend_sig()
474    }
475
476    fn lookup_raw_pkh_pk(&self, pkh: &hash160::Hash) -> Option<bitcoin::PublicKey> {
477        (**self).lookup_raw_pkh_pk(pkh)
478    }
479
480    fn lookup_raw_pkh_x_only_pk(&self, pkh: &hash160::Hash) -> Option<XOnlyPublicKey> {
481        (**self).lookup_raw_pkh_x_only_pk(pkh)
482    }
483
484    fn lookup_raw_pkh_ecdsa_sig(
485        &self,
486        pkh: &hash160::Hash,
487    ) -> Option<(bitcoin::PublicKey, ElementsSig)> {
488        (**self).lookup_raw_pkh_ecdsa_sig(pkh)
489    }
490
491    fn lookup_raw_pkh_tap_leaf_script_sig(
492        &self,
493        pkh: &(hash160::Hash, TapLeafHash),
494    ) -> Option<(XOnlyPublicKey, elements::SchnorrSig)> {
495        (**self).lookup_raw_pkh_tap_leaf_script_sig(pkh)
496    }
497
498    fn lookup_tap_control_block_map(
499        &self,
500    ) -> Option<&BTreeMap<ControlBlock, (elements::Script, LeafVersion)>> {
501        (**self).lookup_tap_control_block_map()
502    }
503
504    fn lookup_sha256(&self, h: &Pk::Sha256) -> Option<Preimage32> {
505        (**self).lookup_sha256(h)
506    }
507
508    fn lookup_hash256(&self, h: &Pk::Hash256) -> Option<Preimage32> {
509        (**self).lookup_hash256(h)
510    }
511
512    fn lookup_ripemd160(&self, h: &Pk::Ripemd160) -> Option<Preimage32> {
513        (**self).lookup_ripemd160(h)
514    }
515
516    fn lookup_hash160(&self, h: &Pk::Hash160) -> Option<Preimage32> {
517        (**self).lookup_hash160(h)
518    }
519
520    fn check_older(&self, t: Sequence) -> bool {
521        (**self).check_older(t)
522    }
523
524    fn check_after(&self, n: LockTime) -> bool {
525        (**self).check_after(n)
526    }
527
528    fn lookup_nversion(&self) -> Option<u32> {
529        (**self).lookup_nversion()
530    }
531
532    fn lookup_hashprevouts(&self) -> Option<sha256d::Hash> {
533        (**self).lookup_hashprevouts()
534    }
535
536    fn lookup_hashsequence(&self) -> Option<sha256d::Hash> {
537        (**self).lookup_hashsequence()
538    }
539
540    fn lookup_hashissuances(&self) -> Option<sha256d::Hash> {
541        (**self).lookup_hashissuances()
542    }
543
544    fn lookup_outpoint(&self) -> Option<OutPoint> {
545        (**self).lookup_outpoint()
546    }
547
548    fn lookup_scriptcode(&self) -> Option<&Script> {
549        (**self).lookup_scriptcode()
550    }
551
552    fn lookup_value(&self) -> Option<confidential::Value> {
553        (**self).lookup_value()
554    }
555
556    fn lookup_nsequence(&self) -> Option<u32> {
557        (**self).lookup_nsequence()
558    }
559
560    fn lookup_outputs(&self) -> Option<&[elements::TxOut]> {
561        (**self).lookup_outputs()
562    }
563
564    fn lookup_nlocktime(&self) -> Option<u32> {
565        (**self).lookup_nlocktime()
566    }
567
568    fn lookup_sighashu32(&self) -> Option<u32> {
569        (**self).lookup_sighashu32()
570    }
571
572    fn lookup_spent_utxos(&self) -> Option<&[elements::TxOut]> {
573        (**self).lookup_spent_utxos()
574    }
575
576    fn lookup_tx(&self) -> Option<&elements::Transaction> {
577        (**self).lookup_tx()
578    }
579
580    fn lookup_curr_inp(&self) -> Option<usize> {
581        (**self).lookup_curr_inp()
582    }
583
584    fn lookup_csfs_sig(&self, pk: &XOnlyPublicKey, msg: &CsfsMsg) -> Option<schnorr::Signature> {
585        (**self).lookup_csfs_sig(pk, msg)
586    }
587
588    fn lookup_price_oracle_sig(
589        &self,
590        pk: &XOnlyPublicKey,
591        time: u64,
592    ) -> Option<(schnorr::Signature, i64, u64)> {
593        (**self).lookup_price_oracle_sig(pk, time)
594    }
595}
596
597macro_rules! impl_tuple_satisfier {
598    ($($ty:ident),*) => {
599        #[allow(non_snake_case)]
600        impl<$($ty,)* Pk> Satisfier<Pk> for ($($ty,)*)
601        where
602            Pk: MiniscriptKey + ToPublicKey,
603            $($ty: Satisfier< Pk>,)*
604        {
605            fn lookup_ecdsa_sig(&self, key: &Pk) -> Option<ElementsSig> {
606                let &($(ref $ty,)*) = self;
607                $(
608                    if let Some(result) = $ty.lookup_ecdsa_sig(key) {
609                        return Some(result);
610                    }
611                )*
612                None
613            }
614
615            fn lookup_tap_key_spend_sig(&self) -> Option<elements::SchnorrSig> {
616                let &($(ref $ty,)*) = self;
617                $(
618                    if let Some(result) = $ty.lookup_tap_key_spend_sig() {
619                        return Some(result);
620                    }
621                )*
622                None
623            }
624
625            fn lookup_tap_leaf_script_sig(&self, key: &Pk, h: &TapLeafHash) -> Option<elements::SchnorrSig> {
626                let &($(ref $ty,)*) = self;
627                $(
628                    if let Some(result) = $ty.lookup_tap_leaf_script_sig(key, h) {
629                        return Some(result);
630                    }
631                )*
632                None
633            }
634
635            fn lookup_raw_pkh_ecdsa_sig(
636                &self,
637                key_hash: &hash160::Hash,
638            ) -> Option<(bitcoin::PublicKey, ElementsSig)> {
639                let &($(ref $ty,)*) = self;
640                $(
641                    if let Some(result) = $ty.lookup_raw_pkh_ecdsa_sig(key_hash) {
642                        return Some(result);
643                    }
644                )*
645                None
646            }
647
648            fn lookup_raw_pkh_tap_leaf_script_sig(
649                &self,
650                key_hash: &(hash160::Hash, TapLeafHash),
651            ) -> Option<(XOnlyPublicKey, elements::SchnorrSig)> {
652                let &($(ref $ty,)*) = self;
653                $(
654                    if let Some(result) = $ty.lookup_raw_pkh_tap_leaf_script_sig(key_hash) {
655                        return Some(result);
656                    }
657                )*
658                None
659            }
660
661            fn lookup_raw_pkh_pk(
662                &self,
663                key_hash: &hash160::Hash,
664            ) -> Option<bitcoin::PublicKey> {
665                let &($(ref $ty,)*) = self;
666                $(
667                    if let Some(result) = $ty.lookup_raw_pkh_pk(key_hash) {
668                        return Some(result);
669                    }
670                )*
671                None
672            }
673
674            fn lookup_raw_pkh_x_only_pk(
675                &self,
676                key_hash: &hash160::Hash,
677            ) -> Option<XOnlyPublicKey> {
678                let &($(ref $ty,)*) = self;
679                $(
680                    if let Some(result) = $ty.lookup_raw_pkh_x_only_pk(key_hash) {
681                        return Some(result);
682                    }
683                )*
684                None
685            }
686
687            fn lookup_tap_control_block_map(
688                &self,
689            ) -> Option<&BTreeMap<ControlBlock, (elements::Script, LeafVersion)>> {
690                let &($(ref $ty,)*) = self;
691                $(
692                    if let Some(result) = $ty.lookup_tap_control_block_map() {
693                        return Some(result);
694                    }
695                )*
696                None
697            }
698
699            fn lookup_sha256(&self, h: &Pk::Sha256) -> Option<Preimage32> {
700                let &($(ref $ty,)*) = self;
701                $(
702                    if let Some(result) = $ty.lookup_sha256(h) {
703                        return Some(result);
704                    }
705                )*
706                None
707            }
708
709            fn lookup_hash256(&self, h: &Pk::Hash256) -> Option<Preimage32> {
710                let &($(ref $ty,)*) = self;
711                $(
712                    if let Some(result) = $ty.lookup_hash256(h) {
713                        return Some(result);
714                    }
715                )*
716                None
717            }
718
719            fn lookup_ripemd160(&self, h: &Pk::Ripemd160) -> Option<Preimage32> {
720                let &($(ref $ty,)*) = self;
721                $(
722                    if let Some(result) = $ty.lookup_ripemd160(h) {
723                        return Some(result);
724                    }
725                )*
726                None
727            }
728
729            fn lookup_hash160(&self, h: &Pk::Hash160) -> Option<Preimage32> {
730                let &($(ref $ty,)*) = self;
731                $(
732                    if let Some(result) = $ty.lookup_hash160(h) {
733                        return Some(result);
734                    }
735                )*
736                None
737            }
738
739            fn check_older(&self, n: Sequence) -> bool {
740                let &($(ref $ty,)*) = self;
741                $(
742                    if $ty.check_older(n) {
743                        return true;
744                    }
745                )*
746                false
747            }
748
749            fn check_after(&self, n: LockTime) -> bool {
750                let &($(ref $ty,)*) = self;
751                $(
752                    if $ty.check_after(n) {
753                        return true;
754                    }
755                )*
756                false
757            }
758
759            fn lookup_nversion(&self) -> Option<u32> {
760                let &($(ref $ty,)*) = self;
761                $(
762                    if let Some(result) = $ty.lookup_nversion() {
763                        return Some(result);
764                    }
765                )*
766                None
767            }
768
769            fn lookup_hashprevouts(&self) -> Option<sha256d::Hash> {
770                let &($(ref $ty,)*) = self;
771                $(
772                    if let Some(result) = $ty.lookup_hashprevouts() {
773                        return Some(result);
774                    }
775                )*
776                None
777            }
778
779            fn lookup_hashsequence(&self) -> Option<sha256d::Hash> {
780                let &($(ref $ty,)*) = self;
781                $(
782                    if let Some(result) = $ty.lookup_hashsequence() {
783                        return Some(result);
784                    }
785                )*
786                None
787            }
788
789            fn lookup_hashissuances(&self) -> Option<sha256d::Hash> {
790                let &($(ref $ty,)*) = self;
791                $(
792                    if let Some(result) = $ty.lookup_hashissuances() {
793                        return Some(result);
794                    }
795                )*
796                None
797            }
798
799            fn lookup_outpoint(&self) -> Option<OutPoint> {
800                let &($(ref $ty,)*) = self;
801                $(
802                    if let Some(result) = $ty.lookup_outpoint() {
803                        return Some(result);
804                    }
805                )*
806                None
807            }
808
809            fn lookup_scriptcode(&self) -> Option<&Script> {
810                let &($(ref $ty,)*) = self;
811                $(
812                    if let Some(result) = $ty.lookup_scriptcode() {
813                        return Some(result);
814                    }
815                )*
816                None
817            }
818
819            fn lookup_value(&self) -> Option<confidential::Value> {
820                let &($(ref $ty,)*) = self;
821                $(
822                    if let Some(result) = $ty.lookup_value() {
823                        return Some(result);
824                    }
825                )*
826                None
827            }
828
829            fn lookup_nsequence(&self) -> Option<u32> {
830                let &($(ref $ty,)*) = self;
831                $(
832                    if let Some(result) = $ty.lookup_nsequence() {
833                        return Some(result);
834                    }
835                )*
836                None
837            }
838
839            fn lookup_outputs(&self) -> Option<&[elements::TxOut]> {
840                let &($(ref $ty,)*) = self;
841                $(
842                    if let Some(result) = $ty.lookup_outputs() {
843                        return Some(result);
844                    }
845                )*
846                None
847            }
848
849            fn lookup_nlocktime(&self) -> Option<u32> {
850                let &($(ref $ty,)*) = self;
851                $(
852                    if let Some(result) = $ty.lookup_nlocktime() {
853                        return Some(result);
854                    }
855                )*
856                None
857            }
858
859            fn lookup_sighashu32(&self) -> Option<u32> {
860                let &($(ref $ty,)*) = self;
861                $(
862                    if let Some(result) = $ty.lookup_sighashu32() {
863                        return Some(result);
864                    }
865                )*
866                None
867            }
868
869            fn lookup_spent_utxos(&self) -> Option<&[elements::TxOut]> {
870                let &($(ref $ty,)*) = self;
871                $(
872                    if let Some(result) = $ty.lookup_spent_utxos() {
873                        return Some(result);
874                    }
875                )*
876                None
877            }
878
879            fn lookup_curr_inp(&self) -> Option<usize> {
880                let &($(ref $ty,)*) = self;
881                $(
882                    if let Some(result) = $ty.lookup_curr_inp() {
883                        return Some(result);
884                    }
885                )*
886                None
887            }
888
889            fn lookup_tx(&self) -> Option<&elements::Transaction> {
890                let &($(ref $ty,)*) = self;
891                $(
892                    if let Some(result) = $ty.lookup_tx() {
893                        return Some(result);
894                    }
895                )*
896                None
897            }
898
899            fn lookup_csfs_sig(&self, pk: &XOnlyPublicKey, msg: &CsfsMsg) -> Option<schnorr::Signature> {
900                let &($(ref $ty,)*) = self;
901                $(
902                    if let Some(result) = $ty.lookup_csfs_sig(pk, msg) {
903                        return Some(result);
904                    }
905                )*
906                None
907            }
908
909            fn lookup_price_oracle_sig(&self, pk: &XOnlyPublicKey, time: u64) -> Option<(schnorr::Signature, i64, u64)> {
910                let &($(ref $ty,)*) = self;
911                $(
912                    if let Some(result) = $ty.lookup_price_oracle_sig(pk, time) {
913                        return Some(result);
914                    }
915                )*
916                None
917            }
918        }
919    }
920}
921
922impl_tuple_satisfier!(A);
923impl_tuple_satisfier!(A, B);
924impl_tuple_satisfier!(A, B, C);
925impl_tuple_satisfier!(A, B, C, D);
926impl_tuple_satisfier!(A, B, C, D, E);
927impl_tuple_satisfier!(A, B, C, D, E, F);
928impl_tuple_satisfier!(A, B, C, D, E, F, G);
929impl_tuple_satisfier!(A, B, C, D, E, F, G, H);
930
931/// A witness, if available, for a Miniscript fragment
932#[derive(Clone, PartialEq, Eq, Debug)]
933pub enum Witness {
934    /// Witness Available and the value of the witness
935    Stack(Vec<Vec<u8>>),
936    /// Third party can possibly satisfy the fragment but we cannot
937    /// Witness Unavailable
938    Unavailable,
939    /// No third party can produce a satisfaction without private key
940    /// Witness Impossible
941    Impossible,
942}
943
944impl PartialOrd for Witness {
945    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
946        Some(self.cmp(other))
947    }
948}
949
950impl Ord for Witness {
951    fn cmp(&self, other: &Self) -> cmp::Ordering {
952        match (self, other) {
953            (Witness::Stack(v1), Witness::Stack(v2)) => {
954                let w1 = witness_size(v1);
955                let w2 = witness_size(v2);
956                w1.cmp(&w2)
957            }
958            (Witness::Stack(_), _) => cmp::Ordering::Less,
959            (_, Witness::Stack(_)) => cmp::Ordering::Greater,
960            (Witness::Impossible, Witness::Unavailable) => cmp::Ordering::Less,
961            (Witness::Unavailable, Witness::Impossible) => cmp::Ordering::Greater,
962            (Witness::Impossible, Witness::Impossible) => cmp::Ordering::Equal,
963            (Witness::Unavailable, Witness::Unavailable) => cmp::Ordering::Equal,
964        }
965    }
966}
967
968impl Witness {
969    /// Turn a signature into (part of) a satisfaction
970    fn signature<Pk: ToPublicKey, S: Satisfier<Pk>, Ctx: ScriptContext>(
971        sat: S,
972        pk: &Pk,
973        leaf_hash: &TapLeafHash,
974    ) -> Self {
975        match Ctx::sig_type() {
976            super::context::SigType::Ecdsa => match sat.lookup_ecdsa_sig(pk) {
977                Some(sig) => Witness::Stack(vec![elementssig_to_rawsig(&sig)]),
978                // Signatures cannot be forged
979                None => Witness::Impossible,
980            },
981            super::context::SigType::Schnorr => match sat.lookup_tap_leaf_script_sig(pk, leaf_hash)
982            {
983                Some(sig) => Witness::Stack(vec![sig.to_vec()]),
984                // Signatures cannot be forged
985                None => Witness::Impossible,
986            },
987        }
988    }
989
990    /// Turn a public key related to a pkh into (part of) a satisfaction
991    fn pkh_public_key<Pk: ToPublicKey, S: Satisfier<Pk>, Ctx: ScriptContext>(
992        sat: S,
993        pkh: &hash160::Hash,
994    ) -> Self {
995        // public key hashes are assumed to be unavailable
996        // instead of impossible since it is the same as pub-key hashes
997        match Ctx::sig_type() {
998            SigType::Ecdsa => match sat.lookup_raw_pkh_pk(pkh) {
999                Some(pk) => Witness::Stack(vec![pk.to_bytes()]),
1000                None => Witness::Unavailable,
1001            },
1002            SigType::Schnorr => match sat.lookup_raw_pkh_x_only_pk(pkh) {
1003                Some(pk) => Witness::Stack(vec![pk.serialize().to_vec()]),
1004                None => Witness::Unavailable,
1005            },
1006        }
1007    }
1008
1009    /// Turn a key/signature pair related to a pkh into (part of) a satisfaction
1010    fn pkh_signature<Pk: ToPublicKey, S: Satisfier<Pk>, Ctx: ScriptContext>(
1011        sat: S,
1012        pkh: &hash160::Hash,
1013        leaf_hash: &TapLeafHash,
1014    ) -> Self {
1015        match Ctx::sig_type() {
1016            SigType::Ecdsa => match sat.lookup_raw_pkh_ecdsa_sig(pkh) {
1017                Some((pk, sig)) => {
1018                    let ser_sig = elementssig_to_rawsig(&sig);
1019                    Witness::Stack(vec![ser_sig, pk.to_public_key().to_bytes()])
1020                }
1021                None => Witness::Impossible,
1022            },
1023            SigType::Schnorr => match sat.lookup_raw_pkh_tap_leaf_script_sig(&(*pkh, *leaf_hash)) {
1024                Some((pk, sig)) => Witness::Stack(vec![
1025                    sig.to_vec(),
1026                    pk.to_x_only_pubkey().serialize().to_vec(),
1027                ]),
1028                None => Witness::Impossible,
1029            },
1030        }
1031    }
1032
1033    /// Turn a hash preimage into (part of) a satisfaction
1034    pub fn ripemd160_preimage<Pk: ToPublicKey, S: Satisfier<Pk>>(
1035        sat: S,
1036        h: &Pk::Ripemd160,
1037    ) -> Self {
1038        match sat.lookup_ripemd160(h) {
1039            Some(pre) => Witness::Stack(vec![pre.to_vec()]),
1040            // Note hash preimages are unavailable instead of impossible
1041            None => Witness::Unavailable,
1042        }
1043    }
1044
1045    /// Turn a hash preimage into (part of) a satisfaction
1046    pub fn hash160_preimage<Pk: ToPublicKey, S: Satisfier<Pk>>(sat: S, h: &Pk::Hash160) -> Self {
1047        match sat.lookup_hash160(h) {
1048            Some(pre) => Witness::Stack(vec![pre.to_vec()]),
1049            // Note hash preimages are unavailable instead of impossible
1050            None => Witness::Unavailable,
1051        }
1052    }
1053
1054    /// Turn a hash preimage into (part of) a satisfaction
1055    pub fn sha256_preimage<Pk: ToPublicKey, S: Satisfier<Pk>>(sat: S, h: &Pk::Sha256) -> Self {
1056        match sat.lookup_sha256(h) {
1057            Some(pre) => Witness::Stack(vec![pre.to_vec()]),
1058            // Note hash preimages are unavailable instead of impossible
1059            None => Witness::Unavailable,
1060        }
1061    }
1062
1063    /// Turn a hash preimage into (part of) a satisfaction
1064    pub fn hash256_preimage<Pk: ToPublicKey, S: Satisfier<Pk>>(sat: S, h: &Pk::Hash256) -> Self {
1065        match sat.lookup_hash256(h) {
1066            Some(pre) => Witness::Stack(vec![pre.to_vec()]),
1067            // Note hash preimages are unavailable instead of impossible
1068            None => Witness::Unavailable,
1069        }
1070    }
1071}
1072
1073impl Witness {
1074    /// Produce something like a 32-byte 0 push
1075    pub fn hash_dissatisfaction() -> Self {
1076        Witness::Stack(vec![vec![0; 32]])
1077    }
1078
1079    /// Construct a satisfaction equivalent to an empty stack
1080    pub fn empty() -> Self {
1081        Witness::Stack(vec![])
1082    }
1083
1084    /// Construct a satisfaction equivalent to `OP_1`
1085    pub fn push_1() -> Self {
1086        Witness::Stack(vec![vec![1]])
1087    }
1088
1089    /// Construct a satisfaction equivalent to a single empty push
1090    pub fn push_0() -> Self {
1091        Witness::Stack(vec![vec![]])
1092    }
1093
1094    /// Concatenate, or otherwise combine, two satisfactions
1095    pub fn combine(one: Self, two: Self) -> Self {
1096        match (one, two) {
1097            (Witness::Impossible, _) | (_, Witness::Impossible) => Witness::Impossible,
1098            (Witness::Unavailable, _) | (_, Witness::Unavailable) => Witness::Unavailable,
1099            (Witness::Stack(mut a), Witness::Stack(b)) => {
1100                a.extend(b);
1101                Witness::Stack(a)
1102            }
1103        }
1104    }
1105}
1106
1107/// A (dis)satisfaction of a Miniscript fragment
1108#[derive(Clone, PartialEq, Eq, Debug)]
1109pub struct Satisfaction {
1110    /// The actual witness stack
1111    pub stack: Witness,
1112    /// Whether or not this (dis)satisfaction has a signature somewhere
1113    /// in it
1114    pub has_sig: bool,
1115}
1116
1117impl Satisfaction {
1118    /// Construct a satisfaction that is impossible to satisfy with no sig
1119    pub fn impossible() -> Self {
1120        Satisfaction {
1121            stack: Witness::Impossible,
1122            has_sig: false,
1123        }
1124    }
1125
1126    /// Construct a satisfaction that is impossible to satisfy with no sig
1127    pub fn empty() -> Self {
1128        Satisfaction {
1129            stack: Witness::empty(),
1130            has_sig: false,
1131        }
1132    }
1133
1134    /// Combines two satisfactions
1135    pub fn combine(one: Self, two: Self) -> Self {
1136        Satisfaction {
1137            stack: Witness::combine(one.stack, two.stack),
1138            has_sig: one.has_sig || two.has_sig,
1139        }
1140    }
1141
1142    // produce a non-malleable satisafaction for thesh frag
1143    fn thresh<Pk, Ctx, Sat, Ext, F>(
1144        k: usize,
1145        subs: &[Arc<Miniscript<Pk, Ctx, Ext>>],
1146        stfr: &Sat,
1147        root_has_sig: bool,
1148        leaf_hash: &TapLeafHash,
1149        min_fn: &mut F,
1150    ) -> Self
1151    where
1152        Pk: MiniscriptKey + ToPublicKey,
1153        Ctx: ScriptContext,
1154        Sat: Satisfier<Pk>,
1155        Ext: ParseableExt,
1156        F: FnMut(Satisfaction, Satisfaction) -> Satisfaction,
1157    {
1158        let mut sats = subs
1159            .iter()
1160            .map(|s| {
1161                Self::satisfy_helper(
1162                    &s.node,
1163                    stfr,
1164                    root_has_sig,
1165                    leaf_hash,
1166                    min_fn,
1167                    &mut Self::thresh,
1168                )
1169            })
1170            .collect::<Vec<_>>();
1171        // Start with the to-return stack set to all dissatisfactions
1172        let mut ret_stack = subs
1173            .iter()
1174            .map(|s| {
1175                Self::dissatisfy_helper(
1176                    &s.node,
1177                    stfr,
1178                    root_has_sig,
1179                    leaf_hash,
1180                    min_fn,
1181                    &mut Self::thresh,
1182                )
1183            })
1184            .collect::<Vec<_>>();
1185
1186        // Sort everything by (sat cost - dissat cost), except that
1187        // satisfactions without signatures beat satisfactions with
1188        // signatures
1189        let mut sat_indices = (0..subs.len()).collect::<Vec<_>>();
1190        sat_indices.sort_by_key(|&i| {
1191            let stack_weight = match (&sats[i].stack, &ret_stack[i].stack) {
1192                (Witness::Unavailable, _) | (Witness::Impossible, _) => i64::MAX,
1193                // This can only be the case when we have PkH without the corresponding
1194                // Pubkey.
1195                (_, Witness::Unavailable) | (_, Witness::Impossible) => i64::MIN,
1196                (Witness::Stack(ref s), Witness::Stack(ref d)) => {
1197                    witness_size(s) as i64 - witness_size(d) as i64
1198                }
1199            };
1200            let is_impossible = sats[i].stack == Witness::Impossible;
1201            // First consider the candidates that are not impossible to satisfy
1202            // by any party. Among those first consider the ones that have no sig
1203            // because third party can malleate them if they are not chosen.
1204            // Lastly, choose by weight.
1205            (is_impossible, sats[i].has_sig, stack_weight)
1206        });
1207
1208        for i in 0..k {
1209            mem::swap(&mut ret_stack[sat_indices[i]], &mut sats[sat_indices[i]]);
1210        }
1211
1212        // We preferably take satisfactions that are not impossible
1213        // If we cannot find `k` satisfactions that are not impossible
1214        // then the threshold branch is impossible to satisfy
1215        // For example, the fragment thresh(2, hash, 0, 0, 0)
1216        // is has an impossible witness
1217        assert!(k > 0);
1218        if sats[sat_indices[k - 1]].stack == Witness::Impossible {
1219            Satisfaction {
1220                stack: Witness::Impossible,
1221                // If the witness is impossible, we don't care about the
1222                // has_sig flag
1223                has_sig: false,
1224            }
1225        }
1226        // We are now guaranteed that all elements in `k` satisfactions
1227        // are not impossible(we sort by is_impossible bool).
1228        // The above loop should have taken everything without a sig
1229        // (since those were sorted higher than non-sigs). If there
1230        // are remaining non-sig satisfactions this indicates a
1231        // malleability vector
1232        // For example, the fragment thresh(2, hash, hash, 0, 0)
1233        // is uniquely satisfyiable because there is no satisfaction
1234        // for the 0 fragment
1235        else if k < sat_indices.len()
1236            && !sats[sat_indices[k]].has_sig
1237            && sats[sat_indices[k]].stack != Witness::Impossible
1238        {
1239            // All arguments should be `d`, so dissatisfactions have no
1240            // signatures; and in this branch we assume too many weak
1241            // arguments, so none of the satisfactions should have
1242            // signatures either.
1243            for sat in &ret_stack {
1244                assert!(!sat.has_sig);
1245            }
1246            Satisfaction {
1247                stack: Witness::Unavailable,
1248                has_sig: false,
1249            }
1250        } else {
1251            // Otherwise flatten everything out
1252            Satisfaction {
1253                has_sig: ret_stack.iter().any(|sat| sat.has_sig),
1254                stack: ret_stack.into_iter().fold(Witness::empty(), |acc, next| {
1255                    Witness::combine(next.stack, acc)
1256                }),
1257            }
1258        }
1259    }
1260
1261    // produce a possily malleable satisafaction for thesh frag
1262    fn thresh_mall<Pk, Ctx, Sat, Ext, F>(
1263        k: usize,
1264        subs: &[Arc<Miniscript<Pk, Ctx, Ext>>],
1265        stfr: &Sat,
1266        root_has_sig: bool,
1267        leaf_hash: &TapLeafHash,
1268        min_fn: &mut F,
1269    ) -> Self
1270    where
1271        Pk: MiniscriptKey + ToPublicKey,
1272        Ctx: ScriptContext,
1273        Sat: Satisfier<Pk>,
1274        Ext: ParseableExt,
1275        F: FnMut(Satisfaction, Satisfaction) -> Satisfaction,
1276    {
1277        let mut sats = subs
1278            .iter()
1279            .map(|s| {
1280                Self::satisfy_helper(
1281                    &s.node,
1282                    stfr,
1283                    root_has_sig,
1284                    leaf_hash,
1285                    min_fn,
1286                    &mut Self::thresh_mall,
1287                )
1288            })
1289            .collect::<Vec<_>>();
1290        // Start with the to-return stack set to all dissatisfactions
1291        let mut ret_stack = subs
1292            .iter()
1293            .map(|s| {
1294                Self::dissatisfy_helper(
1295                    &s.node,
1296                    stfr,
1297                    root_has_sig,
1298                    leaf_hash,
1299                    min_fn,
1300                    &mut Self::thresh_mall,
1301                )
1302            })
1303            .collect::<Vec<_>>();
1304
1305        // Sort everything by (sat cost - dissat cost), except that
1306        // satisfactions without signatures beat satisfactions with
1307        // signatures
1308        let mut sat_indices = (0..subs.len()).collect::<Vec<_>>();
1309        sat_indices.sort_by_key(|&i| {
1310            // For malleable satifactions, directly choose smallest weights
1311            match (&sats[i].stack, &ret_stack[i].stack) {
1312                (Witness::Unavailable, _) | (Witness::Impossible, _) => i64::MAX,
1313                // This is only possible when one of the branches has PkH
1314                (_, Witness::Unavailable) | (_, Witness::Impossible) => i64::MIN,
1315                (Witness::Stack(ref s), Witness::Stack(ref d)) => {
1316                    witness_size(s) as i64 - witness_size(d) as i64
1317                }
1318            }
1319        });
1320
1321        // swap the satisfactions
1322        for i in 0..k {
1323            mem::swap(&mut ret_stack[sat_indices[i]], &mut sats[sat_indices[i]]);
1324        }
1325
1326        // combine the witness
1327        // no non-malleability checks needed
1328        Satisfaction {
1329            has_sig: ret_stack.iter().any(|sat| sat.has_sig),
1330            stack: ret_stack.into_iter().fold(Witness::empty(), |acc, next| {
1331                Witness::combine(next.stack, acc)
1332            }),
1333        }
1334    }
1335
1336    fn minimum(sat1: Self, sat2: Self) -> Self {
1337        // If there is only one available satisfaction, we must choose that
1338        // regardless of has_sig marker.
1339        // This handles the case where both are impossible.
1340        match (&sat1.stack, &sat2.stack) {
1341            (&Witness::Impossible, _) => return sat2,
1342            (_, &Witness::Impossible) => return sat1,
1343            _ => {}
1344        }
1345        match (sat1.has_sig, sat2.has_sig) {
1346            // If neither option has a signature, this is a malleability
1347            // vector, so choose neither one.
1348            (false, false) => Satisfaction {
1349                stack: Witness::Unavailable,
1350                has_sig: false,
1351            },
1352            // If only one has a signature, take the one that doesn't; a
1353            // third party could malleate by removing the signature, but
1354            // can't malleate if he'd have to add it
1355            (false, true) => Satisfaction {
1356                stack: sat1.stack,
1357                has_sig: false,
1358            },
1359            (true, false) => Satisfaction {
1360                stack: sat2.stack,
1361                has_sig: false,
1362            },
1363            // If both have a signature associated with them, choose the
1364            // cheaper one (where "cheaper" is defined such that available
1365            // things are cheaper than unavailable ones)
1366            (true, true) => Satisfaction {
1367                stack: cmp::min(sat1.stack, sat2.stack),
1368                has_sig: true,
1369            },
1370        }
1371    }
1372
1373    // calculate the minimum witness allowing witness malleability
1374    fn minimum_mall(sat1: Self, sat2: Self) -> Self {
1375        match (&sat1.stack, &sat2.stack) {
1376            // If there is only one possible satisfaction, use it regardless
1377            // of the other one
1378            (&Witness::Impossible, _) | (&Witness::Unavailable, _) => return sat2,
1379            (_, &Witness::Impossible) | (_, &Witness::Unavailable) => return sat1,
1380            _ => {}
1381        }
1382        Satisfaction {
1383            stack: cmp::min(sat1.stack, sat2.stack),
1384            // The fragment is has_sig only if both of the
1385            // fragments are has_sig
1386            has_sig: sat1.has_sig && sat2.has_sig,
1387        }
1388    }
1389
1390    // produce a non-malleable satisfaction
1391    fn satisfy_helper<Pk, Ctx, Sat, Ext, F, G>(
1392        term: &Terminal<Pk, Ctx, Ext>,
1393        stfr: &Sat,
1394        root_has_sig: bool,
1395        leaf_hash: &TapLeafHash,
1396        min_fn: &mut F,
1397        thresh_fn: &mut G,
1398    ) -> Self
1399    where
1400        Pk: MiniscriptKey + ToPublicKey,
1401        Ctx: ScriptContext,
1402        Sat: Satisfier<Pk>,
1403        Ext: ParseableExt,
1404        F: FnMut(Satisfaction, Satisfaction) -> Satisfaction,
1405        G: FnMut(
1406            usize,
1407            &[Arc<Miniscript<Pk, Ctx, Ext>>],
1408            &Sat,
1409            bool,
1410            &TapLeafHash,
1411            &mut F,
1412        ) -> Satisfaction,
1413    {
1414        match *term {
1415            Terminal::PkK(ref pk) => Satisfaction {
1416                stack: Witness::signature::<_, _, Ctx>(stfr, pk, leaf_hash),
1417                has_sig: true,
1418            },
1419            Terminal::PkH(ref pk) => {
1420                let wit = Witness::signature::<_, _, Ctx>(stfr, pk, leaf_hash);
1421                let pk_bytes = match Ctx::sig_type() {
1422                    SigType::Ecdsa => pk.to_public_key().to_bytes(),
1423                    SigType::Schnorr => pk.to_x_only_pubkey().serialize().to_vec(),
1424                };
1425                Satisfaction {
1426                    stack: Witness::combine(wit, Witness::Stack(vec![pk_bytes])),
1427                    has_sig: true,
1428                }
1429            }
1430            Terminal::RawPkH(ref pkh) => Satisfaction {
1431                stack: Witness::pkh_signature::<_, _, Ctx>(stfr, pkh, leaf_hash),
1432                has_sig: true,
1433            },
1434            Terminal::After(t) => Satisfaction {
1435                stack: if stfr.check_after(t.into()) {
1436                    Witness::empty()
1437                } else if root_has_sig {
1438                    // If the root terminal has signature, the
1439                    // signature covers the nLockTime and nSequence
1440                    // values. The sender of the transaction should
1441                    // take care that it signs the value such that the
1442                    // timelock is not met
1443                    Witness::Impossible
1444                } else {
1445                    Witness::Unavailable
1446                },
1447                has_sig: false,
1448            },
1449            Terminal::Older(t) => Satisfaction {
1450                stack: if stfr.check_older(t) {
1451                    Witness::empty()
1452                } else if root_has_sig {
1453                    // If the root terminal has signature, the
1454                    // signature covers the nLockTime and nSequence
1455                    // values. The sender of the transaction should
1456                    // take care that it signs the value such that the
1457                    // timelock is not met
1458                    Witness::Impossible
1459                } else {
1460                    Witness::Unavailable
1461                },
1462
1463                has_sig: false,
1464            },
1465            Terminal::Ripemd160(ref h) => Satisfaction {
1466                stack: Witness::ripemd160_preimage(stfr, h),
1467                has_sig: false,
1468            },
1469            Terminal::Hash160(ref h) => Satisfaction {
1470                stack: Witness::hash160_preimage(stfr, h),
1471                has_sig: false,
1472            },
1473            Terminal::Sha256(ref h) => Satisfaction {
1474                stack: Witness::sha256_preimage(stfr, h),
1475                has_sig: false,
1476            },
1477            Terminal::Hash256(ref h) => Satisfaction {
1478                stack: Witness::hash256_preimage(stfr, h),
1479                has_sig: false,
1480            },
1481            Terminal::True => Satisfaction {
1482                stack: Witness::empty(),
1483                has_sig: false,
1484            },
1485            Terminal::False => Satisfaction {
1486                stack: Witness::Impossible,
1487                has_sig: false,
1488            },
1489            Terminal::Alt(ref sub)
1490            | Terminal::Swap(ref sub)
1491            | Terminal::Check(ref sub)
1492            | Terminal::Verify(ref sub)
1493            | Terminal::NonZero(ref sub)
1494            | Terminal::ZeroNotEqual(ref sub) => {
1495                Self::satisfy_helper(&sub.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn)
1496            }
1497            Terminal::DupIf(ref sub) => {
1498                let sat = Self::satisfy_helper(
1499                    &sub.node,
1500                    stfr,
1501                    root_has_sig,
1502                    leaf_hash,
1503                    min_fn,
1504                    thresh_fn,
1505                );
1506                Satisfaction {
1507                    stack: Witness::combine(sat.stack, Witness::push_1()),
1508                    has_sig: sat.has_sig,
1509                }
1510            }
1511            Terminal::AndV(ref l, ref r) | Terminal::AndB(ref l, ref r) => {
1512                let l_sat =
1513                    Self::satisfy_helper(&l.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
1514                let r_sat =
1515                    Self::satisfy_helper(&r.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
1516                Satisfaction {
1517                    stack: Witness::combine(r_sat.stack, l_sat.stack),
1518                    has_sig: l_sat.has_sig || r_sat.has_sig,
1519                }
1520            }
1521            Terminal::AndOr(ref a, ref b, ref c) => {
1522                let a_sat =
1523                    Self::satisfy_helper(&a.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
1524                let a_nsat = Self::dissatisfy_helper(
1525                    &a.node,
1526                    stfr,
1527                    root_has_sig,
1528                    leaf_hash,
1529                    min_fn,
1530                    thresh_fn,
1531                );
1532                let b_sat =
1533                    Self::satisfy_helper(&b.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
1534                let c_sat =
1535                    Self::satisfy_helper(&c.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
1536
1537                min_fn(
1538                    Satisfaction {
1539                        stack: Witness::combine(b_sat.stack, a_sat.stack),
1540                        has_sig: a_sat.has_sig || b_sat.has_sig,
1541                    },
1542                    Satisfaction {
1543                        stack: Witness::combine(c_sat.stack, a_nsat.stack),
1544                        has_sig: a_nsat.has_sig || c_sat.has_sig,
1545                    },
1546                )
1547            }
1548            Terminal::OrB(ref l, ref r) => {
1549                let l_sat =
1550                    Self::satisfy_helper(&l.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
1551                let r_sat =
1552                    Self::satisfy_helper(&r.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
1553                let l_nsat = Self::dissatisfy_helper(
1554                    &l.node,
1555                    stfr,
1556                    root_has_sig,
1557                    leaf_hash,
1558                    min_fn,
1559                    thresh_fn,
1560                );
1561                let r_nsat = Self::dissatisfy_helper(
1562                    &r.node,
1563                    stfr,
1564                    root_has_sig,
1565                    leaf_hash,
1566                    min_fn,
1567                    thresh_fn,
1568                );
1569
1570                assert!(!l_nsat.has_sig);
1571                assert!(!r_nsat.has_sig);
1572
1573                min_fn(
1574                    Satisfaction {
1575                        stack: Witness::combine(r_sat.stack, l_nsat.stack),
1576                        has_sig: r_sat.has_sig,
1577                    },
1578                    Satisfaction {
1579                        stack: Witness::combine(r_nsat.stack, l_sat.stack),
1580                        has_sig: l_sat.has_sig,
1581                    },
1582                )
1583            }
1584            Terminal::OrD(ref l, ref r) | Terminal::OrC(ref l, ref r) => {
1585                let l_sat =
1586                    Self::satisfy_helper(&l.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
1587                let r_sat =
1588                    Self::satisfy_helper(&r.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
1589                let l_nsat = Self::dissatisfy_helper(
1590                    &l.node,
1591                    stfr,
1592                    root_has_sig,
1593                    leaf_hash,
1594                    min_fn,
1595                    thresh_fn,
1596                );
1597
1598                assert!(!l_nsat.has_sig);
1599
1600                min_fn(
1601                    l_sat,
1602                    Satisfaction {
1603                        stack: Witness::combine(r_sat.stack, l_nsat.stack),
1604                        has_sig: r_sat.has_sig,
1605                    },
1606                )
1607            }
1608            Terminal::OrI(ref l, ref r) => {
1609                let l_sat =
1610                    Self::satisfy_helper(&l.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
1611                let r_sat =
1612                    Self::satisfy_helper(&r.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
1613                min_fn(
1614                    Satisfaction {
1615                        stack: Witness::combine(l_sat.stack, Witness::push_1()),
1616                        has_sig: l_sat.has_sig,
1617                    },
1618                    Satisfaction {
1619                        stack: Witness::combine(r_sat.stack, Witness::push_0()),
1620                        has_sig: r_sat.has_sig,
1621                    },
1622                )
1623            }
1624            Terminal::Thresh(k, ref subs) => {
1625                thresh_fn(k, subs, stfr, root_has_sig, leaf_hash, min_fn)
1626            }
1627            Terminal::Multi(k, ref keys) => {
1628                // Collect all available signatures
1629                let mut sig_count = 0;
1630                let mut sigs = Vec::with_capacity(k);
1631                for pk in keys {
1632                    match Witness::signature::<_, _, Ctx>(stfr, pk, leaf_hash) {
1633                        Witness::Stack(sig) => {
1634                            sigs.push(sig);
1635                            sig_count += 1;
1636                        }
1637                        Witness::Impossible => {}
1638                        Witness::Unavailable => unreachable!(
1639                            "Signature satisfaction without witness must be impossible"
1640                        ),
1641                    }
1642                }
1643
1644                if sig_count < k {
1645                    Satisfaction {
1646                        stack: Witness::Impossible,
1647                        has_sig: false,
1648                    }
1649                } else {
1650                    // Throw away the most expensive ones
1651                    for _ in 0..sig_count - k {
1652                        let max_idx = sigs
1653                            .iter()
1654                            .enumerate()
1655                            .max_by_key(|&(_, v)| v.len())
1656                            .unwrap()
1657                            .0;
1658                        sigs[max_idx] = vec![];
1659                    }
1660
1661                    Satisfaction {
1662                        stack: sigs.into_iter().fold(Witness::push_0(), |acc, sig| {
1663                            Witness::combine(acc, Witness::Stack(sig))
1664                        }),
1665                        has_sig: true,
1666                    }
1667                }
1668            }
1669            Terminal::MultiA(k, ref keys) => {
1670                // Collect all available signatures
1671                let mut sig_count = 0;
1672                let mut sigs = vec![vec![vec![]]; keys.len()];
1673                for (i, pk) in keys.iter().rev().enumerate() {
1674                    match Witness::signature::<_, _, Ctx>(stfr, pk, leaf_hash) {
1675                        Witness::Stack(sig) => {
1676                            sigs[i] = sig;
1677                            sig_count += 1;
1678                            // This a privacy issue, we are only selecting the first available
1679                            // sigs. Incase pk at pos 1 is not selected, we know we did not have access to it
1680                            // bitcoin core also implements the same logic for MULTISIG, so I am not bothering
1681                            // permuting the sigs for now
1682                            if sig_count == k {
1683                                break;
1684                            }
1685                        }
1686                        Witness::Impossible => {}
1687                        Witness::Unavailable => unreachable!(
1688                            "Signature satisfaction without witness must be impossible"
1689                        ),
1690                    }
1691                }
1692
1693                if sig_count < k {
1694                    Satisfaction {
1695                        stack: Witness::Impossible,
1696                        has_sig: false,
1697                    }
1698                } else {
1699                    Satisfaction {
1700                        stack: sigs.into_iter().fold(Witness::empty(), |acc, sig| {
1701                            Witness::combine(acc, Witness::Stack(sig))
1702                        }),
1703                        has_sig: true,
1704                    }
1705                }
1706            }
1707            Terminal::Ext(ref e) => e.satisfy(stfr),
1708        }
1709    }
1710
1711    // Helper function to produce a dissatisfaction
1712    fn dissatisfy_helper<Pk, Ctx, Sat, Ext, F, G>(
1713        term: &Terminal<Pk, Ctx, Ext>,
1714        stfr: &Sat,
1715        root_has_sig: bool,
1716        leaf_hash: &TapLeafHash,
1717        min_fn: &mut F,
1718        thresh_fn: &mut G,
1719    ) -> Self
1720    where
1721        Pk: MiniscriptKey + ToPublicKey,
1722        Ctx: ScriptContext,
1723        Sat: Satisfier<Pk>,
1724        Ext: ParseableExt,
1725        F: FnMut(Satisfaction, Satisfaction) -> Satisfaction,
1726        G: FnMut(
1727            usize,
1728            &[Arc<Miniscript<Pk, Ctx, Ext>>],
1729            &Sat,
1730            bool,
1731            &TapLeafHash,
1732            &mut F,
1733        ) -> Satisfaction,
1734    {
1735        match *term {
1736            Terminal::PkK(..) => Satisfaction {
1737                stack: Witness::push_0(),
1738                has_sig: false,
1739            },
1740            Terminal::PkH(ref pk) => {
1741                let pk_bytes = match Ctx::sig_type() {
1742                    SigType::Ecdsa => pk.to_public_key().to_bytes(),
1743                    SigType::Schnorr => pk.to_x_only_pubkey().serialize().to_vec(),
1744                };
1745                Satisfaction {
1746                    stack: Witness::combine(Witness::push_0(), Witness::Stack(vec![pk_bytes])),
1747                    has_sig: false,
1748                }
1749            }
1750            Terminal::RawPkH(ref pkh) => Satisfaction {
1751                stack: Witness::combine(
1752                    Witness::push_0(),
1753                    Witness::pkh_public_key::<_, _, Ctx>(stfr, pkh),
1754                ),
1755                has_sig: false,
1756            },
1757            Terminal::False => Satisfaction {
1758                stack: Witness::empty(),
1759                has_sig: false,
1760            },
1761            Terminal::True => Satisfaction {
1762                stack: Witness::Impossible,
1763                has_sig: false,
1764            },
1765            Terminal::Older(_) => Satisfaction {
1766                stack: Witness::Impossible,
1767                has_sig: false,
1768            },
1769            Terminal::After(_) => Satisfaction {
1770                stack: Witness::Impossible,
1771                has_sig: false,
1772            },
1773            Terminal::Sha256(_)
1774            | Terminal::Hash256(_)
1775            | Terminal::Ripemd160(_)
1776            | Terminal::Hash160(_) => Satisfaction {
1777                stack: Witness::hash_dissatisfaction(),
1778                has_sig: false,
1779            },
1780            Terminal::Alt(ref sub)
1781            | Terminal::Swap(ref sub)
1782            | Terminal::Check(ref sub)
1783            | Terminal::ZeroNotEqual(ref sub) => {
1784                Self::dissatisfy_helper(&sub.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn)
1785            }
1786            Terminal::DupIf(_) | Terminal::NonZero(_) => Satisfaction {
1787                stack: Witness::push_0(),
1788                has_sig: false,
1789            },
1790            Terminal::Verify(_) => Satisfaction {
1791                stack: Witness::Impossible,
1792                has_sig: false,
1793            },
1794            Terminal::AndV(ref v, ref other) => {
1795                let vsat =
1796                    Self::satisfy_helper(&v.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
1797                let odissat = Self::dissatisfy_helper(
1798                    &other.node,
1799                    stfr,
1800                    root_has_sig,
1801                    leaf_hash,
1802                    min_fn,
1803                    thresh_fn,
1804                );
1805                Satisfaction {
1806                    stack: Witness::combine(odissat.stack, vsat.stack),
1807                    has_sig: vsat.has_sig || odissat.has_sig,
1808                }
1809            }
1810            Terminal::AndB(ref l, ref r)
1811            | Terminal::OrB(ref l, ref r)
1812            | Terminal::OrD(ref l, ref r)
1813            | Terminal::AndOr(ref l, _, ref r) => {
1814                let lnsat = Self::dissatisfy_helper(
1815                    &l.node,
1816                    stfr,
1817                    root_has_sig,
1818                    leaf_hash,
1819                    min_fn,
1820                    thresh_fn,
1821                );
1822                let rnsat = Self::dissatisfy_helper(
1823                    &r.node,
1824                    stfr,
1825                    root_has_sig,
1826                    leaf_hash,
1827                    min_fn,
1828                    thresh_fn,
1829                );
1830                Satisfaction {
1831                    stack: Witness::combine(rnsat.stack, lnsat.stack),
1832                    has_sig: rnsat.has_sig || lnsat.has_sig,
1833                }
1834            }
1835            Terminal::OrC(..) => Satisfaction {
1836                stack: Witness::Impossible,
1837                has_sig: false,
1838            },
1839            Terminal::OrI(ref l, ref r) => {
1840                let lnsat = Self::dissatisfy_helper(
1841                    &l.node,
1842                    stfr,
1843                    root_has_sig,
1844                    leaf_hash,
1845                    min_fn,
1846                    thresh_fn,
1847                );
1848                let dissat_1 = Satisfaction {
1849                    stack: Witness::combine(lnsat.stack, Witness::push_1()),
1850                    has_sig: lnsat.has_sig,
1851                };
1852
1853                let rnsat = Self::dissatisfy_helper(
1854                    &r.node,
1855                    stfr,
1856                    root_has_sig,
1857                    leaf_hash,
1858                    min_fn,
1859                    thresh_fn,
1860                );
1861                let dissat_2 = Satisfaction {
1862                    stack: Witness::combine(rnsat.stack, Witness::push_0()),
1863                    has_sig: rnsat.has_sig,
1864                };
1865
1866                // Dissatisfactions don't need to non-malleable. Use minimum_mall always
1867                Satisfaction::minimum_mall(dissat_1, dissat_2)
1868            }
1869            Terminal::Thresh(_, ref subs) => Satisfaction {
1870                stack: subs.iter().fold(Witness::empty(), |acc, sub| {
1871                    let nsat = Self::dissatisfy_helper(
1872                        &sub.node,
1873                        stfr,
1874                        root_has_sig,
1875                        leaf_hash,
1876                        min_fn,
1877                        thresh_fn,
1878                    );
1879                    assert!(!nsat.has_sig);
1880                    Witness::combine(nsat.stack, acc)
1881                }),
1882                has_sig: false,
1883            },
1884            Terminal::Multi(k, _) => Satisfaction {
1885                stack: Witness::Stack(vec![vec![]; k + 1]),
1886                has_sig: false,
1887            },
1888            Terminal::MultiA(_, ref pks) => Satisfaction {
1889                stack: Witness::Stack(vec![vec![]; pks.len()]),
1890                has_sig: false,
1891            },
1892            Terminal::Ext(ref e) => e.dissatisfy(stfr),
1893        }
1894    }
1895
1896    /// Produce a satisfaction non-malleable satisfaction
1897    pub(super) fn satisfy<Pk, Ctx, Sat, Ext>(
1898        term: &Terminal<Pk, Ctx, Ext>,
1899        stfr: &Sat,
1900        root_has_sig: bool,
1901        leaf_hash: &TapLeafHash,
1902    ) -> Self
1903    where
1904        Pk: MiniscriptKey + ToPublicKey,
1905        Ctx: ScriptContext,
1906        Sat: Satisfier<Pk>,
1907        Ext: ParseableExt,
1908    {
1909        Self::satisfy_helper(
1910            term,
1911            stfr,
1912            root_has_sig,
1913            leaf_hash,
1914            &mut Satisfaction::minimum,
1915            &mut Satisfaction::thresh,
1916        )
1917    }
1918
1919    /// Produce a satisfaction(possibly malleable)
1920    pub(super) fn satisfy_mall<
1921        Pk: MiniscriptKey + ToPublicKey,
1922        Ctx: ScriptContext,
1923        Sat: Satisfier<Pk>,
1924        Ext: ParseableExt,
1925    >(
1926        term: &Terminal<Pk, Ctx, Ext>,
1927        stfr: &Sat,
1928        root_has_sig: bool,
1929        leaf_hash: &TapLeafHash,
1930    ) -> Self {
1931        Self::satisfy_helper(
1932            term,
1933            stfr,
1934            root_has_sig,
1935            leaf_hash,
1936            &mut Satisfaction::minimum_mall,
1937            &mut Satisfaction::thresh_mall,
1938        )
1939    }
1940}