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
// SPDX-License-Identifier: CC0-1.0
//! Implementation of the Finalizer role as defined in [BIP-174].
//!
//! [BIP-174]: <https://github.com/bitcoin/bips/blob/master/bip-0174.media wiki>
use alloc::collections::BTreeMap;
use core::fmt;
use bitcoin::hashes::hash160;
use bitcoin::secp256k1::{Secp256k1, Verification};
use bitcoin::taproot::LeafVersion;
use bitcoin::{sighash, Address, Network, Script, ScriptBuf, Txid, Witness, XOnlyPublicKey};
use miniscript::{
interpreter, BareCtx, Descriptor, ExtParams, Legacy, Miniscript, Satisfier, Segwitv0, SigType,
Tap, ToPublicKey,
};
use crate::error::{write_err, FundingUtxoError};
use crate::prelude::*;
use crate::v2::map::input::{self, Input};
use crate::v2::miniscript::satisfy::InputSatisfier;
use crate::v2::miniscript::InterpreterCheckError;
use crate::v2::{DetermineLockTimeError, PartialSigsSighashTypeError, Psbt};
/// Implements the BIP-370 Finalized role.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Finalizer(Psbt);
impl Finalizer {
/// Creates an `Finalizer`.
///
/// A finalizer can only be created if all inputs have a funding UTXO.
pub fn new(psbt: Psbt) -> Result<Self, Error> {
// TODO: Consider doing this with combinators.
for input in psbt.inputs.iter() {
let _ = input.funding_utxo()?;
}
let _ = psbt.determine_lock_time()?;
psbt.check_partial_sigs_sighash_type()?;
Ok(Self(psbt))
}
/// Returns this PSBT's unique identification.
pub fn id(&self) -> Txid {
self.0.id().expect("Finalizer guarantees lock time can be determined")
}
/// Finalize the PSBT.
///
/// # Returns
///
/// Returns the finalized PSBT without modifying the original.
#[must_use = "returns the finalized PSBT without modifying the original"]
pub fn finalize<C: Verification>(&self, secp: &Secp256k1<C>) -> Result<Psbt, FinalizeError> {
let mut inputs = vec![];
for (input_index, input) in self.0.inputs.iter().enumerate() {
match self.finalize_input(input) {
Ok(input) => inputs.push(input),
// TODO: Do we want to continue loop and return a vector of errors?
Err(error) => return Err(FinalizeError::FinalizeInput { input_index, error }),
}
}
let finalized =
Psbt { global: self.0.global.clone(), inputs, outputs: self.0.outputs.to_vec() };
finalized.interpreter_check(secp)?;
Ok(finalized)
}
// `index` must be the input index of `input` which references an input in `self` - this gets rid of out-of-bounds error path.
fn finalize_input(&self, input: &Input) -> Result<Input, FinalizeInputError> {
let allow_mall = true; // TODO: Add mall and no-mall versions.
let (script_sig, witness) = self.final_script_sig_and_witness(input, allow_mall)?;
Ok(input.finalize(script_sig, witness)?.clone())
}
/// Returns the final script_sig and final witness for this input.
// TODO: Think harder about this.
//
// Input finalizer should only set script sig and witness iff one is required
//
// > The Input Finalizer must only accept a PSBT. For each input, the Input Finalizer determines
// > if the input has enough data to pass validation. If it does, it must construct the 0x07
// > Finalized scriptSig and 0x08 Finalized scriptWitness and place them into the input key-value
// > map. If scriptSig is empty for an input, 0x07 should remain unset rather than assigned an
// > empty array. Likewise, if no scriptWitness exists for an input, 0x08 should remain unset
// > rather than assigned an empty array.
//
// However a finalized input _must_ have them both set.
//
// > It checks whether all inputs have complete scriptSigs and scriptWitnesses by checking for
// > the presence of 0x07 Finalized scriptSig and 0x08 Finalized scriptWitness typed records. If
// > they do, the Transaction Extractor should ...
//
// TODO: Check that we are doing the right thing at the right time between finalization and extraction.
fn final_script_sig_and_witness(
&self,
input: &Input,
allow_mall: bool,
) -> Result<(ScriptBuf, Witness), InputError> {
let (witness, script_sig) = {
let spk =
&input.funding_utxo().expect("guaranteed by Finalizer invariant").script_pubkey;
let sat = InputSatisfier { input };
if spk.is_p2tr() {
// Deal with taproot case separately, we cannot infer the full descriptor for taproot.
let wit = construct_tap_witness(spk, sat, allow_mall)?;
(wit, ScriptBuf::new())
} else {
// Get a descriptor for this input.
let desc = self.get_descriptor(input)?;
// Generate the satisfaction witness and scriptsig.
if !allow_mall {
desc.get_satisfaction(sat)?
} else {
desc.get_satisfaction_mall(sat)?
}
}
};
let witness = Witness::from_slice(&witness);
Ok((script_sig, witness))
}
/// Creates a descriptor from an unfinalized PSBT input.
///
/// Panics on out of bound input index for psbt Also sanity checks that the witness script and
/// redeem script are consistent with the script pubkey. Does *not* check signatures We parse
/// the insane version while satisfying because we want to move the script is probably already
/// created and we want to satisfy it in any way possible.
fn get_descriptor(&self, input: &Input) -> Result<Descriptor<bitcoin::PublicKey>, InputError> {
let mut map: BTreeMap<hash160::Hash, bitcoin::PublicKey> = BTreeMap::new();
// TODO(Tobin): Understand why we use keys from all inputs?
let psbt_inputs = &self.0.inputs;
for psbt_input in psbt_inputs {
// Use BIP32 Derviation to get set of all possible keys.
let public_keys = psbt_input.bip32_derivations.keys();
for key in public_keys {
let bitcoin_key = *key;
let hash = bitcoin_key.pubkey_hash().to_raw_hash();
map.insert(hash, bitcoin_key);
}
}
// Figure out Scriptpubkey
let script_pubkey = &input.funding_utxo().expect("guaranteed by Finalizer").script_pubkey;
// 1. `PK`: creates a `Pk` descriptor(does not check if partial sig is given)
if script_pubkey.is_p2pk() {
let script_pubkey_len = script_pubkey.len();
let pk_bytes = &script_pubkey.to_bytes();
match bitcoin::PublicKey::from_slice(&pk_bytes[1..script_pubkey_len - 1]) {
Ok(pk) => Ok(Descriptor::new_pk(pk)),
Err(e) => Err(InputError::from(e)),
}
} else if script_pubkey.is_p2pkh() {
// 2. `Pkh`: creates a `PkH` descriptor if partial_sigs has the corresponding pk
let partial_sig_contains_pk = input.partial_sigs.iter().find(|&(&pk, _sig)| {
// Indirect way to check the equivalence of pubkey-hashes.
// Create a pubkey hash and check if they are the same.
// THIS IS A BUG AND *WILL* PRODUCE WRONG SATISFACTIONS FOR UNCOMPRESSED KEYS
// Partial sigs loses the compressed flag that is necessary
// TODO: See https://github.com/rust-bitcoin/rust-bitcoin/pull/836
// The type checker will fail again after we update to 0.28 and this can be removed
let addr = Address::p2pkh(pk, Network::Bitcoin);
*script_pubkey == addr.script_pubkey()
});
match partial_sig_contains_pk {
Some((pk, _sig)) => Descriptor::new_pkh(*pk).map_err(InputError::from),
None => Err(InputError::MissingPubkey),
}
} else if script_pubkey.is_p2wpkh() {
// 3. `Wpkh`: creates a `wpkh` descriptor if the partial sig has corresponding pk.
let partial_sig_contains_pk = input.partial_sigs.iter().find(|&(&pk, _sig)| {
match bitcoin::key::CompressedPublicKey::try_from(pk) {
Ok(compressed) => {
// Indirect way to check the equivalence of pubkey-hashes.
// Create a pubkey hash and check if they are the same.
let addr = bitcoin::Address::p2wpkh(&compressed, bitcoin::Network::Bitcoin);
*script_pubkey == addr.script_pubkey()
}
Err(_) => false,
}
});
match partial_sig_contains_pk {
Some((pk, _sig)) => Ok(Descriptor::new_wpkh(*pk)?),
None => Err(InputError::MissingPubkey),
}
} else if script_pubkey.is_p2wsh() {
// 4. `Wsh`: creates a `Wsh` descriptor
if input.redeem_script.is_some() {
return Err(InputError::NonEmptyRedeemScript);
}
if let Some(ref witness_script) = input.witness_script {
if witness_script.to_p2wsh() != *script_pubkey {
return Err(InputError::InvalidWitnessScript {
witness_script: witness_script.clone(),
p2wsh_expected: script_pubkey.clone(),
});
}
let ms = Miniscript::<bitcoin::PublicKey, Segwitv0>::parse_with_ext(
witness_script,
&ExtParams::allow_all(),
)?;
Ok(Descriptor::new_wsh(ms.substitute_raw_pkh(&map))?)
} else {
Err(InputError::MissingWitnessScript)
}
} else if script_pubkey.is_p2sh() {
match input.redeem_script {
None => Err(InputError::MissingRedeemScript),
Some(ref redeem_script) => {
if redeem_script.to_p2sh() != *script_pubkey {
return Err(InputError::InvalidRedeemScript {
redeem: redeem_script.clone(),
p2sh_expected: script_pubkey.clone(),
});
}
if redeem_script.is_p2wsh() {
// 5. `ShWsh` case
if let Some(ref witness_script) = input.witness_script {
if witness_script.to_p2wsh() != *redeem_script {
return Err(InputError::InvalidWitnessScript {
witness_script: witness_script.clone(),
p2wsh_expected: redeem_script.clone(),
});
}
let ms = Miniscript::<bitcoin::PublicKey, Segwitv0>::parse_with_ext(
witness_script,
&ExtParams::allow_all(),
)?;
Ok(Descriptor::new_sh_wsh(ms.substitute_raw_pkh(&map))?)
} else {
Err(InputError::MissingWitnessScript)
}
} else if redeem_script.is_p2wpkh() {
// 6. `ShWpkh` case
let partial_sig_contains_pk =
input.partial_sigs.iter().find(|&(&pk, _sig)| {
match bitcoin::key::CompressedPublicKey::try_from(pk) {
Ok(compressed) => {
let addr = bitcoin::Address::p2wpkh(
&compressed,
bitcoin::Network::Bitcoin,
);
*redeem_script == addr.script_pubkey()
}
Err(_) => false,
}
});
match partial_sig_contains_pk {
Some((pk, _sig)) => Ok(Descriptor::new_sh_wpkh(*pk)?),
None => Err(InputError::MissingPubkey),
}
} else {
//7. regular p2sh
if input.witness_script.is_some() {
return Err(InputError::NonEmptyWitnessScript);
}
if let Some(ref redeem_script) = input.redeem_script {
let ms = Miniscript::<bitcoin::PublicKey, Legacy>::parse_with_ext(
redeem_script,
&ExtParams::allow_all(),
)?;
Ok(Descriptor::new_sh(ms)?)
} else {
Err(InputError::MissingWitnessScript)
}
}
}
}
} else {
// 8. Bare case
if input.witness_script.is_some() {
return Err(InputError::NonEmptyWitnessScript);
}
if input.redeem_script.is_some() {
return Err(InputError::NonEmptyRedeemScript);
}
let ms = Miniscript::<bitcoin::PublicKey, BareCtx>::parse_with_ext(
script_pubkey,
&ExtParams::allow_all(),
)?;
Ok(Descriptor::new_bare(ms.substitute_raw_pkh(&map))?)
}
}
}
// Satisfy the taproot descriptor. It is not possible to infer the complete descriptor from psbt
// because the information about all the scripts might not be present. Also, currently the spec does
// not support hidden branches, so inferring a descriptor is not possible.
fn construct_tap_witness(
spk: &Script,
sat: InputSatisfier,
allow_mall: bool,
) -> Result<Vec<Vec<u8>>, InputError> {
assert!(spk.is_p2tr());
// When miniscript tries to finalize the PSBT, it doesn't have the full descriptor (which
// contained a pkh() fragment) and instead resorts to parsing the raw script sig, which is
// translated into a "expr_raw_pkh" internally.
let mut map: BTreeMap<hash160::Hash, XOnlyPublicKey> = BTreeMap::new();
// We need to satisfy or dissatisfy any given key. `tap_key_origin` is the only field of PSBT
// Input which consist of all the keys added on a descriptor and thus we get keys from it.
let public_keys = sat.input.tap_key_origins.keys();
for key in public_keys {
// TODO: How is this key converting to a miniscript::interpreter::BitcoinKey?
// let hash = key.to_pubkeyhash(SigType::Schnorr);
let bitcoin_key = *key;
let hash = bitcoin_key.to_pubkeyhash(SigType::Schnorr);
map.insert(hash, *key);
}
// try the key spend path first
if let Some(sig) = <InputSatisfier as Satisfier<XOnlyPublicKey>>::lookup_tap_key_spend_sig(&sat)
{
return Ok(vec![sig.to_vec()]);
}
// Next script spends
let (mut min_wit, mut min_wit_len) = (None, None);
if let Some(block_map) =
<InputSatisfier as Satisfier<XOnlyPublicKey>>::lookup_tap_control_block_map(&sat)
{
for (control_block, (script, ver)) in block_map {
if *ver != LeafVersion::TapScript {
// We don't know how to satisfy non default version scripts yet
continue;
}
let ms = match Miniscript::<XOnlyPublicKey, Tap>::parse_with_ext(
script,
&ExtParams::allow_all(),
) {
Ok(ms) => ms.substitute_raw_pkh(&map),
Err(..) => continue, // try another script
};
let mut wit = if allow_mall {
match ms.satisfy_malleable(&sat) {
Ok(ms) => ms,
Err(..) => continue,
}
} else {
match ms.satisfy(&sat) {
Ok(ms) => ms,
Err(..) => continue,
}
};
wit.push(ms.encode().into_bytes());
wit.push(control_block.serialize());
let wit_len = Some(super::witness_size(&wit));
if min_wit_len.is_some() && wit_len > min_wit_len {
continue;
} else {
// store the minimum
min_wit = Some(wit);
min_wit_len = wit_len;
}
}
min_wit.ok_or(InputError::CouldNotSatisfyTr)
} else {
// No control blocks found
Err(InputError::CouldNotSatisfyTr)
}
}
/// Error constructing a [`Finalizer`].
#[derive(Debug)]
pub enum Error {
/// An input is missing its funding UTXO.
FundingUtxo(FundingUtxoError),
/// Finalizer must be able to determine the lock time.
DetermineLockTime(DetermineLockTimeError),
/// An input has incorrect sighash type for its partial sigs (ECDSA).
PartialSigsSighashType(PartialSigsSighashTypeError),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use Error::*;
match *self {
// TODO: Loads of error messages are capitalized, they should not be.
FundingUtxo(ref e) => write_err!(f, "Finalizer missing funding UTXO"; e),
DetermineLockTime(ref e) =>
write_err!(f, "finalizer must be able to determine the lock time"; e),
PartialSigsSighashType(ref e) => write_err!(f, "Finalizer sighash type error"; e),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use Error::*;
match *self {
FundingUtxo(ref e) => Some(e),
DetermineLockTime(ref e) => Some(e),
PartialSigsSighashType(ref e) => Some(e),
}
}
}
impl From<FundingUtxoError> for Error {
fn from(e: FundingUtxoError) -> Self { Self::FundingUtxo(e) }
}
impl From<DetermineLockTimeError> for Error {
fn from(e: DetermineLockTimeError) -> Self { Self::DetermineLockTime(e) }
}
impl From<PartialSigsSighashTypeError> for Error {
fn from(e: PartialSigsSighashTypeError) -> Self { Self::PartialSigsSighashType(e) }
}
/// Error finalizing an input.
#[derive(Debug)]
pub enum FinalizeError {
/// Error finalizing an input.
FinalizeInput {
/// The associated input index for `error`.
input_index: usize,
/// Error finalizing input.
error: FinalizeInputError,
},
/// Error running the interpreter checks.
InterpreterCheck(InterpreterCheckError),
}
impl fmt::Display for FinalizeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use FinalizeError::*;
match *self {
FinalizeInput { input_index, ref error } =>
write_err!(f, "failed to finalize input at index {}", input_index; error),
InterpreterCheck(ref e) => write_err!(f, "error running the interpreter checks"; e),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for FinalizeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use FinalizeError::*;
match *self {
FinalizeInput { input_index: _, ref error } => Some(error),
InterpreterCheck(ref error) => Some(error),
}
}
}
impl From<InterpreterCheckError> for FinalizeError {
fn from(e: InterpreterCheckError) -> Self { Self::InterpreterCheck(e) }
}
/// Error finalizing an input.
#[derive(Debug)]
pub enum FinalizeInputError {
/// Failed to get final script_sig and final witness.
Final(InputError),
/// Failed to create a finalized input from final fields.
Input(input::FinalizeError),
}
impl fmt::Display for FinalizeInputError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use FinalizeInputError::*;
match *self {
Final(ref e) => write_err!(f, "final"; e),
Input(ref e) => write_err!(f, "input"; e),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for FinalizeInputError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use FinalizeInputError::*;
match *self {
Final(ref e) => Some(e),
Input(ref e) => Some(e),
}
}
}
impl From<InputError> for FinalizeInputError {
fn from(e: InputError) -> Self { Self::Final(e) }
}
impl From<input::FinalizeError> for FinalizeInputError {
fn from(e: input::FinalizeError) -> Self { Self::Input(e) }
}
/// Error type for Pbst Input
#[derive(Debug)]
pub enum InputError {
/// Get the secp Errors directly
SecpErr(bitcoin::secp256k1::Error),
/// Key errors
KeyErr(bitcoin::key::FromSliceError),
/// 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(miniscript::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 std::error::Error for InputError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
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),
}
}
}
impl From<crate::miniscript::Error> for InputError {
fn from(e: crate::miniscript::Error) -> Self { Self::MiniscriptError(e) }
}
impl From<interpreter::Error> for InputError {
fn from(e: interpreter::Error) -> Self { Self::Interpreter(e) }
}
impl From<bitcoin::secp256k1::Error> for InputError {
fn from(e: bitcoin::secp256k1::Error) -> Self { Self::SecpErr(e) }
}
impl From<bitcoin::key::FromSliceError> for InputError {
fn from(e: bitcoin::key::FromSliceError) -> Self { Self::KeyErr(e) }
}