psbt_v2/v2/
mod.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! PSBT Version 2.
4//!
5//! A second version of the Partially Signed Bitcoin Transaction format implemented by
6//! [`crate::v0::Psbt`] and described in [BIP-174].
7//!
8//! Allows for inputs and outputs to be added to the PSBT after creation.
9//!
10//! # Roles
11//!
12//! BIP-174 describes various roles, these are implemented in this module as follows:
13//!
14//! - The **Creator** role Use the [`Creator`] type - or if creator and constructor are a single entity just use the `Constructor`.
15//! - The **Constructor**: Use the [`Constructor`] type.
16//! - The **Updater** role: Use the [`Updater`] type and then update additional fields of the [`Psbt`] directly.
17//! - The **Signer** role: Use the [`Signer`] type.
18//! - The **Finalizer** role: Use the `Finalizer` type (requires "miniscript" feature).
19//! - The **Extractor** role: Use the [`Extractor`] type.
20//!
21//! To combine PSBTs use either `psbt.combine_with(other)` or `v2::combine(this, that)`.
22//!
23//! [BIP-174]: <https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki>
24//! [BIP-370]: <https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki>
25
26mod error;
27mod extract;
28mod map;
29#[cfg(feature = "miniscript")]
30mod miniscript;
31
32use core::fmt;
33use core::marker::PhantomData;
34#[cfg(feature = "std")]
35use std::collections::{HashMap, HashSet};
36
37use bitcoin::bip32::{self, KeySource, Xpriv};
38use bitcoin::key::{PrivateKey, PublicKey};
39use bitcoin::locktime::absolute;
40use bitcoin::secp256k1::{Message, Secp256k1, Signing};
41use bitcoin::sighash::{EcdsaSighashType, SighashCache};
42use bitcoin::{ecdsa, transaction, Amount, Sequence, Transaction, TxOut, Txid};
43
44use crate::error::{write_err, FeeError, FundingUtxoError};
45use crate::prelude::*;
46use crate::v2::map::Map;
47
48#[rustfmt::skip]                // Keep public exports separate.
49#[doc(inline)]
50pub use self::{
51    error::{
52        DeserializeError, DetermineLockTimeError, IndexOutOfBoundsError, InputsNotModifiableError,
53        NotUnsignedError, OutputsNotModifiableError, PartialSigsSighashTypeError,
54        PsbtNotModifiableError, SignError,
55    },
56    extract::{Extractor, ExtractError, ExtractTxError, ExtractTxFeeRateError},
57    map::{
58        // We do not re-export any of the input/output/global error types, use form `input::DecodeError`.
59        global::{self, Global},
60        input::{self, Input, InputBuilder},
61        output::{self, Output, OutputBuilder},
62    },
63};
64#[cfg(feature = "base64")]
65pub use self::display_from_str::ParsePsbtError;
66#[cfg(feature = "miniscript")]
67pub use self::miniscript::{
68    FinalizeError, FinalizeInputError, Finalizer, InputError, InterpreterCheckError,
69    InterpreterCheckInputError,
70};
71
72/// Combines these two PSBTs as described by BIP-174 (i.e. combine is the same for BIP-370).
73///
74/// This function is commutative `combine(this, that) = combine(that, this)`.
75pub fn combine(this: Psbt, that: Psbt) -> Result<Psbt, CombineError> { this.combine_with(that) }
76// TODO: Consider adding an iterator API that combines a list of PSBTs.
77
78/// Implements the BIP-370 Creator role.
79///
80/// The `Creator` type is only directly needed if one of the following holds:
81///
82/// - The creator and constructor are separate entities.
83/// - You need to set the fallback lock time.
84/// - You need to set the sighash single flag.
85///
86/// If not use the [`Constructor`]  to carry out both roles e.g., `Constructor::<Modifiable>::default()`.
87///
88/// See `examples/v2-separate-creator-constructor.rs`.
89#[derive(Debug, Clone, PartialEq, Eq, Hash)]
90#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
91#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
92pub struct Creator(Psbt);
93
94impl Creator {
95    /// Creates a new PSBT Creator.
96    pub fn new() -> Self {
97        let psbt = Psbt {
98            global: Global::default(),
99            inputs: Default::default(),
100            outputs: Default::default(),
101        };
102        Creator(psbt)
103    }
104
105    /// Sets the fallback lock time.
106    pub fn fallback_lock_time(mut self, fallback: absolute::LockTime) -> Self {
107        self.0.global.fallback_lock_time = Some(fallback);
108        self
109    }
110
111    /// Sets the "has sighash single" flag in then transaction modifiable flags.
112    pub fn sighash_single(mut self) -> Self {
113        self.0.global.set_sighash_single_flag();
114        self
115    }
116
117    /// Sets the inputs modifiable bit in the transaction modifiable flags.
118    pub fn inputs_modifiable(mut self) -> Self {
119        self.0.global.set_inputs_modifiable_flag();
120        self
121    }
122
123    /// Sets the outputs modifiable bit in the transaction modifiable flags.
124    pub fn outputs_modifiable(mut self) -> Self {
125        self.0.global.set_outputs_modifiable_flag();
126        self
127    }
128
129    /// Sets the transaction version.
130    ///
131    /// You likely do not need this, it is provided for completeness.
132    ///
133    /// The default is [`transaction::Version::TWO`].
134    pub fn transaction_version(mut self, version: transaction::Version) -> Self {
135        self.0.global.tx_version = version;
136        self
137    }
138
139    /// Builds a [`Constructor`] that can add inputs and outputs.
140    ///
141    /// # Examples
142    ///
143    /// ```
144    /// use psbt_v2::v2::{Creator, Constructor, Modifiable};
145    ///
146    /// // Creator role separate from Constructor role.
147    /// let psbt = Creator::new()
148    ///     .inputs_modifiable()
149    ///     .outputs_modifiable()
150    ///     .psbt();
151    /// let _constructor = Constructor::<Modifiable>::new(psbt);
152    ///
153    /// // However, since a single entity is likely to be both a Creator and Constructor.
154    /// let _constructor = Creator::new().constructor_modifiable();
155    ///
156    /// // Or the more terse:
157    /// let _constructor = Constructor::<Modifiable>::default();
158    /// ```
159    pub fn constructor_modifiable(self) -> Constructor<Modifiable> {
160        let mut psbt = self.0;
161        psbt.global.set_inputs_modifiable_flag();
162        psbt.global.set_outputs_modifiable_flag();
163        Constructor(psbt, PhantomData)
164    }
165
166    /// Builds a [`Constructor`] that can only add inputs.
167    ///
168    /// # Examples
169    ///
170    /// ```
171    /// use psbt_v2::v2::{Creator, Constructor, InputsOnlyModifiable};
172    ///
173    /// // Creator role separate from Constructor role.
174    /// let psbt = Creator::new()
175    ///     .inputs_modifiable()
176    ///     .psbt();
177    /// let _constructor = Constructor::<InputsOnlyModifiable>::new(psbt);
178    ///
179    /// // However, since a single entity is likely to be both a Creator and Constructor.
180    /// let _constructor = Creator::new().constructor_inputs_only_modifiable();
181    ///
182    /// // Or the more terse:
183    /// let _constructor = Constructor::<InputsOnlyModifiable>::default();
184    /// ```
185    pub fn constructor_inputs_only_modifiable(self) -> Constructor<InputsOnlyModifiable> {
186        let mut psbt = self.0;
187        psbt.global.set_inputs_modifiable_flag();
188        psbt.global.clear_outputs_modifiable_flag();
189        Constructor(psbt, PhantomData)
190    }
191
192    /// Builds a [`Constructor`] that can only add outputs.
193    ///
194    /// # Examples
195    ///
196    /// ```
197    /// use psbt_v2::v2::{Creator, Constructor, OutputsOnlyModifiable};
198    ///
199    /// // Creator role separate from Constructor role.
200    /// let psbt = Creator::new()
201    ///     .inputs_modifiable()
202    ///     .psbt();
203    /// let _constructor = Constructor::<OutputsOnlyModifiable>::new(psbt);
204    ///
205    /// // However, since a single entity is likely to be both a Creator and Constructor.
206    /// let _constructor = Creator::new().constructor_outputs_only_modifiable();
207    ///
208    /// // Or the more terse:
209    /// let _constructor = Constructor::<OutputsOnlyModifiable>::default();
210    /// ```
211    pub fn constructor_outputs_only_modifiable(self) -> Constructor<OutputsOnlyModifiable> {
212        let mut psbt = self.0;
213        psbt.global.clear_inputs_modifiable_flag();
214        psbt.global.set_outputs_modifiable_flag();
215        Constructor(psbt, PhantomData)
216    }
217
218    /// Returns the created [`Psbt`].
219    ///
220    /// This is only required if the Creator and Constructor are separate entities. If the Creator
221    /// is also acting as the Constructor use one of the `Self::constructor_foo` functions.
222    pub fn psbt(self) -> Psbt { self.0 }
223}
224
225impl Default for Creator {
226    fn default() -> Self { Self::new() }
227}
228
229/// Marker for a `Constructor` with both inputs and outputs modifiable.
230pub enum Modifiable {}
231/// Marker for a `Constructor` with inputs modifiable.
232pub enum InputsOnlyModifiable {}
233/// Marker for a `Constructor` with outputs modifiable.
234pub enum OutputsOnlyModifiable {}
235
236mod sealed {
237    pub trait Mod {}
238    impl Mod for super::Modifiable {}
239    impl Mod for super::InputsOnlyModifiable {}
240    impl Mod for super::OutputsOnlyModifiable {}
241}
242
243/// Marker for if either inputs or outputs are modifiable, or both.
244pub trait Mod: sealed::Mod + Sync + Send + Sized + Unpin {}
245
246impl Mod for Modifiable {}
247impl Mod for InputsOnlyModifiable {}
248impl Mod for OutputsOnlyModifiable {}
249
250/// Implements the BIP-370 Constructor role.
251///
252/// Uses the builder pattern, and generics to make adding inputs and outputs infallible.
253#[derive(Debug, Clone, PartialEq, Eq, Hash)]
254#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
255#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
256pub struct Constructor<T>(Psbt, PhantomData<T>);
257
258impl<T: Mod> Constructor<T> {
259    /// Marks that the `Psbt` can not have any more inputs added to it.
260    pub fn no_more_inputs(mut self) -> Self {
261        self.0.global.clear_inputs_modifiable_flag();
262        self
263    }
264
265    /// Marks that the `Psbt` can not have any more outputs added to it.
266    pub fn no_more_outputs(mut self) -> Self {
267        self.0.global.clear_outputs_modifiable_flag();
268        self
269    }
270
271    /// Returns a PSBT [`Updater`] once construction is completed.
272    pub fn updater(self) -> Result<Updater, DetermineLockTimeError> {
273        self.no_more_inputs().no_more_outputs().psbt().map(Updater)
274    }
275
276    /// Returns the [`Psbt`] in its current state.
277    ///
278    /// This function can be used either to get the [`Psbt`] to pass to another constructor or to
279    /// get the [`Psbt`] ready for update if `no_more_inputs` and `no_more_outputs` have already
280    /// explicitly been called.
281    pub fn psbt(self) -> Result<Psbt, DetermineLockTimeError> {
282        let _ = self.0.determine_lock_time()?;
283        Ok(self.0)
284    }
285}
286
287impl Constructor<Modifiable> {
288    /// Creates a new Constructor.
289    ///
290    /// This function should only be needed if the PSBT Creator and Constructor roles are being
291    /// performed by separate entities, if not use one of the builder functions on the [`Creator`]
292    /// e.g., `constructor_modifiable()`.
293    pub fn new(psbt: Psbt) -> Result<Self, PsbtNotModifiableError> {
294        if !psbt.global.is_inputs_modifiable() {
295            Err(InputsNotModifiableError.into())
296        } else if !psbt.global.is_outputs_modifiable() {
297            Err(OutputsNotModifiableError.into())
298        } else {
299            Ok(Self(psbt, PhantomData))
300        }
301    }
302
303    /// Adds an input to the PSBT.
304    pub fn input(mut self, input: Input) -> Self {
305        self.0.inputs.push(input);
306        self.0.global.input_count += 1;
307        self
308    }
309
310    /// Adds an output to the PSBT.
311    pub fn output(mut self, output: Output) -> Self {
312        self.0.outputs.push(output);
313        self.0.global.output_count += 1;
314        self
315    }
316}
317// Useful if the Creator and Constructor are a single entity.
318impl Default for Constructor<Modifiable> {
319    fn default() -> Self { Creator::new().constructor_modifiable() }
320}
321
322impl Constructor<InputsOnlyModifiable> {
323    /// Creates a new Constructor.
324    ///
325    /// This function should only be needed if the PSBT Creator and Constructor roles are being
326    /// performed by separate entities, if not use one of the builder functions on the [`Creator`]
327    /// e.g., `constructor_modifiable()`.
328    pub fn new(psbt: Psbt) -> Result<Self, InputsNotModifiableError> {
329        if psbt.global.is_inputs_modifiable() {
330            Ok(Self(psbt, PhantomData))
331        } else {
332            Err(InputsNotModifiableError)
333        }
334    }
335
336    /// Adds an input to the PSBT.
337    pub fn input(mut self, input: Input) -> Self {
338        self.0.inputs.push(input);
339        self.0.global.input_count += 1;
340        self
341    }
342}
343
344// Useful if the Creator and Constructor are a single entity.
345impl Default for Constructor<InputsOnlyModifiable> {
346    fn default() -> Self { Creator::new().constructor_inputs_only_modifiable() }
347}
348
349impl Constructor<OutputsOnlyModifiable> {
350    /// Creates a new Constructor.
351    ///
352    /// This function should only be needed if the PSBT Creator and Constructor roles are being
353    /// performed by separate entities, if not use one of the builder functions on the [`Creator`]
354    /// e.g., `constructor_modifiable()`.
355    pub fn new(psbt: Psbt) -> Result<Self, OutputsNotModifiableError> {
356        if psbt.global.is_outputs_modifiable() {
357            Ok(Self(psbt, PhantomData))
358        } else {
359            Err(OutputsNotModifiableError)
360        }
361    }
362
363    /// Adds an output to the PSBT.
364    pub fn output(mut self, output: Output) -> Self {
365        self.0.outputs.push(output);
366        self.0.global.output_count += 1;
367        self
368    }
369}
370
371// Useful if the Creator and Constructor are a single entity.
372impl Default for Constructor<OutputsOnlyModifiable> {
373    fn default() -> Self { Creator::new().constructor_outputs_only_modifiable() }
374}
375
376/// Implements the BIP-370 Updater role.
377#[derive(Debug, Clone, PartialEq, Eq, Hash)]
378#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
379#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
380pub struct Updater(Psbt);
381
382impl Updater {
383    /// Creates an `Updater`.
384    ///
385    /// An updater can only update a PSBT that has a valid combination of lock times.
386    pub fn new(psbt: Psbt) -> Result<Self, DetermineLockTimeError> {
387        let _ = psbt.determine_lock_time()?;
388        Ok(Self(psbt))
389    }
390
391    /// Returns this PSBT's unique identification.
392    pub fn id(&self) -> Txid {
393        self.0.id().expect("Updater guarantees lock time can be determined")
394    }
395
396    /// Updater role, update the sequence number for input at `index`.
397    pub fn set_sequence(
398        mut self,
399        n: Sequence,
400        input_index: usize,
401    ) -> Result<Updater, IndexOutOfBoundsError> {
402        let input = self.0.checked_input_mut(input_index)?;
403        input.sequence = Some(n);
404        Ok(self)
405    }
406
407    // /// Converts the inner PSBT v2 to a PSBT v0.
408    // pub fn into_psbt_v0(self) -> v0::Psbt {
409    //     let unsigned_tx =
410    //         self.0.unsigned_tx().expect("Updater guarantees lock time can be determined");
411    //     let psbt = self.psbt();
412
413    //     let global = psbt.global.into_v0(unsigned_tx);
414    //     let inputs = psbt.inputs.into_iter().map(|input| input.into_v0()).collect();
415    //     let outputs = psbt.outputs.into_iter().map(|output| output.into_v0()).collect();
416
417    //     v0::Psbt { global, inputs, outputs }
418    // }
419
420    /// Returns the inner [`Psbt`].
421    pub fn psbt(self) -> Psbt { self.0 }
422}
423
424impl TryFrom<Psbt> for Updater {
425    type Error = DetermineLockTimeError;
426
427    fn try_from(psbt: Psbt) -> Result<Self, Self::Error> { Self::new(psbt) }
428}
429
430/// Implements the BIP-370 Signer role.
431#[derive(Debug, Clone, PartialEq, Eq, Hash)]
432#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
433#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
434pub struct Signer(Psbt);
435
436impl Signer {
437    /// Creates a `Signer`.
438    ///
439    /// An updater can only update a PSBT that has a valid combination of lock times.
440    pub fn new(psbt: Psbt) -> Result<Self, DetermineLockTimeError> {
441        let _ = psbt.determine_lock_time()?;
442        Ok(Self(psbt))
443    }
444
445    /// Returns this PSBT's unique identification.
446    pub fn id(&self) -> Result<Txid, DetermineLockTimeError> { self.0.id() }
447
448    /// Creates an unsigned transaction from the inner [`Psbt`].
449    pub fn unsigned_tx(&self) -> Transaction {
450        self.0.unsigned_tx().expect("Signer guarantees lock time can be determined")
451    }
452
453    /// Attempts to create _all_ the required signatures for this PSBT using `k`.
454    ///
455    /// **NOTE**: Taproot inputs are, as yet, not supported by this function. We currently only
456    /// attempt to sign ECDSA inputs.
457    ///
458    /// If you just want to sign an input with one specific key consider using `sighash_ecdsa`. This
459    /// function does not support scripts that contain `OP_CODESEPARATOR`.
460    ///
461    /// # Returns
462    ///
463    /// Either Ok(SigningKeys) or Err((SigningKeys, SigningErrors)), where
464    /// - SigningKeys: A map of input index -> pubkey associated with secret key used to sign.
465    /// - SigningKeys: A map of input index -> the error encountered while attempting to sign.
466    ///
467    /// If an error is returned some signatures may already have been added to the PSBT. Since
468    /// `partial_sigs` is a [`BTreeMap`] it is safe to retry, previous sigs will be overwritten.
469    pub fn sign<C, K>(
470        self,
471        k: &K,
472        secp: &Secp256k1<C>,
473    ) -> Result<(Psbt, SigningKeys), (SigningKeys, SigningErrors)>
474    where
475        C: Signing,
476        K: GetKey,
477    {
478        let tx = self.unsigned_tx();
479        let mut psbt = self.psbt();
480
481        psbt.sign(tx, k, secp).map(|signing_keys| (psbt, signing_keys))
482    }
483
484    /// Sets the PSBT_GLOBAL_TX_MODIFIABLE as required after signing an ECDSA input.
485    ///
486    /// > For PSBTv2s, a signer must update the PSBT_GLOBAL_TX_MODIFIABLE field after signing
487    /// > inputs so that it accurately reflects the state of the PSBT.
488    pub fn ecdsa_clear_tx_modifiable(&mut self, ty: EcdsaSighashType) {
489        self.0.clear_tx_modifiable(ty as u8)
490    }
491
492    /// Returns the inner [`Psbt`].
493    pub fn psbt(self) -> Psbt { self.0 }
494}
495
496/// A Partially Signed Transaction.
497#[derive(Debug, Clone, PartialEq, Eq, Hash)]
498#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
499#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
500pub struct Psbt {
501    /// The global map.
502    pub global: Global,
503    /// The corresponding key-value map for each input in the unsigned transaction.
504    pub inputs: Vec<Input>,
505    /// The corresponding key-value map for each output in the unsigned transaction.
506    pub outputs: Vec<Output>,
507}
508
509impl Psbt {
510    // TODO: Add inherent methods to get each of the role types.
511
512    /// Returns this PSBT's unique identification.
513    fn id(&self) -> Result<Txid, DetermineLockTimeError> {
514        let mut tx = self.unsigned_tx()?;
515        // Updaters may change the sequence so to calculate ID we set it to zero.
516        tx.input.iter_mut().for_each(|input| input.sequence = Sequence::ZERO);
517
518        Ok(tx.compute_txid())
519    }
520
521    /// Creates an unsigned transaction from the inner [`Psbt`].
522    ///
523    /// Quidado! this transaction should not be used to determine the ID of
524    /// the [`Pbst`], use `Self::id()` instead.
525    fn unsigned_tx(&self) -> Result<Transaction, DetermineLockTimeError> {
526        let lock_time = self.determine_lock_time()?;
527
528        Ok(Transaction {
529            version: self.global.tx_version,
530            lock_time,
531            input: self.inputs.iter().map(|input| input.unsigned_tx_in()).collect(),
532            output: self.outputs.iter().map(|ouput| ouput.tx_out()).collect(),
533        })
534    }
535
536    /// Determines the lock time as specified in [BIP-370] if it is possible to do so.
537    ///
538    /// [BIP-370]: <https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#determining-lock-time>
539    pub fn determine_lock_time(&self) -> Result<absolute::LockTime, DetermineLockTimeError> {
540        let require_time_based_lock_time =
541            self.inputs.iter().any(|input| input.requires_time_based_lock_time());
542        let require_height_based_lock_time =
543            self.inputs.iter().any(|input| input.requires_height_based_lock_time());
544
545        if require_time_based_lock_time && require_height_based_lock_time {
546            return Err(DetermineLockTimeError);
547        }
548
549        let have_lock_time = self.inputs.iter().any(|input| input.has_lock_time());
550
551        let lock = if have_lock_time {
552            let all_inputs_satisfied_with_height_based_lock_time =
553                self.inputs.iter().all(|input| input.is_satisfied_with_height_based_lock_time());
554
555            // > The lock time chosen is then the maximum value of the chosen type of lock time.
556            if all_inputs_satisfied_with_height_based_lock_time {
557                // We either have only height based or we have both, in which case we must use height based.
558                let height = self
559                    .inputs
560                    .iter()
561                    .map(|input| input.min_height)
562                    .max()
563                    .expect("we know we have at least one non-none min_height field")
564                    .expect("so we know that max is non-none");
565                absolute::LockTime::from(height)
566            } else {
567                let time = self
568                    .inputs
569                    .iter()
570                    .map(|input| input.min_time)
571                    .max()
572                    .expect("we know we have at least one non-none min_height field")
573                    .expect("so we know that max is non-none");
574                absolute::LockTime::from(time)
575            }
576        } else {
577            // > If none of the inputs have a PSBT_IN_REQUIRED_TIME_LOCKTIME and
578            // > PSBT_IN_REQUIRED_HEIGHT_LOCKTIME, then PSBT_GLOBAL_FALLBACK_LOCKTIME must be used.
579            // > If PSBT_GLOBAL_FALLBACK_LOCKTIME is not provided, then it is assumed to be 0.
580            self.global.fallback_lock_time.unwrap_or(absolute::LockTime::ZERO)
581        };
582
583        Ok(lock)
584    }
585
586    /// Returns true if all inputs for this PSBT have been finalized.
587    pub fn is_finalized(&self) -> bool { self.inputs.iter().all(|input| input.is_finalized()) }
588
589    /// Serialize a value as bytes in hex.
590    pub fn serialize_hex(&self) -> String { self.serialize().to_lower_hex_string() }
591
592    /// Serialize as raw binary data
593    pub fn serialize(&self) -> Vec<u8> {
594        let mut buf: Vec<u8> = Vec::new();
595
596        //  <magic>
597        buf.extend_from_slice(b"psbt");
598
599        buf.push(0xff_u8);
600
601        buf.extend(self.global.serialize_map());
602
603        for i in &self.inputs {
604            buf.extend(i.serialize_map());
605        }
606
607        for i in &self.outputs {
608            buf.extend(i.serialize_map());
609        }
610
611        buf
612    }
613
614    /// Deserialize a value from raw binary data.
615    pub fn deserialize(bytes: &[u8]) -> Result<Self, DeserializeError> {
616        use DeserializeError::*;
617
618        const MAGIC_BYTES: &[u8] = b"psbt";
619        if bytes.get(0..MAGIC_BYTES.len()) != Some(MAGIC_BYTES) {
620            return Err(InvalidMagic);
621        }
622
623        const PSBT_SERPARATOR: u8 = 0xff_u8;
624        if bytes.get(MAGIC_BYTES.len()) != Some(&PSBT_SERPARATOR) {
625            return Err(InvalidSeparator);
626        }
627
628        let mut d = bytes.get(5..).ok_or(NoMorePairs)?;
629
630        let global = Global::decode(&mut d)?;
631
632        let inputs: Vec<Input> = {
633            let inputs_len: usize = global.input_count;
634            let mut inputs: Vec<Input> = Vec::with_capacity(inputs_len);
635
636            for _ in 0..inputs_len {
637                inputs.push(Input::decode(&mut d)?);
638            }
639
640            inputs
641        };
642
643        let outputs: Vec<Output> = {
644            let outputs_len: usize = global.output_count;
645            let mut outputs: Vec<Output> = Vec::with_capacity(outputs_len);
646
647            for _ in 0..outputs_len {
648                outputs.push(Output::decode(&mut d)?)
649            }
650
651            outputs
652        };
653
654        Ok(Psbt { global, inputs, outputs })
655    }
656
657    /// Returns an iterator for the funding UTXOs of the psbt
658    ///
659    /// For each PSBT input that contains UTXO information `Ok` is returned containing that information.
660    /// The order of returned items is same as the order of inputs.
661    ///
662    /// ## Errors
663    ///
664    /// The function returns error when UTXO information is not present or is invalid.
665    pub fn iter_funding_utxos(&self) -> impl Iterator<Item = Result<&TxOut, FundingUtxoError>> {
666        self.inputs.iter().map(|input| input.funding_utxo())
667    }
668
669    /// Combines this [`Psbt`] with `other` PSBT as described by BIP-174.
670    ///
671    /// BIP-370 does not include any additional requirements for the Combiner role.
672    ///
673    /// This function is commutative `A.combine_with(B) = B.combine_with(A)`.
674    ///
675    /// See [`combine()`] for a non-consuming version of this function.
676    pub fn combine_with(mut self, other: Self) -> Result<Psbt, CombineError> {
677        self.global.combine(other.global)?;
678
679        for (self_input, other_input) in self.inputs.iter_mut().zip(other.inputs.into_iter()) {
680            self_input.combine(other_input)?;
681        }
682
683        for (self_output, other_output) in self.outputs.iter_mut().zip(other.outputs.into_iter()) {
684            self_output.combine(other_output)?;
685        }
686
687        Ok(self)
688    }
689
690    /// Sets the PSBT_GLOBAL_TX_MODIFIABLE as required after signing.
691    // TODO: Consider using consts instead of magic numbers.
692    fn clear_tx_modifiable(&mut self, sighash_type: u8) {
693        let ty = sighash_type;
694        // If the Signer added a signature that does not use SIGHASH_ANYONECANPAY,
695        // the Input Modifiable flag must be set to False.
696        if !(ty == 0x81 || ty == 0x82 || ty == 0x83) {
697            self.global.clear_inputs_modifiable_flag();
698        }
699
700        // If the Signer added a signature that does not use SIGHASH_NONE,
701        // the Outputs Modifiable flag must be set to False.
702        if !(ty == 0x02 || ty == 0x82) {
703            self.global.clear_outputs_modifiable_flag();
704        }
705
706        // If the Signer added a signature that uses SIGHASH_SINGLE,
707        // the Has SIGHASH_SINGLE flag must be set to True.
708        if ty == 0x03 || ty == 0x83 {
709            self.global.set_sighash_single_flag();
710        }
711    }
712
713    /// Attempts to create _all_ the required signatures for this PSBT using `k`.
714    ///
715    /// **NOTE**: Taproot inputs are, as yet, not supported by this function. We currently only
716    /// attempt to sign ECDSA inputs.
717    ///
718    /// If you just want to sign an input with one specific key consider using `sighash_ecdsa`. This
719    /// function does not support scripts that contain `OP_CODESEPARATOR`.
720    ///
721    /// # Returns
722    ///
723    /// Either Ok(SigningKeys) or Err((SigningKeys, SigningErrors)), where
724    /// - SigningKeys: A map of input index -> pubkey associated with secret key used to sign.
725    /// - SigningKeys: A map of input index -> the error encountered while attempting to sign.
726    ///
727    /// If an error is returned some signatures may already have been added to the PSBT. Since
728    /// `partial_sigs` is a [`BTreeMap`] it is safe to retry, previous sigs will be overwritten.
729    fn sign<C, K>(
730        &mut self,
731        tx: Transaction,
732        k: &K,
733        secp: &Secp256k1<C>,
734    ) -> Result<SigningKeys, (SigningKeys, SigningErrors)>
735    where
736        C: Signing,
737        K: GetKey,
738    {
739        let mut cache = SighashCache::new(&tx);
740
741        let mut used = BTreeMap::new();
742        let mut errors = BTreeMap::new();
743
744        for i in 0..self.global.input_count {
745            if let Ok(SigningAlgorithm::Ecdsa) = self.signing_algorithm(i) {
746                match self.bip32_sign_ecdsa(k, i, &mut cache, secp) {
747                    Ok(v) => {
748                        used.insert(i, v);
749                    }
750                    Err(e) => {
751                        errors.insert(i, e);
752                    }
753                }
754            };
755        }
756        if errors.is_empty() {
757            Ok(used)
758        } else {
759            Err((used, errors))
760        }
761    }
762
763    /// Attempts to create all signatures required by this PSBT's `bip32_derivation` field, adding
764    /// them to `partial_sigs`.
765    ///
766    /// # Returns
767    ///
768    /// - Ok: A list of the public keys used in signing.
769    /// - Err: Error encountered trying to calculate the sighash AND we had the signing key.
770    fn bip32_sign_ecdsa<C, K, T>(
771        &mut self,
772        k: &K,
773        input_index: usize,
774        cache: &mut SighashCache<T>,
775        secp: &Secp256k1<C>,
776    ) -> Result<Vec<PublicKey>, SignError>
777    where
778        C: Signing,
779        T: Borrow<Transaction>,
780        K: GetKey,
781    {
782        let msg_sighash_ty_res = self.sighash_ecdsa(input_index, cache);
783        let sighash_ty = msg_sighash_ty_res.clone().ok().map(|(_msg, sighash_ty)| sighash_ty);
784
785        let input = &mut self.inputs[input_index]; // Index checked in call to `sighash_ecdsa`.
786        let mut used = vec![]; // List of pubkeys used to sign the input.
787
788        for (pk, key_source) in input.bip32_derivations.iter() {
789            let sk = if let Ok(Some(sk)) = k.get_key(KeyRequest::Bip32(key_source.clone()), secp) {
790                sk
791            } else if let Ok(Some(sk)) = k.get_key(KeyRequest::Pubkey(PublicKey::new(*pk)), secp) {
792                sk
793            } else {
794                continue;
795            };
796
797            // Only return the error if we have a secret key to sign this input.
798            let (msg, sighash_ty) = match msg_sighash_ty_res {
799                Err(e) => return Err(e),
800                Ok((msg, sighash_ty)) => (msg, sighash_ty),
801            };
802
803            let sig = ecdsa::Signature {
804                signature: secp.sign_ecdsa(&msg, &sk.inner),
805                sighash_type: sighash_ty,
806            };
807
808            let pk = sk.public_key(secp);
809
810            input.partial_sigs.insert(pk, sig);
811            used.push(pk);
812        }
813
814        let ty = sighash_ty.expect("at this stage we know its ok");
815        self.clear_tx_modifiable(ty as u8);
816
817        Ok(used)
818    }
819
820    /// Returns the sighash message to sign an ECDSA input along with the sighash type.
821    ///
822    /// Uses the [`EcdsaSighashType`] from this input if one is specified. If no sighash type is
823    /// specified uses [`EcdsaSighashType::All`]. This function does not support scripts that
824    /// contain `OP_CODESEPARATOR`.
825    pub fn sighash_ecdsa<T: Borrow<Transaction>>(
826        &self,
827        input_index: usize,
828        cache: &mut SighashCache<T>,
829    ) -> Result<(Message, EcdsaSighashType), SignError> {
830        use OutputType::*;
831
832        if self.signing_algorithm(input_index)? != SigningAlgorithm::Ecdsa {
833            return Err(SignError::WrongSigningAlgorithm);
834        }
835
836        let input = self.checked_input(input_index)?;
837        let utxo = input.funding_utxo()?;
838        let spk = &utxo.script_pubkey; // scriptPubkey for input spend utxo.
839
840        let hash_ty = input.ecdsa_hash_ty().map_err(|_| SignError::InvalidSighashType)?; // Only support standard sighash types.
841
842        match self.output_type(input_index)? {
843            Bare => {
844                let sighash = cache
845                    .legacy_signature_hash(input_index, spk, hash_ty.to_u32())
846                    .expect("input checked above");
847                Ok((Message::from(sighash), hash_ty))
848            }
849            Sh => {
850                let script_code =
851                    input.redeem_script.as_ref().ok_or(SignError::MissingRedeemScript)?;
852                let sighash = cache
853                    .legacy_signature_hash(input_index, script_code, hash_ty.to_u32())
854                    .expect("input checked above");
855                Ok((Message::from(sighash), hash_ty))
856            }
857            Wpkh => {
858                let sighash = cache.p2wpkh_signature_hash(input_index, spk, utxo.value, hash_ty)?;
859                Ok((Message::from(sighash), hash_ty))
860            }
861            ShWpkh => {
862                let redeem_script = input.redeem_script.as_ref().expect("checked above");
863                let sighash =
864                    cache.p2wpkh_signature_hash(input_index, redeem_script, utxo.value, hash_ty)?;
865                Ok((Message::from(sighash), hash_ty))
866            }
867            Wsh | ShWsh => {
868                let witness_script =
869                    input.witness_script.as_ref().ok_or(SignError::MissingWitnessScript)?;
870                let sighash = cache
871                    .p2wsh_signature_hash(input_index, witness_script, utxo.value, hash_ty)
872                    .map_err(SignError::SegwitV0Sighash)?;
873                Ok((Message::from(sighash), hash_ty))
874            }
875            Tr => {
876                // This PSBT signing API is WIP, taproot to come shortly.
877                Err(SignError::Unsupported)
878            }
879        }
880    }
881
882    /// Gets a reference to the input at `input_index` after checking that it is a valid index.
883    fn checked_input(&self, index: usize) -> Result<&Input, IndexOutOfBoundsError> {
884        self.check_input_index(index)?;
885        Ok(&self.inputs[index])
886    }
887
888    /// Gets a mutable reference to the input at `input_index` after checking that it is a valid index.
889    fn checked_input_mut(&mut self, index: usize) -> Result<&mut Input, IndexOutOfBoundsError> {
890        self.check_input_index(index)?;
891        Ok(&mut self.inputs[index])
892    }
893    /// Checks that `index` is valid for this PSBT.
894    fn check_input_index(&self, index: usize) -> Result<(), IndexOutOfBoundsError> {
895        if index >= self.inputs.len() {
896            return Err(IndexOutOfBoundsError::Inputs { index, length: self.inputs.len() });
897        }
898        if index >= self.global.input_count {
899            return Err(IndexOutOfBoundsError::Count { index, count: self.global.input_count });
900        }
901        Ok(())
902    }
903
904    /// Returns the algorithm used to sign this PSBT's input at `input_index`.
905    fn signing_algorithm(&self, input_index: usize) -> Result<SigningAlgorithm, SignError> {
906        let output_type = self.output_type(input_index)?;
907        Ok(output_type.signing_algorithm())
908    }
909
910    /// Returns the [`OutputType`] of the spend utxo for this PBST's input at `input_index`.
911    fn output_type(&self, input_index: usize) -> Result<OutputType, SignError> {
912        let input = self.checked_input(input_index)?;
913        let utxo = input.funding_utxo()?;
914        let spk = utxo.script_pubkey.clone();
915
916        // Anything that is not segwit and is not p2sh is `Bare`.
917        if !(spk.is_witness_program() || spk.is_p2sh()) {
918            return Ok(OutputType::Bare);
919        }
920
921        if spk.is_p2wpkh() {
922            return Ok(OutputType::Wpkh);
923        }
924
925        if spk.is_p2wsh() {
926            return Ok(OutputType::Wsh);
927        }
928
929        if spk.is_p2sh() {
930            if input.redeem_script.as_ref().map(|s| s.is_p2wpkh()).unwrap_or(false) {
931                return Ok(OutputType::ShWpkh);
932            }
933            if input.redeem_script.as_ref().map(|x| x.is_p2wsh()).unwrap_or(false) {
934                return Ok(OutputType::ShWsh);
935            }
936            return Ok(OutputType::Sh);
937        }
938
939        if spk.is_p2tr() {
940            return Ok(OutputType::Tr);
941        }
942
943        // Something is wrong with the input scriptPubkey or we do not know how to sign
944        // because there has been a new softfork that we do not yet support.
945        Err(SignError::UnknownOutputType)
946    }
947
948    /// Calculates transaction fee.
949    ///
950    /// 'Fee' being the amount that will be paid for mining a transaction with the current inputs
951    /// and outputs i.e., the difference in value of the total inputs and the total outputs.
952    pub fn fee(&self) -> Result<Amount, FeeError> {
953        use FeeError::*;
954
955        // For the inputs we have to get the value from the input UTXOs.
956        let mut input_value: u64 = 0;
957        for input in self.iter_funding_utxos() {
958            input_value = input_value.checked_add(input?.value.to_sat()).ok_or(InputOverflow)?;
959        }
960        // For the outputs we have the value directly in the `Output`.
961        let mut output_value: u64 = 0;
962        for output in &self.outputs {
963            output_value =
964                output_value.checked_add(output.amount.to_sat()).ok_or(OutputOverflow)?;
965        }
966
967        input_value.checked_sub(output_value).map(Amount::from_sat).ok_or(Negative)
968    }
969
970    /// Checks the sighash types of input partial sigs (ECDSA).
971    ///
972    /// This can be used at anytime but is primarily used during PSBT finalizing.
973    #[cfg(feature = "miniscript")]
974    pub(crate) fn check_partial_sigs_sighash_type(
975        &self,
976    ) -> Result<(), PartialSigsSighashTypeError> {
977        use PartialSigsSighashTypeError::*;
978
979        for (input_index, input) in self.inputs.iter().enumerate() {
980            let target_ecdsa_sighash_ty = match input.sighash_type {
981                Some(psbt_hash_ty) => psbt_hash_ty
982                    .ecdsa_hash_ty()
983                    .map_err(|error| NonStandardInputSighashType { input_index, error })?,
984                None => EcdsaSighashType::All,
985            };
986
987            for (key, ecdsa_sig) in &input.partial_sigs {
988                let flag = EcdsaSighashType::from_standard(ecdsa_sig.sighash_type as u32)
989                    .map_err(|error| NonStandardPartialSigsSighashType { input_index, error })?;
990                if target_ecdsa_sighash_ty != flag {
991                    return Err(WrongSighashFlag {
992                        input_index,
993                        required: target_ecdsa_sighash_ty,
994                        got: flag,
995                        pubkey: *key,
996                    });
997                }
998            }
999        }
1000        Ok(())
1001    }
1002}
1003
1004/// Data required to call [`GetKey`] to get the private key to sign an input.
1005#[derive(Debug, Clone, PartialEq, Eq)]
1006#[non_exhaustive]
1007pub enum KeyRequest {
1008    /// Request a private key using the associated public key.
1009    Pubkey(PublicKey),
1010    /// Request a private key using BIP-32 fingerprint and derivation path.
1011    Bip32(KeySource),
1012}
1013
1014/// Trait to get a private key from a key request, key is then used to sign an input.
1015pub trait GetKey {
1016    /// An error occurred while getting the key.
1017    type Error: core::fmt::Debug;
1018
1019    /// Attempts to get the private key for `key_request`.
1020    ///
1021    /// # Returns
1022    /// - `Some(key)` if the key is found.
1023    /// - `None` if the key was not found but no error was encountered.
1024    /// - `Err` if an error was encountered while looking for the key.
1025    fn get_key<C: Signing>(
1026        &self,
1027        key_request: KeyRequest,
1028        secp: &Secp256k1<C>,
1029    ) -> Result<Option<PrivateKey>, Self::Error>;
1030}
1031
1032impl GetKey for Xpriv {
1033    type Error = GetKeyError;
1034
1035    fn get_key<C: Signing>(
1036        &self,
1037        key_request: KeyRequest,
1038        secp: &Secp256k1<C>,
1039    ) -> Result<Option<PrivateKey>, Self::Error> {
1040        match key_request {
1041            KeyRequest::Pubkey(_) => Err(GetKeyError::NotSupported),
1042            KeyRequest::Bip32((fingerprint, path)) => {
1043                let key = if self.fingerprint(secp) == fingerprint {
1044                    let k = self.derive_priv(secp, &path)?;
1045                    Some(k.to_priv())
1046                } else {
1047                    None
1048                };
1049                Ok(key)
1050            }
1051        }
1052    }
1053}
1054
1055/// Map of input index -> pubkey associated with secret key used to create signature for that input.
1056pub type SigningKeys = BTreeMap<usize, Vec<PublicKey>>;
1057
1058/// Map of input index -> the error encountered while attempting to sign that input.
1059pub type SigningErrors = BTreeMap<usize, SignError>;
1060
1061#[rustfmt::skip]
1062macro_rules! impl_get_key_for_set {
1063    ($set:ident) => {
1064
1065impl GetKey for $set<Xpriv> {
1066    type Error = GetKeyError;
1067
1068    fn get_key<C: Signing>(
1069        &self,
1070        key_request: KeyRequest,
1071        secp: &Secp256k1<C>
1072    ) -> Result<Option<PrivateKey>, Self::Error> {
1073        match key_request {
1074            KeyRequest::Pubkey(_) => Err(GetKeyError::NotSupported),
1075            KeyRequest::Bip32((fingerprint, path)) => {
1076                for xpriv in self.iter() {
1077                    if xpriv.parent_fingerprint == fingerprint {
1078                        let k = xpriv.derive_priv(secp, &path)?;
1079                        return Ok(Some(k.to_priv()));
1080                    }
1081                }
1082                Ok(None)
1083            }
1084        }
1085    }
1086}}}
1087
1088impl_get_key_for_set!(BTreeSet);
1089#[cfg(feature = "std")]
1090impl_get_key_for_set!(HashSet);
1091
1092#[rustfmt::skip]
1093macro_rules! impl_get_key_for_map {
1094    ($map:ident) => {
1095
1096impl GetKey for $map<PublicKey, PrivateKey> {
1097    type Error = GetKeyError;
1098
1099    fn get_key<C: Signing>(
1100        &self,
1101        key_request: KeyRequest,
1102        _: &Secp256k1<C>,
1103    ) -> Result<Option<PrivateKey>, Self::Error> {
1104        match key_request {
1105            KeyRequest::Pubkey(pk) => Ok(self.get(&pk).cloned()),
1106            KeyRequest::Bip32(_) => Err(GetKeyError::NotSupported),
1107        }
1108    }
1109}}}
1110impl_get_key_for_map!(BTreeMap);
1111#[cfg(feature = "std")]
1112impl_get_key_for_map!(HashMap);
1113
1114/// Errors when getting a key.
1115#[derive(Debug, Clone, PartialEq, Eq)]
1116#[non_exhaustive]
1117pub enum GetKeyError {
1118    /// A bip32 error.
1119    Bip32(bip32::Error),
1120    /// The GetKey operation is not supported for this key request.
1121    NotSupported,
1122}
1123
1124impl fmt::Display for GetKeyError {
1125    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1126        use GetKeyError::*;
1127
1128        match *self {
1129            Bip32(ref e) => write_err!(f, "a bip23 error"; e),
1130            NotSupported =>
1131                f.write_str("the GetKey operation is not supported for this key request"),
1132        }
1133    }
1134}
1135
1136#[cfg(feature = "std")]
1137impl std::error::Error for GetKeyError {
1138    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1139        use GetKeyError::*;
1140
1141        match *self {
1142            NotSupported => None,
1143            Bip32(ref e) => Some(e),
1144        }
1145    }
1146}
1147
1148impl From<bip32::Error> for GetKeyError {
1149    fn from(e: bip32::Error) -> Self { GetKeyError::Bip32(e) }
1150}
1151
1152/// The various output types supported by the Bitcoin network.
1153#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1154#[non_exhaustive]
1155pub enum OutputType {
1156    /// An output of type: pay-to-pubkey or pay-to-pubkey-hash.
1157    Bare,
1158    /// A pay-to-witness-pubkey-hash output (P2WPKH).
1159    Wpkh,
1160    /// A pay-to-witness-script-hash output (P2WSH).
1161    Wsh,
1162    /// A nested segwit output, pay-to-witness-pubkey-hash nested in a pay-to-script-hash.
1163    ShWpkh,
1164    /// A nested segwit output, pay-to-witness-script-hash nested in a pay-to-script-hash.
1165    ShWsh,
1166    /// A pay-to-script-hash output excluding wrapped segwit (P2SH).
1167    Sh,
1168    /// A taproot output (P2TR).
1169    Tr,
1170}
1171
1172impl OutputType {
1173    /// The signing algorithm used to sign this output type.
1174    pub fn signing_algorithm(&self) -> SigningAlgorithm {
1175        use OutputType::*;
1176
1177        match self {
1178            Bare | Wpkh | Wsh | ShWpkh | ShWsh | Sh => SigningAlgorithm::Ecdsa,
1179            Tr => SigningAlgorithm::Schnorr,
1180        }
1181    }
1182}
1183
1184/// Signing algorithms supported by the Bitcoin network.
1185#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1186pub enum SigningAlgorithm {
1187    /// The Elliptic Curve Digital Signature Algorithm (see [wikipedia]).
1188    ///
1189    /// [wikipedia]: https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm
1190    Ecdsa,
1191    /// The Schnorr signature algorithm (see [wikipedia]).
1192    ///
1193    /// [wikipedia]: https://en.wikipedia.org/wiki/Schnorr_signature
1194    Schnorr,
1195}
1196
1197/// An error occurred while decoding a v2 PSBT.
1198#[derive(Debug)]
1199#[non_exhaustive]
1200pub enum DecodeError {
1201    /// Magic bytes for a PSBT must be the ASCII for "psbt" serialized in most
1202    /// significant byte order.
1203    InvalidMagic,
1204    /// The separator for a PSBT must be `0xff`.
1205    InvalidSeparator,
1206    /// Signals that there are no more key-value pairs in a key-value map.
1207    NoMorePairs,
1208    /// Error decoding global map.
1209    Global(global::DecodeError),
1210    /// Error decoding input map.
1211    Input(input::DecodeError),
1212    /// Error decoding output map.
1213    Output(output::DecodeError),
1214}
1215
1216impl fmt::Display for DecodeError {
1217    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1218        use DecodeError::*;
1219
1220        match *self {
1221            InvalidMagic => f.write_str("invalid magic"),
1222            InvalidSeparator => f.write_str("invalid separator"),
1223            NoMorePairs => f.write_str("no more key-value pairs for this psbt map"),
1224            Global(ref e) => write_err!(f, "global map decode error"; e),
1225            Input(ref e) => write_err!(f, "input map decode error"; e),
1226            Output(ref e) => write_err!(f, "output map decode error"; e),
1227        }
1228    }
1229}
1230
1231#[cfg(feature = "std")]
1232impl std::error::Error for DecodeError {
1233    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1234        use DecodeError::*;
1235
1236        match *self {
1237            InvalidMagic | InvalidSeparator | NoMorePairs => None,
1238            Global(ref e) => Some(e),
1239            Input(ref e) => Some(e),
1240            Output(ref e) => Some(e),
1241        }
1242    }
1243}
1244
1245impl From<global::DecodeError> for DecodeError {
1246    fn from(e: global::DecodeError) -> Self { Self::Global(e) }
1247}
1248
1249impl From<input::DecodeError> for DecodeError {
1250    fn from(e: input::DecodeError) -> Self { Self::Input(e) }
1251}
1252
1253impl From<output::DecodeError> for DecodeError {
1254    fn from(e: output::DecodeError) -> Self { Self::Output(e) }
1255}
1256
1257/// If the "base64" feature is enabled we implement `Display` and `FromStr` using base64 encoding.
1258#[cfg(feature = "base64")]
1259mod display_from_str {
1260    use core::fmt::{self, Display, Formatter};
1261    use core::str::FromStr;
1262
1263    use bitcoin::base64::display::Base64Display;
1264    use bitcoin::base64::prelude::{Engine as _, BASE64_STANDARD};
1265
1266    use super::*;
1267
1268    impl Display for Psbt {
1269        fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1270            write!(f, "{}", Base64Display::new(&self.serialize(), &BASE64_STANDARD))
1271        }
1272    }
1273
1274    impl FromStr for Psbt {
1275        type Err = ParsePsbtError;
1276
1277        fn from_str(s: &str) -> Result<Self, Self::Err> {
1278            let data = BASE64_STANDARD.decode(s).map_err(ParsePsbtError::Base64Encoding)?;
1279            Psbt::deserialize(&data).map_err(ParsePsbtError::PsbtEncoding)
1280        }
1281    }
1282
1283    /// Error encountered during PSBT decoding from Base64 string.
1284    #[derive(Debug)]
1285    #[non_exhaustive]
1286    pub enum ParsePsbtError {
1287        /// Error in internal PSBT data structure.
1288        PsbtEncoding(DeserializeError),
1289        /// Error in PSBT Base64 encoding.
1290        Base64Encoding(bitcoin::base64::DecodeError),
1291    }
1292
1293    impl Display for ParsePsbtError {
1294        fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1295            use self::ParsePsbtError::*;
1296
1297            match *self {
1298                PsbtEncoding(ref e) => write_err!(f, "error in internal PSBT data structure"; e),
1299                Base64Encoding(ref e) => write_err!(f, "error in PSBT base64 encoding"; e),
1300            }
1301        }
1302    }
1303
1304    #[cfg(feature = "std")]
1305    impl std::error::Error for ParsePsbtError {
1306        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1307            use self::ParsePsbtError::*;
1308
1309            match self {
1310                PsbtEncoding(e) => Some(e),
1311                Base64Encoding(e) => Some(e),
1312            }
1313        }
1314    }
1315}
1316
1317/// Error combining two input maps.
1318#[derive(Debug, Clone, PartialEq, Eq)]
1319#[non_exhaustive]
1320pub enum CombineError {
1321    /// Error while combining the global maps.
1322    Global(global::CombineError),
1323    /// Error while combining the input maps.
1324    Input(input::CombineError),
1325    /// Error while combining the output maps.
1326    Output(output::CombineError),
1327}
1328
1329impl fmt::Display for CombineError {
1330    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1331        use CombineError::*;
1332
1333        match *self {
1334            Global(ref e) => write_err!(f, "error while combining the global maps"; e),
1335            Input(ref e) => write_err!(f, "error while combining the input maps"; e),
1336            Output(ref e) => write_err!(f, "error while combining the output maps"; e),
1337        }
1338    }
1339}
1340
1341#[cfg(feature = "std")]
1342impl std::error::Error for CombineError {
1343    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1344        use CombineError::*;
1345
1346        match *self {
1347            Global(ref e) => Some(e),
1348            Input(ref e) => Some(e),
1349            Output(ref e) => Some(e),
1350        }
1351    }
1352}
1353
1354impl From<global::CombineError> for CombineError {
1355    fn from(e: global::CombineError) -> Self { Self::Global(e) }
1356}
1357
1358impl From<input::CombineError> for CombineError {
1359    fn from(e: input::CombineError) -> Self { Self::Input(e) }
1360}
1361
1362impl From<output::CombineError> for CombineError {
1363    fn from(e: output::CombineError) -> Self { Self::Output(e) }
1364}