1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
// SPDX-License-Identifier: CC0-1.0

//! # Satisfaction and Dissatisfaction
//!
//! Traits and implementations to support producing witnesses for Miniscript
//! scriptpubkeys.
//!

use core::{cmp, fmt, i64, mem};

use bitcoin::hashes::hash160;
use bitcoin::key::XOnlyPublicKey;
use bitcoin::taproot::{ControlBlock, LeafVersion, TapLeafHash, TapNodeHash};
use bitcoin::{absolute, ScriptBuf, Sequence};
use sync::Arc;

use super::context::SigType;
use crate::plan::AssetProvider;
use crate::prelude::*;
use crate::util::witness_size;
use crate::{AbsLockTime, Miniscript, MiniscriptKey, ScriptContext, Terminal, ToPublicKey};

/// Type alias for 32 byte Preimage.
pub type Preimage32 = [u8; 32];
/// Trait describing a lookup table for signatures, hash preimages, etc.
/// Every method has a default implementation that simply returns `None`
/// on every query. Users are expected to override the methods that they
/// have data for.
pub trait Satisfier<Pk: MiniscriptKey + ToPublicKey> {
    /// Given a public key, look up an ECDSA signature with that key
    fn lookup_ecdsa_sig(&self, _: &Pk) -> Option<bitcoin::ecdsa::Signature> { None }

    /// Lookup the tap key spend sig
    fn lookup_tap_key_spend_sig(&self) -> Option<bitcoin::taproot::Signature> { None }

    /// Given a public key and a associated leaf hash, look up an schnorr signature with that key
    fn lookup_tap_leaf_script_sig(
        &self,
        _: &Pk,
        _: &TapLeafHash,
    ) -> Option<bitcoin::taproot::Signature> {
        None
    }

    /// Obtain a reference to the control block for a ver and script
    fn lookup_tap_control_block_map(
        &self,
    ) -> Option<&BTreeMap<ControlBlock, (bitcoin::ScriptBuf, LeafVersion)>> {
        None
    }

    /// Given a raw `Pkh`, lookup corresponding [`bitcoin::PublicKey`]
    fn lookup_raw_pkh_pk(&self, _: &hash160::Hash) -> Option<bitcoin::PublicKey> { None }

    /// Given a raw `Pkh`, lookup corresponding [`bitcoin::secp256k1::XOnlyPublicKey`]
    fn lookup_raw_pkh_x_only_pk(&self, _: &hash160::Hash) -> Option<XOnlyPublicKey> { None }

    /// Given a keyhash, look up the EC signature and the associated key
    /// Even if signatures for public key Hashes are not available, the users
    /// can use this map to provide pkh -> pk mapping which can be useful
    /// for dissatisfying pkh.
    fn lookup_raw_pkh_ecdsa_sig(
        &self,
        _: &hash160::Hash,
    ) -> Option<(bitcoin::PublicKey, bitcoin::ecdsa::Signature)> {
        None
    }

    /// Given a keyhash, look up the schnorr signature and the associated key
    /// Even if signatures for public key Hashes are not available, the users
    /// can use this map to provide pkh -> pk mapping which can be useful
    /// for dissatisfying pkh.
    fn lookup_raw_pkh_tap_leaf_script_sig(
        &self,
        _: &(hash160::Hash, TapLeafHash),
    ) -> Option<(XOnlyPublicKey, bitcoin::taproot::Signature)> {
        None
    }

    /// Given a SHA256 hash, look up its preimage
    fn lookup_sha256(&self, _: &Pk::Sha256) -> Option<Preimage32> { None }

    /// Given a HASH256 hash, look up its preimage
    fn lookup_hash256(&self, _: &Pk::Hash256) -> Option<Preimage32> { None }

    /// Given a RIPEMD160 hash, look up its preimage
    fn lookup_ripemd160(&self, _: &Pk::Ripemd160) -> Option<Preimage32> { None }

    /// Given a HASH160 hash, look up its preimage
    fn lookup_hash160(&self, _: &Pk::Hash160) -> Option<Preimage32> { None }

    /// Assert whether an relative locktime is satisfied
    ///
    /// NOTE: If a descriptor mixes time-based and height-based timelocks, the implementation of
    /// this method MUST only allow timelocks of either unit, but not both. Allowing both could cause
    /// miniscript to construct an invalid witness.
    fn check_older(&self, _: Sequence) -> bool { false }

    /// Assert whether a absolute locktime is satisfied
    ///
    /// NOTE: If a descriptor mixes time-based and height-based timelocks, the implementation of
    /// this method MUST only allow timelocks of either unit, but not both. Allowing both could cause
    /// miniscript to construct an invalid witness.
    fn check_after(&self, _: absolute::LockTime) -> bool { false }
}

// Allow use of `()` as a "no conditions available" satisfier
impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk> for () {}

impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk> for Sequence {
    fn check_older(&self, n: Sequence) -> bool {
        if !self.is_relative_lock_time() {
            return false;
        }

        // We need a relative lock time type in rust-bitcoin to clean this up.

        /* If nSequence encodes a relative lock-time, this mask is
         * applied to extract that lock-time from the sequence field. */
        const SEQUENCE_LOCKTIME_MASK: u32 = 0x0000ffff;
        const SEQUENCE_LOCKTIME_TYPE_FLAG: u32 = 0x00400000;

        let mask = SEQUENCE_LOCKTIME_MASK | SEQUENCE_LOCKTIME_TYPE_FLAG;
        let masked_n = n.to_consensus_u32() & mask;
        let masked_seq = self.to_consensus_u32() & mask;
        if masked_n < SEQUENCE_LOCKTIME_TYPE_FLAG && masked_seq >= SEQUENCE_LOCKTIME_TYPE_FLAG {
            false
        } else {
            masked_n <= masked_seq
        }
    }
}

impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk> for absolute::LockTime {
    fn check_after(&self, n: absolute::LockTime) -> bool {
        use absolute::LockTime::*;

        match (n, *self) {
            (Blocks(n), Blocks(lock_time)) => n <= lock_time,
            (Seconds(n), Seconds(lock_time)) => n <= lock_time,
            _ => false, // Not the same units.
        }
    }
}

macro_rules! impl_satisfier_for_map_key_to_ecdsa_sig {
    ($(#[$($attr:meta)*])* impl Satisfier<Pk> for $map:ident<$key:ty, $val:ty>) => {
        $(#[$($attr)*])*
        impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk>
            for $map<Pk, bitcoin::ecdsa::Signature>
        {
            fn lookup_ecdsa_sig(&self, key: &Pk) -> Option<bitcoin::ecdsa::Signature> {
                self.get(key).copied()
            }
        }
    };
}

impl_satisfier_for_map_key_to_ecdsa_sig! {
    impl Satisfier<Pk> for BTreeMap<Pk, bitcoin::ecdsa::Signature>
}

impl_satisfier_for_map_key_to_ecdsa_sig! {
    #[cfg(feature = "std")]
    impl Satisfier<Pk> for HashMap<Pk, bitcoin::ecdsa::Signature>
}

macro_rules! impl_satisfier_for_map_key_hash_to_taproot_sig {
    ($(#[$($attr:meta)*])* impl Satisfier<Pk> for $map:ident<$key:ty, $val:ty>) => {
        $(#[$($attr)*])*
        impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk>
            for $map<(Pk, TapLeafHash), bitcoin::taproot::Signature>
        {
            fn lookup_tap_leaf_script_sig(
                &self,
                key: &Pk,
                h: &TapLeafHash,
            ) -> Option<bitcoin::taproot::Signature> {
                // Unfortunately, there is no way to get a &(a, b) from &a and &b without allocating
                // If we change the signature the of lookup_tap_leaf_script_sig to accept a tuple. We would
                // face the same problem while satisfying PkK.
                // We use this signature to optimize for the psbt common use case.
                self.get(&(key.clone(), *h)).copied()
            }
        }
    };
}

impl_satisfier_for_map_key_hash_to_taproot_sig! {
    impl Satisfier<Pk> for BTreeMap<(Pk, TapLeafHash), bitcoin::taproot::Signature>
}

impl_satisfier_for_map_key_hash_to_taproot_sig! {
    #[cfg(feature = "std")]
    impl Satisfier<Pk> for HashMap<(Pk, TapLeafHash), bitcoin::taproot::Signature>
}

macro_rules! impl_satisfier_for_map_hash_to_key_ecdsa_sig {
    ($(#[$($attr:meta)*])* impl Satisfier<Pk> for $map:ident<$key:ty, $val:ty>) => {
        $(#[$($attr)*])*
        impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk>
            for $map<hash160::Hash, (Pk, bitcoin::ecdsa::Signature)>
        where
            Pk: MiniscriptKey + ToPublicKey,
        {
            fn lookup_ecdsa_sig(&self, key: &Pk) -> Option<bitcoin::ecdsa::Signature> {
                self.get(&key.to_pubkeyhash(SigType::Ecdsa)).map(|x| x.1)
            }

            fn lookup_raw_pkh_pk(&self, pk_hash: &hash160::Hash) -> Option<bitcoin::PublicKey> {
                self.get(pk_hash).map(|x| x.0.to_public_key())
            }

            fn lookup_raw_pkh_ecdsa_sig(
                &self,
                pk_hash: &hash160::Hash,
            ) -> Option<(bitcoin::PublicKey, bitcoin::ecdsa::Signature)> {
                self.get(pk_hash)
                    .map(|&(ref pk, sig)| (pk.to_public_key(), sig))
            }
        }
    };
}

impl_satisfier_for_map_hash_to_key_ecdsa_sig! {
    impl Satisfier<Pk> for BTreeMap<hash160::Hash, (Pk, bitcoin::ecdsa::Signature)>
}

impl_satisfier_for_map_hash_to_key_ecdsa_sig! {
    #[cfg(feature = "std")]
    impl Satisfier<Pk> for HashMap<hash160::Hash, (Pk, bitcoin::ecdsa::Signature)>
}

macro_rules! impl_satisfier_for_map_hash_tapleafhash_to_key_taproot_sig {
    ($(#[$($attr:meta)*])* impl Satisfier<Pk> for $map:ident<$key:ty, $val:ty>) => {
        $(#[$($attr)*])*
        impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk>
            for $map<(hash160::Hash, TapLeafHash), (Pk, bitcoin::taproot::Signature)>
        where
            Pk: MiniscriptKey + ToPublicKey,
        {
            fn lookup_tap_leaf_script_sig(
                &self,
                key: &Pk,
                h: &TapLeafHash,
            ) -> Option<bitcoin::taproot::Signature> {
                self.get(&(key.to_pubkeyhash(SigType::Schnorr), *h))
                    .map(|x| x.1)
            }

            fn lookup_raw_pkh_tap_leaf_script_sig(
                &self,
                pk_hash: &(hash160::Hash, TapLeafHash),
            ) -> Option<(XOnlyPublicKey, bitcoin::taproot::Signature)> {
                self.get(pk_hash)
                    .map(|&(ref pk, sig)| (pk.to_x_only_pubkey(), sig))
            }
        }
    };
}

impl_satisfier_for_map_hash_tapleafhash_to_key_taproot_sig! {
    impl Satisfier<Pk> for BTreeMap<(hash160::Hash, TapLeafHash), (Pk, bitcoin::taproot::Signature)>
}

impl_satisfier_for_map_hash_tapleafhash_to_key_taproot_sig! {
    #[cfg(feature = "std")]
    impl Satisfier<Pk> for HashMap<(hash160::Hash, TapLeafHash), (Pk, bitcoin::taproot::Signature)>
}

impl<'a, Pk: MiniscriptKey + ToPublicKey, S: Satisfier<Pk>> Satisfier<Pk> for &'a S {
    fn lookup_ecdsa_sig(&self, p: &Pk) -> Option<bitcoin::ecdsa::Signature> {
        (**self).lookup_ecdsa_sig(p)
    }

    fn lookup_tap_leaf_script_sig(
        &self,
        p: &Pk,
        h: &TapLeafHash,
    ) -> Option<bitcoin::taproot::Signature> {
        (**self).lookup_tap_leaf_script_sig(p, h)
    }

    fn lookup_raw_pkh_pk(&self, pkh: &hash160::Hash) -> Option<bitcoin::PublicKey> {
        (**self).lookup_raw_pkh_pk(pkh)
    }

    fn lookup_raw_pkh_x_only_pk(&self, pkh: &hash160::Hash) -> Option<XOnlyPublicKey> {
        (**self).lookup_raw_pkh_x_only_pk(pkh)
    }

    fn lookup_raw_pkh_ecdsa_sig(
        &self,
        pkh: &hash160::Hash,
    ) -> Option<(bitcoin::PublicKey, bitcoin::ecdsa::Signature)> {
        (**self).lookup_raw_pkh_ecdsa_sig(pkh)
    }

    fn lookup_tap_key_spend_sig(&self) -> Option<bitcoin::taproot::Signature> {
        (**self).lookup_tap_key_spend_sig()
    }

    fn lookup_raw_pkh_tap_leaf_script_sig(
        &self,
        pkh: &(hash160::Hash, TapLeafHash),
    ) -> Option<(XOnlyPublicKey, bitcoin::taproot::Signature)> {
        (**self).lookup_raw_pkh_tap_leaf_script_sig(pkh)
    }

    fn lookup_tap_control_block_map(
        &self,
    ) -> Option<&BTreeMap<ControlBlock, (bitcoin::ScriptBuf, LeafVersion)>> {
        (**self).lookup_tap_control_block_map()
    }

    fn lookup_sha256(&self, h: &Pk::Sha256) -> Option<Preimage32> { (**self).lookup_sha256(h) }

    fn lookup_hash256(&self, h: &Pk::Hash256) -> Option<Preimage32> { (**self).lookup_hash256(h) }

    fn lookup_ripemd160(&self, h: &Pk::Ripemd160) -> Option<Preimage32> {
        (**self).lookup_ripemd160(h)
    }

    fn lookup_hash160(&self, h: &Pk::Hash160) -> Option<Preimage32> { (**self).lookup_hash160(h) }

    fn check_older(&self, t: Sequence) -> bool { (**self).check_older(t) }

    fn check_after(&self, n: absolute::LockTime) -> bool { (**self).check_after(n) }
}

impl<'a, Pk: MiniscriptKey + ToPublicKey, S: Satisfier<Pk>> Satisfier<Pk> for &'a mut S {
    fn lookup_ecdsa_sig(&self, p: &Pk) -> Option<bitcoin::ecdsa::Signature> {
        (**self).lookup_ecdsa_sig(p)
    }

    fn lookup_tap_leaf_script_sig(
        &self,
        p: &Pk,
        h: &TapLeafHash,
    ) -> Option<bitcoin::taproot::Signature> {
        (**self).lookup_tap_leaf_script_sig(p, h)
    }

    fn lookup_tap_key_spend_sig(&self) -> Option<bitcoin::taproot::Signature> {
        (**self).lookup_tap_key_spend_sig()
    }

    fn lookup_raw_pkh_pk(&self, pkh: &hash160::Hash) -> Option<bitcoin::PublicKey> {
        (**self).lookup_raw_pkh_pk(pkh)
    }

    fn lookup_raw_pkh_x_only_pk(&self, pkh: &hash160::Hash) -> Option<XOnlyPublicKey> {
        (**self).lookup_raw_pkh_x_only_pk(pkh)
    }

    fn lookup_raw_pkh_ecdsa_sig(
        &self,
        pkh: &hash160::Hash,
    ) -> Option<(bitcoin::PublicKey, bitcoin::ecdsa::Signature)> {
        (**self).lookup_raw_pkh_ecdsa_sig(pkh)
    }

    fn lookup_raw_pkh_tap_leaf_script_sig(
        &self,
        pkh: &(hash160::Hash, TapLeafHash),
    ) -> Option<(XOnlyPublicKey, bitcoin::taproot::Signature)> {
        (**self).lookup_raw_pkh_tap_leaf_script_sig(pkh)
    }

    fn lookup_tap_control_block_map(
        &self,
    ) -> Option<&BTreeMap<ControlBlock, (bitcoin::ScriptBuf, LeafVersion)>> {
        (**self).lookup_tap_control_block_map()
    }

    fn lookup_sha256(&self, h: &Pk::Sha256) -> Option<Preimage32> { (**self).lookup_sha256(h) }

    fn lookup_hash256(&self, h: &Pk::Hash256) -> Option<Preimage32> { (**self).lookup_hash256(h) }

    fn lookup_ripemd160(&self, h: &Pk::Ripemd160) -> Option<Preimage32> {
        (**self).lookup_ripemd160(h)
    }

    fn lookup_hash160(&self, h: &Pk::Hash160) -> Option<Preimage32> { (**self).lookup_hash160(h) }

    fn check_older(&self, t: Sequence) -> bool { (**self).check_older(t) }

    fn check_after(&self, n: absolute::LockTime) -> bool { (**self).check_after(n) }
}

macro_rules! impl_tuple_satisfier {
    ($($ty:ident),*) => {
        #[allow(non_snake_case)]
        impl<$($ty,)* Pk> Satisfier<Pk> for ($($ty,)*)
        where
            Pk: MiniscriptKey + ToPublicKey,
            $($ty: Satisfier< Pk>,)*
        {
            fn lookup_ecdsa_sig(&self, key: &Pk) -> Option<bitcoin::ecdsa::Signature> {
                let &($(ref $ty,)*) = self;
                $(
                    if let Some(result) = $ty.lookup_ecdsa_sig(key) {
                        return Some(result);
                    }
                )*
                None
            }

            fn lookup_tap_key_spend_sig(&self) -> Option<bitcoin::taproot::Signature> {
                let &($(ref $ty,)*) = self;
                $(
                    if let Some(result) = $ty.lookup_tap_key_spend_sig() {
                        return Some(result);
                    }
                )*
                None
            }

            fn lookup_tap_leaf_script_sig(&self, key: &Pk, h: &TapLeafHash) -> Option<bitcoin::taproot::Signature> {
                let &($(ref $ty,)*) = self;
                $(
                    if let Some(result) = $ty.lookup_tap_leaf_script_sig(key, h) {
                        return Some(result);
                    }
                )*
                None
            }

            fn lookup_raw_pkh_ecdsa_sig(
                &self,
                key_hash: &hash160::Hash,
            ) -> Option<(bitcoin::PublicKey, bitcoin::ecdsa::Signature)> {
                let &($(ref $ty,)*) = self;
                $(
                    if let Some(result) = $ty.lookup_raw_pkh_ecdsa_sig(key_hash) {
                        return Some(result);
                    }
                )*
                None
            }

            fn lookup_raw_pkh_tap_leaf_script_sig(
                &self,
                key_hash: &(hash160::Hash, TapLeafHash),
            ) -> Option<(XOnlyPublicKey, bitcoin::taproot::Signature)> {
                let &($(ref $ty,)*) = self;
                $(
                    if let Some(result) = $ty.lookup_raw_pkh_tap_leaf_script_sig(key_hash) {
                        return Some(result);
                    }
                )*
                None
            }

            fn lookup_raw_pkh_pk(
                &self,
                key_hash: &hash160::Hash,
            ) -> Option<bitcoin::PublicKey> {
                let &($(ref $ty,)*) = self;
                $(
                    if let Some(result) = $ty.lookup_raw_pkh_pk(key_hash) {
                        return Some(result);
                    }
                )*
                None
            }
            fn lookup_raw_pkh_x_only_pk(
                &self,
                key_hash: &hash160::Hash,
            ) -> Option<XOnlyPublicKey> {
                let &($(ref $ty,)*) = self;
                $(
                    if let Some(result) = $ty.lookup_raw_pkh_x_only_pk(key_hash) {
                        return Some(result);
                    }
                )*
                None
            }

            fn lookup_tap_control_block_map(
                &self,
            ) -> Option<&BTreeMap<ControlBlock, (bitcoin::ScriptBuf, LeafVersion)>> {
                let &($(ref $ty,)*) = self;
                $(
                    if let Some(result) = $ty.lookup_tap_control_block_map() {
                        return Some(result);
                    }
                )*
                None
            }

            fn lookup_sha256(&self, h: &Pk::Sha256) -> Option<Preimage32> {
                let &($(ref $ty,)*) = self;
                $(
                    if let Some(result) = $ty.lookup_sha256(h) {
                        return Some(result);
                    }
                )*
                None
            }

            fn lookup_hash256(&self, h: &Pk::Hash256) -> Option<Preimage32> {
                let &($(ref $ty,)*) = self;
                $(
                    if let Some(result) = $ty.lookup_hash256(h) {
                        return Some(result);
                    }
                )*
                None
            }

            fn lookup_ripemd160(&self, h: &Pk::Ripemd160) -> Option<Preimage32> {
                let &($(ref $ty,)*) = self;
                $(
                    if let Some(result) = $ty.lookup_ripemd160(h) {
                        return Some(result);
                    }
                )*
                None
            }

            fn lookup_hash160(&self, h: &Pk::Hash160) -> Option<Preimage32> {
                let &($(ref $ty,)*) = self;
                $(
                    if let Some(result) = $ty.lookup_hash160(h) {
                        return Some(result);
                    }
                )*
                None
            }

            fn check_older(&self, n: Sequence) -> bool {
                let &($(ref $ty,)*) = self;
                $(
                    if $ty.check_older(n) {
                        return true;
                    }
                )*
                false
            }

            fn check_after(&self, n: absolute::LockTime) -> bool {
                let &($(ref $ty,)*) = self;
                $(
                    if $ty.check_after(n) {
                        return true;
                    }
                )*
                false
            }
        }
    }
}

impl_tuple_satisfier!(A);
impl_tuple_satisfier!(A, B);
impl_tuple_satisfier!(A, B, C);
impl_tuple_satisfier!(A, B, C, D);
impl_tuple_satisfier!(A, B, C, D, E);
impl_tuple_satisfier!(A, B, C, D, E, F);
impl_tuple_satisfier!(A, B, C, D, E, F, G);
impl_tuple_satisfier!(A, B, C, D, E, F, G, H);

#[derive(Debug, Clone, PartialEq, Eq)]
/// Type of schnorr signature to produce
pub enum SchnorrSigType {
    /// Key spend signature
    KeySpend {
        /// Merkle root to tweak the key, if present
        merkle_root: Option<TapNodeHash>,
    },
    /// Script spend signature
    ScriptSpend {
        /// Leaf hash of the script
        leaf_hash: TapLeafHash,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Placeholder for some data in a [`Plan`]
///
/// [`Plan`]: crate::plan::Plan
pub enum Placeholder<Pk: MiniscriptKey> {
    /// Public key and its size
    Pubkey(Pk, usize),
    /// Public key hash and public key size
    PubkeyHash(hash160::Hash, usize),
    /// ECDSA signature given the raw pubkey
    EcdsaSigPk(Pk),
    /// ECDSA signature given the pubkey hash
    EcdsaSigPkHash(hash160::Hash),
    /// Schnorr signature and its size
    SchnorrSigPk(Pk, SchnorrSigType, usize),
    /// Schnorr signature given the pubkey hash, the tapleafhash, and the sig size
    SchnorrSigPkHash(hash160::Hash, TapLeafHash, usize),
    /// SHA-256 preimage
    Sha256Preimage(Pk::Sha256),
    /// HASH256 preimage
    Hash256Preimage(Pk::Hash256),
    /// RIPEMD160 preimage
    Ripemd160Preimage(Pk::Ripemd160),
    /// HASH160 preimage
    Hash160Preimage(Pk::Hash160),
    /// Hash dissatisfaction (32 bytes of 0x00)
    HashDissatisfaction,
    /// OP_1
    PushOne,
    /// \<empty item\>
    PushZero,
    /// Taproot leaf script
    TapScript(ScriptBuf),
    /// Taproot control block
    TapControlBlock(ControlBlock),
}

impl<Pk: MiniscriptKey> fmt::Display for Placeholder<Pk> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use Placeholder::*;
        match self {
            Pubkey(pk, size) => write!(f, "Pubkey(pk: {}, size: {})", pk, size),
            PubkeyHash(hash, size) => write!(f, "PubkeyHash(hash: {}, size: {})", hash, size),
            EcdsaSigPk(pk) => write!(f, "EcdsaSigPk(pk: {})", pk),
            EcdsaSigPkHash(hash) => write!(f, "EcdsaSigPkHash(pkh: {})", hash),
            SchnorrSigPk(pk, tap_leaf_hash, size) => write!(
                f,
                "SchnorrSig(pk: {}, tap_leaf_hash: {:?}, size: {})",
                pk, tap_leaf_hash, size
            ),
            SchnorrSigPkHash(pkh, tap_leaf_hash, size) => write!(
                f,
                "SchnorrSigPkHash(pkh: {}, tap_leaf_hash: {:?}, size: {})",
                pkh, tap_leaf_hash, size
            ),
            Sha256Preimage(hash) => write!(f, "Sha256Preimage(hash: {})", hash),
            Hash256Preimage(hash) => write!(f, "Hash256Preimage(hash: {})", hash),
            Ripemd160Preimage(hash) => write!(f, "Ripemd160Preimage(hash: {})", hash),
            Hash160Preimage(hash) => write!(f, "Hash160Preimage(hash: {})", hash),
            HashDissatisfaction => write!(f, "HashDissatisfaction"),
            PushOne => write!(f, "PushOne"),
            PushZero => write!(f, "PushZero"),
            TapScript(script) => write!(f, "TapScript(script: {})", script),
            TapControlBlock(control_block) => write!(
                f,
                "TapControlBlock(control_block: {})",
                bitcoin::consensus::encode::serialize_hex(&control_block.serialize())
            ),
        }
    }
}

impl<Pk: MiniscriptKey + ToPublicKey> Placeholder<Pk> {
    /// Replaces the placeholders with the information given by the satisfier
    pub fn satisfy_self<Sat: Satisfier<Pk>>(&self, sat: &Sat) -> Option<Vec<u8>> {
        match self {
            Placeholder::Pubkey(pk, size) => {
                if *size == 33 {
                    Some(pk.to_x_only_pubkey().serialize().to_vec())
                } else {
                    Some(pk.to_public_key().to_bytes())
                }
            }
            Placeholder::PubkeyHash(pkh, size) => sat
                .lookup_raw_pkh_pk(pkh)
                .map(|p| p.to_public_key())
                .or(sat.lookup_raw_pkh_ecdsa_sig(pkh).map(|(p, _)| p))
                .map(|pk| {
                    let pk = pk.to_bytes();
                    // We have to add a 1-byte OP_PUSH
                    debug_assert!(1 + pk.len() == *size);
                    pk
                }),
            Placeholder::Hash256Preimage(h) => sat.lookup_hash256(h).map(|p| p.to_vec()),
            Placeholder::Sha256Preimage(h) => sat.lookup_sha256(h).map(|p| p.to_vec()),
            Placeholder::Hash160Preimage(h) => sat.lookup_hash160(h).map(|p| p.to_vec()),
            Placeholder::Ripemd160Preimage(h) => sat.lookup_ripemd160(h).map(|p| p.to_vec()),
            Placeholder::EcdsaSigPk(pk) => sat.lookup_ecdsa_sig(pk).map(|s| s.to_vec()),
            Placeholder::EcdsaSigPkHash(pkh) => {
                sat.lookup_raw_pkh_ecdsa_sig(pkh).map(|(_, s)| s.to_vec())
            }
            Placeholder::SchnorrSigPk(pk, SchnorrSigType::ScriptSpend { leaf_hash }, size) => sat
                .lookup_tap_leaf_script_sig(pk, leaf_hash)
                .map(|s| s.to_vec())
                .map(|s| {
                    debug_assert!(s.len() == *size);
                    s
                }),
            Placeholder::SchnorrSigPk(_, _, size) => {
                sat.lookup_tap_key_spend_sig().map(|s| s.to_vec()).map(|s| {
                    debug_assert!(s.len() == *size);
                    s
                })
            }
            Placeholder::SchnorrSigPkHash(pkh, tap_leaf_hash, size) => sat
                .lookup_raw_pkh_tap_leaf_script_sig(&(*pkh, *tap_leaf_hash))
                .map(|(_, s)| {
                    let sig = s.to_vec();
                    debug_assert!(sig.len() == *size);
                    sig
                }),
            Placeholder::HashDissatisfaction => Some(vec![0; 32]),
            Placeholder::PushZero => Some(vec![]),
            Placeholder::PushOne => Some(vec![1]),
            Placeholder::TapScript(s) => Some(s.to_bytes()),
            Placeholder::TapControlBlock(cb) => Some(cb.serialize()),
        }
    }
}

/// A witness, if available, for a Miniscript fragment
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Witness<T> {
    /// Witness Available and the value of the witness
    Stack(Vec<T>),
    /// Third party can possibly satisfy the fragment but we cannot
    /// Witness Unavailable
    Unavailable,
    /// No third party can produce a satisfaction without private key
    /// Witness Impossible
    Impossible,
}

impl<Pk: MiniscriptKey> PartialOrd for Witness<Placeholder<Pk>> {
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { Some(self.cmp(other)) }
}

impl<Pk: MiniscriptKey> Ord for Witness<Placeholder<Pk>> {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        match (self, other) {
            (Witness::Stack(v1), Witness::Stack(v2)) => {
                let w1 = witness_size(v1);
                let w2 = witness_size(v2);
                w1.cmp(&w2)
            }
            (Witness::Stack(_), _) => cmp::Ordering::Less,
            (_, Witness::Stack(_)) => cmp::Ordering::Greater,
            (Witness::Impossible, Witness::Unavailable) => cmp::Ordering::Less,
            (Witness::Unavailable, Witness::Impossible) => cmp::Ordering::Greater,
            (Witness::Impossible, Witness::Impossible) => cmp::Ordering::Equal,
            (Witness::Unavailable, Witness::Unavailable) => cmp::Ordering::Equal,
        }
    }
}

impl<Pk: MiniscriptKey + ToPublicKey> Witness<Placeholder<Pk>> {
    /// Turn a signature into (part of) a satisfaction
    fn signature<S: AssetProvider<Pk>, Ctx: ScriptContext>(
        sat: &S,
        pk: &Pk,
        leaf_hash: &TapLeafHash,
    ) -> Self {
        match Ctx::sig_type() {
            super::context::SigType::Ecdsa => {
                if sat.provider_lookup_ecdsa_sig(pk) {
                    Witness::Stack(vec![Placeholder::EcdsaSigPk(pk.clone())])
                } else {
                    // Signatures cannot be forged
                    Witness::Impossible
                }
            }
            super::context::SigType::Schnorr => {
                match sat.provider_lookup_tap_leaf_script_sig(pk, leaf_hash) {
                    Some(size) => Witness::Stack(vec![Placeholder::SchnorrSigPk(
                        pk.clone(),
                        SchnorrSigType::ScriptSpend { leaf_hash: *leaf_hash },
                        size,
                    )]),
                    // Signatures cannot be forged
                    None => Witness::Impossible,
                }
            }
        }
    }

    /// Turn a public key related to a pkh into (part of) a satisfaction
    fn pkh_public_key<S: AssetProvider<Pk>, Ctx: ScriptContext>(
        sat: &S,
        pkh: &hash160::Hash,
    ) -> Self {
        // public key hashes are assumed to be unavailable
        // instead of impossible since it is the same as pub-key hashes
        match Ctx::sig_type() {
            SigType::Ecdsa => match sat.provider_lookup_raw_pkh_pk(pkh) {
                Some(pk) => Witness::Stack(vec![Placeholder::PubkeyHash(*pkh, Ctx::pk_len(&pk))]),
                None => Witness::Unavailable,
            },
            SigType::Schnorr => match sat.provider_lookup_raw_pkh_x_only_pk(pkh) {
                Some(pk) => Witness::Stack(vec![Placeholder::PubkeyHash(*pkh, Ctx::pk_len(&pk))]),
                None => Witness::Unavailable,
            },
        }
    }

    /// Turn a key/signature pair related to a pkh into (part of) a satisfaction
    fn pkh_signature<S: AssetProvider<Pk>, Ctx: ScriptContext>(
        sat: &S,
        pkh: &hash160::Hash,
        leaf_hash: &TapLeafHash,
    ) -> Self {
        match Ctx::sig_type() {
            SigType::Ecdsa => match sat.provider_lookup_raw_pkh_ecdsa_sig(pkh) {
                Some(pk) => Witness::Stack(vec![
                    Placeholder::EcdsaSigPkHash(*pkh),
                    Placeholder::PubkeyHash(*pkh, Ctx::pk_len(&pk)),
                ]),
                None => Witness::Impossible,
            },
            SigType::Schnorr => {
                match sat.provider_lookup_raw_pkh_tap_leaf_script_sig(&(*pkh, *leaf_hash)) {
                    Some((pk, size)) => Witness::Stack(vec![
                        Placeholder::SchnorrSigPkHash(*pkh, *leaf_hash, size),
                        Placeholder::PubkeyHash(*pkh, Ctx::pk_len(&pk)),
                    ]),
                    None => Witness::Impossible,
                }
            }
        }
    }

    /// Turn a hash preimage into (part of) a satisfaction
    fn ripemd160_preimage<S: AssetProvider<Pk>>(sat: &S, h: &Pk::Ripemd160) -> Self {
        if sat.provider_lookup_ripemd160(h) {
            Witness::Stack(vec![Placeholder::Ripemd160Preimage(h.clone())])
        // Note hash preimages are unavailable instead of impossible
        } else {
            Witness::Unavailable
        }
    }

    /// Turn a hash preimage into (part of) a satisfaction
    fn hash160_preimage<S: AssetProvider<Pk>>(sat: &S, h: &Pk::Hash160) -> Self {
        if sat.provider_lookup_hash160(h) {
            Witness::Stack(vec![Placeholder::Hash160Preimage(h.clone())])
        // Note hash preimages are unavailable instead of impossible
        } else {
            Witness::Unavailable
        }
    }

    /// Turn a hash preimage into (part of) a satisfaction
    fn sha256_preimage<S: AssetProvider<Pk>>(sat: &S, h: &Pk::Sha256) -> Self {
        if sat.provider_lookup_sha256(h) {
            Witness::Stack(vec![Placeholder::Sha256Preimage(h.clone())])
        // Note hash preimages are unavailable instead of impossible
        } else {
            Witness::Unavailable
        }
    }

    /// Turn a hash preimage into (part of) a satisfaction
    fn hash256_preimage<S: AssetProvider<Pk>>(sat: &S, h: &Pk::Hash256) -> Self {
        if sat.provider_lookup_hash256(h) {
            Witness::Stack(vec![Placeholder::Hash256Preimage(h.clone())])
        // Note hash preimages are unavailable instead of impossible
        } else {
            Witness::Unavailable
        }
    }
}

impl<Pk: MiniscriptKey> Witness<Placeholder<Pk>> {
    /// Produce something like a 32-byte 0 push
    fn hash_dissatisfaction() -> Self { Witness::Stack(vec![Placeholder::HashDissatisfaction]) }

    /// Construct a satisfaction equivalent to an empty stack
    fn empty() -> Self { Witness::Stack(vec![]) }

    /// Construct a satisfaction equivalent to `OP_1`
    fn push_1() -> Self { Witness::Stack(vec![Placeholder::PushOne]) }

    /// Construct a satisfaction equivalent to a single empty push
    fn push_0() -> Self { Witness::Stack(vec![Placeholder::PushZero]) }

    /// Concatenate, or otherwise combine, two satisfactions
    fn combine(one: Self, two: Self) -> Self {
        match (one, two) {
            (Witness::Impossible, _) | (_, Witness::Impossible) => Witness::Impossible,
            (Witness::Unavailable, _) | (_, Witness::Unavailable) => Witness::Unavailable,
            (Witness::Stack(mut a), Witness::Stack(b)) => {
                a.extend(b);
                Witness::Stack(a)
            }
        }
    }
}

/// A (dis)satisfaction of a Miniscript fragment
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Satisfaction<T> {
    /// The actual witness stack
    pub stack: Witness<T>,
    /// Whether or not this (dis)satisfaction has a signature somewhere
    /// in it
    pub has_sig: bool,
    /// The absolute timelock used by this satisfaction
    pub absolute_timelock: Option<AbsLockTime>,
    /// The relative timelock used by this satisfaction
    pub relative_timelock: Option<Sequence>,
}

impl<Pk: MiniscriptKey + ToPublicKey> Satisfaction<Placeholder<Pk>> {
    pub(crate) fn build_template<P, Ctx>(
        term: &Terminal<Pk, Ctx>,
        provider: &P,
        root_has_sig: bool,
        leaf_hash: &TapLeafHash,
    ) -> Self
    where
        Ctx: ScriptContext,
        P: AssetProvider<Pk>,
    {
        Self::satisfy_helper(
            term,
            provider,
            root_has_sig,
            leaf_hash,
            &mut Satisfaction::minimum,
            &mut Satisfaction::thresh,
        )
    }

    pub(crate) fn build_template_mall<P, Ctx>(
        term: &Terminal<Pk, Ctx>,
        provider: &P,
        root_has_sig: bool,
        leaf_hash: &TapLeafHash,
    ) -> Self
    where
        Ctx: ScriptContext,
        P: AssetProvider<Pk>,
    {
        Self::satisfy_helper(
            term,
            provider,
            root_has_sig,
            leaf_hash,
            &mut Satisfaction::minimum_mall,
            &mut Satisfaction::thresh_mall,
        )
    }

    // produce a non-malleable satisafaction for thesh frag
    fn thresh<Ctx, Sat, F>(
        k: usize,
        subs: &[Arc<Miniscript<Pk, Ctx>>],
        stfr: &Sat,
        root_has_sig: bool,
        leaf_hash: &TapLeafHash,
        min_fn: &mut F,
    ) -> Self
    where
        Ctx: ScriptContext,
        Sat: AssetProvider<Pk>,
        F: FnMut(
            Satisfaction<Placeholder<Pk>>,
            Satisfaction<Placeholder<Pk>>,
        ) -> Satisfaction<Placeholder<Pk>>,
    {
        let mut sats = subs
            .iter()
            .map(|s| {
                Self::satisfy_helper(
                    &s.node,
                    stfr,
                    root_has_sig,
                    leaf_hash,
                    min_fn,
                    &mut Self::thresh,
                )
            })
            .collect::<Vec<_>>();
        // Start with the to-return stack set to all dissatisfactions
        let mut ret_stack = subs
            .iter()
            .map(|s| {
                Self::dissatisfy_helper(
                    &s.node,
                    stfr,
                    root_has_sig,
                    leaf_hash,
                    min_fn,
                    &mut Self::thresh,
                )
            })
            .collect::<Vec<_>>();

        // Sort everything by (sat cost - dissat cost), except that
        // satisfactions without signatures beat satisfactions with
        // signatures
        let mut sat_indices = (0..subs.len()).collect::<Vec<_>>();
        sat_indices.sort_by_key(|&i| {
            let stack_weight = match (&sats[i].stack, &ret_stack[i].stack) {
                (&Witness::Unavailable, _) | (&Witness::Impossible, _) => i64::MAX,
                // This can only be the case when we have PkH without the corresponding
                // Pubkey.
                (_, &Witness::Unavailable) | (_, &Witness::Impossible) => i64::MIN,
                (Witness::Stack(s), Witness::Stack(d)) => {
                    witness_size(s) as i64 - witness_size(d) as i64
                }
            };
            let is_impossible = sats[i].stack == Witness::Impossible;
            // First consider the candidates that are not impossible to satisfy
            // by any party. Among those first consider the ones that have no sig
            // because third party can malleate them if they are not chosen.
            // Lastly, choose by weight.
            (is_impossible, sats[i].has_sig, stack_weight)
        });

        for i in 0..k {
            mem::swap(&mut ret_stack[sat_indices[i]], &mut sats[sat_indices[i]]);
        }

        // We preferably take satisfactions that are not impossible
        // If we cannot find `k` satisfactions that are not impossible
        // then the threshold branch is impossible to satisfy
        // For example, the fragment thresh(2, hash, 0, 0, 0)
        // is has an impossible witness
        assert!(k > 0);
        if sats[sat_indices[k - 1]].stack == Witness::Impossible {
            Satisfaction {
                stack: Witness::Impossible,
                // If the witness is impossible, we don't care about the
                // has_sig flag, nor about the timelocks
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            }
        }
        // We are now guaranteed that all elements in `k` satisfactions
        // are not impossible(we sort by is_impossible bool).
        // The above loop should have taken everything without a sig
        // (since those were sorted higher than non-sigs). If there
        // are remaining non-sig satisfactions this indicates a
        // malleability vector
        // For example, the fragment thresh(2, hash, hash, 0, 0)
        // is uniquely satisfyiable because there is no satisfaction
        // for the 0 fragment
        else if k < sat_indices.len()
            && !sats[sat_indices[k]].has_sig
            && sats[sat_indices[k]].stack != Witness::Impossible
        {
            // All arguments should be `d`, so dissatisfactions have no
            // signatures; and in this branch we assume too many weak
            // arguments, so none of the satisfactions should have
            // signatures either.
            for sat in &ret_stack {
                assert!(!sat.has_sig);
            }
            Satisfaction {
                stack: Witness::Unavailable,
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            }
        } else {
            // Otherwise flatten everything out
            Satisfaction {
                has_sig: ret_stack.iter().any(|sat| sat.has_sig),
                relative_timelock: ret_stack
                    .iter()
                    .filter_map(|sat| sat.relative_timelock)
                    .max(),
                absolute_timelock: ret_stack
                    .iter()
                    .filter_map(|sat| sat.absolute_timelock)
                    .max(),
                stack: ret_stack
                    .into_iter()
                    .fold(Witness::empty(), |acc, next| Witness::combine(next.stack, acc)),
            }
        }
    }

    // produce a possily malleable satisafaction for thesh frag
    fn thresh_mall<Ctx, Sat, F>(
        k: usize,
        subs: &[Arc<Miniscript<Pk, Ctx>>],
        stfr: &Sat,
        root_has_sig: bool,
        leaf_hash: &TapLeafHash,
        min_fn: &mut F,
    ) -> Self
    where
        Ctx: ScriptContext,
        Sat: AssetProvider<Pk>,
        F: FnMut(
            Satisfaction<Placeholder<Pk>>,
            Satisfaction<Placeholder<Pk>>,
        ) -> Satisfaction<Placeholder<Pk>>,
    {
        let mut sats = subs
            .iter()
            .map(|s| {
                Self::satisfy_helper(
                    &s.node,
                    stfr,
                    root_has_sig,
                    leaf_hash,
                    min_fn,
                    &mut Self::thresh_mall,
                )
            })
            .collect::<Vec<_>>();
        // Start with the to-return stack set to all dissatisfactions
        let mut ret_stack = subs
            .iter()
            .map(|s| {
                Self::dissatisfy_helper(
                    &s.node,
                    stfr,
                    root_has_sig,
                    leaf_hash,
                    min_fn,
                    &mut Self::thresh_mall,
                )
            })
            .collect::<Vec<_>>();

        // Sort everything by (sat cost - dissat cost), except that
        // satisfactions without signatures beat satisfactions with
        // signatures
        let mut sat_indices = (0..subs.len()).collect::<Vec<_>>();
        sat_indices.sort_by_key(|&i| {
            // For malleable satifactions, directly choose smallest weights
            match (&sats[i].stack, &ret_stack[i].stack) {
                (&Witness::Unavailable, _) | (&Witness::Impossible, _) => i64::MAX,
                // This is only possible when one of the branches has PkH
                (_, &Witness::Unavailable) | (_, &Witness::Impossible) => i64::MIN,
                (Witness::Stack(s), Witness::Stack(d)) => {
                    witness_size(s) as i64 - witness_size(d) as i64
                }
            }
        });

        // swap the satisfactions
        for i in 0..k {
            mem::swap(&mut ret_stack[sat_indices[i]], &mut sats[sat_indices[i]]);
        }

        // combine the witness
        // no non-malleability checks needed
        Satisfaction {
            has_sig: ret_stack.iter().any(|sat| sat.has_sig),
            relative_timelock: ret_stack
                .iter()
                .filter_map(|sat| sat.relative_timelock)
                .max(),
            absolute_timelock: ret_stack
                .iter()
                .filter_map(|sat| sat.absolute_timelock)
                .max(),
            stack: ret_stack
                .into_iter()
                .fold(Witness::empty(), |acc, next| Witness::combine(next.stack, acc)),
        }
    }

    fn minimum(sat1: Self, sat2: Self) -> Self {
        // If there is only one available satisfaction, we must choose that
        // regardless of has_sig marker.
        // This handles the case where both are impossible.
        match (&sat1.stack, &sat2.stack) {
            (&Witness::Impossible, _) => return sat2,
            (_, &Witness::Impossible) => return sat1,
            _ => {}
        }
        match (sat1.has_sig, sat2.has_sig) {
            // If neither option has a signature, this is a malleability
            // vector, so choose neither one.
            (false, false) => Satisfaction {
                stack: Witness::Unavailable,
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            },
            // If only one has a signature, take the one that doesn't; a
            // third party could malleate by removing the signature, but
            // can't malleate if he'd have to add it
            (false, true) => Satisfaction {
                stack: sat1.stack,
                has_sig: false,
                relative_timelock: sat1.relative_timelock,
                absolute_timelock: sat1.absolute_timelock,
            },
            (true, false) => Satisfaction {
                stack: sat2.stack,
                has_sig: false,
                relative_timelock: sat2.relative_timelock,
                absolute_timelock: sat2.absolute_timelock,
            },
            // If both have a signature associated with them, choose the
            // cheaper one (where "cheaper" is defined such that available
            // things are cheaper than unavailable ones)
            (true, true) if sat1.stack < sat2.stack => Satisfaction {
                stack: sat1.stack,
                has_sig: true,
                relative_timelock: sat1.relative_timelock,
                absolute_timelock: sat1.absolute_timelock,
            },
            (true, true) => Satisfaction {
                stack: sat2.stack,
                has_sig: true,
                relative_timelock: sat2.relative_timelock,
                absolute_timelock: sat2.absolute_timelock,
            },
        }
    }

    // calculate the minimum witness allowing witness malleability
    fn minimum_mall(sat1: Self, sat2: Self) -> Self {
        match (&sat1.stack, &sat2.stack) {
            // If there is only one possible satisfaction, use it regardless
            // of the other one
            (&Witness::Impossible, _) | (&Witness::Unavailable, _) => return sat2,
            (_, &Witness::Impossible) | (_, &Witness::Unavailable) => return sat1,
            _ => {}
        }
        let (stack, absolute_timelock, relative_timelock) = if sat1.stack < sat2.stack {
            (sat1.stack, sat1.absolute_timelock, sat1.relative_timelock)
        } else {
            (sat2.stack, sat2.absolute_timelock, sat2.relative_timelock)
        };
        Satisfaction {
            stack,
            // The fragment is has_sig only if both of the
            // fragments are has_sig
            has_sig: sat1.has_sig && sat2.has_sig,
            relative_timelock,
            absolute_timelock,
        }
    }

    // produce a non-malleable satisfaction
    fn satisfy_helper<Ctx, Sat, F, G>(
        term: &Terminal<Pk, Ctx>,
        stfr: &Sat,
        root_has_sig: bool,
        leaf_hash: &TapLeafHash,
        min_fn: &mut F,
        thresh_fn: &mut G,
    ) -> Self
    where
        Ctx: ScriptContext,
        Sat: AssetProvider<Pk>,
        F: FnMut(
            Satisfaction<Placeholder<Pk>>,
            Satisfaction<Placeholder<Pk>>,
        ) -> Satisfaction<Placeholder<Pk>>,
        G: FnMut(
            usize,
            &[Arc<Miniscript<Pk, Ctx>>],
            &Sat,
            bool,
            &TapLeafHash,
            &mut F,
        ) -> Satisfaction<Placeholder<Pk>>,
    {
        match *term {
            Terminal::PkK(ref pk) => Satisfaction {
                stack: Witness::signature::<_, Ctx>(stfr, pk, leaf_hash),
                has_sig: true,
                relative_timelock: None,
                absolute_timelock: None,
            },
            Terminal::PkH(ref pk) => {
                let wit = Witness::signature::<_, Ctx>(stfr, pk, leaf_hash);
                Satisfaction {
                    stack: Witness::combine(
                        wit,
                        Witness::Stack(vec![Placeholder::Pubkey(pk.clone(), Ctx::pk_len(pk))]),
                    ),
                    has_sig: true,
                    relative_timelock: None,
                    absolute_timelock: None,
                }
            }
            Terminal::RawPkH(ref pkh) => Satisfaction {
                stack: Witness::pkh_signature::<_, Ctx>(stfr, pkh, leaf_hash),
                has_sig: true,
                relative_timelock: None,
                absolute_timelock: None,
            },
            Terminal::After(t) => {
                let (stack, absolute_timelock) = if stfr.check_after(t.into()) {
                    (Witness::empty(), Some(t))
                } else if root_has_sig {
                    // If the root terminal has signature, the
                    // signature covers the nLockTime and nSequence
                    // values. The sender of the transaction should
                    // take care that it signs the value such that the
                    // timelock is not met
                    (Witness::Impossible, None)
                } else {
                    (Witness::Unavailable, None)
                };
                Satisfaction { stack, has_sig: false, relative_timelock: None, absolute_timelock }
            }
            Terminal::Older(t) => {
                let (stack, relative_timelock) = if stfr.check_older(t) {
                    (Witness::empty(), Some(t))
                } else if root_has_sig {
                    // If the root terminal has signature, the
                    // signature covers the nLockTime and nSequence
                    // values. The sender of the transaction should
                    // take care that it signs the value such that the
                    // timelock is not met
                    (Witness::Impossible, None)
                } else {
                    (Witness::Unavailable, None)
                };
                Satisfaction { stack, has_sig: false, relative_timelock, absolute_timelock: None }
            }
            Terminal::Ripemd160(ref h) => Satisfaction {
                stack: Witness::ripemd160_preimage(stfr, h),
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            },
            Terminal::Hash160(ref h) => Satisfaction {
                stack: Witness::hash160_preimage(stfr, h),
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            },
            Terminal::Sha256(ref h) => Satisfaction {
                stack: Witness::sha256_preimage(stfr, h),
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            },
            Terminal::Hash256(ref h) => Satisfaction {
                stack: Witness::hash256_preimage(stfr, h),
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            },
            Terminal::True => Satisfaction {
                stack: Witness::empty(),
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            },
            Terminal::False => Satisfaction {
                stack: Witness::Impossible,
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            },
            Terminal::Alt(ref sub)
            | Terminal::Swap(ref sub)
            | Terminal::Check(ref sub)
            | Terminal::Verify(ref sub)
            | Terminal::NonZero(ref sub)
            | Terminal::ZeroNotEqual(ref sub) => {
                Self::satisfy_helper(&sub.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn)
            }
            Terminal::DupIf(ref sub) => {
                let sat = Self::satisfy_helper(
                    &sub.node,
                    stfr,
                    root_has_sig,
                    leaf_hash,
                    min_fn,
                    thresh_fn,
                );
                Satisfaction {
                    stack: Witness::combine(sat.stack, Witness::push_1()),
                    has_sig: sat.has_sig,
                    relative_timelock: sat.relative_timelock,
                    absolute_timelock: sat.absolute_timelock,
                }
            }
            Terminal::AndV(ref l, ref r) | Terminal::AndB(ref l, ref r) => {
                let l_sat =
                    Self::satisfy_helper(&l.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
                let r_sat =
                    Self::satisfy_helper(&r.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
                Satisfaction {
                    stack: Witness::combine(r_sat.stack, l_sat.stack),
                    has_sig: l_sat.has_sig || r_sat.has_sig,
                    relative_timelock: cmp::max(l_sat.relative_timelock, r_sat.relative_timelock),
                    absolute_timelock: cmp::max(l_sat.absolute_timelock, r_sat.absolute_timelock),
                }
            }
            Terminal::AndOr(ref a, ref b, ref c) => {
                let a_sat =
                    Self::satisfy_helper(&a.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
                let a_nsat = Self::dissatisfy_helper(
                    &a.node,
                    stfr,
                    root_has_sig,
                    leaf_hash,
                    min_fn,
                    thresh_fn,
                );
                let b_sat =
                    Self::satisfy_helper(&b.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
                let c_sat =
                    Self::satisfy_helper(&c.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);

                min_fn(
                    Satisfaction {
                        stack: Witness::combine(b_sat.stack, a_sat.stack),
                        has_sig: a_sat.has_sig || b_sat.has_sig,
                        relative_timelock: cmp::max(
                            a_sat.relative_timelock,
                            b_sat.relative_timelock,
                        ),
                        absolute_timelock: cmp::max(
                            a_sat.absolute_timelock,
                            b_sat.absolute_timelock,
                        ),
                    },
                    Satisfaction {
                        stack: Witness::combine(c_sat.stack, a_nsat.stack),
                        has_sig: a_nsat.has_sig || c_sat.has_sig,
                        // timelocks can't be dissatisfied, so here we ignore a_nsat and only consider c_sat
                        relative_timelock: c_sat.relative_timelock,
                        absolute_timelock: c_sat.absolute_timelock,
                    },
                )
            }
            Terminal::OrB(ref l, ref r) => {
                let l_sat =
                    Self::satisfy_helper(&l.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
                let r_sat =
                    Self::satisfy_helper(&r.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
                let l_nsat = Self::dissatisfy_helper(
                    &l.node,
                    stfr,
                    root_has_sig,
                    leaf_hash,
                    min_fn,
                    thresh_fn,
                );
                let r_nsat = Self::dissatisfy_helper(
                    &r.node,
                    stfr,
                    root_has_sig,
                    leaf_hash,
                    min_fn,
                    thresh_fn,
                );

                assert!(!l_nsat.has_sig);
                assert!(!r_nsat.has_sig);

                min_fn(
                    Satisfaction {
                        stack: Witness::combine(r_sat.stack, l_nsat.stack),
                        has_sig: r_sat.has_sig,
                        relative_timelock: r_sat.relative_timelock,
                        absolute_timelock: r_sat.absolute_timelock,
                    },
                    Satisfaction {
                        stack: Witness::combine(r_nsat.stack, l_sat.stack),
                        has_sig: l_sat.has_sig,
                        relative_timelock: l_sat.relative_timelock,
                        absolute_timelock: l_sat.absolute_timelock,
                    },
                )
            }
            Terminal::OrD(ref l, ref r) | Terminal::OrC(ref l, ref r) => {
                let l_sat =
                    Self::satisfy_helper(&l.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
                let r_sat =
                    Self::satisfy_helper(&r.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
                let l_nsat = Self::dissatisfy_helper(
                    &l.node,
                    stfr,
                    root_has_sig,
                    leaf_hash,
                    min_fn,
                    thresh_fn,
                );

                assert!(!l_nsat.has_sig);

                min_fn(
                    l_sat,
                    Satisfaction {
                        stack: Witness::combine(r_sat.stack, l_nsat.stack),
                        has_sig: r_sat.has_sig,
                        relative_timelock: r_sat.relative_timelock,
                        absolute_timelock: r_sat.absolute_timelock,
                    },
                )
            }
            Terminal::OrI(ref l, ref r) => {
                let l_sat =
                    Self::satisfy_helper(&l.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
                let r_sat =
                    Self::satisfy_helper(&r.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
                min_fn(
                    Satisfaction {
                        stack: Witness::combine(l_sat.stack, Witness::push_1()),
                        has_sig: l_sat.has_sig,
                        relative_timelock: l_sat.relative_timelock,
                        absolute_timelock: l_sat.absolute_timelock,
                    },
                    Satisfaction {
                        stack: Witness::combine(r_sat.stack, Witness::push_0()),
                        has_sig: r_sat.has_sig,
                        relative_timelock: r_sat.relative_timelock,
                        absolute_timelock: r_sat.absolute_timelock,
                    },
                )
            }
            Terminal::Thresh(k, ref subs) => {
                thresh_fn(k, subs, stfr, root_has_sig, leaf_hash, min_fn)
            }
            Terminal::Multi(k, ref keys) => {
                // Collect all available signatures
                let mut sig_count = 0;
                let mut sigs = Vec::with_capacity(k);
                for pk in keys {
                    match Witness::signature::<_, Ctx>(stfr, pk, leaf_hash) {
                        Witness::Stack(sig) => {
                            sigs.push(sig);
                            sig_count += 1;
                        }
                        Witness::Impossible => {}
                        Witness::Unavailable => unreachable!(
                            "Signature satisfaction without witness must be impossible"
                        ),
                    }
                }

                if sig_count < k {
                    Satisfaction {
                        stack: Witness::Impossible,
                        has_sig: false,
                        relative_timelock: None,
                        absolute_timelock: None,
                    }
                } else {
                    // Throw away the most expensive ones
                    for _ in 0..sig_count - k {
                        let max_idx = sigs
                            .iter()
                            .enumerate()
                            .max_by_key(|&(_, v)| v.len())
                            .unwrap()
                            .0;
                        sigs[max_idx] = vec![];
                    }

                    Satisfaction {
                        stack: sigs.into_iter().fold(Witness::push_0(), |acc, sig| {
                            Witness::combine(acc, Witness::Stack(sig))
                        }),
                        has_sig: true,
                        relative_timelock: None,
                        absolute_timelock: None,
                    }
                }
            }
            Terminal::MultiA(k, ref keys) => {
                // Collect all available signatures
                let mut sig_count = 0;
                let mut sigs = vec![vec![Placeholder::PushZero]; keys.len()];
                for (i, pk) in keys.iter().rev().enumerate() {
                    match Witness::signature::<_, Ctx>(stfr, pk, leaf_hash) {
                        Witness::Stack(sig) => {
                            sigs[i] = sig;
                            sig_count += 1;
                            // This a privacy issue, we are only selecting the first available
                            // sigs. Incase pk at pos 1 is not selected, we know we did not have access to it
                            // bitcoin core also implements the same logic for MULTISIG, so I am not bothering
                            // permuting the sigs for now
                            if sig_count == k {
                                break;
                            }
                        }
                        Witness::Impossible => {}
                        Witness::Unavailable => unreachable!(
                            "Signature satisfaction without witness must be impossible"
                        ),
                    }
                }

                if sig_count < k {
                    Satisfaction {
                        stack: Witness::Impossible,
                        has_sig: false,
                        relative_timelock: None,
                        absolute_timelock: None,
                    }
                } else {
                    Satisfaction {
                        stack: sigs.into_iter().fold(Witness::empty(), |acc, sig| {
                            Witness::combine(acc, Witness::Stack(sig))
                        }),
                        has_sig: true,
                        relative_timelock: None,
                        absolute_timelock: None,
                    }
                }
            }
        }
    }

    // Helper function to produce a dissatisfaction
    fn dissatisfy_helper<Ctx, Sat, F, G>(
        term: &Terminal<Pk, Ctx>,
        stfr: &Sat,
        root_has_sig: bool,
        leaf_hash: &TapLeafHash,
        min_fn: &mut F,
        thresh_fn: &mut G,
    ) -> Self
    where
        Ctx: ScriptContext,
        Sat: AssetProvider<Pk>,
        F: FnMut(
            Satisfaction<Placeholder<Pk>>,
            Satisfaction<Placeholder<Pk>>,
        ) -> Satisfaction<Placeholder<Pk>>,
        G: FnMut(
            usize,
            &[Arc<Miniscript<Pk, Ctx>>],
            &Sat,
            bool,
            &TapLeafHash,
            &mut F,
        ) -> Satisfaction<Placeholder<Pk>>,
    {
        match *term {
            Terminal::PkK(..) => Satisfaction {
                stack: Witness::push_0(),
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            },
            Terminal::PkH(ref pk) => Satisfaction {
                stack: Witness::combine(
                    Witness::push_0(),
                    Witness::Stack(vec![Placeholder::Pubkey(pk.clone(), Ctx::pk_len(pk))]),
                ),
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            },
            Terminal::RawPkH(ref pkh) => Satisfaction {
                stack: Witness::combine(
                    Witness::push_0(),
                    Witness::pkh_public_key::<_, Ctx>(stfr, pkh),
                ),
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            },
            Terminal::False => Satisfaction {
                stack: Witness::empty(),
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            },
            Terminal::True
            | Terminal::Older(_)
            | Terminal::After(_)
            | Terminal::Verify(_)
            | Terminal::OrC(..) => Satisfaction {
                stack: Witness::Impossible,
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            },
            Terminal::Sha256(_)
            | Terminal::Hash256(_)
            | Terminal::Ripemd160(_)
            | Terminal::Hash160(_) => Satisfaction {
                stack: Witness::hash_dissatisfaction(),
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            },
            Terminal::Alt(ref sub)
            | Terminal::Swap(ref sub)
            | Terminal::Check(ref sub)
            | Terminal::ZeroNotEqual(ref sub) => {
                Self::dissatisfy_helper(&sub.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn)
            }
            Terminal::DupIf(_) | Terminal::NonZero(_) => Satisfaction {
                stack: Witness::push_0(),
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            },
            Terminal::AndV(ref v, ref other) => {
                let vsat =
                    Self::satisfy_helper(&v.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn);
                let odissat = Self::dissatisfy_helper(
                    &other.node,
                    stfr,
                    root_has_sig,
                    leaf_hash,
                    min_fn,
                    thresh_fn,
                );
                Satisfaction {
                    stack: Witness::combine(odissat.stack, vsat.stack),
                    has_sig: vsat.has_sig || odissat.has_sig,
                    relative_timelock: None,
                    absolute_timelock: None,
                }
            }
            Terminal::AndB(ref l, ref r)
            | Terminal::OrB(ref l, ref r)
            | Terminal::OrD(ref l, ref r)
            | Terminal::AndOr(ref l, _, ref r) => {
                let lnsat = Self::dissatisfy_helper(
                    &l.node,
                    stfr,
                    root_has_sig,
                    leaf_hash,
                    min_fn,
                    thresh_fn,
                );
                let rnsat = Self::dissatisfy_helper(
                    &r.node,
                    stfr,
                    root_has_sig,
                    leaf_hash,
                    min_fn,
                    thresh_fn,
                );
                Satisfaction {
                    stack: Witness::combine(rnsat.stack, lnsat.stack),
                    has_sig: rnsat.has_sig || lnsat.has_sig,
                    relative_timelock: None,
                    absolute_timelock: None,
                }
            }
            Terminal::OrI(ref l, ref r) => {
                let lnsat = Self::dissatisfy_helper(
                    &l.node,
                    stfr,
                    root_has_sig,
                    leaf_hash,
                    min_fn,
                    thresh_fn,
                );
                let dissat_1 = Satisfaction {
                    stack: Witness::combine(lnsat.stack, Witness::push_1()),
                    has_sig: lnsat.has_sig,
                    relative_timelock: None,
                    absolute_timelock: None,
                };

                let rnsat = Self::dissatisfy_helper(
                    &r.node,
                    stfr,
                    root_has_sig,
                    leaf_hash,
                    min_fn,
                    thresh_fn,
                );
                let dissat_2 = Satisfaction {
                    stack: Witness::combine(rnsat.stack, Witness::push_0()),
                    has_sig: rnsat.has_sig,
                    relative_timelock: None,
                    absolute_timelock: None,
                };

                // Dissatisfactions don't need to non-malleable. Use minimum_mall always
                Satisfaction::minimum_mall(dissat_1, dissat_2)
            }
            Terminal::Thresh(_, ref subs) => Satisfaction {
                stack: subs.iter().fold(Witness::empty(), |acc, sub| {
                    let nsat = Self::dissatisfy_helper(
                        &sub.node,
                        stfr,
                        root_has_sig,
                        leaf_hash,
                        min_fn,
                        thresh_fn,
                    );
                    assert!(!nsat.has_sig);
                    Witness::combine(nsat.stack, acc)
                }),
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            },
            Terminal::Multi(k, _) => Satisfaction {
                stack: Witness::Stack(vec![Placeholder::PushZero; k + 1]),
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            },
            Terminal::MultiA(_, ref pks) => Satisfaction {
                stack: Witness::Stack(vec![Placeholder::PushZero; pks.len()]),
                has_sig: false,
                relative_timelock: None,
                absolute_timelock: None,
            },
        }
    }

    /// Try creating the final witness using a [`Satisfier`]
    pub fn try_completing<Sat: Satisfier<Pk>>(&self, stfr: &Sat) -> Option<Satisfaction<Vec<u8>>> {
        let Satisfaction { stack, has_sig, relative_timelock, absolute_timelock } = self;
        let stack = match stack {
            Witness::Stack(stack) => Witness::Stack(
                stack
                    .iter()
                    .map(|placeholder| placeholder.satisfy_self(stfr))
                    .collect::<Option<_>>()?,
            ),
            Witness::Unavailable => Witness::Unavailable,
            Witness::Impossible => Witness::Impossible,
        };
        Some(Satisfaction {
            stack,
            has_sig: *has_sig,
            relative_timelock: *relative_timelock,
            absolute_timelock: *absolute_timelock,
        })
    }
}

impl Satisfaction<Vec<u8>> {
    /// Produce a satisfaction non-malleable satisfaction
    pub(super) fn satisfy<Ctx, Pk, Sat>(
        term: &Terminal<Pk, Ctx>,
        stfr: &Sat,
        root_has_sig: bool,
        leaf_hash: &TapLeafHash,
    ) -> Self
    where
        Ctx: ScriptContext,
        Pk: MiniscriptKey + ToPublicKey,
        Sat: Satisfier<Pk>,
    {
        Satisfaction::<Placeholder<Pk>>::build_template(term, &stfr, root_has_sig, leaf_hash)
            .try_completing(stfr)
            .expect("the same satisfier should manage to complete the template")
    }

    /// Produce a satisfaction(possibly malleable)
    pub(super) fn satisfy_mall<Ctx, Pk, Sat>(
        term: &Terminal<Pk, Ctx>,
        stfr: &Sat,
        root_has_sig: bool,
        leaf_hash: &TapLeafHash,
    ) -> Self
    where
        Ctx: ScriptContext,
        Pk: MiniscriptKey + ToPublicKey,
        Sat: Satisfier<Pk>,
    {
        Satisfaction::<Placeholder<Pk>>::build_template_mall(term, &stfr, root_has_sig, leaf_hash)
            .try_completing(stfr)
            .expect("the same satisfier should manage to complete the template")
    }
}