Skip to main content

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