-
Notifications
You must be signed in to change notification settings - Fork 141
/
mod.rs
1770 lines (1590 loc) · 73.6 KB
/
mod.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
// Miniscript
// Written in 2018 by
// Andrew Poelstra <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//
//! # Output Descriptors
//!
//! Tools for representing Bitcoin output's scriptPubKeys as abstract spending
//! policies known as "output descriptors". These include a Miniscript which
//! describes the actual signing policy, as well as the blockchain format (P2SH,
//! Segwit v0, etc.)
//!
//! The format represents EC public keys abstractly to allow wallets to replace
//! these with BIP32 paths, pay-to-contract instructions, etc.
//!
use core::fmt;
use core::ops::Range;
use core::str::{self, FromStr};
use bitcoin::blockdata::witness::Witness;
use bitcoin::hashes::{hash160, ripemd160, sha256};
use bitcoin::util::address::WitnessVersion;
use bitcoin::{self, secp256k1, Address, Network, Script, TxIn};
use sync::Arc;
use self::checksum::verify_checksum;
use crate::miniscript::{Legacy, Miniscript, Segwitv0};
use crate::prelude::*;
use crate::{
expression, hash256, miniscript, BareCtx, Error, ForEachKey, MiniscriptKey, Satisfier,
ToPublicKey, TranslatePk, Translator,
};
mod bare;
mod segwitv0;
mod sh;
mod sortedmulti;
mod tr;
// Descriptor Exports
pub use self::bare::{Bare, Pkh};
pub use self::segwitv0::{Wpkh, Wsh, WshInner};
pub use self::sh::{Sh, ShInner};
pub use self::sortedmulti::SortedMultiVec;
pub use self::tr::{TapTree, Tr};
mod checksum;
mod key;
pub use self::key::{
ConversionError, DefiniteDescriptorKey, DescriptorKeyParseError, DescriptorPublicKey,
DescriptorSecretKey, DescriptorXKey, InnerXKey, SinglePriv, SinglePub, SinglePubKey, Wildcard,
};
/// Alias type for a map of public key to secret key
///
/// This map is returned whenever a descriptor that contains secrets is parsed using
/// [`Descriptor::parse_descriptor`], since the descriptor will always only contain
/// public keys. This map allows looking up the corresponding secret key given a
/// public key from the descriptor.
pub type KeyMap = HashMap<DescriptorPublicKey, DescriptorSecretKey>;
/// Script descriptor
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Descriptor<Pk: MiniscriptKey> {
/// A raw scriptpubkey (including pay-to-pubkey) under Legacy context
Bare(Bare<Pk>),
/// Pay-to-PubKey-Hash
Pkh(Pkh<Pk>),
/// Pay-to-Witness-PubKey-Hash
Wpkh(Wpkh<Pk>),
/// Pay-to-ScriptHash(includes nested wsh/wpkh/sorted multi)
Sh(Sh<Pk>),
/// Pay-to-Witness-ScriptHash with Segwitv0 context
Wsh(Wsh<Pk>),
/// Pay-to-Taproot
Tr(Tr<Pk>),
}
impl<Pk: MiniscriptKey> From<Bare<Pk>> for Descriptor<Pk> {
#[inline]
fn from(inner: Bare<Pk>) -> Self {
Descriptor::Bare(inner)
}
}
impl<Pk: MiniscriptKey> From<Pkh<Pk>> for Descriptor<Pk> {
#[inline]
fn from(inner: Pkh<Pk>) -> Self {
Descriptor::Pkh(inner)
}
}
impl<Pk: MiniscriptKey> From<Wpkh<Pk>> for Descriptor<Pk> {
#[inline]
fn from(inner: Wpkh<Pk>) -> Self {
Descriptor::Wpkh(inner)
}
}
impl<Pk: MiniscriptKey> From<Sh<Pk>> for Descriptor<Pk> {
#[inline]
fn from(inner: Sh<Pk>) -> Self {
Descriptor::Sh(inner)
}
}
impl<Pk: MiniscriptKey> From<Wsh<Pk>> for Descriptor<Pk> {
#[inline]
fn from(inner: Wsh<Pk>) -> Self {
Descriptor::Wsh(inner)
}
}
impl<Pk: MiniscriptKey> From<Tr<Pk>> for Descriptor<Pk> {
#[inline]
fn from(inner: Tr<Pk>) -> Self {
Descriptor::Tr(inner)
}
}
/// Descriptor Type of the descriptor
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum DescriptorType {
/// Bare descriptor(Contains the native P2pk)
Bare,
/// Pure Sh Descriptor. Does not contain nested Wsh/Wpkh
Sh,
/// Pkh Descriptor
Pkh,
/// Wpkh Descriptor
Wpkh,
/// Wsh
Wsh,
/// Sh Wrapped Wsh
ShWsh,
/// Sh wrapped Wpkh
ShWpkh,
/// Sh Sorted Multi
ShSortedMulti,
/// Wsh Sorted Multi
WshSortedMulti,
/// Sh Wsh Sorted Multi
ShWshSortedMulti,
/// Tr Descriptor
Tr,
}
impl DescriptorType {
/// Returns the segwit version implied by the descriptor type.
///
/// This will return `Some(WitnessVersion::V0)` whether it is "native" segwitv0 or "wrapped" p2sh segwit.
pub fn segwit_version(&self) -> Option<WitnessVersion> {
use self::DescriptorType::*;
match self {
Tr => Some(WitnessVersion::V1),
Wpkh | ShWpkh | Wsh | ShWsh | ShWshSortedMulti | WshSortedMulti => {
Some(WitnessVersion::V0)
}
Bare | Sh | Pkh | ShSortedMulti => None,
}
}
}
impl<Pk: MiniscriptKey> Descriptor<Pk> {
// Keys
/// Create a new pk descriptor
pub fn new_pk(pk: Pk) -> Self {
// roundabout way to constuct `c:pk_k(pk)`
let ms: Miniscript<Pk, BareCtx> =
Miniscript::from_ast(miniscript::decode::Terminal::Check(Arc::new(
Miniscript::from_ast(miniscript::decode::Terminal::PkK(pk))
.expect("Type check cannot fail"),
)))
.expect("Type check cannot fail");
Descriptor::Bare(Bare::new(ms).expect("Context checks cannot fail for p2pk"))
}
/// Create a new PkH descriptor
pub fn new_pkh(pk: Pk) -> Self {
Descriptor::Pkh(Pkh::new(pk))
}
/// Create a new Wpkh descriptor
/// Will return Err if uncompressed key is used
pub fn new_wpkh(pk: Pk) -> Result<Self, Error> {
Ok(Descriptor::Wpkh(Wpkh::new(pk)?))
}
/// Create a new sh wrapped wpkh from `Pk`.
/// Errors when uncompressed keys are supplied
pub fn new_sh_wpkh(pk: Pk) -> Result<Self, Error> {
Ok(Descriptor::Sh(Sh::new_wpkh(pk)?))
}
// Miniscripts
/// Create a new sh for a given redeem script
/// Errors when miniscript exceeds resource limits under p2sh context
/// or does not type check at the top level
pub fn new_sh(ms: Miniscript<Pk, Legacy>) -> Result<Self, Error> {
Ok(Descriptor::Sh(Sh::new(ms)?))
}
/// Create a new wsh descriptor from witness script
/// Errors when miniscript exceeds resource limits under p2sh context
/// or does not type check at the top level
pub fn new_wsh(ms: Miniscript<Pk, Segwitv0>) -> Result<Self, Error> {
Ok(Descriptor::Wsh(Wsh::new(ms)?))
}
/// Create a new sh wrapped wsh descriptor with witness script
/// Errors when miniscript exceeds resource limits under wsh context
/// or does not type check at the top level
pub fn new_sh_wsh(ms: Miniscript<Pk, Segwitv0>) -> Result<Self, Error> {
Ok(Descriptor::Sh(Sh::new_wsh(ms)?))
}
/// Create a new bare descriptor from witness script
/// Errors when miniscript exceeds resource limits under bare context
/// or does not type check at the top level
pub fn new_bare(ms: Miniscript<Pk, BareCtx>) -> Result<Self, Error> {
Ok(Descriptor::Bare(Bare::new(ms)?))
}
// Wrap with sh
/// Create a new sh wrapper for the given wpkh descriptor
pub fn new_sh_with_wpkh(wpkh: Wpkh<Pk>) -> Self {
Descriptor::Sh(Sh::new_with_wpkh(wpkh))
}
/// Create a new sh wrapper for the given wsh descriptor
pub fn new_sh_with_wsh(wsh: Wsh<Pk>) -> Self {
Descriptor::Sh(Sh::new_with_wsh(wsh))
}
// sorted multi
/// Create a new sh sortedmulti descriptor with threshold `k`
/// and Vec of `pks`.
/// Errors when miniscript exceeds resource limits under p2sh context
pub fn new_sh_sortedmulti(k: usize, pks: Vec<Pk>) -> Result<Self, Error> {
Ok(Descriptor::Sh(Sh::new_sortedmulti(k, pks)?))
}
/// Create a new sh wrapped wsh sortedmulti descriptor from threshold
/// `k` and Vec of `pks`
/// Errors when miniscript exceeds resource limits under segwit context
pub fn new_sh_wsh_sortedmulti(k: usize, pks: Vec<Pk>) -> Result<Self, Error> {
Ok(Descriptor::Sh(Sh::new_wsh_sortedmulti(k, pks)?))
}
/// Create a new wsh sorted multi descriptor
/// Errors when miniscript exceeds resource limits under p2sh context
pub fn new_wsh_sortedmulti(k: usize, pks: Vec<Pk>) -> Result<Self, Error> {
Ok(Descriptor::Wsh(Wsh::new_sortedmulti(k, pks)?))
}
/// Create new tr descriptor
/// Errors when miniscript exceeds resource limits under Tap context
pub fn new_tr(key: Pk, script: Option<tr::TapTree<Pk>>) -> Result<Self, Error> {
Ok(Descriptor::Tr(Tr::new(key, script)?))
}
/// Get the [DescriptorType] of [Descriptor]
pub fn desc_type(&self) -> DescriptorType {
match *self {
Descriptor::Bare(ref _bare) => DescriptorType::Bare,
Descriptor::Pkh(ref _pkh) => DescriptorType::Pkh,
Descriptor::Wpkh(ref _wpkh) => DescriptorType::Wpkh,
Descriptor::Sh(ref sh) => match sh.as_inner() {
ShInner::Wsh(ref wsh) => match wsh.as_inner() {
WshInner::SortedMulti(ref _smv) => DescriptorType::ShWshSortedMulti,
WshInner::Ms(ref _ms) => DescriptorType::ShWsh,
},
ShInner::Wpkh(ref _wpkh) => DescriptorType::ShWpkh,
ShInner::SortedMulti(ref _smv) => DescriptorType::ShSortedMulti,
ShInner::Ms(ref _ms) => DescriptorType::Sh,
},
Descriptor::Wsh(ref wsh) => match wsh.as_inner() {
WshInner::SortedMulti(ref _smv) => DescriptorType::WshSortedMulti,
WshInner::Ms(ref _ms) => DescriptorType::Wsh,
},
Descriptor::Tr(ref _tr) => DescriptorType::Tr,
}
}
/// Checks whether the descriptor is safe.
///
/// Checks whether all the spend paths in the descriptor are possible on the
/// bitcoin network under the current standardness and consensus rules. Also
/// checks whether the descriptor requires signatures on all spend paths and
/// whether the script is malleable.
///
/// In general, all the guarantees of miniscript hold only for safe scripts.
/// The signer may not be able to find satisfactions even if one exists.
pub fn sanity_check(&self) -> Result<(), Error> {
match *self {
Descriptor::Bare(ref bare) => bare.sanity_check(),
Descriptor::Pkh(_) => Ok(()),
Descriptor::Wpkh(ref wpkh) => wpkh.sanity_check(),
Descriptor::Wsh(ref wsh) => wsh.sanity_check(),
Descriptor::Sh(ref sh) => sh.sanity_check(),
Descriptor::Tr(ref tr) => tr.sanity_check(),
}
}
/// Computes an upper bound on the difference in weight between a
/// non-satisfied `TxIn` and a satisfied `TxIn`.
///
/// A non-satisfied `TxIn` contains the `scriptSigLen` varint recording the
/// value 0 (which is 4WU) and also the `witnessStackLen` for transactions
/// that have at least one witness spend, which will also record the value 0
/// (which is 1WU).
///
/// Hence, "satisfaction weight" contains the additional varint weight of
/// `scriptSigLen` and `witnessStackLen` (which occurs when the varint value
/// increases over the 1byte threshold), and also the weights of `scriptSig`
/// and the rest of the `witnessField` (which is the stack items and the
/// stack-item-len varints of each item).
///
/// This assumes a ec-signatures is always 73 bytes, and the sighash prefix
/// is always included (+1 byte).
///
/// # Errors
/// When the descriptor is impossible to safisfy (ex: sh(OP_FALSE)).
pub fn max_satisfaction_weight(&self) -> Result<usize, Error> {
let weight = match *self {
Descriptor::Bare(ref bare) => bare.max_satisfaction_weight()?,
Descriptor::Pkh(ref pkh) => pkh.max_satisfaction_weight(),
Descriptor::Wpkh(ref wpkh) => wpkh.max_satisfaction_weight(),
Descriptor::Wsh(ref wsh) => wsh.max_satisfaction_weight()?,
Descriptor::Sh(ref sh) => sh.max_satisfaction_weight()?,
Descriptor::Tr(ref tr) => tr.max_satisfaction_weight()?,
};
Ok(weight)
}
}
impl<Pk: MiniscriptKey + ToPublicKey> Descriptor<Pk> {
/// Computes the Bitcoin address of the descriptor, if one exists
///
/// Some descriptors like pk() don't have an address.
///
/// # Errors
/// For raw/bare descriptors that don't have an address.
pub fn address(&self, network: Network) -> Result<Address, Error> {
match *self {
Descriptor::Bare(_) => Err(Error::BareDescriptorAddr),
Descriptor::Pkh(ref pkh) => Ok(pkh.address(network)),
Descriptor::Wpkh(ref wpkh) => Ok(wpkh.address(network)),
Descriptor::Wsh(ref wsh) => Ok(wsh.address(network)),
Descriptor::Sh(ref sh) => Ok(sh.address(network)),
Descriptor::Tr(ref tr) => Ok(tr.address(network)),
}
}
/// Computes the scriptpubkey of the descriptor.
pub fn script_pubkey(&self) -> Script {
match *self {
Descriptor::Bare(ref bare) => bare.script_pubkey(),
Descriptor::Pkh(ref pkh) => pkh.script_pubkey(),
Descriptor::Wpkh(ref wpkh) => wpkh.script_pubkey(),
Descriptor::Wsh(ref wsh) => wsh.script_pubkey(),
Descriptor::Sh(ref sh) => sh.script_pubkey(),
Descriptor::Tr(ref tr) => tr.script_pubkey(),
}
}
/// Computes the scriptSig that will be in place for an unsigned input
/// spending an output with this descriptor. For pre-segwit descriptors,
/// which use the scriptSig for signatures, this returns the empty script.
///
/// This is used in Segwit transactions to produce an unsigned transaction
/// whose txid will not change during signing (since only the witness data
/// will change).
pub fn unsigned_script_sig(&self) -> Script {
match *self {
Descriptor::Bare(_) => Script::new(),
Descriptor::Pkh(_) => Script::new(),
Descriptor::Wpkh(_) => Script::new(),
Descriptor::Wsh(_) => Script::new(),
Descriptor::Sh(ref sh) => sh.unsigned_script_sig(),
Descriptor::Tr(_) => Script::new(),
}
}
/// Computes the the underlying script before any hashing is done. For
/// `Bare`, `Pkh` and `Wpkh` this is the scriptPubkey; for `ShWpkh` and `Sh`
/// this is the redeemScript; for the others it is the witness script.
///
/// # Errors
/// If the descriptor is a taproot descriptor.
pub fn explicit_script(&self) -> Result<Script, Error> {
match *self {
Descriptor::Bare(ref bare) => Ok(bare.script_pubkey()),
Descriptor::Pkh(ref pkh) => Ok(pkh.script_pubkey()),
Descriptor::Wpkh(ref wpkh) => Ok(wpkh.script_pubkey()),
Descriptor::Wsh(ref wsh) => Ok(wsh.inner_script()),
Descriptor::Sh(ref sh) => Ok(sh.inner_script()),
Descriptor::Tr(_) => Err(Error::TrNoScriptCode),
}
}
/// Computes the `scriptCode` of a transaction output.
///
/// The `scriptCode` is the Script of the previous transaction output being
/// serialized in the sighash when evaluating a `CHECKSIG` & co. OP code.
///
/// # Errors
/// If the descriptor is a taproot descriptor.
pub fn script_code(&self) -> Result<Script, Error> {
match *self {
Descriptor::Bare(ref bare) => Ok(bare.ecdsa_sighash_script_code()),
Descriptor::Pkh(ref pkh) => Ok(pkh.ecdsa_sighash_script_code()),
Descriptor::Wpkh(ref wpkh) => Ok(wpkh.ecdsa_sighash_script_code()),
Descriptor::Wsh(ref wsh) => Ok(wsh.ecdsa_sighash_script_code()),
Descriptor::Sh(ref sh) => Ok(sh.ecdsa_sighash_script_code()),
Descriptor::Tr(_) => Err(Error::TrNoScriptCode),
}
}
/// Returns satisfying non-malleable witness and scriptSig to spend an
/// output controlled by the given descriptor if it possible to
/// construct one using the satisfier S.
pub fn get_satisfaction<S>(&self, satisfier: S) -> Result<(Vec<Vec<u8>>, Script), Error>
where
S: Satisfier<Pk>,
{
match *self {
Descriptor::Bare(ref bare) => bare.get_satisfaction(satisfier),
Descriptor::Pkh(ref pkh) => pkh.get_satisfaction(satisfier),
Descriptor::Wpkh(ref wpkh) => wpkh.get_satisfaction(satisfier),
Descriptor::Wsh(ref wsh) => wsh.get_satisfaction(satisfier),
Descriptor::Sh(ref sh) => sh.get_satisfaction(satisfier),
Descriptor::Tr(ref tr) => tr.get_satisfaction(satisfier),
}
}
/// Returns a possilbly mallable satisfying non-malleable witness and scriptSig to spend an
/// output controlled by the given descriptor if it possible to
/// construct one using the satisfier S.
pub fn get_satisfaction_mall<S>(&self, satisfier: S) -> Result<(Vec<Vec<u8>>, Script), Error>
where
S: Satisfier<Pk>,
{
match *self {
Descriptor::Bare(ref bare) => bare.get_satisfaction_mall(satisfier),
Descriptor::Pkh(ref pkh) => pkh.get_satisfaction_mall(satisfier),
Descriptor::Wpkh(ref wpkh) => wpkh.get_satisfaction_mall(satisfier),
Descriptor::Wsh(ref wsh) => wsh.get_satisfaction_mall(satisfier),
Descriptor::Sh(ref sh) => sh.get_satisfaction_mall(satisfier),
Descriptor::Tr(ref tr) => tr.get_satisfaction_mall(satisfier),
}
}
/// Attempts to produce a non-malleable satisfying witness and scriptSig to spend an
/// output controlled by the given descriptor; add the data to a given
/// `TxIn` output.
pub fn satisfy<S>(&self, txin: &mut TxIn, satisfier: S) -> Result<(), Error>
where
S: Satisfier<Pk>,
{
let (witness, script_sig) = self.get_satisfaction(satisfier)?;
txin.witness = Witness::from_vec(witness);
txin.script_sig = script_sig;
Ok(())
}
}
impl<P, Q> TranslatePk<P, Q> for Descriptor<P>
where
P: MiniscriptKey,
Q: MiniscriptKey,
{
type Output = Descriptor<Q>;
/// Converts a descriptor using abstract keys to one using specific keys.
fn translate_pk<T, E>(&self, t: &mut T) -> Result<Self::Output, E>
where
T: Translator<P, Q, E>,
{
let desc = match *self {
Descriptor::Bare(ref bare) => Descriptor::Bare(bare.translate_pk(t)?),
Descriptor::Pkh(ref pk) => Descriptor::Pkh(pk.translate_pk(t)?),
Descriptor::Wpkh(ref pk) => Descriptor::Wpkh(pk.translate_pk(t)?),
Descriptor::Sh(ref sh) => Descriptor::Sh(sh.translate_pk(t)?),
Descriptor::Wsh(ref wsh) => Descriptor::Wsh(wsh.translate_pk(t)?),
Descriptor::Tr(ref tr) => Descriptor::Tr(tr.translate_pk(t)?),
};
Ok(desc)
}
}
impl<Pk: MiniscriptKey> ForEachKey<Pk> for Descriptor<Pk> {
fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, pred: F) -> bool
where
Pk: 'a,
{
match *self {
Descriptor::Bare(ref bare) => bare.for_each_key(pred),
Descriptor::Pkh(ref pkh) => pkh.for_each_key(pred),
Descriptor::Wpkh(ref wpkh) => wpkh.for_each_key(pred),
Descriptor::Wsh(ref wsh) => wsh.for_each_key(pred),
Descriptor::Sh(ref sh) => sh.for_each_key(pred),
Descriptor::Tr(ref tr) => tr.for_each_key(pred),
}
}
}
impl Descriptor<DescriptorPublicKey> {
/// Whether or not the descriptor has any wildcards
#[deprecated(note = "use has_wildcards instead")]
pub fn is_deriveable(&self) -> bool {
self.has_wildcard()
}
/// Whether or not the descriptor has any wildcards i.e. `/*`.
pub fn has_wildcard(&self) -> bool {
self.for_any_key(|key| key.has_wildcard())
}
/// Replaces all wildcards (i.e. `/*`) in the descriptor with a particular derivation index,
/// turning it into a *definite* descriptor.
///
/// # Panics
///
/// If index ≥ 2^31
pub fn at_derivation_index(&self, index: u32) -> Descriptor<DefiniteDescriptorKey> {
struct Derivator(u32);
impl Translator<DescriptorPublicKey, DefiniteDescriptorKey, ()> for Derivator {
fn pk(&mut self, pk: &DescriptorPublicKey) -> Result<DefiniteDescriptorKey, ()> {
Ok(pk.clone().at_derivation_index(self.0))
}
translate_hash_clone!(DescriptorPublicKey, DescriptorPublicKey, ());
}
self.translate_pk(&mut Derivator(index))
.expect("BIP 32 key index substitution cannot fail")
}
#[deprecated(note = "use at_derivation_index instead")]
/// Deprecated name for [`at_derivation_index`].
pub fn derive(&self, index: u32) -> Descriptor<DefiniteDescriptorKey> {
self.at_derivation_index(index)
}
/// Convert all the public keys in the descriptor to [`bitcoin::PublicKey`] by deriving them or
/// otherwise converting them. All [`bitcoin::XOnlyPublicKey`]s are converted to by adding a
/// default(0x02) y-coordinate.
///
/// This is a shorthand for:
///
/// ```
/// # use miniscript::{Descriptor, DescriptorPublicKey, bitcoin::secp256k1::Secp256k1};
/// # use core::str::FromStr;
/// # let descriptor = Descriptor::<DescriptorPublicKey>::from_str("tr(xpub6BgBgsespWvERF3LHQu6CnqdvfEvtMcQjYrcRzx53QJjSxarj2afYWcLteoGVky7D3UKDP9QyrLprQ3VCECoY49yfdDEHGCtMMj92pReUsQ/0/*)")
/// .expect("Valid ranged descriptor");
/// # let index = 42;
/// # let secp = Secp256k1::verification_only();
/// let derived_descriptor = descriptor.at_derivation_index(index).derived_descriptor(&secp);
/// # assert_eq!(descriptor.derived_descriptor(&secp, index), derived_descriptor);
/// ```
///
/// and is only here really here for backwards compatbility.
/// See [`at_derivation_index`] and `[derived_descriptor`] for more documentation.
///
/// [`at_derivation_index`]: Self::at_derivation_index
/// [`derived_descriptor`]: crate::DerivedDescriptor::derived_descriptor
///
/// # Errors
///
/// This function will return an error if hardened derivation is attempted.
pub fn derived_descriptor<C: secp256k1::Verification>(
&self,
secp: &secp256k1::Secp256k1<C>,
index: u32,
) -> Result<Descriptor<bitcoin::PublicKey>, ConversionError> {
self.at_derivation_index(index).derived_descriptor(&secp)
}
/// Parse a descriptor that may contain secret keys
///
/// Internally turns every secret key found into the corresponding public key and then returns a
/// a descriptor that only contains public keys and a map to lookup the secret key given a public key.
pub fn parse_descriptor<C: secp256k1::Signing>(
secp: &secp256k1::Secp256k1<C>,
s: &str,
) -> Result<(Descriptor<DescriptorPublicKey>, KeyMap), Error> {
fn parse_key<C: secp256k1::Signing>(
s: &String,
key_map: &mut KeyMap,
secp: &secp256k1::Secp256k1<C>,
) -> Result<DescriptorPublicKey, Error> {
let (public_key, secret_key) = match DescriptorSecretKey::from_str(s) {
Ok(sk) => (
sk.to_public(secp)
.map_err(|e| Error::Unexpected(e.to_string()))?,
Some(sk),
),
Err(_) => (
DescriptorPublicKey::from_str(s)
.map_err(|e| Error::Unexpected(e.to_string()))?,
None,
),
};
if let Some(secret_key) = secret_key {
key_map.insert(public_key.clone(), secret_key);
}
Ok(public_key)
}
let mut keymap_pk = KeyMapWrapper(HashMap::new(), secp);
struct KeyMapWrapper<'a, C: secp256k1::Signing>(KeyMap, &'a secp256k1::Secp256k1<C>);
impl<'a, C: secp256k1::Signing> Translator<String, DescriptorPublicKey, Error>
for KeyMapWrapper<'a, C>
{
fn pk(&mut self, pk: &String) -> Result<DescriptorPublicKey, Error> {
parse_key(pk, &mut self.0, self.1)
}
fn sha256(&mut self, sha256: &String) -> Result<sha256::Hash, Error> {
let hash =
sha256::Hash::from_str(sha256).map_err(|e| Error::Unexpected(e.to_string()))?;
Ok(hash)
}
fn hash256(&mut self, hash256: &String) -> Result<hash256::Hash, Error> {
let hash = hash256::Hash::from_str(hash256)
.map_err(|e| Error::Unexpected(e.to_string()))?;
Ok(hash)
}
fn ripemd160(&mut self, ripemd160: &String) -> Result<ripemd160::Hash, Error> {
let hash = ripemd160::Hash::from_str(ripemd160)
.map_err(|e| Error::Unexpected(e.to_string()))?;
Ok(hash)
}
fn hash160(&mut self, hash160: &String) -> Result<hash160::Hash, Error> {
let hash = hash160::Hash::from_str(hash160)
.map_err(|e| Error::Unexpected(e.to_string()))?;
Ok(hash)
}
}
let descriptor = Descriptor::<String>::from_str(s)?;
let descriptor = descriptor
.translate_pk(&mut keymap_pk)
.map_err(|e| Error::Unexpected(e.to_string()))?;
Ok((descriptor, keymap_pk.0))
}
/// Serialize a descriptor to string with its secret keys
pub fn to_string_with_secret(&self, key_map: &KeyMap) -> String {
struct KeyMapLookUp<'a>(&'a KeyMap);
impl<'a> Translator<DescriptorPublicKey, String, ()> for KeyMapLookUp<'a> {
fn pk(&mut self, pk: &DescriptorPublicKey) -> Result<String, ()> {
key_to_string(pk, self.0)
}
fn sha256(&mut self, sha256: &sha256::Hash) -> Result<String, ()> {
Ok(sha256.to_string())
}
fn hash256(&mut self, hash256: &hash256::Hash) -> Result<String, ()> {
Ok(hash256.to_string())
}
fn ripemd160(&mut self, ripemd160: &ripemd160::Hash) -> Result<String, ()> {
Ok(ripemd160.to_string())
}
fn hash160(&mut self, hash160: &hash160::Hash) -> Result<String, ()> {
Ok(hash160.to_string())
}
}
fn key_to_string(pk: &DescriptorPublicKey, key_map: &KeyMap) -> Result<String, ()> {
Ok(match key_map.get(pk) {
Some(secret) => secret.to_string(),
None => pk.to_string(),
})
}
let descriptor = self
.translate_pk(&mut KeyMapLookUp(key_map))
.expect("Translation to string cannot fail");
descriptor.to_string()
}
/// Utility method for deriving the descriptor at each index in a range to find one matching
/// `script_pubkey`.
///
/// If it finds a match then it returns the index it was derived at and the concrete
/// descriptor at that index. If the descriptor is non-derivable then it will simply check the
/// script pubkey against the descriptor and return it if it matches (in this case the index
/// returned will be meaningless).
pub fn find_derivation_index_for_spk<C: secp256k1::Verification>(
&self,
secp: &secp256k1::Secp256k1<C>,
script_pubkey: &Script,
range: Range<u32>,
) -> Result<Option<(u32, Descriptor<bitcoin::PublicKey>)>, ConversionError> {
let range = if self.has_wildcard() { range } else { 0..1 };
for i in range {
let concrete = self.derived_descriptor(secp, i)?;
if &concrete.script_pubkey() == script_pubkey {
return Ok(Some((i, concrete)));
}
}
Ok(None)
}
}
impl Descriptor<DefiniteDescriptorKey> {
/// Convert all the public keys in the descriptor to [`bitcoin::PublicKey`] by deriving them or
/// otherwise converting them. All [`bitcoin::XOnlyPublicKey`]s are converted to by adding a
/// default(0x02) y-coordinate.
///
/// # Examples
///
/// ```
/// use miniscript::descriptor::{Descriptor, DescriptorPublicKey};
/// use miniscript::bitcoin::secp256k1;
/// use std::str::FromStr;
///
/// // test from bip 86
/// let secp = secp256k1::Secp256k1::verification_only();
/// let descriptor = Descriptor::<DescriptorPublicKey>::from_str("tr(xpub6BgBgsespWvERF3LHQu6CnqdvfEvtMcQjYrcRzx53QJjSxarj2afYWcLteoGVky7D3UKDP9QyrLprQ3VCECoY49yfdDEHGCtMMj92pReUsQ/0/*)")
/// .expect("Valid ranged descriptor");
/// let result = descriptor.at_derivation_index(0).derived_descriptor(&secp).expect("Non-hardened derivation");
/// assert_eq!(result.to_string(), "tr(03cc8a4bc64d897bddc5fbc2f670f7a8ba0b386779106cf1223c6fc5d7cd6fc115)#6qm9h8ym");
/// ```
///
/// # Errors
///
/// This function will return an error if hardened derivation is attempted.
pub fn derived_descriptor<C: secp256k1::Verification>(
&self,
secp: &secp256k1::Secp256k1<C>,
) -> Result<Descriptor<bitcoin::PublicKey>, ConversionError> {
struct Derivator<'a, C: secp256k1::Verification>(&'a secp256k1::Secp256k1<C>);
impl<'a, C: secp256k1::Verification>
Translator<DefiniteDescriptorKey, bitcoin::PublicKey, ConversionError>
for Derivator<'a, C>
{
fn pk(
&mut self,
pk: &DefiniteDescriptorKey,
) -> Result<bitcoin::PublicKey, ConversionError> {
pk.derive_public_key(&self.0)
}
translate_hash_clone!(DefiniteDescriptorKey, bitcoin::PublicKey, ConversionError);
}
let derived = self.translate_pk(&mut Derivator(secp))?;
Ok(derived)
}
}
impl_from_tree!(
Descriptor<Pk>,
/// Parse an expression tree into a descriptor.
fn from_tree(top: &expression::Tree) -> Result<Descriptor<Pk>, Error> {
Ok(match (top.name, top.args.len() as u32) {
("pkh", 1) => Descriptor::Pkh(Pkh::from_tree(top)?),
("wpkh", 1) => Descriptor::Wpkh(Wpkh::from_tree(top)?),
("sh", 1) => Descriptor::Sh(Sh::from_tree(top)?),
("wsh", 1) => Descriptor::Wsh(Wsh::from_tree(top)?),
("tr", _) => Descriptor::Tr(Tr::from_tree(top)?),
_ => Descriptor::Bare(Bare::from_tree(top)?),
})
}
);
impl_from_str!(
Descriptor<Pk>,
type Err = Error;,
fn from_str(s: &str) -> Result<Descriptor<Pk>, Error> {
// tr tree parsing has special code
// Tr::from_str will check the checksum
// match "tr(" to handle more extensibly
if s.starts_with("tr(") {
Ok(Descriptor::Tr(Tr::from_str(s)?))
} else {
let desc_str = verify_checksum(s)?;
let top = expression::Tree::from_str(desc_str)?;
expression::FromTree::from_tree(&top)
}
}
);
impl<Pk: MiniscriptKey> fmt::Debug for Descriptor<Pk> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Descriptor::Bare(ref sub) => write!(f, "{:?}", sub),
Descriptor::Pkh(ref pkh) => write!(f, "{:?}", pkh),
Descriptor::Wpkh(ref wpkh) => write!(f, "{:?}", wpkh),
Descriptor::Sh(ref sub) => write!(f, "{:?}", sub),
Descriptor::Wsh(ref sub) => write!(f, "{:?}", sub),
Descriptor::Tr(ref tr) => write!(f, "{:?}", tr),
}
}
}
impl<Pk: MiniscriptKey> fmt::Display for Descriptor<Pk> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Descriptor::Bare(ref sub) => write!(f, "{}", sub),
Descriptor::Pkh(ref pkh) => write!(f, "{}", pkh),
Descriptor::Wpkh(ref wpkh) => write!(f, "{}", wpkh),
Descriptor::Sh(ref sub) => write!(f, "{}", sub),
Descriptor::Wsh(ref sub) => write!(f, "{}", sub),
Descriptor::Tr(ref tr) => write!(f, "{}", tr),
}
}
}
serde_string_impl_pk!(Descriptor, "a script descriptor");
#[cfg(test)]
mod tests {
use core::cmp;
use core::str::FromStr;
use bitcoin::blockdata::opcodes::all::{OP_CLTV, OP_CSV};
use bitcoin::blockdata::script::Instruction;
use bitcoin::blockdata::{opcodes, script};
use bitcoin::hashes::hex::{FromHex, ToHex};
use bitcoin::hashes::{hash160, sha256};
use bitcoin::util::bip32;
use bitcoin::{self, secp256k1, EcdsaSighashType, PublicKey, Sequence};
use super::checksum::desc_checksum;
use super::tr::Tr;
use super::*;
use crate::descriptor::key::Wildcard;
use crate::descriptor::{DescriptorPublicKey, DescriptorSecretKey, DescriptorXKey, SinglePub};
#[cfg(feature = "compiler")]
use crate::policy;
use crate::{hex_script, Descriptor, DummyKey, Error, Miniscript, Satisfier};
type StdDescriptor = Descriptor<PublicKey>;
const TEST_PK: &'static str =
"pk(020000000000000000000000000000000000000000000000000000000000000002)";
impl cmp::PartialEq for DescriptorSecretKey {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(&DescriptorSecretKey::Single(ref a), &DescriptorSecretKey::Single(ref b)) => {
a.origin == b.origin && a.key == b.key
}
(&DescriptorSecretKey::XPrv(ref a), &DescriptorSecretKey::XPrv(ref b)) => {
a.origin == b.origin
&& a.xkey == b.xkey
&& a.derivation_path == b.derivation_path
&& a.wildcard == b.wildcard
}
_ => false,
}
}
}
fn roundtrip_descriptor(s: &str) {
let desc = Descriptor::<DummyKey>::from_str(&s).unwrap();
let output = desc.to_string();
let normalize_aliases = s.replace("c:pk_k(", "pk(").replace("c:pk_h(", "pkh(");
assert_eq!(
format!(
"{}#{}",
&normalize_aliases,
desc_checksum(&normalize_aliases).unwrap()
),
output
);
}
#[test]
fn desc_rtt_tests() {
roundtrip_descriptor("c:pk_k()");
roundtrip_descriptor("wsh(pk())");
roundtrip_descriptor("wsh(c:pk_k())");
roundtrip_descriptor("c:pk_h()");
}
#[test]
fn parse_descriptor() {
StdDescriptor::from_str("(").unwrap_err();
StdDescriptor::from_str("(x()").unwrap_err();
StdDescriptor::from_str("(\u{7f}()3").unwrap_err();
StdDescriptor::from_str("pk()").unwrap_err();
StdDescriptor::from_str("nl:0").unwrap_err(); //issue 63
let compressed_pk = DummyKey.to_string();
assert_eq!(
StdDescriptor::from_str("sh(sortedmulti)")
.unwrap_err()
.to_string(),
"unexpected «no arguments given for sortedmulti»"
); //issue 202
assert_eq!(
StdDescriptor::from_str(&format!("sh(sortedmulti(2,{}))", compressed_pk))
.unwrap_err()
.to_string(),
"unexpected «higher threshold than there were keys in sortedmulti»"
); //issue 202
StdDescriptor::from_str(TEST_PK).unwrap();
let uncompressed_pk =
"0414fc03b8df87cd7b872996810db8458d61da8448e531569c8517b469a119d267be5645686309c6e6736dbd93940707cc9143d3cf29f1b877ff340e2cb2d259cf";
// Context tests
StdDescriptor::from_str(&format!("pk({})", uncompressed_pk)).unwrap();
StdDescriptor::from_str(&format!("pkh({})", uncompressed_pk)).unwrap();
StdDescriptor::from_str(&format!("sh(pk({}))", uncompressed_pk)).unwrap();
StdDescriptor::from_str(&format!("wpkh({})", uncompressed_pk)).unwrap_err();
StdDescriptor::from_str(&format!("sh(wpkh({}))", uncompressed_pk)).unwrap_err();
StdDescriptor::from_str(&format!("wsh(pk{})", uncompressed_pk)).unwrap_err();
StdDescriptor::from_str(&format!("sh(wsh(pk{}))", uncompressed_pk)).unwrap_err();
StdDescriptor::from_str(&format!(
"or_i(pk({}),pk({}))",
uncompressed_pk, uncompressed_pk
))
.unwrap_err();
}
#[test]
pub fn script_pubkey() {
let bare = StdDescriptor::from_str(&format!(
"multi(1,020000000000000000000000000000000000000000000000000000000000000002)"
))
.unwrap();
assert_eq!(
bare.script_pubkey(),
hex_script(
"512102000000000000000000000000000000000000000000000000000000000000000251ae"
)
);
assert_eq!(
bare.address(Network::Bitcoin).unwrap_err().to_string(),
"Bare descriptors don't have address"
);
let pk = StdDescriptor::from_str(TEST_PK).unwrap();
assert_eq!(
pk.script_pubkey(),
Script::from(vec![
0x21, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xac,
])
);
let pkh = StdDescriptor::from_str(
"pkh(\
020000000000000000000000000000000000000000000000000000000000000002\
)",
)
.unwrap();
assert_eq!(
pkh.script_pubkey(),
script::Builder::new()
.push_opcode(opcodes::all::OP_DUP)
.push_opcode(opcodes::all::OP_HASH160)
.push_slice(
&hash160::Hash::from_hex("84e9ed95a38613f0527ff685a9928abe2d4754d4",).unwrap()
[..]
)
.push_opcode(opcodes::all::OP_EQUALVERIFY)
.push_opcode(opcodes::all::OP_CHECKSIG)
.into_script()
);
assert_eq!(
pkh.address(Network::Bitcoin,).unwrap().to_string(),
"1D7nRvrRgzCg9kYBwhPH3j3Gs6SmsRg3Wq"
);