-
Notifications
You must be signed in to change notification settings - Fork 138
/
satisfy.rs
1844 lines (1717 loc) · 69 KB
/
satisfy.rs
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
// SPDX-License-Identifier: CC0-1.0
//! # Satisfaction and Dissatisfaction
//!
//! Traits and implementations to support producing witnesses for Miniscript
//! scriptpubkeys.
//!
use core::{cmp, fmt, mem};
use bitcoin::hashes::hash160;
use bitcoin::key::XOnlyPublicKey;
use bitcoin::taproot::{ControlBlock, LeafVersion, TapLeafHash, TapNodeHash};
use bitcoin::{absolute, relative, 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, RelLockTime, ScriptContext, Terminal, Threshold,
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, _: relative::LockTime) -> 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: relative::LockTime) -> bool {
if let Some(lt) = self.to_relative_lock_time() {
Satisfier::<Pk>::check_older(<, n)
} else {
false
}
}
}
impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk> for RelLockTime {
fn check_older(&self, n: relative::LockTime) -> bool {
<relative::LockTime as Satisfier<Pk>>::check_older(&(*self).into(), n)
}
}
impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk> for relative::LockTime {
fn check_older(&self, n: relative::LockTime) -> bool { n.is_implied_by(*self) }
}
impl<Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk> for absolute::LockTime {
fn check_after(&self, n: absolute::LockTime) -> bool { n.is_implied_by(*self) }
}
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<Pk: MiniscriptKey + ToPublicKey, S: Satisfier<Pk>> Satisfier<Pk> for &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: relative::LockTime) -> bool { (**self).check_older(t) }
fn check_after(&self, n: absolute::LockTime) -> bool { (**self).check_after(n) }
}
impl<Pk: MiniscriptKey + ToPublicKey, S: Satisfier<Pk>> Satisfier<Pk> for &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: relative::LockTime) -> 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: relative::LockTime) -> 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, Hash)]
/// 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, Hash)]
/// 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, Hash)]
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, Hash)]
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<RelLockTime>,
}
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>(
thresh: &Threshold<Arc<Miniscript<Pk, Ctx>>, 0>,
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 = thresh
.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 = thresh
.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..thresh.n()).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)
});