forked from rust-bitcoin/rust-miniscript
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmod.rs
1690 lines (1537 loc) · 68.3 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
// SPDX-License-Identifier: CC0-1.0
//! # Partially-Signed Bitcoin Transactions
//!
//! This module implements the Finalizer and Extractor roles defined in
//! BIP 174, PSBT, described at
//! `https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki`
//!
use core::convert::TryFrom;
use core::fmt;
#[cfg(feature = "std")]
use std::error;
use bitcoin::hashes::{hash160, sha256d, Hash};
use bitcoin::psbt::{self, Psbt};
#[cfg(not(test))] // https://github.com/rust-lang/rust/issues/121684
use bitcoin::secp256k1;
use bitcoin::secp256k1::{Secp256k1, VerifyOnly};
use bitcoin::sighash::{self, SighashCache};
use bitcoin::taproot::{self, ControlBlock, LeafVersion, TapLeafHash};
use bitcoin::{absolute, bip32, transaction, Script, ScriptBuf, Sequence};
use crate::miniscript::context::SigType;
use crate::prelude::*;
use crate::{
descriptor, interpreter, DefiniteDescriptorKey, Descriptor, DescriptorPublicKey, MiniscriptKey,
Preimage32, Satisfier, ToPublicKey, TranslatePk, Translator,
};
mod finalizer;
#[allow(deprecated)]
pub use self::finalizer::{finalize, finalize_mall, interpreter_check};
/// Error type for entire Psbt
#[derive(Debug)]
pub enum Error {
/// Input Error type
InputError(InputError, usize),
/// Wrong Input Count
WrongInputCount {
/// Input count in tx
in_tx: usize,
/// Input count in psbt
in_map: usize,
},
/// Psbt Input index out of bounds
InputIdxOutofBounds {
/// Inputs in pbst
psbt_inp: usize,
/// requested index
index: usize,
},
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::InputError(ref inp_err, index) => write!(f, "{} at index {}", inp_err, index),
Error::WrongInputCount { in_tx, in_map } => {
write!(f, "PSBT had {} inputs in transaction but {} inputs in map", in_tx, in_map)
}
Error::InputIdxOutofBounds { psbt_inp, index } => write!(
f,
"psbt input index {} out of bounds: psbt.inputs.len() {}",
index, psbt_inp
),
}
}
}
#[cfg(feature = "std")]
impl error::Error for Error {
fn cause(&self) -> Option<&dyn error::Error> {
use self::Error::*;
match self {
InputError(e, _) => Some(e),
WrongInputCount { .. } | InputIdxOutofBounds { .. } => None,
}
}
}
/// Error type for Pbst Input
#[derive(Debug)]
pub enum InputError {
/// Get the secp Errors directly
SecpErr(bitcoin::secp256k1::Error),
/// Key errors
KeyErr(bitcoin::key::Error),
/// Could not satisfy taproot descriptor
/// This error is returned when both script path and key paths could not be
/// satisfied. We cannot return a detailed error because we try all miniscripts
/// in script spend path, we cannot know which miniscript failed.
CouldNotSatisfyTr,
/// Error doing an interpreter-check on a finalized psbt
Interpreter(interpreter::Error),
/// Redeem script does not match the p2sh hash
InvalidRedeemScript {
/// Redeem script
redeem: ScriptBuf,
/// Expected p2sh Script
p2sh_expected: ScriptBuf,
},
/// Witness script does not match the p2wsh hash
InvalidWitnessScript {
/// Witness Script
witness_script: ScriptBuf,
/// Expected p2wsh script
p2wsh_expected: ScriptBuf,
},
/// Invalid sig
InvalidSignature {
/// The bitcoin public key
pubkey: bitcoin::PublicKey,
/// The (incorrect) signature
sig: Vec<u8>,
},
/// Pass through the underlying errors in miniscript
MiniscriptError(super::Error),
/// Missing redeem script for p2sh
MissingRedeemScript,
/// Missing witness
MissingWitness,
/// used for public key corresponding to pkh/wpkh
MissingPubkey,
/// Missing witness script for segwit descriptors
MissingWitnessScript,
///Missing both the witness and non-witness utxo
MissingUtxo,
/// Non empty Witness script for p2sh
NonEmptyWitnessScript,
/// Non empty Redeem script
NonEmptyRedeemScript,
/// Non Standard sighash type
NonStandardSighashType(sighash::NonStandardSighashTypeError),
/// Sighash did not match
WrongSighashFlag {
/// required sighash type
required: sighash::EcdsaSighashType,
/// the sighash type we got
got: sighash::EcdsaSighashType,
/// the corresponding publickey
pubkey: bitcoin::PublicKey,
},
}
#[cfg(feature = "std")]
impl error::Error for InputError {
fn cause(&self) -> Option<&dyn error::Error> {
use self::InputError::*;
match self {
CouldNotSatisfyTr
| InvalidRedeemScript { .. }
| InvalidWitnessScript { .. }
| InvalidSignature { .. }
| MissingRedeemScript
| MissingWitness
| MissingPubkey
| MissingWitnessScript
| MissingUtxo
| NonEmptyWitnessScript
| NonEmptyRedeemScript
| NonStandardSighashType(_)
| WrongSighashFlag { .. } => None,
SecpErr(e) => Some(e),
KeyErr(e) => Some(e),
Interpreter(e) => Some(e),
MiniscriptError(e) => Some(e),
}
}
}
impl fmt::Display for InputError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
InputError::InvalidSignature { ref pubkey, ref sig } => {
write!(f, "PSBT: bad signature {} for key {:?}", pubkey, sig)
}
InputError::KeyErr(ref e) => write!(f, "Key Err: {}", e),
InputError::Interpreter(ref e) => write!(f, "Interpreter: {}", e),
InputError::SecpErr(ref e) => write!(f, "Secp Err: {}", e),
InputError::InvalidRedeemScript { ref redeem, ref p2sh_expected } => write!(
f,
"Redeem script {} does not match the p2sh script {}",
redeem, p2sh_expected
),
InputError::InvalidWitnessScript { ref witness_script, ref p2wsh_expected } => write!(
f,
"Witness script {} does not match the p2wsh script {}",
witness_script, p2wsh_expected
),
InputError::MiniscriptError(ref e) => write!(f, "Miniscript Error: {}", e),
InputError::MissingWitness => write!(f, "PSBT is missing witness"),
InputError::MissingRedeemScript => write!(f, "PSBT is Redeem script"),
InputError::MissingUtxo => {
write!(f, "PSBT is missing both witness and non-witness UTXO")
}
InputError::MissingWitnessScript => write!(f, "PSBT is missing witness script"),
InputError::MissingPubkey => write!(f, "Missing pubkey for a pkh/wpkh"),
InputError::NonEmptyRedeemScript => {
write!(f, "PSBT has non-empty redeem script at for legacy transactions")
}
InputError::NonEmptyWitnessScript => {
write!(f, "PSBT has non-empty witness script at for legacy input")
}
InputError::WrongSighashFlag { required, got, pubkey } => write!(
f,
"PSBT: signature with key {:?} had \
sighashflag {:?} rather than required {:?}",
pubkey, got, required
),
InputError::CouldNotSatisfyTr => write!(f, "Could not satisfy Tr descriptor"),
InputError::NonStandardSighashType(ref e) => {
write!(f, "Non-standard sighash type {}", e)
}
}
}
}
#[doc(hidden)]
impl From<super::Error> for InputError {
fn from(e: super::Error) -> InputError { InputError::MiniscriptError(e) }
}
#[doc(hidden)]
impl From<bitcoin::secp256k1::Error> for InputError {
fn from(e: bitcoin::secp256k1::Error) -> InputError { InputError::SecpErr(e) }
}
#[doc(hidden)]
impl From<bitcoin::key::Error> for InputError {
fn from(e: bitcoin::key::Error) -> InputError { InputError::KeyErr(e) }
}
/// Psbt satisfier for at inputs at a particular index
/// Takes in &psbt because multiple inputs will share
/// the same psbt structure
/// All operations on this structure will panic if index
/// is more than number of inputs in pbst
pub struct PsbtInputSatisfier<'psbt> {
/// pbst
pub psbt: &'psbt Psbt,
/// input index
pub index: usize,
}
impl<'psbt> PsbtInputSatisfier<'psbt> {
/// create a new PsbtInputsatisfier from
/// psbt and index
pub fn new(psbt: &'psbt Psbt, index: usize) -> Self { Self { psbt, index } }
}
impl<'psbt, Pk: MiniscriptKey + ToPublicKey> Satisfier<Pk> for PsbtInputSatisfier<'psbt> {
fn lookup_tap_key_spend_sig(&self) -> Option<bitcoin::taproot::Signature> {
self.psbt.inputs[self.index].tap_key_sig
}
fn lookup_tap_leaf_script_sig(
&self,
pk: &Pk,
lh: &TapLeafHash,
) -> Option<bitcoin::taproot::Signature> {
self.psbt.inputs[self.index]
.tap_script_sigs
.get(&(pk.to_x_only_pubkey(), *lh))
.copied()
}
fn lookup_raw_pkh_pk(&self, pkh: &hash160::Hash) -> Option<bitcoin::PublicKey> {
self.psbt.inputs[self.index]
.bip32_derivation
.iter()
.find(|&(pubkey, _)| pubkey.to_pubkeyhash(SigType::Ecdsa) == *pkh)
.map(|(pubkey, _)| bitcoin::PublicKey::new(*pubkey))
}
fn lookup_tap_control_block_map(
&self,
) -> Option<&BTreeMap<ControlBlock, (bitcoin::ScriptBuf, LeafVersion)>> {
Some(&self.psbt.inputs[self.index].tap_scripts)
}
fn lookup_raw_pkh_tap_leaf_script_sig(
&self,
pkh: &(hash160::Hash, TapLeafHash),
) -> Option<(bitcoin::secp256k1::XOnlyPublicKey, bitcoin::taproot::Signature)> {
self.psbt.inputs[self.index]
.tap_script_sigs
.iter()
.find(|&((pubkey, lh), _sig)| {
pubkey.to_pubkeyhash(SigType::Schnorr) == pkh.0 && *lh == pkh.1
})
.map(|((x_only_pk, _leaf_hash), sig)| (*x_only_pk, *sig))
}
fn lookup_ecdsa_sig(&self, pk: &Pk) -> Option<bitcoin::ecdsa::Signature> {
self.psbt.inputs[self.index]
.partial_sigs
.get(&pk.to_public_key())
.copied()
}
fn lookup_raw_pkh_ecdsa_sig(
&self,
pkh: &hash160::Hash,
) -> Option<(bitcoin::PublicKey, bitcoin::ecdsa::Signature)> {
self.psbt.inputs[self.index]
.partial_sigs
.iter()
.find(|&(pubkey, _sig)| pubkey.to_pubkeyhash(SigType::Ecdsa) == *pkh)
.map(|(pk, sig)| (*pk, *sig))
}
fn check_after(&self, n: absolute::LockTime) -> bool {
if !self.psbt.unsigned_tx.input[self.index].enables_lock_time() {
return false;
}
let lock_time = self.psbt.unsigned_tx.lock_time;
<dyn Satisfier<Pk>>::check_after(&lock_time, n)
}
fn check_older(&self, n: Sequence) -> bool {
let seq = self.psbt.unsigned_tx.input[self.index].sequence;
// https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki
// Disable flag set => return true.
if !n.is_relative_lock_time() {
return true;
}
if self.psbt.unsigned_tx.version < transaction::Version::TWO || !seq.is_relative_lock_time()
{
return false;
}
<dyn Satisfier<Pk>>::check_older(&seq, n)
}
fn lookup_hash160(&self, h: &Pk::Hash160) -> Option<Preimage32> {
self.psbt.inputs[self.index]
.hash160_preimages
.get(&Pk::to_hash160(h))
.and_then(|x: &Vec<u8>| try_vec_as_preimage32(x))
}
fn lookup_sha256(&self, h: &Pk::Sha256) -> Option<Preimage32> {
self.psbt.inputs[self.index]
.sha256_preimages
.get(&Pk::to_sha256(h))
.and_then(|x: &Vec<u8>| try_vec_as_preimage32(x))
}
fn lookup_hash256(&self, h: &Pk::Hash256) -> Option<Preimage32> {
self.psbt.inputs[self.index]
.hash256_preimages
.get(&sha256d::Hash::from_byte_array(Pk::to_hash256(h).to_byte_array())) // upstream psbt operates on hash256
.and_then(|x: &Vec<u8>| try_vec_as_preimage32(x))
}
fn lookup_ripemd160(&self, h: &Pk::Ripemd160) -> Option<Preimage32> {
self.psbt.inputs[self.index]
.ripemd160_preimages
.get(&Pk::to_ripemd160(h))
.and_then(|x: &Vec<u8>| try_vec_as_preimage32(x))
}
}
fn try_vec_as_preimage32(vec: &[u8]) -> Option<Preimage32> {
if vec.len() == 32 {
let mut arr = [0u8; 32];
arr.copy_from_slice(vec);
Some(arr)
} else {
None
}
}
// Basic sanity checks on psbts.
// rust-bitcoin TODO: (Long term)
// Brainstorm about how we can enforce these in type system while having a nice API
fn sanity_check(psbt: &Psbt) -> Result<(), Error> {
if psbt.unsigned_tx.input.len() != psbt.inputs.len() {
return Err(Error::WrongInputCount {
in_tx: psbt.unsigned_tx.input.len(),
in_map: psbt.inputs.len(),
});
}
// Check well-formedness of input data
for (index, input) in psbt.inputs.iter().enumerate() {
// TODO: fix this after https://github.com/rust-bitcoin/rust-bitcoin/issues/838
let target_ecdsa_sighash_ty = match input.sighash_type {
Some(psbt_hash_ty) => psbt_hash_ty
.ecdsa_hash_ty()
.map_err(|e| Error::InputError(InputError::NonStandardSighashType(e), index))?,
None => sighash::EcdsaSighashType::All,
};
for (key, ecdsa_sig) in &input.partial_sigs {
let flag = sighash::EcdsaSighashType::from_standard(ecdsa_sig.hash_ty as u32).map_err(
|_| {
Error::InputError(
InputError::Interpreter(interpreter::Error::NonStandardSighash(
ecdsa_sig.to_vec(),
)),
index,
)
},
)?;
if target_ecdsa_sighash_ty != flag {
return Err(Error::InputError(
InputError::WrongSighashFlag {
required: target_ecdsa_sighash_ty,
got: flag,
pubkey: *key,
},
index,
));
}
// Signatures are well-formed in psbt partial sigs
}
}
Ok(())
}
/// Additional operations for miniscript descriptors for various psbt roles.
/// Note that these APIs would generally error when used on scripts that are not
/// miniscripts.
pub trait PsbtExt {
/// Finalize the psbt. This function takes in a mutable reference to psbt
/// and populates the final_witness and final_scriptsig
/// for all miniscript inputs.
///
/// Finalizes all inputs that it can finalize, and returns an error for each input
/// that it cannot finalize. Also performs a sanity interpreter check on the
/// finalized psbt which involves checking the signatures/ preimages/timelocks.
///
/// Input finalization also fails if it is not possible to satisfy any of the inputs non-malleably
/// See [finalizer::finalize_mall] if you want to allow malleable satisfactions
///
/// For finalizing individual inputs, see also [`PsbtExt::finalize_inp`]
///
/// # Errors:
///
/// - A vector of errors, one of each of failed finalized input
fn finalize_mut<C: secp256k1::Verification>(
&mut self,
secp: &secp256k1::Secp256k1<C>,
) -> Result<(), Vec<Error>>;
/// Same as [`PsbtExt::finalize_mut`], but does not mutate the input psbt and
/// returns a new psbt
///
/// # Errors:
///
/// - Returns a mutated psbt with all inputs `finalize_mut` could finalize
/// - A vector of input errors, one of each of failed finalized input
fn finalize<C: secp256k1::Verification>(
self,
secp: &secp256k1::Secp256k1<C>,
) -> Result<Psbt, (Psbt, Vec<Error>)>;
/// Same as [PsbtExt::finalize_mut], but allows for malleable satisfactions
fn finalize_mall_mut<C: secp256k1::Verification>(
&mut self,
secp: &Secp256k1<C>,
) -> Result<(), Vec<Error>>;
/// Same as [PsbtExt::finalize], but allows for malleable satisfactions
fn finalize_mall<C: secp256k1::Verification>(
self,
secp: &Secp256k1<C>,
) -> Result<Psbt, (Psbt, Vec<Error>)>;
/// Same as [`PsbtExt::finalize_mut`], but only tries to finalize a single input leaving other
/// inputs as is. Use this when not all of inputs that you are trying to
/// satisfy are miniscripts
///
/// # Errors:
///
/// - Input error detailing why the finalization failed. The psbt is not mutated when the finalization fails
fn finalize_inp_mut<C: secp256k1::Verification>(
&mut self,
secp: &secp256k1::Secp256k1<C>,
index: usize,
) -> Result<(), Error>;
/// Same as [`PsbtExt::finalize_inp_mut`], but does not mutate the psbt and returns a new one
///
/// # Errors:
/// Returns a tuple containing
/// - Original psbt
/// - Input Error detailing why the input finalization failed
fn finalize_inp<C: secp256k1::Verification>(
self,
secp: &secp256k1::Secp256k1<C>,
index: usize,
) -> Result<Psbt, (Psbt, Error)>;
/// Same as [`PsbtExt::finalize_inp_mut`], but allows for malleable satisfactions
fn finalize_inp_mall_mut<C: secp256k1::Verification>(
&mut self,
secp: &secp256k1::Secp256k1<C>,
index: usize,
) -> Result<(), Error>;
/// Same as [`PsbtExt::finalize_inp`], but allows for malleable satisfactions
fn finalize_inp_mall<C: secp256k1::Verification>(
self,
secp: &secp256k1::Secp256k1<C>,
index: usize,
) -> Result<Psbt, (Psbt, Error)>;
/// Psbt extractor as defined in BIP174 that takes in a psbt reference
/// and outputs a extracted bitcoin::Transaction
/// Also does the interpreter sanity check
/// Will error if the final ScriptSig or final Witness are missing
/// or the interpreter check fails.
fn extract<C: secp256k1::Verification>(
&self,
secp: &Secp256k1<C>,
) -> Result<bitcoin::Transaction, Error>;
/// Update PSBT input with a descriptor and check consistency of `*_utxo` fields.
///
/// This is the checked version of [`update_with_descriptor_unchecked`]. It checks that the
/// `witness_utxo` and `non_witness_utxo` are sane and have a `script_pubkey` that matches the
/// descriptor. In particular, it makes sure pre-segwit descriptors always have `non_witness_utxo`
/// present (and the txid matches). If both `witness_utxo` and `non_witness_utxo` are present
/// then it also checks they are consistent with each other.
///
/// Hint: because of the *[segwit bug]* some PSBT signers require that `non_witness_utxo` is
/// present on segwitv0 inputs regardless but this function doesn't enforce this so you will
/// have to do this check its presence manually (if it is present this *will* check its
/// validity).
///
/// The `descriptor` **must not have any wildcards** in it
/// otherwise an error will be returned however it can (and should) have extended keys in it.
///
/// [`update_with_descriptor_unchecked`]: PsbtInputExt::update_with_descriptor_unchecked
/// [segwit bug]: https://bitcoinhackers.org/@lukedashjr/104287698361196952
fn update_input_with_descriptor(
&mut self,
input_index: usize,
descriptor: &Descriptor<DefiniteDescriptorKey>,
) -> Result<(), UtxoUpdateError>;
/// Update PSBT output with a descriptor and check consistency of the output's `script_pubkey`
///
/// This is the checked version of [`update_with_descriptor_unchecked`]. It checks that the
/// output's `script_pubkey` matches the descriptor.
///
/// The `descriptor` **must not have any wildcards** in it
/// otherwise an error will be returned however it can (and should) have extended keys in it.
///
/// [`update_with_descriptor_unchecked`]: PsbtOutputExt::update_with_descriptor_unchecked
fn update_output_with_descriptor(
&mut self,
output_index: usize,
descriptor: &Descriptor<DefiniteDescriptorKey>,
) -> Result<(), OutputUpdateError>;
/// Get the sighash message(data to sign) at input index `idx`.
///
/// Based on the sighash
/// flag specified in the [`Psbt`] sighash field. If the input sighash flag psbt field is `None`
/// the [`sighash::TapSighashType::Default`](bitcoin::sighash::TapSighashType::Default) is chosen
/// for for taproot spends, otherwise [`EcdsaSighashType::All`](bitcoin::sighash::EcdsaSighashType::All) is chosen.
/// If the utxo at `idx` is a taproot output, returns a [`PsbtSighashMsg::TapSighash`] variant.
/// If the utxo at `idx` is a pre-taproot segwit output, returns a [`PsbtSighashMsg::SegwitV0Sighash`] variant.
/// For legacy outputs, returns a [`PsbtSighashMsg::LegacySighash`] variant.
/// The `tapleaf_hash` parameter can be used to specify which tapleaf script hash has to be computed. If
/// `tapleaf_hash` is [`None`], and the output is taproot output, the key spend hash is computed. This parameter must be
/// set to [`None`] while computing sighash for pre-taproot outputs.
/// The function also updates the sighash cache with transaction computed during sighash computation of this input
///
/// # Arguments:
///
/// * `idx`: The input index of psbt to sign
/// * `cache`: The [`SighashCache`] for used to cache/read previously cached computations
/// * `tapleaf_hash`: If the output is taproot, compute the sighash for this particular leaf.
///
/// [`SighashCache`]: bitcoin::sighash::SighashCache
fn sighash_msg<T: Borrow<bitcoin::Transaction>>(
&self,
idx: usize,
cache: &mut SighashCache<T>,
tapleaf_hash: Option<TapLeafHash>,
) -> Result<PsbtSighashMsg, SighashError>;
}
impl PsbtExt for Psbt {
fn finalize_mut<C: secp256k1::Verification>(
&mut self,
secp: &secp256k1::Secp256k1<C>,
) -> Result<(), Vec<Error>> {
// Actually construct the witnesses
let mut errors = vec![];
for index in 0..self.inputs.len() {
match finalizer::finalize_input(self, index, secp, /*allow_mall*/ false) {
Ok(..) => {}
Err(e) => {
errors.push(e);
}
}
}
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
fn finalize<C: secp256k1::Verification>(
mut self,
secp: &secp256k1::Secp256k1<C>,
) -> Result<Psbt, (Psbt, Vec<Error>)> {
match self.finalize_mut(secp) {
Ok(..) => Ok(self),
Err(e) => Err((self, e)),
}
}
fn finalize_mall_mut<C: secp256k1::Verification>(
&mut self,
secp: &secp256k1::Secp256k1<C>,
) -> Result<(), Vec<Error>> {
let mut errors = vec![];
for index in 0..self.inputs.len() {
match finalizer::finalize_input(self, index, secp, /*allow_mall*/ true) {
Ok(..) => {}
Err(e) => {
errors.push(e);
}
}
}
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
fn finalize_mall<C: secp256k1::Verification>(
mut self,
secp: &Secp256k1<C>,
) -> Result<Psbt, (Psbt, Vec<Error>)> {
match self.finalize_mall_mut(secp) {
Ok(..) => Ok(self),
Err(e) => Err((self, e)),
}
}
fn finalize_inp_mut<C: secp256k1::Verification>(
&mut self,
secp: &secp256k1::Secp256k1<C>,
index: usize,
) -> Result<(), Error> {
if index >= self.inputs.len() {
return Err(Error::InputIdxOutofBounds { psbt_inp: self.inputs.len(), index });
}
finalizer::finalize_input(self, index, secp, /*allow_mall*/ false)
}
fn finalize_inp<C: secp256k1::Verification>(
mut self,
secp: &secp256k1::Secp256k1<C>,
index: usize,
) -> Result<Psbt, (Psbt, Error)> {
match self.finalize_inp_mut(secp, index) {
Ok(..) => Ok(self),
Err(e) => Err((self, e)),
}
}
fn finalize_inp_mall_mut<C: secp256k1::Verification>(
&mut self,
secp: &secp256k1::Secp256k1<C>,
index: usize,
) -> Result<(), Error> {
if index >= self.inputs.len() {
return Err(Error::InputIdxOutofBounds { psbt_inp: self.inputs.len(), index });
}
finalizer::finalize_input(self, index, secp, /*allow_mall*/ false)
}
fn finalize_inp_mall<C: secp256k1::Verification>(
mut self,
secp: &secp256k1::Secp256k1<C>,
index: usize,
) -> Result<Psbt, (Psbt, Error)> {
match self.finalize_inp_mall_mut(secp, index) {
Ok(..) => Ok(self),
Err(e) => Err((self, e)),
}
}
fn extract<C: secp256k1::Verification>(
&self,
secp: &Secp256k1<C>,
) -> Result<bitcoin::Transaction, Error> {
sanity_check(self)?;
let mut ret = self.unsigned_tx.clone();
for (n, input) in self.inputs.iter().enumerate() {
if input.final_script_sig.is_none() && input.final_script_witness.is_none() {
return Err(Error::InputError(InputError::MissingWitness, n));
}
if let Some(witness) = input.final_script_witness.as_ref() {
ret.input[n].witness = witness.clone();
}
if let Some(script_sig) = input.final_script_sig.as_ref() {
ret.input[n].script_sig = script_sig.clone();
}
}
interpreter_check(self, secp)?;
Ok(ret)
}
fn update_input_with_descriptor(
&mut self,
input_index: usize,
desc: &Descriptor<DefiniteDescriptorKey>,
) -> Result<(), UtxoUpdateError> {
let n_inputs = self.inputs.len();
let input = self
.inputs
.get_mut(input_index)
.ok_or(UtxoUpdateError::IndexOutOfBounds(input_index, n_inputs))?;
let txin = self
.unsigned_tx
.input
.get(input_index)
.ok_or(UtxoUpdateError::MissingInputUtxo)?;
let desc_type = desc.desc_type();
if let Some(non_witness_utxo) = &input.non_witness_utxo {
if txin.previous_output.txid != non_witness_utxo.txid() {
return Err(UtxoUpdateError::UtxoCheck);
}
}
let expected_spk = {
match (&input.witness_utxo, &input.non_witness_utxo) {
(Some(witness_utxo), None) => {
if desc_type.segwit_version().is_some() {
witness_utxo.script_pubkey.clone()
} else {
return Err(UtxoUpdateError::UtxoCheck);
}
}
(None, Some(non_witness_utxo)) => non_witness_utxo
.output
.get(txin.previous_output.vout as usize)
.ok_or(UtxoUpdateError::UtxoCheck)?
.script_pubkey
.clone(),
(Some(witness_utxo), Some(non_witness_utxo)) => {
if witness_utxo
!= non_witness_utxo
.output
.get(txin.previous_output.vout as usize)
.ok_or(UtxoUpdateError::UtxoCheck)?
{
return Err(UtxoUpdateError::UtxoCheck);
}
witness_utxo.script_pubkey.clone()
}
(None, None) => return Err(UtxoUpdateError::UtxoCheck),
}
};
let (_, spk_check_passed) =
update_item_with_descriptor_helper(input, desc, Some(&expected_spk))
.map_err(UtxoUpdateError::DerivationError)?;
if !spk_check_passed {
return Err(UtxoUpdateError::MismatchedScriptPubkey);
}
Ok(())
}
fn update_output_with_descriptor(
&mut self,
output_index: usize,
desc: &Descriptor<DefiniteDescriptorKey>,
) -> Result<(), OutputUpdateError> {
let n_outputs = self.outputs.len();
let output = self
.outputs
.get_mut(output_index)
.ok_or(OutputUpdateError::IndexOutOfBounds(output_index, n_outputs))?;
let txout = self
.unsigned_tx
.output
.get(output_index)
.ok_or(OutputUpdateError::MissingTxOut)?;
let (_, spk_check_passed) =
update_item_with_descriptor_helper(output, desc, Some(&txout.script_pubkey))
.map_err(OutputUpdateError::DerivationError)?;
if !spk_check_passed {
return Err(OutputUpdateError::MismatchedScriptPubkey);
}
Ok(())
}
fn sighash_msg<T: Borrow<bitcoin::Transaction>>(
&self,
idx: usize,
cache: &mut SighashCache<T>,
tapleaf_hash: Option<TapLeafHash>,
) -> Result<PsbtSighashMsg, SighashError> {
// Infer a descriptor at idx
if idx >= self.inputs.len() {
return Err(SighashError::IndexOutOfBounds(idx, self.inputs.len()));
}
let inp = &self.inputs[idx];
let prevouts = finalizer::prevouts(self).map_err(|_e| SighashError::MissingSpendUtxos)?;
// Note that as per Psbt spec we should have access to spent_utxos for the transaction
// Even if the transaction does not require SighashAll, we create `Prevouts::All` for code simplicity
let prevouts = bitcoin::sighash::Prevouts::All(&prevouts);
let inp_spk =
finalizer::get_scriptpubkey(self, idx).map_err(|_e| SighashError::MissingInputUtxo)?;
if inp_spk.is_p2tr() {
let hash_ty = inp
.sighash_type
.map(|sighash_type| sighash_type.taproot_hash_ty())
.unwrap_or(Ok(sighash::TapSighashType::Default))
.map_err(|_e| SighashError::InvalidSighashType)?;
match tapleaf_hash {
Some(leaf_hash) => {
let tap_sighash_msg = cache
.taproot_script_spend_signature_hash(idx, &prevouts, leaf_hash, hash_ty)?;
Ok(PsbtSighashMsg::TapSighash(tap_sighash_msg))
}
None => {
let tap_sighash_msg =
cache.taproot_key_spend_signature_hash(idx, &prevouts, hash_ty)?;
Ok(PsbtSighashMsg::TapSighash(tap_sighash_msg))
}
}
} else {
let hash_ty = inp
.sighash_type
.map(|sighash_type| sighash_type.ecdsa_hash_ty())
.unwrap_or(Ok(sighash::EcdsaSighashType::All))
.map_err(|_e| SighashError::InvalidSighashType)?;
let amt = finalizer::get_utxo(self, idx)
.map_err(|_e| SighashError::MissingInputUtxo)?
.value;
let is_nested_wpkh = inp_spk.is_p2sh()
&& inp
.redeem_script
.as_ref()
.map(|x| x.is_p2wpkh())
.unwrap_or(false);
let is_nested_wsh = inp_spk.is_p2sh()
&& inp
.redeem_script
.as_ref()
.map(|x| x.is_p2wsh())
.unwrap_or(false);
if inp_spk.is_p2wpkh() || inp_spk.is_p2wsh() || is_nested_wpkh || is_nested_wsh {
let msg = if inp_spk.is_p2wpkh() {
cache.p2wpkh_signature_hash(idx, &inp_spk, amt, hash_ty)?
} else if is_nested_wpkh {
let script_code = inp
.redeem_script
.as_ref()
.expect("redeem script non-empty checked earlier");
cache.p2wpkh_signature_hash(idx, script_code, amt, hash_ty)?
} else {
let witness_script = inp
.witness_script
.as_ref()
.ok_or(SighashError::MissingWitnessScript)?;
cache.p2wsh_signature_hash(idx, witness_script, amt, hash_ty)?
};
Ok(PsbtSighashMsg::SegwitV0Sighash(msg))
} else {
// legacy sighash case
let script_code = if inp_spk.is_p2sh() {
inp.redeem_script
.as_ref()
.ok_or(SighashError::MissingRedeemScript)?
} else {
&inp_spk
};
let msg = cache.legacy_signature_hash(idx, script_code, hash_ty.to_u32())?;
Ok(PsbtSighashMsg::LegacySighash(msg))
}
}
}
}
/// Extension trait for PSBT inputs
pub trait PsbtInputExt {
/// Given the descriptor for a utxo being spent populate the PSBT input's fields so it can be signed.
///
/// If the descriptor contains wildcards or otherwise cannot be transformed into a concrete
/// descriptor an error will be returned. The descriptor *can* (and should) have extended keys in
/// it so PSBT fields like `bip32_derivation` and `tap_key_origins` can be populated.
///
/// Note that his method doesn't check that the `witness_utxo` or `non_witness_utxo` is
/// consistent with the descriptor. To do that see [`update_input_with_descriptor`].
///
/// ## Return value
///
/// For convenience, this returns the concrete descriptor that is computed internally to fill
/// out the PSBT input fields. This can be used to manually check that the `script_pubkey` in
/// `witness_utxo` and/or `non_witness_utxo` is consistent with the descriptor.
///
/// [`update_input_with_descriptor`]: PsbtExt::update_input_with_descriptor
fn update_with_descriptor_unchecked(
&mut self,
descriptor: &Descriptor<DefiniteDescriptorKey>,
) -> Result<Descriptor<bitcoin::PublicKey>, descriptor::ConversionError>;
}
impl PsbtInputExt for psbt::Input {
fn update_with_descriptor_unchecked(
&mut self,
descriptor: &Descriptor<DefiniteDescriptorKey>,
) -> Result<Descriptor<bitcoin::PublicKey>, descriptor::ConversionError> {
let (derived, _) = update_item_with_descriptor_helper(self, descriptor, None)?;
Ok(derived)
}
}
/// Extension trait for PSBT outputs
pub trait PsbtOutputExt {
/// Given the descriptor of a PSBT output populate the relevant metadata
///
/// If the descriptor contains wildcards or otherwise cannot be transformed into a concrete
/// descriptor an error will be returned. The descriptor *can* (and should) have extended keys in
/// it so PSBT fields like `bip32_derivation` and `tap_key_origins` can be populated.
///
/// Note that this method doesn't check that the `script_pubkey` of the output being
/// updated matches the descriptor. To do that see [`update_output_with_descriptor`].
///
/// ## Return value
///
/// For convenience, this returns the concrete descriptor that is computed internally to fill
/// out the PSBT output fields. This can be used to manually check that the `script_pubkey` is
/// consistent with the descriptor.
///
/// [`update_output_with_descriptor`]: PsbtExt::update_output_with_descriptor
fn update_with_descriptor_unchecked(
&mut self,
descriptor: &Descriptor<DefiniteDescriptorKey>,
) -> Result<Descriptor<bitcoin::PublicKey>, descriptor::ConversionError>;
}
impl PsbtOutputExt for psbt::Output {
fn update_with_descriptor_unchecked(
&mut self,
descriptor: &Descriptor<DefiniteDescriptorKey>,
) -> Result<Descriptor<bitcoin::PublicKey>, descriptor::ConversionError> {
let (derived, _) = update_item_with_descriptor_helper(self, descriptor, None)?;
Ok(derived)
}
}
// Traverse the pkh lookup while maintaining a reverse map for storing the map
// hash160 -> (XonlyPublicKey)/PublicKey
struct KeySourceLookUp(
pub BTreeMap<secp256k1::PublicKey, bip32::KeySource>,
pub secp256k1::Secp256k1<VerifyOnly>,
);
impl Translator<DefiniteDescriptorKey, bitcoin::PublicKey, descriptor::ConversionError>
for KeySourceLookUp
{
fn pk(
&mut self,
xpk: &DefiniteDescriptorKey,
) -> Result<bitcoin::PublicKey, descriptor::ConversionError> {
let derived = xpk.derive_public_key(&self.1)?;
self.0.insert(
derived.to_public_key().inner,
(
xpk.master_fingerprint(),
xpk.full_derivation_path()
.ok_or(descriptor::ConversionError::MultiKey)?,
),
);
Ok(derived)
}