Skip to main content

psbt_v2/v0/bitcoin/
mod.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! Partially Signed Bitcoin Transactions.
4//!
5//! Implementation of BIP174 Partially Signed Bitcoin Transaction Format as
6//! defined at <https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki>
7//! except we define PSBTs containing non-standard sighash types as invalid.
8//!
9
10#[macro_use]
11mod macros;
12mod error;
13mod map;
14pub mod raw;
15pub mod serialize;
16
17use core::{cmp, fmt};
18#[cfg(feature = "std")]
19use std::collections::{HashMap, HashSet};
20
21use bitcoin::bip32::{self, DerivationPath, KeySource, Xpriv, Xpub};
22use bitcoin::blockdata::transaction::{self, Transaction, TxOut};
23use bitcoin::key::{Keypair, Parity, PrivateKey, PublicKey, TapTweak, XOnlyPublicKey};
24use bitcoin::secp256k1::{Message, Secp256k1, Signing, Verification};
25use bitcoin::sighash::{self, EcdsaSighashType, Prevouts, SighashCache, TapSighashType};
26use bitcoin::taproot::TapLeafHash;
27use bitcoin::{ecdsa, taproot, Amount, FeeRate};
28
29use crate::error::write_err;
30use crate::prelude::*;
31use crate::PsbtSighashType;
32
33#[rustfmt::skip]                // Keep public re-exports separate.
34#[doc(inline)]
35pub use self::{
36    map::{Input, Output},
37    error::Error,
38};
39
40/// A Partially Signed Transaction.
41#[derive(Debug, Clone, PartialEq, Eq, Hash)]
42#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
43pub struct Psbt {
44    /// The unsigned transaction, scriptSigs and witnesses for each input must be empty.
45    pub unsigned_tx: Transaction,
46    /// The version number of this PSBT. If omitted, the version number is 0.
47    pub version: u32,
48    /// A global map from extended public keys to the used key fingerprint and
49    /// derivation path as defined by BIP 32.
50    pub xpub: BTreeMap<Xpub, KeySource>,
51    /// Global proprietary key-value pairs.
52    #[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::btreemap_as_seq_byte_values"))]
53    pub proprietary: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
54    /// Unknown global key-value pairs.
55    #[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::btreemap_as_seq_byte_values"))]
56    pub unknown: BTreeMap<raw::Key, Vec<u8>>,
57
58    /// The corresponding key-value map for each input in the unsigned transaction.
59    pub inputs: Vec<Input>,
60    /// The corresponding key-value map for each output in the unsigned transaction.
61    pub outputs: Vec<Output>,
62}
63
64impl Psbt {
65    /// Returns an iterator for the funding UTXOs of the psbt
66    ///
67    /// For each PSBT input that contains UTXO information `Ok` is returned containing that information.
68    /// The order of returned items is same as the order of inputs.
69    ///
70    /// ## Errors
71    ///
72    /// The function returns error when UTXO information is not present or is invalid.
73    ///
74    /// ## Panics
75    ///
76    /// The function panics if the length of transaction inputs is not equal to the length of PSBT inputs.
77    pub fn iter_funding_utxos(&self) -> impl Iterator<Item = Result<&TxOut, Error>> {
78        assert_eq!(self.inputs.len(), self.unsigned_tx.input.len());
79        self.unsigned_tx.input.iter().zip(&self.inputs).map(|(tx_input, psbt_input)| {
80            match (&psbt_input.witness_utxo, &psbt_input.non_witness_utxo) {
81                (Some(witness_utxo), _) => Ok(witness_utxo),
82                (None, Some(non_witness_utxo)) => {
83                    let vout = tx_input.previous_output.vout as usize;
84                    non_witness_utxo.output.get(vout).ok_or(Error::PsbtUtxoOutOfbounds)
85                }
86                (None, None) => Err(Error::MissingUtxo),
87            }
88        })
89    }
90
91    /// Checks that unsigned transaction does not have scriptSig's or witness data.
92    fn unsigned_tx_checks(&self) -> Result<(), Error> {
93        for txin in &self.unsigned_tx.input {
94            if !txin.script_sig.is_empty() {
95                return Err(Error::UnsignedTxHasScriptSigs);
96            }
97
98            if !txin.witness.is_empty() {
99                return Err(Error::UnsignedTxHasScriptWitnesses);
100            }
101        }
102
103        Ok(())
104    }
105
106    /// Creates a PSBT from an unsigned transaction.
107    ///
108    /// # Errors
109    ///
110    /// If transactions is not unsigned.
111    pub fn from_unsigned_tx(tx: Transaction) -> Result<Self, Error> {
112        let psbt = Psbt {
113            inputs: vec![Default::default(); tx.input.len()],
114            outputs: vec![Default::default(); tx.output.len()],
115
116            unsigned_tx: tx,
117            xpub: Default::default(),
118            version: 0,
119            proprietary: Default::default(),
120            unknown: Default::default(),
121        };
122        psbt.unsigned_tx_checks()?;
123        Ok(psbt)
124    }
125
126    /// The default `max_fee_rate` value used for extracting transactions with [`extract_tx`]
127    ///
128    /// As of 2023, even the biggest overpayers during the highest fee markets only paid around
129    /// 1000 sats/vByte. 25k sats/vByte is obviously a mistake at this point.
130    ///
131    /// [`extract_tx`]: Psbt::extract_tx
132    pub const DEFAULT_MAX_FEE_RATE: FeeRate = FeeRate::from_sat_per_vb_unchecked(25_000);
133
134    /// An alias for [`extract_tx_fee_rate_limit`].
135    ///
136    /// [`extract_tx_fee_rate_limit`]: Psbt::extract_tx_fee_rate_limit
137    #[allow(clippy::result_large_err)]
138    pub fn extract_tx(self) -> Result<Transaction, ExtractTxError> {
139        self.internal_extract_tx_with_fee_rate_limit(Self::DEFAULT_MAX_FEE_RATE)
140    }
141
142    /// Extracts the [`Transaction`] from a [`Psbt`] by filling in the available signature information.
143    ///
144    /// ## Errors
145    ///
146    /// [`ExtractTxError`] variants will contain either the [`Psbt`] itself or the [`Transaction`]
147    /// that was extracted. These can be extracted from the Errors in order to recover.
148    /// See the error documentation for info on the variants. In general, it covers large fees.
149    #[allow(clippy::result_large_err)]
150    pub fn extract_tx_fee_rate_limit(self) -> Result<Transaction, ExtractTxError> {
151        self.internal_extract_tx_with_fee_rate_limit(Self::DEFAULT_MAX_FEE_RATE)
152    }
153
154    /// Extracts the [`Transaction`] from a [`Psbt`] by filling in the available signature information.
155    ///
156    /// ## Errors
157    ///
158    /// See [`extract_tx`].
159    ///
160    /// [`extract_tx`]: Psbt::extract_tx
161    #[allow(clippy::result_large_err)]
162    pub fn extract_tx_with_fee_rate_limit(
163        self,
164        max_fee_rate: FeeRate,
165    ) -> Result<Transaction, ExtractTxError> {
166        self.internal_extract_tx_with_fee_rate_limit(max_fee_rate)
167    }
168
169    /// Perform [`extract_tx_fee_rate_limit`] without the fee rate check.
170    ///
171    /// This can result in a transaction with absurdly high fees. Use with caution.
172    ///
173    /// [`extract_tx_fee_rate_limit`]: Psbt::extract_tx_fee_rate_limit
174    pub fn extract_tx_unchecked_fee_rate(self) -> Transaction { self.internal_extract_tx() }
175
176    #[inline]
177    fn internal_extract_tx(self) -> Transaction {
178        let mut tx: Transaction = self.unsigned_tx;
179
180        for (vin, psbtin) in tx.input.iter_mut().zip(self.inputs.into_iter()) {
181            vin.script_sig = psbtin.final_script_sig.unwrap_or_default();
182            vin.witness = psbtin.final_script_witness.unwrap_or_default();
183        }
184
185        tx
186    }
187
188    #[inline]
189    #[allow(clippy::result_large_err)]
190    fn internal_extract_tx_with_fee_rate_limit(
191        self,
192        max_fee_rate: FeeRate,
193    ) -> Result<Transaction, ExtractTxError> {
194        let fee = match self.fee() {
195            Ok(fee) => fee,
196            Err(Error::MissingUtxo) =>
197                return Err(ExtractTxError::MissingInputValue { tx: self.internal_extract_tx() }),
198            Err(Error::NegativeFee) => return Err(ExtractTxError::SendingTooMuch { psbt: self }),
199            Err(Error::FeeOverflow) =>
200                return Err(ExtractTxError::AbsurdFeeRate {
201                    fee_rate: FeeRate::MAX,
202                    tx: self.internal_extract_tx(),
203                }),
204            _ => unreachable!(),
205        };
206
207        // Note: Move prevents usage of &self from now on.
208        let tx = self.internal_extract_tx();
209
210        // Now that the extracted Transaction is made, decide how to return it.
211        let fee_rate =
212            FeeRate::from_sat_per_kwu(fee.to_sat().saturating_mul(1000) / tx.weight().to_wu());
213        // Prefer to return an AbsurdFeeRate error when both trigger.
214        if fee_rate > max_fee_rate {
215            return Err(ExtractTxError::AbsurdFeeRate { fee_rate, tx });
216        }
217
218        Ok(tx)
219    }
220
221    /// Combines this [`Psbt`] with `other` PSBT as described by BIP 174.
222    ///
223    /// In accordance with BIP 174 this function is commutative i.e., `A.combine(B) == B.combine(A)`
224    pub fn combine(&mut self, other: Self) -> Result<(), Error> {
225        if self.unsigned_tx != other.unsigned_tx {
226            return Err(Error::UnexpectedUnsignedTx {
227                expected: Box::new(self.unsigned_tx.clone()),
228                actual: Box::new(other.unsigned_tx),
229            });
230        }
231
232        // BIP 174: The Combiner must remove any duplicate key-value pairs, in accordance with
233        //          the specification. It can pick arbitrarily when conflicts occur.
234
235        // Keeping the highest version
236        self.version = cmp::max(self.version, other.version);
237
238        // Merging xpubs
239        for (xpub, (fingerprint1, derivation1)) in other.xpub {
240            match self.xpub.entry(xpub) {
241                btree_map::Entry::Vacant(entry) => {
242                    entry.insert((fingerprint1, derivation1));
243                }
244                btree_map::Entry::Occupied(mut entry) => {
245                    // Here in case of the conflict we select the version with algorithm:
246                    // 1) if everything is equal we do nothing
247                    // 2) report an error if
248                    //    - derivation paths are equal and fingerprints are not
249                    //    - derivation paths are of the same length, but not equal
250                    //    - derivation paths has different length, but the shorter one
251                    //      is not the strict suffix of the longer one
252                    // 3) choose longest derivation otherwise
253
254                    let (fingerprint2, derivation2) = entry.get().clone();
255
256                    if (derivation1 == derivation2 && fingerprint1 == fingerprint2)
257                        || (derivation1.len() < derivation2.len()
258                            && derivation1[..]
259                                == derivation2[derivation2.len() - derivation1.len()..])
260                    {
261                        continue;
262                    } else if derivation2[..]
263                        == derivation1[derivation1.len() - derivation2.len()..]
264                    {
265                        entry.insert((fingerprint1, derivation1));
266                        continue;
267                    }
268                    return Err(Error::CombineInconsistentKeySources(Box::new(xpub)));
269                }
270            }
271        }
272
273        self.proprietary.extend(other.proprietary);
274        self.unknown.extend(other.unknown);
275
276        for (self_input, other_input) in self.inputs.iter_mut().zip(other.inputs.into_iter()) {
277            self_input.combine(other_input);
278        }
279
280        for (self_output, other_output) in self.outputs.iter_mut().zip(other.outputs.into_iter()) {
281            self_output.combine(other_output);
282        }
283
284        Ok(())
285    }
286
287    /// Attempts to create _all_ the required signatures for this PSBT using `k`.
288    ///
289    /// If you just want to sign an input with one specific key consider using `sighash_ecdsa` or
290    /// `sighash_taproot`. This function does not support scripts that contain `OP_CODESEPARATOR`.
291    ///
292    /// # Returns
293    ///
294    /// A map of input index -> keys used to sign, for Taproot specifics please see [`SigningKeys`].
295    ///
296    /// If an error is returned some signatures may already have been added to the PSBT. Since
297    /// `partial_sigs` is a [`BTreeMap`] it is safe to retry, previous sigs will be overwritten.
298    pub fn sign<C, K>(
299        &mut self,
300        k: &K,
301        secp: &Secp256k1<C>,
302    ) -> Result<SigningKeysMap, (SigningKeysMap, SigningErrors)>
303    where
304        C: Signing + Verification,
305        K: GetKey,
306    {
307        let tx = self.unsigned_tx.clone(); // clone because we need to mutably borrow when signing.
308        let mut cache = SighashCache::new(&tx);
309
310        let mut used = BTreeMap::new();
311        let mut errors = BTreeMap::new();
312
313        for i in 0..self.inputs.len() {
314            match self.signing_algorithm(i) {
315                Ok(SigningAlgorithm::Ecdsa) =>
316                    match self.bip32_sign_ecdsa(k, i, &mut cache, secp) {
317                        Ok(v) => {
318                            used.insert(i, SigningKeys::Ecdsa(v));
319                        }
320                        Err(e) => {
321                            errors.insert(i, e);
322                        }
323                    },
324                Ok(SigningAlgorithm::Schnorr) => {
325                    match self.bip32_sign_schnorr(k, i, &mut cache, secp) {
326                        Ok(v) => {
327                            used.insert(i, SigningKeys::Schnorr(v));
328                        }
329                        Err(e) => {
330                            errors.insert(i, e);
331                        }
332                    }
333                }
334                Err(e) => {
335                    errors.insert(i, e);
336                }
337            }
338        }
339        if errors.is_empty() {
340            Ok(used)
341        } else {
342            Err((used, errors))
343        }
344    }
345
346    /// Attempts to create all signatures required by this PSBT's `bip32_derivation` field, adding
347    /// them to `partial_sigs`.
348    ///
349    /// # Returns
350    ///
351    /// - Ok: A list of the public keys used in signing.
352    /// - Err: Error encountered trying to calculate the sighash AND we had the signing key.
353    fn bip32_sign_ecdsa<C, K, T>(
354        &mut self,
355        k: &K,
356        input_index: usize,
357        cache: &mut SighashCache<T>,
358        secp: &Secp256k1<C>,
359    ) -> Result<Vec<PublicKey>, SignError>
360    where
361        C: Signing,
362        T: Borrow<Transaction>,
363        K: GetKey,
364    {
365        let msg_sighash_ty_res = self.sighash_ecdsa(input_index, cache);
366
367        let input = &mut self.inputs[input_index]; // Index checked in call to `sighash_ecdsa`.
368
369        let mut used = vec![]; // List of pubkeys used to sign the input.
370
371        for (pk, key_source) in input.bip32_derivation.iter() {
372            let sk = if let Ok(Some(sk)) = k.get_key(KeyRequest::Bip32(key_source.clone()), secp) {
373                sk
374            } else if let Ok(Some(sk)) = k.get_key(KeyRequest::Pubkey(*pk), secp) {
375                sk
376            } else {
377                continue;
378            };
379
380            // Only return the error if we have a secret key to sign this input.
381            let (msg, sighash_ty) = match msg_sighash_ty_res {
382                Err(e) => return Err(e),
383                Ok((msg, sighash_ty)) => (msg, sighash_ty),
384            };
385
386            let sig = ecdsa::Signature {
387                signature: secp.sign_ecdsa(&msg, &sk.inner),
388                sighash_type: sighash_ty,
389            };
390
391            let pk = sk.public_key(secp);
392
393            input.partial_sigs.insert(pk, sig);
394            used.push(pk);
395        }
396
397        Ok(used)
398    }
399
400    /// Attempts to create all signatures required by this PSBT's `tap_key_origins` field, adding
401    /// them to `tap_key_sig` or `tap_script_sigs`.
402    ///
403    /// # Returns
404    ///
405    /// - Ok: A list of the xonly public keys used in signing. When signing a key path spend we
406    ///   return the internal key.
407    /// - Err: Error encountered trying to calculate the sighash AND we had the signing key.
408    fn bip32_sign_schnorr<C, K, T>(
409        &mut self,
410        k: &K,
411        input_index: usize,
412        cache: &mut SighashCache<T>,
413        secp: &Secp256k1<C>,
414    ) -> Result<Vec<XOnlyPublicKey>, SignError>
415    where
416        C: Signing + Verification,
417        T: Borrow<Transaction>,
418        K: GetKey,
419    {
420        let mut input = self.checked_input(input_index)?.clone();
421
422        let mut used = vec![]; // List of pubkeys used to sign the input.
423
424        for (&xonly, (leaf_hashes, key_source)) in input.tap_key_origins.iter() {
425            let sk = if let Ok(Some(secret_key)) =
426                k.get_key(KeyRequest::Bip32(key_source.clone()), secp)
427            {
428                secret_key
429            } else if let Ok(Some(sk)) = k.get_key(KeyRequest::XOnlyPubkey(xonly), secp) {
430                sk
431            } else {
432                continue;
433            };
434
435            // Considering the responsibility of the PSBT's finalizer to extract valid signatures,
436            // the goal of this algorithm is to provide signatures to the best of our ability:
437            // 1) If the conditions for key path spend are met, proceed to provide the signature for key path spend
438            // 2) If the conditions for script path spend are met, proceed to provide the signature for script path spend
439
440            // key path spend
441            if let Some(internal_key) = input.tap_internal_key {
442                // BIP 371: The internal key does not have leaf hashes, so can be indicated with a hashes len of 0.
443
444                // Based on input.tap_internal_key.is_some() alone, it is not sufficient to determine whether it is a key path spend.
445                // According to BIP 371, we also need to consider the condition leaf_hashes.is_empty() for a more accurate determination.
446                if internal_key == xonly && leaf_hashes.is_empty() && input.tap_key_sig.is_none() {
447                    let (msg, sighash_type) = self.sighash_taproot(input_index, cache, None)?;
448                    let key_pair = Keypair::from_secret_key(secp, &sk.inner)
449                        .tap_tweak(secp, input.tap_merkle_root)
450                        .to_keypair();
451
452                    #[cfg(feature = "rand")]
453                    let signature = secp.sign_schnorr(&msg, &key_pair);
454                    #[cfg(not(feature = "rand"))]
455                    let signature = secp.sign_schnorr_no_aux_rand(&msg, &key_pair);
456
457                    let signature = taproot::Signature { signature, sighash_type };
458                    input.tap_key_sig = Some(signature);
459
460                    used.push(internal_key);
461                }
462            }
463
464            // script path spend
465            if let Some((leaf_hashes, _)) = input.tap_key_origins.get(&xonly) {
466                let leaf_hashes = leaf_hashes
467                    .iter()
468                    .filter(|lh| !input.tap_script_sigs.contains_key(&(xonly, **lh)))
469                    .cloned()
470                    .collect::<Vec<_>>();
471
472                if !leaf_hashes.is_empty() {
473                    let key_pair = Keypair::from_secret_key(secp, &sk.inner);
474
475                    for lh in leaf_hashes {
476                        let (msg, sighash_type) =
477                            self.sighash_taproot(input_index, cache, Some(lh))?;
478
479                        #[cfg(feature = "rand")]
480                        let signature = secp.sign_schnorr(&msg, &key_pair);
481                        #[cfg(not(feature = "rand"))]
482                        let signature = secp.sign_schnorr_no_aux_rand(&msg, &key_pair);
483
484                        let signature = taproot::Signature { signature, sighash_type };
485                        input.tap_script_sigs.insert((xonly, lh), signature);
486                    }
487
488                    used.push(sk.public_key(secp).into());
489                }
490            }
491        }
492
493        self.inputs[input_index] = input; // input_index is checked above.
494
495        Ok(used)
496    }
497
498    /// Returns the sighash message to sign an ECDSA input along with the sighash type.
499    ///
500    /// Uses the [`EcdsaSighashType`] from this input if one is specified. If no sighash type is
501    /// specified uses [`EcdsaSighashType::All`]. This function does not support scripts that
502    /// contain `OP_CODESEPARATOR`.
503    pub fn sighash_ecdsa<T: Borrow<Transaction>>(
504        &self,
505        input_index: usize,
506        cache: &mut SighashCache<T>,
507    ) -> Result<(Message, EcdsaSighashType), SignError> {
508        use OutputType::*;
509
510        if self.signing_algorithm(input_index)? != SigningAlgorithm::Ecdsa {
511            return Err(SignError::WrongSigningAlgorithm);
512        }
513
514        let input = self.checked_input(input_index)?;
515        let utxo = self.spend_utxo(input_index)?;
516        let spk = &utxo.script_pubkey; // scriptPubkey for input spend utxo.
517
518        let hash_ty = input.ecdsa_hash_ty().map_err(|_| SignError::InvalidSighashType)?; // Only support standard sighash types.
519
520        match self.output_type(input_index)? {
521            Bare => {
522                let sighash = cache
523                    .legacy_signature_hash(input_index, spk, hash_ty.to_u32())
524                    .expect("input checked above");
525                Ok((Message::from(sighash), hash_ty))
526            }
527            Sh => {
528                let script_code =
529                    input.redeem_script.as_ref().ok_or(SignError::MissingRedeemScript)?;
530                let sighash = cache
531                    .legacy_signature_hash(input_index, script_code, hash_ty.to_u32())
532                    .expect("input checked above");
533                Ok((Message::from(sighash), hash_ty))
534            }
535            Wpkh => {
536                let sighash = cache.p2wpkh_signature_hash(input_index, spk, utxo.value, hash_ty)?;
537                Ok((Message::from(sighash), hash_ty))
538            }
539            ShWpkh => {
540                let redeem_script = input.redeem_script.as_ref().expect("checked above");
541                let sighash =
542                    cache.p2wpkh_signature_hash(input_index, redeem_script, utxo.value, hash_ty)?;
543                Ok((Message::from(sighash), hash_ty))
544            }
545            Wsh | ShWsh => {
546                let witness_script =
547                    input.witness_script.as_ref().ok_or(SignError::MissingWitnessScript)?;
548                let sighash = cache
549                    .p2wsh_signature_hash(input_index, witness_script, utxo.value, hash_ty)
550                    .map_err(SignError::SegwitV0Sighash)?;
551                Ok((Message::from(sighash), hash_ty))
552            }
553            Tr => {
554                // This PSBT signing API is WIP, taproot to come shortly.
555                Err(SignError::Unsupported)
556            }
557        }
558    }
559
560    /// Returns the sighash message to sign an SCHNORR input along with the sighash type.
561    ///
562    /// Uses the [`TapSighashType`] from this input if one is specified. If no sighash type is
563    /// specified uses [`TapSighashType::Default`].
564    fn sighash_taproot<T: Borrow<Transaction>>(
565        &self,
566        input_index: usize,
567        cache: &mut SighashCache<T>,
568        leaf_hash: Option<TapLeafHash>,
569    ) -> Result<(Message, TapSighashType), SignError> {
570        use OutputType::*;
571
572        if self.signing_algorithm(input_index)? != SigningAlgorithm::Schnorr {
573            return Err(SignError::WrongSigningAlgorithm);
574        }
575
576        let input = self.checked_input(input_index)?;
577
578        match self.output_type(input_index)? {
579            Tr => {
580                let hash_ty = input
581                    .sighash_type
582                    .unwrap_or_else(|| TapSighashType::Default.into())
583                    .taproot_hash_ty()
584                    .map_err(|_| SignError::InvalidSighashType)?;
585
586                let spend_utxos =
587                    (0..self.inputs.len()).map(|i| self.spend_utxo(i).ok()).collect::<Vec<_>>();
588                let all_spend_utxos;
589
590                let is_anyone_can_pay = PsbtSighashType::from(hash_ty).to_u32() & 0x80 != 0;
591
592                let prev_outs = if is_anyone_can_pay {
593                    Prevouts::One(
594                        input_index,
595                        spend_utxos[input_index].ok_or(SignError::MissingSpendUtxo)?,
596                    )
597                } else if spend_utxos.iter().all(Option::is_some) {
598                    all_spend_utxos = spend_utxos.iter().filter_map(|x| *x).collect::<Vec<_>>();
599                    Prevouts::All(&all_spend_utxos)
600                } else {
601                    return Err(SignError::MissingSpendUtxo);
602                };
603
604                let sighash = if let Some(leaf_hash) = leaf_hash {
605                    cache.taproot_script_spend_signature_hash(
606                        input_index,
607                        &prev_outs,
608                        leaf_hash,
609                        hash_ty,
610                    )?
611                } else {
612                    cache.taproot_key_spend_signature_hash(input_index, &prev_outs, hash_ty)?
613                };
614                Ok((Message::from(sighash), hash_ty))
615            }
616            _ => Err(SignError::Unsupported),
617        }
618    }
619
620    /// Returns the spending utxo for this PSBT's input at `input_index`.
621    pub fn spend_utxo(&self, input_index: usize) -> Result<&TxOut, SignError> {
622        let input = self.checked_input(input_index)?;
623        let utxo = if let Some(witness_utxo) = &input.witness_utxo {
624            witness_utxo
625        } else if let Some(non_witness_utxo) = &input.non_witness_utxo {
626            let vout = self.unsigned_tx.input[input_index].previous_output.vout;
627            &non_witness_utxo.output[vout as usize]
628        } else {
629            return Err(SignError::MissingSpendUtxo);
630        };
631        Ok(utxo)
632    }
633
634    /// Gets the input at `input_index` after checking that it is a valid index.
635    fn checked_input(&self, input_index: usize) -> Result<&Input, IndexOutOfBoundsError> {
636        self.check_index_is_within_bounds(input_index)?;
637        Ok(&self.inputs[input_index])
638    }
639
640    /// Checks `input_index` is within bounds for the PSBT `inputs` array and
641    /// for the PSBT `unsigned_tx` `input` array.
642    fn check_index_is_within_bounds(
643        &self,
644        input_index: usize,
645    ) -> Result<(), IndexOutOfBoundsError> {
646        if input_index >= self.inputs.len() {
647            return Err(IndexOutOfBoundsError::Inputs {
648                index: input_index,
649                length: self.inputs.len(),
650            });
651        }
652
653        if input_index >= self.unsigned_tx.input.len() {
654            return Err(IndexOutOfBoundsError::TxInput {
655                index: input_index,
656                length: self.unsigned_tx.input.len(),
657            });
658        }
659
660        Ok(())
661    }
662
663    /// Returns the algorithm used to sign this PSBT's input at `input_index`.
664    fn signing_algorithm(&self, input_index: usize) -> Result<SigningAlgorithm, SignError> {
665        let output_type = self.output_type(input_index)?;
666        Ok(output_type.signing_algorithm())
667    }
668
669    /// Returns the [`OutputType`] of the spend utxo for this PBST's input at `input_index`.
670    pub(crate) fn output_type(&self, input_index: usize) -> Result<OutputType, SignError> {
671        let input = self.checked_input(input_index)?;
672        let utxo = self.spend_utxo(input_index)?;
673        let spk = utxo.script_pubkey.clone();
674
675        // Anything that is not segwit and is not p2sh is `Bare`.
676        if !(spk.is_witness_program() || spk.is_p2sh()) {
677            return Ok(OutputType::Bare);
678        }
679
680        if spk.is_p2wpkh() {
681            return Ok(OutputType::Wpkh);
682        }
683
684        if spk.is_p2wsh() {
685            return Ok(OutputType::Wsh);
686        }
687
688        if spk.is_p2sh() {
689            if input.redeem_script.as_ref().map(|s| s.is_p2wpkh()).unwrap_or(false) {
690                return Ok(OutputType::ShWpkh);
691            }
692            if input.redeem_script.as_ref().map(|x| x.is_p2wsh()).unwrap_or(false) {
693                return Ok(OutputType::ShWsh);
694            }
695            return Ok(OutputType::Sh);
696        }
697
698        if spk.is_p2tr() {
699            return Ok(OutputType::Tr);
700        }
701
702        // Something is wrong with the input scriptPubkey or we do not know how to sign
703        // because there has been a new softfork that we do not yet support.
704        Err(SignError::UnknownOutputType)
705    }
706
707    /// Calculates transaction fee.
708    ///
709    /// 'Fee' being the amount that will be paid for mining a transaction with the current inputs
710    /// and outputs i.e., the difference in value of the total inputs and the total outputs.
711    ///
712    /// ## Errors
713    ///
714    /// - [`Error::MissingUtxo`] when UTXO information for any input is not present or is invalid.
715    /// - [`Error::NegativeFee`] if calculated value is negative.
716    /// - [`Error::FeeOverflow`] if an integer overflow occurs.
717    pub fn fee(&self) -> Result<Amount, Error> {
718        let mut inputs: u64 = 0;
719        for utxo in self.iter_funding_utxos() {
720            inputs = inputs.checked_add(utxo?.value.to_sat()).ok_or(Error::FeeOverflow)?;
721        }
722        let mut outputs: u64 = 0;
723        for out in &self.unsigned_tx.output {
724            outputs = outputs.checked_add(out.value.to_sat()).ok_or(Error::FeeOverflow)?;
725        }
726        inputs.checked_sub(outputs).map(Amount::from_sat).ok_or(Error::NegativeFee)
727    }
728}
729
730/// Data required to call [`GetKey`] to get the private key to sign an input.
731#[derive(Clone, Debug, PartialEq, Eq)]
732#[non_exhaustive]
733pub enum KeyRequest {
734    /// Request a private key using the associated public key.
735    Pubkey(PublicKey),
736    /// Request a private key using BIP-32 fingerprint and derivation path.
737    Bip32(KeySource),
738    /// Request a private key using the associated x-only public key.
739    XOnlyPubkey(XOnlyPublicKey),
740}
741
742/// Trait to get a private key from a key request, key is then used to sign an input.
743pub trait GetKey {
744    /// An error occurred while getting the key.
745    type Error: core::fmt::Debug;
746
747    /// Attempts to get the private key for `key_request`.
748    ///
749    /// # Returns
750    /// - `Some(key)` if the key is found.
751    /// - `None` if the key was not found but no error was encountered.
752    /// - `Err` if an error was encountered while looking for the key.
753    fn get_key<C: Signing>(
754        &self,
755        key_request: KeyRequest,
756        secp: &Secp256k1<C>,
757    ) -> Result<Option<PrivateKey>, Self::Error>;
758}
759
760impl GetKey for Xpriv {
761    type Error = GetKeyError;
762
763    fn get_key<C: Signing>(
764        &self,
765        key_request: KeyRequest,
766        secp: &Secp256k1<C>,
767    ) -> Result<Option<PrivateKey>, Self::Error> {
768        match key_request {
769            KeyRequest::Pubkey(_) => Err(GetKeyError::NotSupported),
770            KeyRequest::XOnlyPubkey(_) => Err(GetKeyError::NotSupported),
771            KeyRequest::Bip32((fingerprint, path)) => {
772                let key = if self.fingerprint(secp) == fingerprint {
773                    let k = self.derive_priv(secp, &path)?;
774                    Some(k.to_priv())
775                } else if self.parent_fingerprint == fingerprint
776                    && !path.is_empty()
777                    && path[0] == self.child_number
778                {
779                    let path = DerivationPath::from_iter(path.into_iter().skip(1).copied());
780                    let k = self.derive_priv(secp, &path)?;
781                    Some(k.to_priv())
782                } else {
783                    None
784                };
785                Ok(key)
786            }
787        }
788    }
789}
790
791/// Map of input index -> signing key for that input (see [`SigningKeys`]).
792pub type SigningKeysMap = BTreeMap<usize, SigningKeys>;
793
794/// A list of keys used to sign an input.
795#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
796pub enum SigningKeys {
797    /// Keys used to sign an ECDSA input.
798    Ecdsa(Vec<PublicKey>),
799    /// Keys used to sign a Taproot input.
800    ///
801    /// - Key path spend: This is the internal key.
802    /// - Script path spend: This is the pubkey associated with the secret key that signed.
803    Schnorr(Vec<XOnlyPublicKey>),
804}
805
806/// Map of input index -> the error encountered while attempting to sign that input.
807pub type SigningErrors = BTreeMap<usize, SignError>;
808
809#[rustfmt::skip]
810macro_rules! impl_get_key_for_set {
811    ($set:ident) => {
812
813impl GetKey for $set<Xpriv> {
814    type Error = GetKeyError;
815
816    fn get_key<C: Signing>(
817        &self,
818        key_request: KeyRequest,
819        secp: &Secp256k1<C>
820    ) -> Result<Option<PrivateKey>, Self::Error> {
821        // OK to stop at the first error because Xpriv::get_key() can only fail
822        // if this isn't a KeyRequest::Bip32, which would fail for all Xprivs.
823        self.iter()
824            .find_map(|xpriv| xpriv.get_key(key_request.clone(), secp).transpose())
825            .transpose()
826    }
827}}}
828impl_get_key_for_set!(BTreeSet);
829#[cfg(feature = "std")]
830impl_get_key_for_set!(HashSet);
831
832#[rustfmt::skip]
833macro_rules! impl_get_key_for_pubkey_map {
834    ($map:ident) => {
835
836impl GetKey for $map<PublicKey, PrivateKey> {
837    type Error = GetKeyError;
838
839    fn get_key<C: Signing>(
840        &self,
841        key_request: KeyRequest,
842        _: &Secp256k1<C>,
843    ) -> Result<Option<PrivateKey>, Self::Error> {
844        match key_request {
845            KeyRequest::Pubkey(pk) => Ok(self.get(&pk).cloned()),
846            KeyRequest::XOnlyPubkey(xonly) => {
847                let pubkey_even = PublicKey::new(xonly.public_key(Parity::Even));
848                let key = self.get(&pubkey_even).cloned();
849
850                if key.is_some() {
851                    return Ok(key);
852                }
853
854                let pubkey_odd = PublicKey::new(xonly.public_key(Parity::Odd));
855                if let Some(priv_key) = self.get(&pubkey_odd).copied() {
856                    let negated_priv_key  = priv_key.negate();
857                    return Ok(Some(negated_priv_key));
858                }
859
860                Ok(None)
861            },
862            KeyRequest::Bip32(_) => Err(GetKeyError::NotSupported),
863        }
864    }
865}}}
866impl_get_key_for_pubkey_map!(BTreeMap);
867#[cfg(feature = "std")]
868impl_get_key_for_pubkey_map!(HashMap);
869
870#[rustfmt::skip]
871macro_rules! impl_get_key_for_xonly_map {
872    ($map:ident) => {
873
874impl GetKey for $map<XOnlyPublicKey, PrivateKey> {
875    type Error = GetKeyError;
876
877    fn get_key<C: Signing>(
878        &self,
879        key_request: KeyRequest,
880        secp: &Secp256k1<C>,
881    ) -> Result<Option<PrivateKey>, Self::Error> {
882        match key_request {
883            KeyRequest::XOnlyPubkey(xonly) => Ok(self.get(&xonly).cloned()),
884            KeyRequest::Pubkey(pk) => {
885                let (xonly, parity) = pk.inner.x_only_public_key();
886
887                if let Some(mut priv_key) = self.get(&XOnlyPublicKey::from(xonly)).cloned() {
888                    let computed_pk = priv_key.public_key(&secp);
889                    let (_, computed_parity) = computed_pk.inner.x_only_public_key();
890
891                    if computed_parity != parity {
892                        priv_key = priv_key.negate();
893                    }
894
895                    return Ok(Some(priv_key));
896                }
897
898                Ok(None)
899            },
900            KeyRequest::Bip32(_) => Err(GetKeyError::NotSupported),
901        }
902    }
903}}}
904impl_get_key_for_xonly_map!(BTreeMap);
905#[cfg(feature = "std")]
906impl_get_key_for_xonly_map!(HashMap);
907
908/// Errors when getting a key.
909#[derive(Debug, Clone, PartialEq, Eq)]
910#[non_exhaustive]
911pub enum GetKeyError {
912    /// A bip32 error.
913    Bip32(bip32::Error),
914    /// The GetKey operation is not supported for this key request.
915    NotSupported,
916}
917
918impl From<core::convert::Infallible> for GetKeyError {
919    fn from(never: core::convert::Infallible) -> Self { match never {} }
920}
921
922impl fmt::Display for GetKeyError {
923    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
924        use GetKeyError::*;
925
926        match *self {
927            Bip32(ref e) => write_err!(f, "a bip23 error"; e),
928            NotSupported =>
929                f.write_str("the GetKey operation is not supported for this key request"),
930        }
931    }
932}
933
934#[cfg(feature = "std")]
935impl std::error::Error for GetKeyError {
936    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
937        use GetKeyError::*;
938
939        match *self {
940            NotSupported => None,
941            Bip32(ref e) => Some(e),
942        }
943    }
944}
945
946impl From<bip32::Error> for GetKeyError {
947    fn from(e: bip32::Error) -> Self { GetKeyError::Bip32(e) }
948}
949
950/// The various output types supported by the Bitcoin network.
951#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
952#[non_exhaustive]
953pub enum OutputType {
954    /// An output of type: pay-to-pubkey or pay-to-pubkey-hash.
955    Bare,
956    /// A pay-to-witness-pubkey-hash output (P2WPKH).
957    Wpkh,
958    /// A pay-to-witness-script-hash output (P2WSH).
959    Wsh,
960    /// A nested segwit output, pay-to-witness-pubkey-hash nested in a pay-to-script-hash.
961    ShWpkh,
962    /// A nested segwit output, pay-to-witness-script-hash nested in a pay-to-script-hash.
963    ShWsh,
964    /// A pay-to-script-hash output excluding wrapped segwit (P2SH).
965    Sh,
966    /// A taproot output (P2TR).
967    Tr,
968}
969
970impl OutputType {
971    /// The signing algorithm used to sign this output type.
972    pub fn signing_algorithm(&self) -> SigningAlgorithm {
973        use OutputType::*;
974
975        match self {
976            Bare | Wpkh | Wsh | ShWpkh | ShWsh | Sh => SigningAlgorithm::Ecdsa,
977            Tr => SigningAlgorithm::Schnorr,
978        }
979    }
980}
981
982/// Signing algorithms supported by the Bitcoin network.
983#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
984pub enum SigningAlgorithm {
985    /// The Elliptic Curve Digital Signature Algorithm (see [wikipedia]).
986    ///
987    /// [wikipedia]: https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm
988    Ecdsa,
989    /// The Schnorr signature algorithm (see [wikipedia]).
990    ///
991    /// [wikipedia]: https://en.wikipedia.org/wiki/Schnorr_signature
992    Schnorr,
993}
994
995/// Errors encountered while calculating the sighash message.
996#[derive(Debug, Clone, PartialEq, Eq)]
997#[non_exhaustive]
998pub enum SignError {
999    /// Input index out of bounds.
1000    IndexOutOfBounds(IndexOutOfBoundsError),
1001    /// Invalid Sighash type.
1002    InvalidSighashType,
1003    /// Missing input utxo.
1004    MissingInputUtxo,
1005    /// Missing Redeem script.
1006    MissingRedeemScript,
1007    /// Missing spending utxo.
1008    MissingSpendUtxo,
1009    /// Missing witness script.
1010    MissingWitnessScript,
1011    /// Signing algorithm and key type does not match.
1012    MismatchedAlgoKey,
1013    /// Attempted to ECDSA sign an non-ECDSA input.
1014    NotEcdsa,
1015    /// The `scriptPubkey` is not a P2WPKH script.
1016    NotWpkh,
1017    /// Sighash computation error (segwit v0 input).
1018    SegwitV0Sighash(transaction::InputsIndexError),
1019    /// Sighash computation error (p2wpkh input).
1020    P2wpkhSighash(sighash::P2wpkhError),
1021    /// Sighash computation error (taproot input).
1022    TaprootError(sighash::TaprootError),
1023    /// Unable to determine the output type.
1024    UnknownOutputType,
1025    /// Unable to find key.
1026    KeyNotFound,
1027    /// Attempt to sign an input with the wrong signing algorithm.
1028    WrongSigningAlgorithm,
1029    /// Signing request currently unsupported.
1030    Unsupported,
1031}
1032
1033impl From<core::convert::Infallible> for SignError {
1034    fn from(never: core::convert::Infallible) -> Self { match never {} }
1035}
1036
1037impl fmt::Display for SignError {
1038    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1039        use SignError::*;
1040
1041        match *self {
1042            IndexOutOfBounds(ref e) => write_err!(f, "index out of bounds"; e),
1043            InvalidSighashType => write!(f, "invalid sighash type"),
1044            MissingInputUtxo => write!(f, "missing input utxo in PBST"),
1045            MissingRedeemScript => write!(f, "missing redeem script"),
1046            MissingSpendUtxo => write!(f, "missing spend utxo in PSBT"),
1047            MissingWitnessScript => write!(f, "missing witness script"),
1048            MismatchedAlgoKey => write!(f, "signing algorithm and key type does not match"),
1049            NotEcdsa => write!(f, "attempted to ECDSA sign an non-ECDSA input"),
1050            NotWpkh => write!(f, "the scriptPubkey is not a P2WPKH script"),
1051            SegwitV0Sighash(ref e) => write_err!(f, "segwit v0 sighash"; e),
1052            P2wpkhSighash(ref e) => write_err!(f, "p2wpkh sighash"; e),
1053            TaprootError(ref e) => write_err!(f, "taproot sighash"; e),
1054            UnknownOutputType => write!(f, "unable to determine the output type"),
1055            KeyNotFound => write!(f, "unable to find key"),
1056            WrongSigningAlgorithm =>
1057                write!(f, "attempt to sign an input with the wrong signing algorithm"),
1058            Unsupported => write!(f, "signing request currently unsupported"),
1059        }
1060    }
1061}
1062
1063#[cfg(feature = "std")]
1064impl std::error::Error for SignError {
1065    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1066        use SignError::*;
1067
1068        match *self {
1069            SegwitV0Sighash(ref e) => Some(e),
1070            P2wpkhSighash(ref e) => Some(e),
1071            TaprootError(ref e) => Some(e),
1072            IndexOutOfBounds(ref e) => Some(e),
1073            InvalidSighashType
1074            | MissingInputUtxo
1075            | MissingRedeemScript
1076            | MissingSpendUtxo
1077            | MissingWitnessScript
1078            | MismatchedAlgoKey
1079            | NotEcdsa
1080            | NotWpkh
1081            | UnknownOutputType
1082            | KeyNotFound
1083            | WrongSigningAlgorithm
1084            | Unsupported => None,
1085        }
1086    }
1087}
1088
1089impl From<sighash::P2wpkhError> for SignError {
1090    fn from(e: sighash::P2wpkhError) -> Self { Self::P2wpkhSighash(e) }
1091}
1092
1093impl From<IndexOutOfBoundsError> for SignError {
1094    fn from(e: IndexOutOfBoundsError) -> Self { SignError::IndexOutOfBounds(e) }
1095}
1096
1097impl From<sighash::TaprootError> for SignError {
1098    fn from(e: sighash::TaprootError) -> Self { SignError::TaprootError(e) }
1099}
1100
1101/// This error is returned when extracting a [`Transaction`] from a [`Psbt`].
1102#[derive(Debug, Clone, PartialEq, Eq)]
1103#[non_exhaustive]
1104#[allow(clippy::result_large_err)]
1105pub enum ExtractTxError {
1106    /// The [`FeeRate`] is too high
1107    AbsurdFeeRate {
1108        /// The [`FeeRate`]
1109        fee_rate: FeeRate,
1110        /// The extracted [`Transaction`] (use this to ignore the error)
1111        tx: Transaction,
1112    },
1113    /// One or more of the inputs lacks value information (witness_utxo or non_witness_utxo)
1114    MissingInputValue {
1115        /// The extracted [`Transaction`] (use this to ignore the error)
1116        tx: Transaction,
1117    },
1118    /// Input value is less than Output Value, and the [`Transaction`] would be invalid.
1119    SendingTooMuch {
1120        /// The original [`Psbt`] is returned untouched.
1121        psbt: Psbt,
1122    },
1123}
1124
1125impl From<core::convert::Infallible> for ExtractTxError {
1126    fn from(never: core::convert::Infallible) -> Self { match never {} }
1127}
1128
1129impl fmt::Display for ExtractTxError {
1130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1131        use ExtractTxError::*;
1132
1133        match *self {
1134            AbsurdFeeRate { fee_rate, .. } =>
1135                write!(f, "An absurdly high fee rate of {}", fee_rate),
1136            MissingInputValue { .. } => write!(
1137                f,
1138                "One of the inputs lacked value information (witness_utxo or non_witness_utxo)"
1139            ),
1140            SendingTooMuch { .. } => write!(
1141                f,
1142                "Transaction would be invalid due to output value being greater than input value."
1143            ),
1144        }
1145    }
1146}
1147
1148#[cfg(feature = "std")]
1149impl std::error::Error for ExtractTxError {
1150    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1151        use ExtractTxError::*;
1152
1153        match *self {
1154            AbsurdFeeRate { .. } | MissingInputValue { .. } | SendingTooMuch { .. } => None,
1155        }
1156    }
1157}
1158
1159/// Input index out of bounds (actual index, maximum index allowed).
1160#[derive(Debug, Clone, PartialEq, Eq)]
1161#[non_exhaustive]
1162pub enum IndexOutOfBoundsError {
1163    /// The index is out of bounds for the `psbt.inputs` vector.
1164    Inputs {
1165        /// Attempted index access.
1166        index: usize,
1167        /// Length of the PBST inputs vector.
1168        length: usize,
1169    },
1170    /// The index is out of bounds for the `psbt.unsigned_tx.input` vector.
1171    TxInput {
1172        /// Attempted index access.
1173        index: usize,
1174        /// Length of the PBST's unsigned transaction input vector.
1175        length: usize,
1176    },
1177}
1178
1179impl From<core::convert::Infallible> for IndexOutOfBoundsError {
1180    fn from(never: core::convert::Infallible) -> Self { match never {} }
1181}
1182
1183impl fmt::Display for IndexOutOfBoundsError {
1184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1185        use IndexOutOfBoundsError::*;
1186
1187        match *self {
1188            Inputs { ref index, ref length } => write!(
1189                f,
1190                "index {} is out-of-bounds for PSBT inputs vector length {}",
1191                index, length
1192            ),
1193            TxInput { ref index, ref length } => write!(
1194                f,
1195                "index {} is out-of-bounds for PSBT unsigned tx input vector length {}",
1196                index, length
1197            ),
1198        }
1199    }
1200}
1201
1202#[cfg(feature = "std")]
1203impl std::error::Error for IndexOutOfBoundsError {
1204    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1205        use IndexOutOfBoundsError::*;
1206
1207        match *self {
1208            Inputs { .. } | TxInput { .. } => None,
1209        }
1210    }
1211}
1212
1213#[cfg(feature = "base64")]
1214mod display_from_str {
1215    use core::fmt::{self, Display, Formatter};
1216    use core::str::FromStr;
1217
1218    use bitcoin::base64::display::Base64Display;
1219    use bitcoin::base64::prelude::{Engine as _, BASE64_STANDARD};
1220
1221    use super::*;
1222    use crate::error::write_err;
1223
1224    /// Error encountered during PSBT decoding from Base64 string.
1225    #[derive(Debug)]
1226    #[non_exhaustive]
1227    pub enum PsbtParseError {
1228        /// Error in internal PSBT data structure.
1229        PsbtEncoding(Error),
1230        /// Error in PSBT Base64 encoding.
1231        Base64Encoding(bitcoin::base64::DecodeError),
1232    }
1233
1234    impl From<core::convert::Infallible> for PsbtParseError {
1235        fn from(never: core::convert::Infallible) -> Self { match never {} }
1236    }
1237
1238    impl Display for PsbtParseError {
1239        fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1240            use self::PsbtParseError::*;
1241
1242            match *self {
1243                PsbtEncoding(ref e) => write_err!(f, "error in internal PSBT data structure"; e),
1244                Base64Encoding(ref e) => write_err!(f, "error in PSBT base64 encoding"; e),
1245            }
1246        }
1247    }
1248
1249    #[cfg(feature = "std")]
1250    impl std::error::Error for PsbtParseError {
1251        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1252            use self::PsbtParseError::*;
1253
1254            match self {
1255                PsbtEncoding(e) => Some(e),
1256                Base64Encoding(e) => Some(e),
1257            }
1258        }
1259    }
1260
1261    impl Display for Psbt {
1262        fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1263            write!(f, "{}", Base64Display::new(&self.serialize(), &BASE64_STANDARD))
1264        }
1265    }
1266
1267    impl FromStr for Psbt {
1268        type Err = PsbtParseError;
1269
1270        fn from_str(s: &str) -> Result<Self, Self::Err> {
1271            let data = BASE64_STANDARD.decode(s).map_err(PsbtParseError::Base64Encoding)?;
1272            Psbt::deserialize(&data).map_err(PsbtParseError::PsbtEncoding)
1273        }
1274    }
1275}
1276#[cfg(feature = "base64")]
1277pub use self::display_from_str::PsbtParseError;
1278
1279#[cfg(test)]
1280mod tests {
1281    use std::collections::BTreeMap;
1282
1283    use bitcoin::bip32::{ChildNumber, KeySource, Xpriv, Xpub};
1284    use bitcoin::blockdata::locktime::absolute;
1285    use bitcoin::blockdata::script::ScriptBuf;
1286    use bitcoin::blockdata::transaction::{self, OutPoint, Sequence, Transaction, TxIn, TxOut};
1287    use bitcoin::blockdata::witness::Witness;
1288    use bitcoin::hashes::{hash160, ripemd160, sha256, Hash};
1289    use bitcoin::hex::{test_hex_unwrap as hex, FromHex};
1290    use bitcoin::secp256k1::Secp256k1;
1291    use bitcoin::NetworkKind;
1292    #[cfg(feature = "rand")]
1293    use {
1294        bitcoin::bip32::{DerivationPath, Fingerprint},
1295        bitcoin::key::WPubkeyHash,
1296        bitcoin::locktime,
1297        bitcoin::witness_version::WitnessVersion,
1298        bitcoin::WitnessProgram,
1299    };
1300
1301    use super::*;
1302    use crate::v0::bitcoin::map::{Input, Output};
1303    use crate::v0::bitcoin::raw;
1304    use crate::v0::bitcoin::serialize::{Deserialize, Serialize};
1305
1306    #[track_caller]
1307    pub fn hex_psbt(s: &str) -> Result<Psbt, crate::v0::bitcoin::error::Error> {
1308        let r: Result<Vec<u8>, bitcoin::hex::HexToBytesError> = Vec::from_hex(s);
1309        match r {
1310            Err(_e) => panic!("unable to parse hex string {}", s),
1311            Ok(v) => Psbt::deserialize(&v),
1312        }
1313    }
1314
1315    #[track_caller]
1316    fn psbt_with_values(input: u64, output: u64) -> Psbt {
1317        Psbt {
1318            unsigned_tx: Transaction {
1319                version: transaction::Version::TWO,
1320                lock_time: absolute::LockTime::ZERO,
1321                input: vec![TxIn {
1322                    previous_output: OutPoint {
1323                        txid: "f61b1742ca13176464adb3cb66050c00787bb3a4eead37e985f2df1e37718126"
1324                            .parse()
1325                            .unwrap(),
1326                        vout: 0,
1327                    },
1328                    script_sig: ScriptBuf::new(),
1329                    sequence: Sequence::ENABLE_LOCKTIME_NO_RBF,
1330                    witness: Witness::default(),
1331                }],
1332                output: vec![TxOut {
1333                    value: Amount::from_sat(output),
1334                    script_pubkey: ScriptBuf::from_hex(
1335                        "a9143545e6e33b832c47050f24d3eeb93c9c03948bc787",
1336                    )
1337                    .unwrap(),
1338                }],
1339            },
1340            xpub: Default::default(),
1341            version: 0,
1342            proprietary: BTreeMap::new(),
1343            unknown: BTreeMap::new(),
1344
1345            inputs: vec![Input {
1346                witness_utxo: Some(TxOut {
1347                    value: Amount::from_sat(input),
1348                    script_pubkey: ScriptBuf::from_hex(
1349                        "a914339725ba21efd62ac753a9bcd067d6c7a6a39d0587",
1350                    )
1351                    .unwrap(),
1352                }),
1353                ..Default::default()
1354            }],
1355            outputs: vec![],
1356        }
1357    }
1358
1359    #[test]
1360    fn trivial_psbt() {
1361        let psbt = Psbt {
1362            unsigned_tx: Transaction {
1363                version: transaction::Version::TWO,
1364                lock_time: absolute::LockTime::ZERO,
1365                input: vec![],
1366                output: vec![],
1367            },
1368            xpub: Default::default(),
1369            version: 0,
1370            proprietary: BTreeMap::new(),
1371            unknown: BTreeMap::new(),
1372
1373            inputs: vec![],
1374            outputs: vec![],
1375        };
1376        assert_eq!(psbt.serialize_hex(), "70736274ff01000a0200000000000000000000");
1377    }
1378
1379    #[test]
1380    fn psbt_uncompressed_key() {
1381        let psbt: Psbt = hex_psbt("70736274ff01003302000000010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff000000000000420204bb0d5d0cca36e7b9c80f63bc04c1240babb83bcd2803ef7ac8b6e2af594291daec281e856c98d210c5ab14dfd5828761f8ee7d5f45ca21ad3e4c4b41b747a3a047304402204f67e2afb76142d44fae58a2495d33a3419daa26cd0db8d04f3452b63289ac0f022010762a9fb67e94cc5cad9026f6dc99ff7f070f4278d30fbc7d0c869dd38c7fe70100").unwrap();
1382        assert!(psbt.inputs[0].partial_sigs.len() == 1);
1383        let pk = psbt.inputs[0].partial_sigs.iter().next().unwrap().0;
1384        assert!(!pk.compressed);
1385    }
1386
1387    #[test]
1388    fn psbt_high_fee_checks() {
1389        let psbt = psbt_with_values(5_000_000_000_000, 1000);
1390        assert_eq!(
1391            psbt.clone().extract_tx().map_err(|e| match e {
1392                ExtractTxError::AbsurdFeeRate { fee_rate, .. } => fee_rate,
1393                _ => panic!(""),
1394            }),
1395            Err(FeeRate::from_sat_per_kwu(15060240960843))
1396        );
1397        assert_eq!(
1398            psbt.clone().extract_tx_fee_rate_limit().map_err(|e| match e {
1399                ExtractTxError::AbsurdFeeRate { fee_rate, .. } => fee_rate,
1400                _ => panic!(""),
1401            }),
1402            Err(FeeRate::from_sat_per_kwu(15060240960843))
1403        );
1404        assert_eq!(
1405            psbt.clone()
1406                .extract_tx_with_fee_rate_limit(FeeRate::from_sat_per_kwu(15060240960842))
1407                .map_err(|e| match e {
1408                    ExtractTxError::AbsurdFeeRate { fee_rate, .. } => fee_rate,
1409                    _ => panic!(""),
1410                }),
1411            Err(FeeRate::from_sat_per_kwu(15060240960843))
1412        );
1413        assert!(psbt
1414            .extract_tx_with_fee_rate_limit(FeeRate::from_sat_per_kwu(15060240960843))
1415            .is_ok());
1416
1417        // Testing that extract_tx will error at 25k sat/vbyte (6250000 sat/kwu)
1418        assert_eq!(
1419            psbt_with_values(2076001, 1000).extract_tx().map_err(|e| match e {
1420                ExtractTxError::AbsurdFeeRate { fee_rate, .. } => fee_rate,
1421                _ => panic!(""),
1422            }),
1423            Err(FeeRate::from_sat_per_kwu(6250003)) // 6250000 is 25k sat/vbyte
1424        );
1425
1426        // Lowering the input satoshis by 1 lowers the sat/kwu by 3
1427        // Putting it exactly at 25k sat/vbyte
1428        assert!(psbt_with_values(2076000, 1000).extract_tx().is_ok());
1429    }
1430
1431    #[test]
1432    fn serialize_then_deserialize_output() {
1433        let secp = &Secp256k1::new();
1434        let seed = hex!("000102030405060708090a0b0c0d0e0f");
1435
1436        let mut hd_keypaths: BTreeMap<PublicKey, KeySource> = Default::default();
1437
1438        let mut sk: Xpriv = Xpriv::new_master(NetworkKind::Main, &seed).unwrap();
1439
1440        let fprint = sk.fingerprint(secp);
1441
1442        let dpath: Vec<ChildNumber> = vec![
1443            ChildNumber::from_normal_idx(0).unwrap(),
1444            ChildNumber::from_normal_idx(1).unwrap(),
1445            ChildNumber::from_normal_idx(2).unwrap(),
1446            ChildNumber::from_normal_idx(4).unwrap(),
1447            ChildNumber::from_normal_idx(42).unwrap(),
1448            ChildNumber::from_hardened_idx(69).unwrap(),
1449            ChildNumber::from_normal_idx(420).unwrap(),
1450            ChildNumber::from_normal_idx(31337).unwrap(),
1451        ];
1452
1453        sk = sk.derive_priv(secp, &dpath).unwrap();
1454
1455        let pk = Xpub::from_priv(secp, &sk);
1456
1457        hd_keypaths.insert(pk.public_key.into(), (fprint, dpath.into()));
1458
1459        let expected: Output = Output {
1460            redeem_script: Some(
1461                ScriptBuf::from_hex("76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac").unwrap(),
1462            ),
1463            witness_script: Some(
1464                ScriptBuf::from_hex("a9143545e6e33b832c47050f24d3eeb93c9c03948bc787").unwrap(),
1465            ),
1466            bip32_derivation: hd_keypaths,
1467            ..Default::default()
1468        };
1469
1470        let actual = Output::deserialize(&expected.serialize()).unwrap();
1471
1472        assert_eq!(expected, actual);
1473    }
1474
1475    #[test]
1476    fn serialize_then_deserialize_global() {
1477        let expected = Psbt {
1478            unsigned_tx: Transaction {
1479                version: transaction::Version::TWO,
1480                lock_time: absolute::LockTime::from_consensus(1257139),
1481                input: vec![TxIn {
1482                    previous_output: OutPoint {
1483                        txid: "f61b1742ca13176464adb3cb66050c00787bb3a4eead37e985f2df1e37718126"
1484                            .parse()
1485                            .unwrap(),
1486                        vout: 0,
1487                    },
1488                    script_sig: ScriptBuf::new(),
1489                    sequence: Sequence::ENABLE_LOCKTIME_NO_RBF,
1490                    witness: Witness::default(),
1491                }],
1492                output: vec![
1493                    TxOut {
1494                        value: Amount::from_sat(99_999_699),
1495                        script_pubkey: ScriptBuf::from_hex(
1496                            "76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac",
1497                        )
1498                        .unwrap(),
1499                    },
1500                    TxOut {
1501                        value: Amount::from_sat(100_000_000),
1502                        script_pubkey: ScriptBuf::from_hex(
1503                            "a9143545e6e33b832c47050f24d3eeb93c9c03948bc787",
1504                        )
1505                        .unwrap(),
1506                    },
1507                ],
1508            },
1509            xpub: Default::default(),
1510            version: 0,
1511            proprietary: Default::default(),
1512            unknown: Default::default(),
1513            inputs: vec![Input::default()],
1514            outputs: vec![Output::default(), Output::default()],
1515        };
1516
1517        let actual: Psbt = Psbt::deserialize(&expected.serialize()).unwrap();
1518        assert_eq!(expected, actual);
1519    }
1520
1521    #[test]
1522    fn serialize_then_deserialize_psbtkvpair() {
1523        let expected = raw::Pair {
1524            key: raw::Key { type_value: 0u8, key: vec![42u8, 69u8] },
1525            value: vec![69u8, 42u8, 4u8],
1526        };
1527
1528        let actual = raw::Pair::deserialize(&expected.serialize()).unwrap();
1529
1530        assert_eq!(expected, actual);
1531    }
1532
1533    #[test]
1534    fn deserialize_and_serialize_psbt_with_two_partial_sigs() {
1535        let hex = "70736274ff0100890200000001207ae985d787dfe6143d5c58fad79cc7105e0e799fcf033b7f2ba17e62d7b3200000000000ffffffff02563d03000000000022002019899534b9a011043c0dd57c3ff9a381c3522c5f27c6a42319085b56ca543a1d6adc020000000000220020618b47a07ebecca4e156edb1b9ea7c24bdee0139fc049237965ffdaf56d5ee73000000000001012b801a0600000000002200201148e93e9315e37dbed2121be5239257af35adc03ffdfc5d914b083afa44dab82202025fe7371376d53cf8a2783917c28bf30bd690b0a4d4a207690093ca2b920ee076473044022007e06b362e89912abd4661f47945430739b006a85d1b2a16c01dc1a4bd07acab022061576d7aa834988b7ab94ef21d8eebd996ea59ea20529a19b15f0c9cebe3d8ac01220202b3fe93530020a8294f0e527e33fbdff184f047eb6b5a1558a352f62c29972f8a473044022002787f926d6817504431ee281183b8119b6845bfaa6befae45e13b6d430c9d2f02202859f149a6cd26ae2f03a107e7f33c7d91730dade305fe077bae677b5d44952a01010547522102b3fe93530020a8294f0e527e33fbdff184f047eb6b5a1558a352f62c29972f8a21025fe7371376d53cf8a2783917c28bf30bd690b0a4d4a207690093ca2b920ee07652ae0001014752210283ef76537f2d58ae3aa3a4bd8ae41c3f230ccadffb1a0bd3ca504d871cff05e7210353d79cc0cb1396f4ce278d005f16d948e02a6aec9ed1109f13747ecb1507b37b52ae00010147522102b3937241777b6665e0d694e52f9c1b188433641df852da6fc42187b5d8a368a321034cdd474f01cc5aa7ff834ad8bcc882a87e854affc775486bc2a9f62e8f49bd7852ae00";
1536        let psbt: Psbt = hex_psbt(hex).unwrap();
1537        assert_eq!(hex, psbt.serialize_hex());
1538    }
1539
1540    #[cfg(feature = "serde")]
1541    #[test]
1542    fn test_serde_psbt() {
1543        //! Create a full PSBT value with various fields filled and make sure it can be JSONized.
1544        use bitcoin::hashes::sha256d;
1545
1546        use crate::v0::bitcoin::map::Input;
1547
1548        // create some values to use in the PSBT
1549        let tx = Transaction {
1550            version: transaction::Version::ONE,
1551            lock_time: absolute::LockTime::ZERO,
1552            input: vec![TxIn {
1553                previous_output: OutPoint {
1554                    txid: "e567952fb6cc33857f392efa3a46c995a28f69cca4bb1b37e0204dab1ec7a389"
1555                        .parse()
1556                        .unwrap(),
1557                    vout: 1,
1558                },
1559                script_sig: ScriptBuf::from_hex("160014be18d152a9b012039daf3da7de4f53349eecb985")
1560                    .unwrap(),
1561                sequence: Sequence::MAX,
1562                witness: Witness::from_slice(&[hex!(
1563                    "03d2e15674941bad4a996372cb87e1856d3652606d98562fe39c5e9e7e413f2105"
1564                )]),
1565            }],
1566            output: vec![TxOut {
1567                value: Amount::from_sat(190_303_501_938),
1568                script_pubkey: ScriptBuf::from_hex(
1569                    "a914339725ba21efd62ac753a9bcd067d6c7a6a39d0587",
1570                )
1571                .unwrap(),
1572            }],
1573        };
1574        let unknown: BTreeMap<raw::Key, Vec<u8>> =
1575            vec![(raw::Key { type_value: 1, key: vec![0, 1] }, vec![3, 4, 5])]
1576                .into_iter()
1577                .collect();
1578        let key_source = ("deadbeef".parse().unwrap(), "0'/1".parse().unwrap());
1579        let keypaths: BTreeMap<bitcoin::PublicKey, KeySource> = vec![(
1580            "0339880dc92394b7355e3d0439fa283c31de7590812ea011c4245c0674a685e883".parse().unwrap(),
1581            key_source.clone(),
1582        )]
1583        .into_iter()
1584        .collect();
1585
1586        let proprietary: BTreeMap<raw::ProprietaryKey, Vec<u8>> = vec![(
1587            raw::ProprietaryKey {
1588                prefix: "prefx".as_bytes().to_vec(),
1589                subtype: 42,
1590                key: "test_key".as_bytes().to_vec(),
1591            },
1592            vec![5, 6, 7],
1593        )]
1594        .into_iter()
1595        .collect();
1596
1597        let psbt = Psbt {
1598            version: 0,
1599            xpub: {
1600                let xpub: Xpub =
1601                    "xpub661MyMwAqRbcGoRVtwfvzZsq2VBJR1LAHfQstHUoxqDorV89vRoMxUZ27kLrraAj6MPi\
1602                    QfrDb27gigC1VS1dBXi5jGpxmMeBXEkKkcXUTg4".parse().unwrap();
1603                vec![(xpub, key_source)].into_iter().collect()
1604            },
1605            unsigned_tx: {
1606                let mut unsigned = tx.clone();
1607                unsigned.input[0].script_sig = ScriptBuf::new();
1608                unsigned.input[0].witness = Witness::default();
1609                unsigned
1610            },
1611            proprietary: proprietary.clone(),
1612            unknown: unknown.clone(),
1613
1614            inputs: vec![
1615                Input {
1616                    non_witness_utxo: Some(tx),
1617                    witness_utxo: Some(TxOut {
1618                        value: Amount::from_sat(190_303_501_938),
1619                        script_pubkey: ScriptBuf::from_hex("a914339725ba21efd62ac753a9bcd067d6c7a6a39d0587").unwrap(),
1620                    }),
1621                    sighash_type: Some("SIGHASH_SINGLE|SIGHASH_ANYONECANPAY".parse::<PsbtSighashType>().unwrap()),
1622                    redeem_script: Some(vec![0x51].into()),
1623                    witness_script: None,
1624                    partial_sigs: vec![(
1625                        "0339880dc92394b7355e3d0439fa283c31de7590812ea011c4245c0674a685e883".parse().unwrap(),
1626                        "304402204f67e2afb76142d44fae58a2495d33a3419daa26cd0db8d04f3452b63289ac0f022010762a9fb67e94cc5cad9026f6dc99ff7f070f4278d30fbc7d0c869dd38c7fe701".parse().unwrap(),
1627                    )].into_iter().collect(),
1628                    bip32_derivation: keypaths.clone(),
1629                    final_script_witness: Some(Witness::from_slice(&[vec![1, 3], vec![5]])),
1630                    ripemd160_preimages: vec![(ripemd160::Hash::hash(&[]), vec![1, 2])].into_iter().collect(),
1631                    sha256_preimages: vec![(sha256::Hash::hash(&[]), vec![1, 2])].into_iter().collect(),
1632                    hash160_preimages: vec![(hash160::Hash::hash(&[]), vec![1, 2])].into_iter().collect(),
1633                    hash256_preimages: vec![(sha256d::Hash::hash(&[]), vec![1, 2])].into_iter().collect(),
1634                    proprietary: proprietary.clone(),
1635                    unknown: unknown.clone(),
1636                    ..Default::default()
1637                }
1638            ],
1639            outputs: vec![
1640                Output {
1641                    bip32_derivation: keypaths,
1642                    proprietary,
1643                    unknown,
1644                    ..Default::default()
1645                }
1646            ],
1647        };
1648        let encoded = serde_json::to_string(&psbt).unwrap();
1649        let decoded: Psbt = serde_json::from_str(&encoded).unwrap();
1650        assert_eq!(psbt, decoded);
1651    }
1652
1653    mod bip_vectors {
1654        use std::collections::BTreeMap;
1655        #[cfg(feature = "base64")]
1656        use std::str::FromStr;
1657
1658        use bitcoin::blockdata::locktime::absolute;
1659        use bitcoin::blockdata::script::ScriptBuf;
1660        use bitcoin::blockdata::transaction::{OutPoint, Sequence, Transaction, TxIn, TxOut};
1661        use bitcoin::blockdata::witness::Witness;
1662        use bitcoin::sighash::EcdsaSighashType;
1663
1664        use super::*;
1665        use crate::v0::bitcoin::map::{Input, Map, Output};
1666        use crate::v0::bitcoin::Psbt;
1667
1668        #[test]
1669        #[should_panic(expected = "InvalidMagic")]
1670        fn invalid_vector_1() {
1671            hex_psbt("0200000001268171371edff285e937adeea4b37b78000c0566cbb3ad64641713ca42171bf6000000006a473044022070b2245123e6bf474d60c5b50c043d4c691a5d2435f09a34a7662a9dc251790a022001329ca9dacf280bdf30740ec0390422422c81cb45839457aeb76fc12edd95b3012102657d118d3357b8e0f4c2cd46db7b39f6d9c38d9a70abcb9b2de5dc8dbfe4ce31feffffff02d3dff505000000001976a914d0c59903c5bac2868760e90fd521a4665aa7652088ac00e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787b32e1300").unwrap();
1672        }
1673
1674        #[cfg(feature = "base64")]
1675        #[test]
1676        #[should_panic(expected = "InvalidMagic")]
1677        fn invalid_vector_1_base64() {
1678            Psbt::from_str("AgAAAAEmgXE3Ht/yhek3re6ks3t4AAwFZsuzrWRkFxPKQhcb9gAAAABqRzBEAiBwsiRRI+a/R01gxbUMBD1MaRpdJDXwmjSnZiqdwlF5CgIgATKcqdrPKAvfMHQOwDkEIkIsgctFg5RXrrdvwS7dlbMBIQJlfRGNM1e44PTCzUbbezn22cONmnCry5st5dyNv+TOMf7///8C09/1BQAAAAAZdqkU0MWZA8W6woaHYOkP1SGkZlqnZSCIrADh9QUAAAAAF6kUNUXm4zuDLEcFDyTT7rk8nAOUi8eHsy4TAA==").unwrap();
1679        }
1680
1681        #[test]
1682        #[should_panic(expected = "ConsensusEncoding")]
1683        fn invalid_vector_2() {
1684            hex_psbt("70736274ff0100750200000001268171371edff285e937adeea4b37b78000c0566cbb3ad64641713ca42171bf60000000000feffffff02d3dff505000000001976a914d0c59903c5bac2868760e90fd521a4665aa7652088ac00e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787b32e1300000100fda5010100000000010289a3c71eab4d20e0371bbba4cc698fa295c9463afa2e397f8533ccb62f9567e50100000017160014be18d152a9b012039daf3da7de4f53349eecb985ffffffff86f8aa43a71dff1448893a530a7237ef6b4608bbb2dd2d0171e63aec6a4890b40100000017160014fe3e9ef1a745e974d902c4355943abcb34bd5353ffffffff0200c2eb0b000000001976a91485cff1097fd9e008bb34af709c62197b38978a4888ac72fef84e2c00000017a914339725ba21efd62ac753a9bcd067d6c7a6a39d05870247304402202712be22e0270f394f568311dc7ca9a68970b8025fdd3b240229f07f8a5f3a240220018b38d7dcd314e734c9276bd6fb40f673325bc4baa144c800d2f2f02db2765c012103d2e15674941bad4a996372cb87e1856d3652606d98562fe39c5e9e7e413f210502483045022100d12b852d85dcd961d2f5f4ab660654df6eedcc794c0c33ce5cc309ffb5fce58d022067338a8e0e1725c197fb1a88af59f51e44e4255b20167c8684031c05d1f2592a01210223b72beef0965d10be0778efecd61fcac6f79a4ea169393380734464f84f2ab30000000000")
1685                .unwrap();
1686        }
1687
1688        #[cfg(feature = "base64")]
1689        #[test]
1690        #[should_panic(expected = "ConsensusEncoding")]
1691        fn invalid_vector_2_base64() {
1692            Psbt::from_str("cHNidP8BAHUCAAAAASaBcTce3/KF6Tet7qSze3gADAVmy7OtZGQXE8pCFxv2AAAAAAD+////AtPf9QUAAAAAGXapFNDFmQPFusKGh2DpD9UhpGZap2UgiKwA4fUFAAAAABepFDVF5uM7gyxHBQ8k0+65PJwDlIvHh7MuEwAAAQD9pQEBAAAAAAECiaPHHqtNIOA3G7ukzGmPopXJRjr6Ljl/hTPMti+VZ+UBAAAAFxYAFL4Y0VKpsBIDna89p95PUzSe7LmF/////4b4qkOnHf8USIk6UwpyN+9rRgi7st0tAXHmOuxqSJC0AQAAABcWABT+Pp7xp0XpdNkCxDVZQ6vLNL1TU/////8CAMLrCwAAAAAZdqkUhc/xCX/Z4Ai7NK9wnGIZeziXikiIrHL++E4sAAAAF6kUM5cluiHv1irHU6m80GfWx6ajnQWHAkcwRAIgJxK+IuAnDzlPVoMR3HyppolwuAJf3TskAinwf4pfOiQCIAGLONfc0xTnNMkna9b7QPZzMlvEuqFEyADS8vAtsnZcASED0uFWdJQbrUqZY3LLh+GFbTZSYG2YVi/jnF6efkE/IQUCSDBFAiEA0SuFLYXc2WHS9fSrZgZU327tzHlMDDPOXMMJ/7X85Y0CIGczio4OFyXBl/saiK9Z9R5E5CVbIBZ8hoQDHAXR8lkqASECI7cr7vCWXRC+B3jv7NYfysb3mk6haTkzgHNEZPhPKrMAAAAAAA==")
1693                .unwrap();
1694        }
1695
1696        #[test]
1697        #[should_panic(expected = "UnsignedTxHasScriptSigs")]
1698        fn invalid_vector_3() {
1699            hex_psbt("70736274ff0100fd0a010200000002ab0949a08c5af7c49b8212f417e2f15ab3f5c33dcf153821a8139f877a5b7be4000000006a47304402204759661797c01b036b25928948686218347d89864b719e1f7fcf57d1e511658702205309eabf56aa4d8891ffd111fdf1336f3a29da866d7f8486d75546ceedaf93190121035cdc61fc7ba971c0b501a646a2a83b102cb43881217ca682dc86e2d73fa88292feffffffab0949a08c5af7c49b8212f417e2f15ab3f5c33dcf153821a8139f877a5b7be40100000000feffffff02603bea0b000000001976a914768a40bbd740cbe81d988e71de2a4d5c71396b1d88ac8e240000000000001976a9146f4620b553fa095e721b9ee0efe9fa039cca459788ac00000000000001012000e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787010416001485d13537f2e265405a34dbafa9e3dda01fb82308000000").unwrap();
1700        }
1701
1702        #[cfg(feature = "base64")]
1703        #[test]
1704        #[should_panic(expected = "UnsignedTxHasScriptSigs")]
1705        fn invalid_vector_3_base64() {
1706            Psbt::from_str("cHNidP8BAP0KAQIAAAACqwlJoIxa98SbghL0F+LxWrP1wz3PFTghqBOfh3pbe+QAAAAAakcwRAIgR1lmF5fAGwNrJZKJSGhiGDR9iYZLcZ4ff89X0eURZYcCIFMJ6r9Wqk2Ikf/REf3xM286KdqGbX+EhtdVRs7tr5MZASEDXNxh/HupccC1AaZGoqg7ECy0OIEhfKaC3Ibi1z+ogpL+////qwlJoIxa98SbghL0F+LxWrP1wz3PFTghqBOfh3pbe+QBAAAAAP7///8CYDvqCwAAAAAZdqkUdopAu9dAy+gdmI5x3ipNXHE5ax2IrI4kAAAAAAAAGXapFG9GILVT+glechue4O/p+gOcykWXiKwAAAAAAAABASAA4fUFAAAAABepFDVF5uM7gyxHBQ8k0+65PJwDlIvHhwEEFgAUhdE1N/LiZUBaNNuvqePdoB+4IwgAAAA=").unwrap();
1707        }
1708
1709        #[test]
1710        #[should_panic(expected = "MustHaveUnsignedTx")]
1711        fn invalid_vector_4() {
1712            hex_psbt("70736274ff000100fda5010100000000010289a3c71eab4d20e0371bbba4cc698fa295c9463afa2e397f8533ccb62f9567e50100000017160014be18d152a9b012039daf3da7de4f53349eecb985ffffffff86f8aa43a71dff1448893a530a7237ef6b4608bbb2dd2d0171e63aec6a4890b40100000017160014fe3e9ef1a745e974d902c4355943abcb34bd5353ffffffff0200c2eb0b000000001976a91485cff1097fd9e008bb34af709c62197b38978a4888ac72fef84e2c00000017a914339725ba21efd62ac753a9bcd067d6c7a6a39d05870247304402202712be22e0270f394f568311dc7ca9a68970b8025fdd3b240229f07f8a5f3a240220018b38d7dcd314e734c9276bd6fb40f673325bc4baa144c800d2f2f02db2765c012103d2e15674941bad4a996372cb87e1856d3652606d98562fe39c5e9e7e413f210502483045022100d12b852d85dcd961d2f5f4ab660654df6eedcc794c0c33ce5cc309ffb5fce58d022067338a8e0e1725c197fb1a88af59f51e44e4255b20167c8684031c05d1f2592a01210223b72beef0965d10be0778efecd61fcac6f79a4ea169393380734464f84f2ab30000000000").unwrap();
1713        }
1714
1715        #[cfg(feature = "base64")]
1716        #[test]
1717        #[should_panic(expected = "MustHaveUnsignedTx")]
1718        fn invalid_vector_4_base64() {
1719            Psbt::from_str("cHNidP8AAQD9pQEBAAAAAAECiaPHHqtNIOA3G7ukzGmPopXJRjr6Ljl/hTPMti+VZ+UBAAAAFxYAFL4Y0VKpsBIDna89p95PUzSe7LmF/////4b4qkOnHf8USIk6UwpyN+9rRgi7st0tAXHmOuxqSJC0AQAAABcWABT+Pp7xp0XpdNkCxDVZQ6vLNL1TU/////8CAMLrCwAAAAAZdqkUhc/xCX/Z4Ai7NK9wnGIZeziXikiIrHL++E4sAAAAF6kUM5cluiHv1irHU6m80GfWx6ajnQWHAkcwRAIgJxK+IuAnDzlPVoMR3HyppolwuAJf3TskAinwf4pfOiQCIAGLONfc0xTnNMkna9b7QPZzMlvEuqFEyADS8vAtsnZcASED0uFWdJQbrUqZY3LLh+GFbTZSYG2YVi/jnF6efkE/IQUCSDBFAiEA0SuFLYXc2WHS9fSrZgZU327tzHlMDDPOXMMJ/7X85Y0CIGczio4OFyXBl/saiK9Z9R5E5CVbIBZ8hoQDHAXR8lkqASECI7cr7vCWXRC+B3jv7NYfysb3mk6haTkzgHNEZPhPKrMAAAAAAA==").unwrap();
1720        }
1721
1722        #[test]
1723        #[should_panic(expected = "DuplicateKey(Key { type_value: 0, key: [] })")]
1724        fn invalid_vector_5() {
1725            hex_psbt("70736274ff0100750200000001268171371edff285e937adeea4b37b78000c0566cbb3ad64641713ca42171bf60000000000feffffff02d3dff505000000001976a914d0c59903c5bac2868760e90fd521a4665aa7652088ac00e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787b32e1300000100fda5010100000000010289a3c71eab4d20e0371bbba4cc698fa295c9463afa2e397f8533ccb62f9567e50100000017160014be18d152a9b012039daf3da7de4f53349eecb985ffffffff86f8aa43a71dff1448893a530a7237ef6b4608bbb2dd2d0171e63aec6a4890b40100000017160014fe3e9ef1a745e974d902c4355943abcb34bd5353ffffffff0200c2eb0b000000001976a91485cff1097fd9e008bb34af709c62197b38978a4888ac72fef84e2c00000017a914339725ba21efd62ac753a9bcd067d6c7a6a39d05870247304402202712be22e0270f394f568311dc7ca9a68970b8025fdd3b240229f07f8a5f3a240220018b38d7dcd314e734c9276bd6fb40f673325bc4baa144c800d2f2f02db2765c012103d2e15674941bad4a996372cb87e1856d3652606d98562fe39c5e9e7e413f210502483045022100d12b852d85dcd961d2f5f4ab660654df6eedcc794c0c33ce5cc309ffb5fce58d022067338a8e0e1725c197fb1a88af59f51e44e4255b20167c8684031c05d1f2592a01210223b72beef0965d10be0778efecd61fcac6f79a4ea169393380734464f84f2ab30000000001003f0200000001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000000000ffffffff010000000000000000036a010000000000000000").unwrap();
1726        }
1727
1728        #[cfg(feature = "base64")]
1729        #[test]
1730        #[should_panic(expected = "DuplicateKey(Key { type_value: 0, key: [] })")]
1731        fn invalid_vector_5_base64() {
1732            Psbt::from_str("cHNidP8BAHUCAAAAASaBcTce3/KF6Tet7qSze3gADAVmy7OtZGQXE8pCFxv2AAAAAAD+////AtPf9QUAAAAAGXapFNDFmQPFusKGh2DpD9UhpGZap2UgiKwA4fUFAAAAABepFDVF5uM7gyxHBQ8k0+65PJwDlIvHh7MuEwAAAQD9pQEBAAAAAAECiaPHHqtNIOA3G7ukzGmPopXJRjr6Ljl/hTPMti+VZ+UBAAAAFxYAFL4Y0VKpsBIDna89p95PUzSe7LmF/////4b4qkOnHf8USIk6UwpyN+9rRgi7st0tAXHmOuxqSJC0AQAAABcWABT+Pp7xp0XpdNkCxDVZQ6vLNL1TU/////8CAMLrCwAAAAAZdqkUhc/xCX/Z4Ai7NK9wnGIZeziXikiIrHL++E4sAAAAF6kUM5cluiHv1irHU6m80GfWx6ajnQWHAkcwRAIgJxK+IuAnDzlPVoMR3HyppolwuAJf3TskAinwf4pfOiQCIAGLONfc0xTnNMkna9b7QPZzMlvEuqFEyADS8vAtsnZcASED0uFWdJQbrUqZY3LLh+GFbTZSYG2YVi/jnF6efkE/IQUCSDBFAiEA0SuFLYXc2WHS9fSrZgZU327tzHlMDDPOXMMJ/7X85Y0CIGczio4OFyXBl/saiK9Z9R5E5CVbIBZ8hoQDHAXR8lkqASECI7cr7vCWXRC+B3jv7NYfysb3mk6haTkzgHNEZPhPKrMAAAAAAQA/AgAAAAH//////////////////////////////////////////wAAAAAA/////wEAAAAAAAAAAANqAQAAAAAAAAAA").unwrap();
1733        }
1734
1735        #[test]
1736        fn valid_vector_1() {
1737            let unserialized = Psbt {
1738                unsigned_tx: Transaction {
1739                    version: transaction::Version::TWO,
1740                    lock_time: absolute::LockTime::from_consensus(1257139),
1741                    input: vec![
1742                        TxIn {
1743                            previous_output: OutPoint {
1744                                txid: "f61b1742ca13176464adb3cb66050c00787bb3a4eead37e985f2df1e37718126".parse().unwrap(),
1745                                vout: 0,
1746                            },
1747                            script_sig: ScriptBuf::new(),
1748                            sequence: Sequence::ENABLE_LOCKTIME_NO_RBF,
1749                            witness: Witness::default(),
1750                        }
1751                    ],
1752                    output: vec![
1753                        TxOut {
1754                            value: Amount::from_sat(99_999_699),
1755                            script_pubkey: ScriptBuf::from_hex("76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac").unwrap(),
1756                        },
1757                        TxOut {
1758                            value: Amount::from_sat(100_000_000),
1759                            script_pubkey: ScriptBuf::from_hex("a9143545e6e33b832c47050f24d3eeb93c9c03948bc787").unwrap(),
1760                        },
1761                    ],
1762                },
1763                xpub: Default::default(),
1764                version: 0,
1765                proprietary: BTreeMap::new(),
1766                unknown: BTreeMap::new(),
1767
1768                inputs: vec![
1769                    Input {
1770                        non_witness_utxo: Some(Transaction {
1771                            version: transaction::Version::ONE,
1772                            lock_time: absolute::LockTime::ZERO,
1773                            input: vec![
1774                                TxIn {
1775                                    previous_output: OutPoint {
1776                                        txid: "e567952fb6cc33857f392efa3a46c995a28f69cca4bb1b37e0204dab1ec7a389".parse().unwrap(),
1777                                        vout: 1,
1778                                    },
1779                                    script_sig: ScriptBuf::from_hex("160014be18d152a9b012039daf3da7de4f53349eecb985").unwrap(),
1780                                    sequence: Sequence::MAX,
1781                                    witness: Witness::from_slice(&[
1782                                        hex!("304402202712be22e0270f394f568311dc7ca9a68970b8025fdd3b240229f07f8a5f3a240220018b38d7dcd314e734c9276bd6fb40f673325bc4baa144c800d2f2f02db2765c01"),
1783                                        hex!("03d2e15674941bad4a996372cb87e1856d3652606d98562fe39c5e9e7e413f2105"),
1784                                    ]),
1785                                },
1786                                TxIn {
1787                                    previous_output: OutPoint {
1788                                        txid: "b490486aec3ae671012dddb2bb08466bef37720a533a894814ff1da743aaf886".parse().unwrap(),
1789                                        vout: 1,
1790                                    },
1791                                    script_sig: ScriptBuf::from_hex("160014fe3e9ef1a745e974d902c4355943abcb34bd5353").unwrap(),
1792                                    sequence: Sequence::MAX,
1793                                    witness: Witness::from_slice(&[
1794                                        hex!("3045022100d12b852d85dcd961d2f5f4ab660654df6eedcc794c0c33ce5cc309ffb5fce58d022067338a8e0e1725c197fb1a88af59f51e44e4255b20167c8684031c05d1f2592a01"),
1795                                        hex!("0223b72beef0965d10be0778efecd61fcac6f79a4ea169393380734464f84f2ab3"),
1796                                    ]),
1797                                }
1798                            ],
1799                            output: vec![
1800                                TxOut {
1801                                    value: Amount::from_sat(200_000_000),
1802                                    script_pubkey: ScriptBuf::from_hex("76a91485cff1097fd9e008bb34af709c62197b38978a4888ac").unwrap(),
1803                                },
1804                                TxOut {
1805                                    value: Amount::from_sat(190_303_501_938),
1806                                    script_pubkey: ScriptBuf::from_hex("a914339725ba21efd62ac753a9bcd067d6c7a6a39d0587").unwrap(),
1807                                },
1808                            ],
1809                        }),
1810                        ..Default::default()
1811                    },
1812                ],
1813                outputs: vec![
1814                    Output {
1815                        ..Default::default()
1816                    },
1817                    Output {
1818                        ..Default::default()
1819                    },
1820                ],
1821            };
1822
1823            let base16str = "70736274ff0100750200000001268171371edff285e937adeea4b37b78000c0566cbb3ad64641713ca42171bf60000000000feffffff02d3dff505000000001976a914d0c59903c5bac2868760e90fd521a4665aa7652088ac00e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787b32e1300000100fda5010100000000010289a3c71eab4d20e0371bbba4cc698fa295c9463afa2e397f8533ccb62f9567e50100000017160014be18d152a9b012039daf3da7de4f53349eecb985ffffffff86f8aa43a71dff1448893a530a7237ef6b4608bbb2dd2d0171e63aec6a4890b40100000017160014fe3e9ef1a745e974d902c4355943abcb34bd5353ffffffff0200c2eb0b000000001976a91485cff1097fd9e008bb34af709c62197b38978a4888ac72fef84e2c00000017a914339725ba21efd62ac753a9bcd067d6c7a6a39d05870247304402202712be22e0270f394f568311dc7ca9a68970b8025fdd3b240229f07f8a5f3a240220018b38d7dcd314e734c9276bd6fb40f673325bc4baa144c800d2f2f02db2765c012103d2e15674941bad4a996372cb87e1856d3652606d98562fe39c5e9e7e413f210502483045022100d12b852d85dcd961d2f5f4ab660654df6eedcc794c0c33ce5cc309ffb5fce58d022067338a8e0e1725c197fb1a88af59f51e44e4255b20167c8684031c05d1f2592a01210223b72beef0965d10be0778efecd61fcac6f79a4ea169393380734464f84f2ab300000000000000";
1824
1825            assert_eq!(unserialized.serialize_hex(), base16str);
1826            assert_eq!(unserialized, hex_psbt(base16str).unwrap());
1827
1828            #[cfg(feature = "base64")]
1829            {
1830                let base64str = "cHNidP8BAHUCAAAAASaBcTce3/KF6Tet7qSze3gADAVmy7OtZGQXE8pCFxv2AAAAAAD+////AtPf9QUAAAAAGXapFNDFmQPFusKGh2DpD9UhpGZap2UgiKwA4fUFAAAAABepFDVF5uM7gyxHBQ8k0+65PJwDlIvHh7MuEwAAAQD9pQEBAAAAAAECiaPHHqtNIOA3G7ukzGmPopXJRjr6Ljl/hTPMti+VZ+UBAAAAFxYAFL4Y0VKpsBIDna89p95PUzSe7LmF/////4b4qkOnHf8USIk6UwpyN+9rRgi7st0tAXHmOuxqSJC0AQAAABcWABT+Pp7xp0XpdNkCxDVZQ6vLNL1TU/////8CAMLrCwAAAAAZdqkUhc/xCX/Z4Ai7NK9wnGIZeziXikiIrHL++E4sAAAAF6kUM5cluiHv1irHU6m80GfWx6ajnQWHAkcwRAIgJxK+IuAnDzlPVoMR3HyppolwuAJf3TskAinwf4pfOiQCIAGLONfc0xTnNMkna9b7QPZzMlvEuqFEyADS8vAtsnZcASED0uFWdJQbrUqZY3LLh+GFbTZSYG2YVi/jnF6efkE/IQUCSDBFAiEA0SuFLYXc2WHS9fSrZgZU327tzHlMDDPOXMMJ/7X85Y0CIGczio4OFyXBl/saiK9Z9R5E5CVbIBZ8hoQDHAXR8lkqASECI7cr7vCWXRC+B3jv7NYfysb3mk6haTkzgHNEZPhPKrMAAAAAAAAA";
1831                assert_eq!(Psbt::from_str(base64str).unwrap(), unserialized);
1832                assert_eq!(base64str, unserialized.to_string());
1833                assert_eq!(Psbt::from_str(base64str).unwrap(), hex_psbt(base16str).unwrap());
1834            }
1835        }
1836
1837        #[test]
1838        fn valid_vector_2() {
1839            let psbt: Psbt = hex_psbt("70736274ff0100a00200000002ab0949a08c5af7c49b8212f417e2f15ab3f5c33dcf153821a8139f877a5b7be40000000000feffffffab0949a08c5af7c49b8212f417e2f15ab3f5c33dcf153821a8139f877a5b7be40100000000feffffff02603bea0b000000001976a914768a40bbd740cbe81d988e71de2a4d5c71396b1d88ac8e240000000000001976a9146f4620b553fa095e721b9ee0efe9fa039cca459788ac000000000001076a47304402204759661797c01b036b25928948686218347d89864b719e1f7fcf57d1e511658702205309eabf56aa4d8891ffd111fdf1336f3a29da866d7f8486d75546ceedaf93190121035cdc61fc7ba971c0b501a646a2a83b102cb43881217ca682dc86e2d73fa882920001012000e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787010416001485d13537f2e265405a34dbafa9e3dda01fb82308000000").unwrap();
1840
1841            assert_eq!(psbt.inputs.len(), 2);
1842            assert_eq!(psbt.outputs.len(), 2);
1843
1844            assert!(&psbt.inputs[0].final_script_sig.is_some());
1845
1846            let redeem_script = psbt.inputs[1].redeem_script.as_ref().unwrap();
1847            let expected_out =
1848                ScriptBuf::from_hex("a9143545e6e33b832c47050f24d3eeb93c9c03948bc787").unwrap();
1849
1850            assert!(redeem_script.is_p2wpkh());
1851            assert_eq!(
1852                redeem_script.to_p2sh(),
1853                psbt.inputs[1].witness_utxo.as_ref().unwrap().script_pubkey
1854            );
1855            assert_eq!(redeem_script.to_p2sh(), expected_out);
1856
1857            for output in psbt.outputs {
1858                assert_eq!(output.get_pairs().len(), 0)
1859            }
1860        }
1861
1862        #[test]
1863        fn valid_vector_3() {
1864            let psbt: Psbt = hex_psbt("70736274ff0100750200000001268171371edff285e937adeea4b37b78000c0566cbb3ad64641713ca42171bf60000000000feffffff02d3dff505000000001976a914d0c59903c5bac2868760e90fd521a4665aa7652088ac00e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787b32e1300000100fda5010100000000010289a3c71eab4d20e0371bbba4cc698fa295c9463afa2e397f8533ccb62f9567e50100000017160014be18d152a9b012039daf3da7de4f53349eecb985ffffffff86f8aa43a71dff1448893a530a7237ef6b4608bbb2dd2d0171e63aec6a4890b40100000017160014fe3e9ef1a745e974d902c4355943abcb34bd5353ffffffff0200c2eb0b000000001976a91485cff1097fd9e008bb34af709c62197b38978a4888ac72fef84e2c00000017a914339725ba21efd62ac753a9bcd067d6c7a6a39d05870247304402202712be22e0270f394f568311dc7ca9a68970b8025fdd3b240229f07f8a5f3a240220018b38d7dcd314e734c9276bd6fb40f673325bc4baa144c800d2f2f02db2765c012103d2e15674941bad4a996372cb87e1856d3652606d98562fe39c5e9e7e413f210502483045022100d12b852d85dcd961d2f5f4ab660654df6eedcc794c0c33ce5cc309ffb5fce58d022067338a8e0e1725c197fb1a88af59f51e44e4255b20167c8684031c05d1f2592a01210223b72beef0965d10be0778efecd61fcac6f79a4ea169393380734464f84f2ab30000000001030401000000000000").unwrap();
1865
1866            assert_eq!(psbt.inputs.len(), 1);
1867            assert_eq!(psbt.outputs.len(), 2);
1868
1869            let tx_input = &psbt.unsigned_tx.input[0];
1870            let psbt_non_witness_utxo = psbt.inputs[0].non_witness_utxo.as_ref().unwrap();
1871
1872            assert_eq!(tx_input.previous_output.txid, psbt_non_witness_utxo.compute_txid());
1873            assert!(psbt_non_witness_utxo.output[tx_input.previous_output.vout as usize]
1874                .script_pubkey
1875                .is_p2pkh());
1876            assert_eq!(
1877                psbt.inputs[0].sighash_type.as_ref().unwrap().ecdsa_hash_ty().unwrap(),
1878                EcdsaSighashType::All
1879            );
1880        }
1881
1882        #[test]
1883        fn valid_vector_4() {
1884            let psbt: Psbt = hex_psbt("70736274ff0100a00200000002ab0949a08c5af7c49b8212f417e2f15ab3f5c33dcf153821a8139f877a5b7be40000000000feffffffab0949a08c5af7c49b8212f417e2f15ab3f5c33dcf153821a8139f877a5b7be40100000000feffffff02603bea0b000000001976a914768a40bbd740cbe81d988e71de2a4d5c71396b1d88ac8e240000000000001976a9146f4620b553fa095e721b9ee0efe9fa039cca459788ac00000000000100df0200000001268171371edff285e937adeea4b37b78000c0566cbb3ad64641713ca42171bf6000000006a473044022070b2245123e6bf474d60c5b50c043d4c691a5d2435f09a34a7662a9dc251790a022001329ca9dacf280bdf30740ec0390422422c81cb45839457aeb76fc12edd95b3012102657d118d3357b8e0f4c2cd46db7b39f6d9c38d9a70abcb9b2de5dc8dbfe4ce31feffffff02d3dff505000000001976a914d0c59903c5bac2868760e90fd521a4665aa7652088ac00e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787b32e13000001012000e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787010416001485d13537f2e265405a34dbafa9e3dda01fb8230800220202ead596687ca806043edc3de116cdf29d5e9257c196cd055cf698c8d02bf24e9910b4a6ba670000008000000080020000800022020394f62be9df19952c5587768aeb7698061ad2c4a25c894f47d8c162b4d7213d0510b4a6ba6700000080010000800200008000").unwrap();
1885
1886            assert_eq!(psbt.inputs.len(), 2);
1887            assert_eq!(psbt.outputs.len(), 2);
1888
1889            assert!(&psbt.inputs[0].final_script_sig.is_none());
1890            assert!(&psbt.inputs[1].final_script_sig.is_none());
1891
1892            let redeem_script = psbt.inputs[1].redeem_script.as_ref().unwrap();
1893            let expected_out =
1894                ScriptBuf::from_hex("a9143545e6e33b832c47050f24d3eeb93c9c03948bc787").unwrap();
1895
1896            assert!(redeem_script.is_p2wpkh());
1897            assert_eq!(
1898                redeem_script.to_p2sh(),
1899                psbt.inputs[1].witness_utxo.as_ref().unwrap().script_pubkey
1900            );
1901            assert_eq!(redeem_script.to_p2sh(), expected_out);
1902
1903            for output in psbt.outputs {
1904                assert!(!output.get_pairs().is_empty())
1905            }
1906        }
1907
1908        #[test]
1909        fn valid_vector_5() {
1910            let psbt: Psbt = hex_psbt("70736274ff0100550200000001279a2323a5dfb51fc45f220fa58b0fc13e1e3342792a85d7e36cd6333b5cbc390000000000ffffffff01a05aea0b000000001976a914ffe9c0061097cc3b636f2cb0460fa4fc427d2b4588ac0000000000010120955eea0b0000000017a9146345200f68d189e1adc0df1c4d16ea8f14c0dbeb87220203b1341ccba7683b6af4f1238cd6e97e7167d569fac47f1e48d47541844355bd4646304302200424b58effaaa694e1559ea5c93bbfd4a89064224055cdf070b6771469442d07021f5c8eb0fea6516d60b8acb33ad64ede60e8785bfb3aa94b99bdf86151db9a9a010104220020771fd18ad459666dd49f3d564e3dbc42f4c84774e360ada16816a8ed488d5681010547522103b1341ccba7683b6af4f1238cd6e97e7167d569fac47f1e48d47541844355bd462103de55d1e1dac805e3f8a58c1fbf9b94c02f3dbaafe127fefca4995f26f82083bd52ae220603b1341ccba7683b6af4f1238cd6e97e7167d569fac47f1e48d47541844355bd4610b4a6ba67000000800000008004000080220603de55d1e1dac805e3f8a58c1fbf9b94c02f3dbaafe127fefca4995f26f82083bd10b4a6ba670000008000000080050000800000").unwrap();
1911
1912            assert_eq!(psbt.inputs.len(), 1);
1913            assert_eq!(psbt.outputs.len(), 1);
1914
1915            assert!(&psbt.inputs[0].final_script_sig.is_none());
1916
1917            let redeem_script = psbt.inputs[0].redeem_script.as_ref().unwrap();
1918            let expected_out =
1919                ScriptBuf::from_hex("a9146345200f68d189e1adc0df1c4d16ea8f14c0dbeb87").unwrap();
1920
1921            assert!(redeem_script.is_p2wsh());
1922            assert_eq!(
1923                redeem_script.to_p2sh(),
1924                psbt.inputs[0].witness_utxo.as_ref().unwrap().script_pubkey
1925            );
1926
1927            assert_eq!(redeem_script.to_p2sh(), expected_out);
1928        }
1929
1930        // This test attempts to deserialize a PSBT with an input map key that is now excluded.
1931        #[test]
1932        fn valid_vector_6() {
1933            // let psbt: Psbt = hex_psbt("70736274ff01003f0200000001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000000000ffffffff010000000000000000036a010000000000000a0f0102030405060708090f0102030405060708090a0b0c0d0e0f0000").map_err(|e| {
1934            //     println!("{}", e);
1935            // }).unwrap();
1936
1937            // assert_eq!(psbt.inputs.len(), 1);
1938            // assert_eq!(psbt.outputs.len(), 1);
1939
1940            // let tx = &psbt.unsigned_tx;
1941            // assert_eq!(
1942            //     tx.compute_txid(),
1943            //     "75c5c9665a570569ad77dd1279e6fd4628a093c4dcbf8d41532614044c14c115".parse().unwrap(),
1944            // );
1945
1946            // let mut unknown: BTreeMap<raw::Key, Vec<u8>> = BTreeMap::new();
1947            // let key: raw::Key = raw::Key { type_value: 0x0fu8, key: hex!("010203040506070809") };
1948            // let value: Vec<u8> = hex!("0102030405060708090a0b0c0d0e0f");
1949
1950            // unknown.insert(key, value);
1951
1952            // assert_eq!(psbt.inputs[0].unknown, unknown)
1953        }
1954    }
1955
1956    mod bip_371_vectors {
1957        use super::*;
1958
1959        #[test]
1960        fn invalid_vectors() {
1961            let err = hex_psbt("70736274ff010071020000000127744ababf3027fe0d6cf23a96eee2efb188ef52301954585883e69b6624b2420000000000ffffffff02787c01000000000016001483a7e34bd99ff03a4962ef8a1a101bb295461ece606b042a010000001600147ac369df1b20e033d6116623957b0ac49f3c52e8000000000001012b00f2052a010000002251205a2c2cf5b52cf31f83ad2e8da63ff03183ecd8f609c7510ae8a48e03910a075701172102fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa232000000").unwrap_err();
1962            assert_eq!(err.to_string(), "invalid xonly public key");
1963            let err = hex_psbt("70736274ff010071020000000127744ababf3027fe0d6cf23a96eee2efb188ef52301954585883e69b6624b2420000000000ffffffff02787c01000000000016001483a7e34bd99ff03a4962ef8a1a101bb295461ece606b042a010000001600147ac369df1b20e033d6116623957b0ac49f3c52e8000000000001012b00f2052a010000002251205a2c2cf5b52cf31f83ad2e8da63ff03183ecd8f609c7510ae8a48e03910a0757011342173bb3d36c074afb716fec6307a069a2e450b995f3c82785945ab8df0e24260dcd703b0cbf34de399184a9481ac2b3586db6601f026a77f7e4938481bc34751701aa000000").unwrap_err();
1964            #[cfg(feature = "std")]
1965            assert_eq!(err.to_string(), "invalid taproot signature");
1966            #[cfg(not(feature = "std"))]
1967            assert_eq!(
1968                err.to_string(),
1969                "invalid taproot signature: invalid taproot signature size: 66"
1970            );
1971            let err = hex_psbt("70736274ff010071020000000127744ababf3027fe0d6cf23a96eee2efb188ef52301954585883e69b6624b2420000000000ffffffff02787c01000000000016001483a7e34bd99ff03a4962ef8a1a101bb295461ece606b042a010000001600147ac369df1b20e033d6116623957b0ac49f3c52e8000000000001012b00f2052a010000002251205a2c2cf5b52cf31f83ad2e8da63ff03183ecd8f609c7510ae8a48e03910a0757221602fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa2321900772b2da75600008001000080000000800100000000000000000000").unwrap_err();
1972            assert_eq!(err.to_string(), "invalid xonly public key");
1973            let err = hex_psbt("70736274ff01007d020000000127744ababf3027fe0d6cf23a96eee2efb188ef52301954585883e69b6624b2420000000000ffffffff02887b0100000000001600142382871c7e8421a00093f754d91281e675874b9f606b042a010000002251205a2c2cf5b52cf31f83ad2e8da63ff03183ecd8f609c7510ae8a48e03910a0757000000000001012b00f2052a010000002251205a2c2cf5b52cf31f83ad2e8da63ff03183ecd8f609c7510ae8a48e03910a0757000001052102fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa23200").unwrap_err();
1974            assert_eq!(err.to_string(), "invalid xonly public key");
1975            let err = hex_psbt("70736274ff01007d020000000127744ababf3027fe0d6cf23a96eee2efb188ef52301954585883e69b6624b2420000000000ffffffff02887b0100000000001600142382871c7e8421a00093f754d91281e675874b9f606b042a010000002251205a2c2cf5b52cf31f83ad2e8da63ff03183ecd8f609c7510ae8a48e03910a0757000000000001012b00f2052a010000002251205a2c2cf5b52cf31f83ad2e8da63ff03183ecd8f609c7510ae8a48e03910a07570000220702fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa2321900772b2da7560000800100008000000080010000000000000000").unwrap_err();
1976            assert_eq!(err.to_string(), "invalid xonly public key");
1977            let err = hex_psbt("70736274ff01005e02000000019bd48765230bf9a72e662001f972556e54f0c6f97feb56bcb5600d817f6995260100000000ffffffff0148e6052a01000000225120030da4fce4f7db28c2cb2951631e003713856597fe963882cb500e68112cca63000000000001012b00f2052a01000000225120c2247efbfd92ac47f6f40b8d42d169175a19fa9fa10e4a25d7f35eb4dd85b6924214022cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2cd970e15f53fc0c82f950fd560ffa919b76172be017368a89913af074f400b094089756aa3739ccc689ec0fcf3a360be32cc0b59b16e93a1e8bb4605726b2ca7a3ff706c4176649632b2cc68e1f912b8a578e3719ce7710885c7a966f49bcd43cb0000").unwrap_err();
1978            #[cfg(feature = "std")]
1979            assert_eq!(err.to_string(), "invalid hash when parsing slice");
1980            #[cfg(not(feature = "std"))]
1981            assert_eq!(
1982                err.to_string(),
1983                "invalid hash when parsing slice: invalid slice length 33 (expected 32)"
1984            );
1985            let err = hex_psbt("70736274ff01005e02000000019bd48765230bf9a72e662001f972556e54f0c6f97feb56bcb5600d817f6995260100000000ffffffff0148e6052a01000000225120030da4fce4f7db28c2cb2951631e003713856597fe963882cb500e68112cca63000000000001012b00f2052a01000000225120c2247efbfd92ac47f6f40b8d42d169175a19fa9fa10e4a25d7f35eb4dd85b69241142cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2cd970e15f53fc0c82f950fd560ffa919b76172be017368a89913af074f400b094289756aa3739ccc689ec0fcf3a360be32cc0b59b16e93a1e8bb4605726b2ca7a3ff706c4176649632b2cc68e1f912b8a578e3719ce7710885c7a966f49bcd43cb01010000").unwrap_err();
1986            #[cfg(feature = "std")]
1987            assert_eq!(err.to_string(), "invalid taproot signature");
1988            #[cfg(not(feature = "std"))]
1989            assert_eq!(
1990                err.to_string(),
1991                "invalid taproot signature: invalid taproot signature size: 66"
1992            );
1993            let err = hex_psbt("70736274ff01005e02000000019bd48765230bf9a72e662001f972556e54f0c6f97feb56bcb5600d817f6995260100000000ffffffff0148e6052a01000000225120030da4fce4f7db28c2cb2951631e003713856597fe963882cb500e68112cca63000000000001012b00f2052a01000000225120c2247efbfd92ac47f6f40b8d42d169175a19fa9fa10e4a25d7f35eb4dd85b69241142cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2cd970e15f53fc0c82f950fd560ffa919b76172be017368a89913af074f400b093989756aa3739ccc689ec0fcf3a360be32cc0b59b16e93a1e8bb4605726b2ca7a3ff706c4176649632b2cc68e1f912b8a578e3719ce7710885c7a966f49bcd43cb0000").unwrap_err();
1994            #[cfg(feature = "std")]
1995            assert_eq!(err.to_string(), "invalid taproot signature");
1996            #[cfg(not(feature = "std"))]
1997            assert_eq!(
1998                err.to_string(),
1999                "invalid taproot signature: invalid taproot signature size: 57"
2000            );
2001            let err = hex_psbt("70736274ff01005e02000000019bd48765230bf9a72e662001f972556e54f0c6f97feb56bcb5600d817f6995260100000000ffffffff0148e6052a01000000225120030da4fce4f7db28c2cb2951631e003713856597fe963882cb500e68112cca63000000000001012b00f2052a01000000225120c2247efbfd92ac47f6f40b8d42d169175a19fa9fa10e4a25d7f35eb4dd85b6926315c150929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac06f7d62059e9497a1a4a267569d9876da60101aff38e3529b9b939ce7f91ae970115f2e490af7cc45c4f78511f36057ce5c5a5c56325a29fb44dfc203f356e1f80023202cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2acc00000").unwrap_err();
2002            assert_eq!(err.to_string(), "invalid control block");
2003            let err = hex_psbt("70736274ff01005e02000000019bd48765230bf9a72e662001f972556e54f0c6f97feb56bcb5600d817f6995260100000000ffffffff0148e6052a01000000225120030da4fce4f7db28c2cb2951631e003713856597fe963882cb500e68112cca63000000000001012b00f2052a01000000225120c2247efbfd92ac47f6f40b8d42d169175a19fa9fa10e4a25d7f35eb4dd85b6926115c150929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac06f7d62059e9497a1a4a267569d9876da60101aff38e3529b9b939ce7f91ae970115f2e490af7cc45c4f78511f36057ce5c5a5c56325a29fb44dfc203f356e123202cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2acc00000").unwrap_err();
2004            assert_eq!(err.to_string(), "invalid control block");
2005        }
2006
2007        fn rtt_psbt(psbt: Psbt) {
2008            let enc = Psbt::serialize(&psbt);
2009            let psbt2 = Psbt::deserialize(&enc).unwrap();
2010            assert_eq!(psbt, psbt2);
2011        }
2012
2013        #[test]
2014        fn valid_psbt_vectors() {
2015            let psbt = hex_psbt("70736274ff010052020000000127744ababf3027fe0d6cf23a96eee2efb188ef52301954585883e69b6624b2420000000000ffffffff0148e6052a01000000160014768e1eeb4cf420866033f80aceff0f9720744969000000000001012b00f2052a010000002251205a2c2cf5b52cf31f83ad2e8da63ff03183ecd8f609c7510ae8a48e03910a07572116fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa2321900772b2da75600008001000080000000800100000000000000011720fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa232002202036b772a6db74d8753c98a827958de6c78ab3312109f37d3e0304484242ece73d818772b2da7540000800100008000000080000000000000000000").unwrap();
2016            let internal_key = psbt.inputs[0].tap_internal_key.unwrap();
2017            assert!(psbt.inputs[0].tap_key_origins.contains_key(&internal_key));
2018            rtt_psbt(psbt);
2019
2020            // vector 2
2021            let psbt = hex_psbt("70736274ff010052020000000127744ababf3027fe0d6cf23a96eee2efb188ef52301954585883e69b6624b2420000000000ffffffff0148e6052a01000000160014768e1eeb4cf420866033f80aceff0f9720744969000000000001012b00f2052a010000002251205a2c2cf5b52cf31f83ad2e8da63ff03183ecd8f609c7510ae8a48e03910a0757011340bb53ec917bad9d906af1ba87181c48b86ace5aae2b53605a725ca74625631476fc6f5baedaf4f2ee0f477f36f58f3970d5b8273b7e497b97af2e3f125c97af342116fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa2321900772b2da75600008001000080000000800100000000000000011720fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa232002202036b772a6db74d8753c98a827958de6c78ab3312109f37d3e0304484242ece73d818772b2da7540000800100008000000080000000000000000000").unwrap();
2022            let internal_key = psbt.inputs[0].tap_internal_key.unwrap();
2023            assert!(psbt.inputs[0].tap_key_origins.contains_key(&internal_key));
2024            assert!(psbt.inputs[0].tap_key_sig.is_some());
2025            rtt_psbt(psbt);
2026
2027            // vector 3
2028            let psbt = hex_psbt("70736274ff01005e020000000127744ababf3027fe0d6cf23a96eee2efb188ef52301954585883e69b6624b2420000000000ffffffff0148e6052a0100000022512083698e458c6664e1595d75da2597de1e22ee97d798e706c4c0a4b5a9823cd743000000000001012b00f2052a010000002251205a2c2cf5b52cf31f83ad2e8da63ff03183ecd8f609c7510ae8a48e03910a07572116fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa2321900772b2da75600008001000080000000800100000000000000011720fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa232000105201124da7aec92ccd06c954562647f437b138b95721a84be2bf2276bbddab3e67121071124da7aec92ccd06c954562647f437b138b95721a84be2bf2276bbddab3e6711900772b2da7560000800100008000000080000000000500000000").unwrap();
2029            let internal_key = psbt.outputs[0].tap_internal_key.unwrap();
2030            assert!(psbt.outputs[0].tap_key_origins.contains_key(&internal_key));
2031            rtt_psbt(psbt);
2032
2033            // vector 4
2034            let psbt = hex_psbt("70736274ff01005e02000000019bd48765230bf9a72e662001f972556e54f0c6f97feb56bcb5600d817f6995260100000000ffffffff0148e6052a0100000022512083698e458c6664e1595d75da2597de1e22ee97d798e706c4c0a4b5a9823cd743000000000001012b00f2052a01000000225120c2247efbfd92ac47f6f40b8d42d169175a19fa9fa10e4a25d7f35eb4dd85b6926215c150929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac06f7d62059e9497a1a4a267569d9876da60101aff38e3529b9b939ce7f91ae970115f2e490af7cc45c4f78511f36057ce5c5a5c56325a29fb44dfc203f356e1f823202cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2acc04215c150929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac097c6e6fea5ff714ff5724499990810e406e98aa10f5bf7e5f6784bc1d0a9a6ce23204320b0bf16f011b53ea7be615924aa7f27e5d29ad20ea1155d848676c3bad1b2acc06215c150929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0cd970e15f53fc0c82f950fd560ffa919b76172be017368a89913af074f400b09115f2e490af7cc45c4f78511f36057ce5c5a5c56325a29fb44dfc203f356e1f82320fa0f7a3cef3b1d0c0a6ce7d26e17ada0b2e5c92d19efad48b41859cb8a451ca9acc021162cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d23901cd970e15f53fc0c82f950fd560ffa919b76172be017368a89913af074f400b09772b2da7560000800100008002000080000000000000000021164320b0bf16f011b53ea7be615924aa7f27e5d29ad20ea1155d848676c3bad1b23901115f2e490af7cc45c4f78511f36057ce5c5a5c56325a29fb44dfc203f356e1f8772b2da75600008001000080010000800000000000000000211650929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac005007c461e5d2116fa0f7a3cef3b1d0c0a6ce7d26e17ada0b2e5c92d19efad48b41859cb8a451ca939016f7d62059e9497a1a4a267569d9876da60101aff38e3529b9b939ce7f91ae970772b2da7560000800100008003000080000000000000000001172050929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0011820f0362e2f75a6f420a5bde3eb221d96ae6720cf25f81890c95b1d775acb515e65000105201124da7aec92ccd06c954562647f437b138b95721a84be2bf2276bbddab3e67121071124da7aec92ccd06c954562647f437b138b95721a84be2bf2276bbddab3e6711900772b2da7560000800100008000000080000000000500000000").unwrap();
2035            assert!(psbt.inputs[0].tap_internal_key.is_some());
2036            assert!(psbt.inputs[0].tap_merkle_root.is_some());
2037            assert!(!psbt.inputs[0].tap_key_origins.is_empty());
2038            assert!(!psbt.inputs[0].tap_scripts.is_empty());
2039            rtt_psbt(psbt);
2040
2041            // vector 5
2042            let psbt = hex_psbt("70736274ff01005e020000000127744ababf3027fe0d6cf23a96eee2efb188ef52301954585883e69b6624b2420000000000ffffffff0148e6052a010000002251200a8cbdc86de1ce1c0f9caeb22d6df7ced3683fe423e05d1e402a879341d6f6f5000000000001012b00f2052a010000002251205a2c2cf5b52cf31f83ad2e8da63ff03183ecd8f609c7510ae8a48e03910a07572116fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa2321900772b2da75600008001000080000000800100000000000000011720fe349064c98d6e2a853fa3c9b12bd8b304a19c195c60efa7ee2393046d3fa2320001052050929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac001066f02c02220736e572900fe1252589a2143c8f3c79f71a0412d2353af755e9701c782694a02ac02c02220631c5f3b5832b8fbdebfb19704ceeb323c21f40f7a24f43d68ef0cc26b125969ac01c0222044faa49a0338de488c8dfffecdfb6f329f380bd566ef20c8df6d813eab1c4273ac210744faa49a0338de488c8dfffecdfb6f329f380bd566ef20c8df6d813eab1c42733901f06b798b92a10ed9a9d0bbfd3af173a53b1617da3a4159ca008216cd856b2e0e772b2da75600008001000080010000800000000003000000210750929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac005007c461e5d2107631c5f3b5832b8fbdebfb19704ceeb323c21f40f7a24f43d68ef0cc26b125969390118ace409889785e0ea70ceebb8e1ca892a7a78eaede0f2e296cf435961a8f4ca772b2da756000080010000800200008000000000030000002107736e572900fe1252589a2143c8f3c79f71a0412d2353af755e9701c782694a02390129a5b4915090162d759afd3fe0f93fa3326056d0b4088cb933cae7826cb8d82c772b2da7560000800100008003000080000000000300000000").unwrap();
2043            assert!(psbt.outputs[0].tap_internal_key.is_some());
2044            assert!(!psbt.outputs[0].tap_key_origins.is_empty());
2045            assert!(psbt.outputs[0].tap_tree.is_some());
2046            rtt_psbt(psbt);
2047
2048            // vector 6
2049            let psbt = hex_psbt("70736274ff01005e02000000019bd48765230bf9a72e662001f972556e54f0c6f97feb56bcb5600d817f6995260100000000ffffffff0148e6052a0100000022512083698e458c6664e1595d75da2597de1e22ee97d798e706c4c0a4b5a9823cd743000000000001012b00f2052a01000000225120c2247efbfd92ac47f6f40b8d42d169175a19fa9fa10e4a25d7f35eb4dd85b69241142cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2cd970e15f53fc0c82f950fd560ffa919b76172be017368a89913af074f400b0940bf818d9757d6ffeb538ba057fb4c1fc4e0f5ef186e765beb564791e02af5fd3d5e2551d4e34e33d86f276b82c99c79aed3f0395a081efcd2cc2c65dd7e693d7941144320b0bf16f011b53ea7be615924aa7f27e5d29ad20ea1155d848676c3bad1b2115f2e490af7cc45c4f78511f36057ce5c5a5c56325a29fb44dfc203f356e1f840e1f1ab6fabfa26b236f21833719dc1d428ab768d80f91f9988d8abef47bfb863bb1f2a529f768c15f00ce34ec283cdc07e88f8428be28f6ef64043c32911811a4114fa0f7a3cef3b1d0c0a6ce7d26e17ada0b2e5c92d19efad48b41859cb8a451ca96f7d62059e9497a1a4a267569d9876da60101aff38e3529b9b939ce7f91ae97040ec1f0379206461c83342285423326708ab031f0da4a253ee45aafa5b8c92034d8b605490f8cd13e00f989989b97e215faa36f12dee3693d2daccf3781c1757f66215c150929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac06f7d62059e9497a1a4a267569d9876da60101aff38e3529b9b939ce7f91ae970115f2e490af7cc45c4f78511f36057ce5c5a5c56325a29fb44dfc203f356e1f823202cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d2acc04215c150929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac097c6e6fea5ff714ff5724499990810e406e98aa10f5bf7e5f6784bc1d0a9a6ce23204320b0bf16f011b53ea7be615924aa7f27e5d29ad20ea1155d848676c3bad1b2acc06215c150929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0cd970e15f53fc0c82f950fd560ffa919b76172be017368a89913af074f400b09115f2e490af7cc45c4f78511f36057ce5c5a5c56325a29fb44dfc203f356e1f82320fa0f7a3cef3b1d0c0a6ce7d26e17ada0b2e5c92d19efad48b41859cb8a451ca9acc021162cb13ac68248de806aa6a3659cf3c03eb6821d09c8114a4e868febde865bb6d23901cd970e15f53fc0c82f950fd560ffa919b76172be017368a89913af074f400b09772b2da7560000800100008002000080000000000000000021164320b0bf16f011b53ea7be615924aa7f27e5d29ad20ea1155d848676c3bad1b23901115f2e490af7cc45c4f78511f36057ce5c5a5c56325a29fb44dfc203f356e1f8772b2da75600008001000080010000800000000000000000211650929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac005007c461e5d2116fa0f7a3cef3b1d0c0a6ce7d26e17ada0b2e5c92d19efad48b41859cb8a451ca939016f7d62059e9497a1a4a267569d9876da60101aff38e3529b9b939ce7f91ae970772b2da7560000800100008003000080000000000000000001172050929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0011820f0362e2f75a6f420a5bde3eb221d96ae6720cf25f81890c95b1d775acb515e65000105201124da7aec92ccd06c954562647f437b138b95721a84be2bf2276bbddab3e67121071124da7aec92ccd06c954562647f437b138b95721a84be2bf2276bbddab3e6711900772b2da7560000800100008000000080000000000500000000").unwrap();
2050            assert!(psbt.inputs[0].tap_internal_key.is_some());
2051            assert!(psbt.inputs[0].tap_merkle_root.is_some());
2052            assert!(!psbt.inputs[0].tap_scripts.is_empty());
2053            assert!(!psbt.inputs[0].tap_script_sigs.is_empty());
2054            assert!(!psbt.inputs[0].tap_key_origins.is_empty());
2055            rtt_psbt(psbt);
2056        }
2057    }
2058
2059    #[test]
2060    fn serialize_and_deserialize_preimage_psbt() {
2061        // create a sha preimage map
2062        let mut sha256_preimages = BTreeMap::new();
2063        sha256_preimages.insert(sha256::Hash::hash(&[1u8, 2u8]), vec![1u8, 2u8]);
2064        sha256_preimages.insert(sha256::Hash::hash(&[1u8]), vec![1u8]);
2065
2066        // same for hash160
2067        let mut hash160_preimages = BTreeMap::new();
2068        hash160_preimages.insert(hash160::Hash::hash(&[1u8, 2u8]), vec![1u8, 2u8]);
2069        hash160_preimages.insert(hash160::Hash::hash(&[1u8]), vec![1u8]);
2070
2071        // same vector as valid_vector_1 from BIPs with added
2072        let mut unserialized = Psbt {
2073            unsigned_tx: Transaction {
2074                version: transaction::Version::TWO,
2075                lock_time: absolute::LockTime::from_consensus(1257139),
2076                input: vec![
2077                    TxIn {
2078                        previous_output: OutPoint {
2079                            txid: "f61b1742ca13176464adb3cb66050c00787bb3a4eead37e985f2df1e37718126".parse().unwrap(),
2080                            vout: 0,
2081                        },
2082                        script_sig: ScriptBuf::new(),
2083                        sequence: Sequence::ENABLE_LOCKTIME_NO_RBF,
2084                        witness: Witness::default(),
2085                    }
2086                ],
2087                output: vec![
2088                    TxOut {
2089                        value: Amount::from_sat(99_999_699),
2090                        script_pubkey: ScriptBuf::from_hex("76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac").unwrap(),
2091                    },
2092                    TxOut {
2093                        value: Amount::from_sat(100_000_000),
2094                        script_pubkey: ScriptBuf::from_hex("a9143545e6e33b832c47050f24d3eeb93c9c03948bc787").unwrap(),
2095                    },
2096                ],
2097            },
2098            version: 0,
2099            xpub: Default::default(),
2100            proprietary: Default::default(),
2101            unknown: BTreeMap::new(),
2102
2103            inputs: vec![
2104                Input {
2105                    non_witness_utxo: Some(Transaction {
2106                        version: transaction::Version::ONE,
2107                        lock_time: absolute::LockTime::ZERO,
2108                        input: vec![
2109                            TxIn {
2110                                previous_output: OutPoint {
2111                                    txid: "e567952fb6cc33857f392efa3a46c995a28f69cca4bb1b37e0204dab1ec7a389".parse().unwrap(),
2112                                    vout: 1,
2113                                },
2114                                script_sig: ScriptBuf::from_hex("160014be18d152a9b012039daf3da7de4f53349eecb985").unwrap(),
2115                                sequence: Sequence::MAX,
2116                                witness: Witness::from_slice(&[
2117                                    hex!("304402202712be22e0270f394f568311dc7ca9a68970b8025fdd3b240229f07f8a5f3a240220018b38d7dcd314e734c9276bd6fb40f673325bc4baa144c800d2f2f02db2765c01"),
2118                                    hex!("03d2e15674941bad4a996372cb87e1856d3652606d98562fe39c5e9e7e413f2105"),
2119                                ]),
2120                            },
2121                            TxIn {
2122                                previous_output: OutPoint {
2123                                    txid: "b490486aec3ae671012dddb2bb08466bef37720a533a894814ff1da743aaf886".parse().unwrap(),
2124                                    vout: 1,
2125                                },
2126                                script_sig: ScriptBuf::from_hex("160014fe3e9ef1a745e974d902c4355943abcb34bd5353").unwrap(),
2127                                sequence: Sequence::MAX,
2128                                witness: Witness::from_slice(&[
2129                                    hex!("3045022100d12b852d85dcd961d2f5f4ab660654df6eedcc794c0c33ce5cc309ffb5fce58d022067338a8e0e1725c197fb1a88af59f51e44e4255b20167c8684031c05d1f2592a01"),
2130                                    hex!("0223b72beef0965d10be0778efecd61fcac6f79a4ea169393380734464f84f2ab3"),
2131                                ]),
2132                            }
2133                        ],
2134                        output: vec![
2135                            TxOut {
2136                                value: Amount::from_sat(200_000_000),
2137                                script_pubkey: ScriptBuf::from_hex("76a91485cff1097fd9e008bb34af709c62197b38978a4888ac").unwrap(),
2138                            },
2139                            TxOut {
2140                                value: Amount::from_sat(190_303_501_938),
2141                                script_pubkey: ScriptBuf::from_hex("a914339725ba21efd62ac753a9bcd067d6c7a6a39d0587").unwrap(),
2142                            },
2143                        ],
2144                    }),
2145                    ..Default::default()
2146                },
2147            ],
2148            outputs: vec![
2149                Output {
2150                    ..Default::default()
2151                },
2152                Output {
2153                    ..Default::default()
2154                },
2155            ],
2156        };
2157        unserialized.inputs[0].hash160_preimages = hash160_preimages;
2158        unserialized.inputs[0].sha256_preimages = sha256_preimages;
2159
2160        let rtt: Psbt = hex_psbt(&unserialized.serialize_hex()).unwrap();
2161        assert_eq!(rtt, unserialized);
2162
2163        // Now add an ripemd160 with incorrect preimage
2164        let mut ripemd160_preimages = BTreeMap::new();
2165        ripemd160_preimages.insert(ripemd160::Hash::hash(&[17u8]), vec![18u8]);
2166        unserialized.inputs[0].ripemd160_preimages = ripemd160_preimages;
2167
2168        // Now the roundtrip should fail as the preimage is incorrect.
2169        let rtt: Result<Psbt, _> = hex_psbt(&unserialized.serialize_hex());
2170        assert!(rtt.is_err());
2171    }
2172
2173    #[test]
2174    fn serialize_and_deserialize_proprietary() {
2175        let mut psbt: Psbt = hex_psbt("70736274ff0100a00200000002ab0949a08c5af7c49b8212f417e2f15ab3f5c33dcf153821a8139f877a5b7be40000000000feffffffab0949a08c5af7c49b8212f417e2f15ab3f5c33dcf153821a8139f877a5b7be40100000000feffffff02603bea0b000000001976a914768a40bbd740cbe81d988e71de2a4d5c71396b1d88ac8e240000000000001976a9146f4620b553fa095e721b9ee0efe9fa039cca459788ac000000000001076a47304402204759661797c01b036b25928948686218347d89864b719e1f7fcf57d1e511658702205309eabf56aa4d8891ffd111fdf1336f3a29da866d7f8486d75546ceedaf93190121035cdc61fc7ba971c0b501a646a2a83b102cb43881217ca682dc86e2d73fa882920001012000e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787010416001485d13537f2e265405a34dbafa9e3dda01fb82308000000").unwrap();
2176        psbt.proprietary.insert(
2177            raw::ProprietaryKey { prefix: b"test".to_vec(), subtype: 0u8, key: b"test".to_vec() },
2178            b"test".to_vec(),
2179        );
2180        assert!(!psbt.proprietary.is_empty());
2181        let rtt: Psbt = hex_psbt(&psbt.serialize_hex()).unwrap();
2182        assert!(!rtt.proprietary.is_empty());
2183    }
2184
2185    // PSBTs taken from BIP 174 test vectors.
2186    #[test]
2187    fn combine_psbts() {
2188        let mut psbt1 = hex_psbt(include_str!("../../../tests/data/psbt1.hex")).unwrap();
2189        let psbt2 = hex_psbt(include_str!("../../../tests/data/psbt2.hex")).unwrap();
2190        let psbt_combined = hex_psbt(include_str!("../../../tests/data/psbt2.hex")).unwrap();
2191
2192        psbt1.combine(psbt2).expect("psbt combine to succeed");
2193        assert_eq!(psbt1, psbt_combined);
2194    }
2195
2196    #[test]
2197    fn combine_psbts_commutative() {
2198        let mut psbt1 = hex_psbt(include_str!("../../../tests/data/psbt1.hex")).unwrap();
2199        let mut psbt2 = hex_psbt(include_str!("../../../tests/data/psbt2.hex")).unwrap();
2200
2201        let psbt1_clone = psbt1.clone();
2202        let psbt2_clone = psbt2.clone();
2203
2204        psbt1.combine(psbt2_clone).expect("psbt1 combine to succeed");
2205        psbt2.combine(psbt1_clone).expect("psbt2 combine to succeed");
2206
2207        assert_eq!(psbt1, psbt2);
2208    }
2209
2210    #[cfg(all(feature = "rand", feature = "std"))]
2211    fn gen_keys() -> (PrivateKey, PublicKey, Secp256k1<bitcoin::secp256k1::All>) {
2212        use bitcoin::secp256k1::rand::thread_rng;
2213
2214        let secp = Secp256k1::new();
2215
2216        let sk = bitcoin::secp256k1::SecretKey::new(&mut thread_rng());
2217        let priv_key = PrivateKey::new(sk, NetworkKind::Test);
2218        let pk = PublicKey::from_private_key(&secp, &priv_key);
2219
2220        (priv_key, pk, secp)
2221    }
2222
2223    #[test]
2224    #[cfg(all(feature = "rand", feature = "std"))]
2225    fn get_key_btree_map() {
2226        let (priv_key, pk, secp) = gen_keys();
2227
2228        let mut key_map = BTreeMap::new();
2229        key_map.insert(pk, priv_key);
2230
2231        let got = key_map.get_key(KeyRequest::Pubkey(pk), &secp).expect("failed to get key");
2232        assert_eq!(got.unwrap(), priv_key)
2233    }
2234
2235    #[test]
2236    #[cfg(all(feature = "rand", feature = "std"))]
2237    fn pubkey_map_get_key_negates_odd_parity_keys() {
2238        let (mut priv_key, mut pk, secp) = gen_keys();
2239        let (xonly, parity) = pk.inner.x_only_public_key();
2240
2241        let mut pubkey_map: HashMap<PublicKey, PrivateKey> = HashMap::new();
2242
2243        if parity == Parity::Even {
2244            priv_key = PrivateKey {
2245                compressed: priv_key.compressed,
2246                network: priv_key.network,
2247                inner: priv_key.inner.negate(),
2248            };
2249            pk = priv_key.public_key(&secp);
2250        }
2251
2252        pubkey_map.insert(pk, priv_key);
2253
2254        let req_result = pubkey_map.get_key(KeyRequest::XOnlyPubkey(xonly), &secp).unwrap();
2255
2256        let retrieved_key = req_result.unwrap();
2257
2258        let retrieved_pub_key = retrieved_key.public_key(&secp);
2259        let (retrieved_xonly, retrieved_parity) = retrieved_pub_key.inner.x_only_public_key();
2260
2261        assert_eq!(xonly, retrieved_xonly);
2262        assert_eq!(
2263            retrieved_parity,
2264            Parity::Even,
2265            "Key should be normalized to have even parity, even when original had odd parity"
2266        );
2267    }
2268
2269    #[test]
2270    fn fee() {
2271        let output_0_val = Amount::from_sat(99_999_699);
2272        let output_1_val = Amount::from_sat(100_000_000);
2273        let prev_output_val = Amount::from_sat(200_000_000);
2274
2275        let mut t = Psbt {
2276            unsigned_tx: Transaction {
2277                version: transaction::Version::TWO,
2278                lock_time: absolute::LockTime::from_consensus(1257139),
2279                input: vec![
2280                    TxIn {
2281                        previous_output: OutPoint {
2282                            txid: "f61b1742ca13176464adb3cb66050c00787bb3a4eead37e985f2df1e37718126".parse().unwrap(),
2283                            vout: 0,
2284                        },
2285                        sequence: Sequence::ENABLE_LOCKTIME_NO_RBF,
2286                        ..Default::default()
2287                    }
2288                ],
2289                output: vec![
2290                    TxOut {
2291                        value: output_0_val,
2292                        script_pubkey:  ScriptBuf::new()
2293                    },
2294                    TxOut {
2295                        value: output_1_val,
2296                        script_pubkey:  ScriptBuf::new()
2297                    },
2298                ],
2299            },
2300            xpub: Default::default(),
2301            version: 0,
2302            proprietary: BTreeMap::new(),
2303            unknown: BTreeMap::new(),
2304
2305            inputs: vec![
2306                Input {
2307                    non_witness_utxo: Some(Transaction {
2308                        version: transaction::Version::ONE,
2309                        lock_time: absolute::LockTime::ZERO,
2310                        input: vec![
2311                            TxIn {
2312                                previous_output: OutPoint {
2313                                    txid: "e567952fb6cc33857f392efa3a46c995a28f69cca4bb1b37e0204dab1ec7a389".parse().unwrap(),
2314                                    vout: 1,
2315                                },
2316                                sequence: Sequence::MAX,
2317                                ..Default::default()
2318                            },
2319                            TxIn {
2320                                previous_output: OutPoint {
2321                                    txid: "b490486aec3ae671012dddb2bb08466bef37720a533a894814ff1da743aaf886".parse().unwrap(),
2322                                    vout: 1,
2323                                },
2324                                sequence: Sequence::MAX,
2325                                ..Default::default()
2326                            }
2327                        ],
2328                        output: vec![
2329                            TxOut {
2330                                value: prev_output_val,
2331                                script_pubkey:  ScriptBuf::new()
2332                            },
2333                            TxOut {
2334                                value: Amount::from_sat(190_303_501_938),
2335                                script_pubkey:  ScriptBuf::new()
2336                            },
2337                        ],
2338                    }),
2339                    ..Default::default()
2340                },
2341            ],
2342            outputs: vec![
2343                Output {
2344                    ..Default::default()
2345                },
2346                Output {
2347                    ..Default::default()
2348                },
2349            ],
2350        };
2351        assert_eq!(
2352            t.fee().expect("fee calculation"),
2353            prev_output_val - (output_0_val + output_1_val)
2354        );
2355        // no previous output
2356        let mut t2 = t.clone();
2357        t2.inputs[0].non_witness_utxo = None;
2358        match t2.fee().unwrap_err() {
2359            Error::MissingUtxo => {}
2360            e => panic!("unexpected error: {:?}", e),
2361        }
2362        //  negative fee
2363        let mut t3 = t.clone();
2364        t3.unsigned_tx.output[0].value = prev_output_val;
2365        match t3.fee().unwrap_err() {
2366            Error::NegativeFee => {}
2367            e => panic!("unexpected error: {:?}", e),
2368        }
2369        // overflow
2370        t.unsigned_tx.output[0].value = Amount::MAX;
2371        t.unsigned_tx.output[1].value = Amount::MAX;
2372        match t.fee().unwrap_err() {
2373            Error::FeeOverflow => {}
2374            e => panic!("unexpected error: {:?}", e),
2375        }
2376    }
2377
2378    #[test]
2379    #[cfg(all(feature = "rand", feature = "std"))]
2380    fn hashmap_can_sign_taproot() {
2381        let (priv_key, pk, secp) = gen_keys();
2382        let internal_key: XOnlyPublicKey = pk.inner.into();
2383
2384        let tx = Transaction {
2385            version: transaction::Version::TWO,
2386            lock_time: locktime::absolute::LockTime::ZERO,
2387            input: vec![TxIn::default()],
2388            output: vec![TxOut { value: Amount::ZERO, script_pubkey: ScriptBuf::new() }],
2389        };
2390
2391        let mut psbt = Psbt::from_unsigned_tx(tx).unwrap();
2392        psbt.inputs[0].tap_internal_key = Some(internal_key);
2393        psbt.inputs[0].witness_utxo = Some(transaction::TxOut {
2394            value: Amount::from_sat(10),
2395            script_pubkey: ScriptBuf::new_p2tr(&secp, internal_key, None),
2396        });
2397
2398        let mut key_map: HashMap<PublicKey, PrivateKey> = HashMap::new();
2399        key_map.insert(pk, priv_key);
2400
2401        let key_source = (Fingerprint::default(), DerivationPath::default());
2402        let mut tap_key_origins = std::collections::BTreeMap::new();
2403        tap_key_origins.insert(internal_key, (vec![], key_source));
2404        psbt.inputs[0].tap_key_origins = tap_key_origins;
2405
2406        let signing_keys = psbt.sign(&key_map, &secp).unwrap();
2407        assert_eq!(signing_keys.len(), 1);
2408        assert_eq!(signing_keys[&0], SigningKeys::Schnorr(vec![internal_key]));
2409    }
2410
2411    #[test]
2412    #[cfg(all(feature = "rand", feature = "std"))]
2413    fn xonly_hashmap_can_sign_taproot() {
2414        let (priv_key, pk, secp) = gen_keys();
2415        let internal_key: XOnlyPublicKey = pk.inner.into();
2416
2417        let tx = Transaction {
2418            version: transaction::Version::TWO,
2419            lock_time: locktime::absolute::LockTime::ZERO,
2420            input: vec![TxIn::default()],
2421            output: vec![TxOut { value: Amount::ZERO, script_pubkey: ScriptBuf::new() }],
2422        };
2423
2424        let mut psbt = Psbt::from_unsigned_tx(tx).unwrap();
2425        psbt.inputs[0].tap_internal_key = Some(internal_key);
2426        psbt.inputs[0].witness_utxo = Some(transaction::TxOut {
2427            value: Amount::from_sat(10),
2428            script_pubkey: ScriptBuf::new_p2tr(&secp, internal_key, None),
2429        });
2430
2431        let mut xonly_key_map: HashMap<XOnlyPublicKey, PrivateKey> = HashMap::new();
2432        xonly_key_map.insert(internal_key, priv_key);
2433
2434        let key_source = (Fingerprint::default(), DerivationPath::default());
2435        let mut tap_key_origins = std::collections::BTreeMap::new();
2436        tap_key_origins.insert(internal_key, (vec![], key_source));
2437        psbt.inputs[0].tap_key_origins = tap_key_origins;
2438
2439        let signing_keys = psbt.sign(&xonly_key_map, &secp).unwrap();
2440        assert_eq!(signing_keys.len(), 1);
2441        assert_eq!(signing_keys[&0], SigningKeys::Schnorr(vec![internal_key]));
2442    }
2443
2444    #[test]
2445    #[cfg(all(feature = "rand", feature = "std"))]
2446    fn sign_psbt() {
2447        let unsigned_tx = Transaction {
2448            version: transaction::Version::TWO,
2449            lock_time: absolute::LockTime::ZERO,
2450            input: vec![TxIn::default(), TxIn::default()],
2451            output: vec![TxOut::NULL],
2452        };
2453        let mut psbt = Psbt::from_unsigned_tx(unsigned_tx).unwrap();
2454
2455        let (priv_key, pk, secp) = gen_keys();
2456
2457        // key_map implements `GetKey` using KeyRequest::Pubkey. A pubkey key request does not use
2458        // keysource so we use default `KeySource` (fingreprint and derivation path) below.
2459        let mut key_map = BTreeMap::new();
2460        key_map.insert(pk, priv_key);
2461
2462        // First input we can spend. See comment above on key_map for why we use defaults here.
2463        let txout_wpkh = TxOut {
2464            value: Amount::from_sat(10),
2465            script_pubkey: ScriptBuf::new_p2wpkh(&WPubkeyHash::hash(&pk.to_bytes())),
2466        };
2467        psbt.inputs[0].witness_utxo = Some(txout_wpkh);
2468
2469        let mut map = BTreeMap::new();
2470        map.insert(pk, (Fingerprint::default(), DerivationPath::default()));
2471        psbt.inputs[0].bip32_derivation = map;
2472
2473        // Second input is unspendable by us e.g., from another wallet that supports future upgrades.
2474        let unknown_prog = WitnessProgram::new(WitnessVersion::V4, &[0xaa; 34]).unwrap();
2475        let txout_unknown_future = TxOut {
2476            value: Amount::from_sat(10),
2477            script_pubkey: ScriptBuf::new_witness_program(&unknown_prog),
2478        };
2479        psbt.inputs[1].witness_utxo = Some(txout_unknown_future);
2480
2481        let (signing_keys, _) = psbt.sign(&key_map, &secp).unwrap_err();
2482
2483        assert_eq!(signing_keys.len(), 1);
2484        assert_eq!(signing_keys[&0], SigningKeys::Ecdsa(vec![pk]));
2485    }
2486}