1mod 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] #[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 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
72pub fn combine(this: Psbt, that: Psbt) -> Result<Psbt, CombineError> { this.combine_with(that) }
76#[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 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 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 pub fn sighash_single(mut self) -> Self {
113 self.0.global.set_sighash_single_flag();
114 self
115 }
116
117 pub fn inputs_modifiable(mut self) -> Self {
119 self.0.global.set_inputs_modifiable_flag();
120 self
121 }
122
123 pub fn outputs_modifiable(mut self) -> Self {
125 self.0.global.set_outputs_modifiable_flag();
126 self
127 }
128
129 pub fn transaction_version(mut self, version: transaction::Version) -> Self {
135 self.0.global.tx_version = version;
136 self
137 }
138
139 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 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 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 pub fn psbt(self) -> Psbt { self.0 }
223}
224
225impl Default for Creator {
226 fn default() -> Self { Self::new() }
227}
228
229pub enum Modifiable {}
231pub enum InputsOnlyModifiable {}
233pub 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
243pub trait Mod: sealed::Mod + Sync + Send + Sized + Unpin {}
245
246impl Mod for Modifiable {}
247impl Mod for InputsOnlyModifiable {}
248impl Mod for OutputsOnlyModifiable {}
249
250#[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 pub fn no_more_inputs(mut self) -> Self {
261 self.0.global.clear_inputs_modifiable_flag();
262 self
263 }
264
265 pub fn no_more_outputs(mut self) -> Self {
267 self.0.global.clear_outputs_modifiable_flag();
268 self
269 }
270
271 pub fn updater(self) -> Result<Updater, DetermineLockTimeError> {
273 self.no_more_inputs().no_more_outputs().psbt().map(Updater)
274 }
275
276 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 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 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 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}
317impl Default for Constructor<Modifiable> {
319 fn default() -> Self { Creator::new().constructor_modifiable() }
320}
321
322impl Constructor<InputsOnlyModifiable> {
323 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 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
344impl Default for Constructor<InputsOnlyModifiable> {
346 fn default() -> Self { Creator::new().constructor_inputs_only_modifiable() }
347}
348
349impl Constructor<OutputsOnlyModifiable> {
350 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 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
371impl Default for Constructor<OutputsOnlyModifiable> {
373 fn default() -> Self { Creator::new().constructor_outputs_only_modifiable() }
374}
375
376#[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 pub fn new(psbt: Psbt) -> Result<Self, DetermineLockTimeError> {
387 let _ = psbt.determine_lock_time()?;
388 Ok(Self(psbt))
389 }
390
391 pub fn id(&self) -> Txid {
393 self.0.id().expect("Updater guarantees lock time can be determined")
394 }
395
396 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 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#[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 pub fn new(psbt: Psbt) -> Result<Self, DetermineLockTimeError> {
441 let _ = psbt.determine_lock_time()?;
442 Ok(Self(psbt))
443 }
444
445 pub fn id(&self) -> Result<Txid, DetermineLockTimeError> { self.0.id() }
447
448 pub fn unsigned_tx(&self) -> Transaction {
450 self.0.unsigned_tx().expect("Signer guarantees lock time can be determined")
451 }
452
453 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 pub fn ecdsa_clear_tx_modifiable(&mut self, ty: EcdsaSighashType) {
489 self.0.clear_tx_modifiable(ty as u8)
490 }
491
492 pub fn psbt(self) -> Psbt { self.0 }
494}
495
496#[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 pub global: Global,
503 pub inputs: Vec<Input>,
505 pub outputs: Vec<Output>,
507}
508
509impl Psbt {
510 fn id(&self) -> Result<Txid, DetermineLockTimeError> {
514 let mut tx = self.unsigned_tx()?;
515 tx.input.iter_mut().for_each(|input| input.sequence = Sequence::ZERO);
517
518 Ok(tx.compute_txid())
519 }
520
521 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 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 if all_inputs_satisfied_with_height_based_lock_time {
557 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 self.global.fallback_lock_time.unwrap_or(absolute::LockTime::ZERO)
581 };
582
583 Ok(lock)
584 }
585
586 pub fn is_finalized(&self) -> bool { self.inputs.iter().all(|input| input.is_finalized()) }
588
589 pub fn serialize_hex(&self) -> String { self.serialize().to_lower_hex_string() }
591
592 pub fn serialize(&self) -> Vec<u8> {
594 let mut buf: Vec<u8> = Vec::new();
595
596 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 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 pub fn iter_funding_utxos(&self) -> impl Iterator<Item = Result<&TxOut, FundingUtxoError>> {
666 self.inputs.iter().map(|input| input.funding_utxo())
667 }
668
669 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 fn clear_tx_modifiable(&mut self, sighash_type: u8) {
693 let ty = sighash_type;
694 if !(ty == 0x81 || ty == 0x82 || ty == 0x83) {
697 self.global.clear_inputs_modifiable_flag();
698 }
699
700 if !(ty == 0x02 || ty == 0x82) {
703 self.global.clear_outputs_modifiable_flag();
704 }
705
706 if ty == 0x03 || ty == 0x83 {
709 self.global.set_sighash_single_flag();
710 }
711 }
712
713 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 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]; let mut used = vec![]; 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 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 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; let hash_ty = input.ecdsa_hash_ty().map_err(|_| SignError::InvalidSighashType)?; 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 Err(SignError::Unsupported)
878 }
879 }
880 }
881
882 fn checked_input(&self, index: usize) -> Result<&Input, IndexOutOfBoundsError> {
884 self.check_input_index(index)?;
885 Ok(&self.inputs[index])
886 }
887
888 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 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 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 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 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 Err(SignError::UnknownOutputType)
946 }
947
948 pub fn fee(&self) -> Result<Amount, FeeError> {
953 use FeeError::*;
954
955 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 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 #[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#[derive(Debug, Clone, PartialEq, Eq)]
1006#[non_exhaustive]
1007pub enum KeyRequest {
1008 Pubkey(PublicKey),
1010 Bip32(KeySource),
1012}
1013
1014pub trait GetKey {
1016 type Error: core::fmt::Debug;
1018
1019 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
1055pub type SigningKeys = BTreeMap<usize, Vec<PublicKey>>;
1057
1058pub 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#[derive(Debug, Clone, PartialEq, Eq)]
1116#[non_exhaustive]
1117pub enum GetKeyError {
1118 Bip32(bip32::Error),
1120 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#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1154#[non_exhaustive]
1155pub enum OutputType {
1156 Bare,
1158 Wpkh,
1160 Wsh,
1162 ShWpkh,
1164 ShWsh,
1166 Sh,
1168 Tr,
1170}
1171
1172impl OutputType {
1173 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#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1186pub enum SigningAlgorithm {
1187 Ecdsa,
1191 Schnorr,
1195}
1196
1197#[derive(Debug)]
1199#[non_exhaustive]
1200pub enum DecodeError {
1201 InvalidMagic,
1204 InvalidSeparator,
1206 NoMorePairs,
1208 Global(global::DecodeError),
1210 Input(input::DecodeError),
1212 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#[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 #[derive(Debug)]
1285 #[non_exhaustive]
1286 pub enum ParsePsbtError {
1287 PsbtEncoding(DeserializeError),
1289 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#[derive(Debug, Clone, PartialEq, Eq)]
1319#[non_exhaustive]
1320pub enum CombineError {
1321 Global(global::CombineError),
1323 Input(input::CombineError),
1325 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}