forked from rust-bitcoin/rust-bitcoin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.rs
1858 lines (1615 loc) · 98 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: CC0-1.0
//! Partially Signed Bitcoin Transactions.
//!
//! Implementation of BIP174 Partially Signed Bitcoin Transaction Format as
//! defined at <https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki>
//! except we define PSBTs containing non-standard sighash types as invalid.
//!
#[cfg(feature = "std")]
use std::collections::{HashMap, HashSet};
use core::{fmt, cmp};
use core::ops::Deref;
use secp256k1::{Message, Secp256k1, Signing};
use bitcoin_internals::write_err;
use crate::{prelude::*, Amount};
use crate::io;
use crate::blockdata::script::Script;
use crate::blockdata::transaction::{Transaction, TxOut};
use crate::consensus::{encode, Encodable, Decodable};
use crate::util::bip32::{self, ExtendedPrivKey, ExtendedPubKey, KeySource};
use crate::util::ecdsa::{EcdsaSig, EcdsaSigError};
use crate::util::key::{PublicKey, PrivateKey};
use crate::sighash::{self, EcdsaSighashType, SighashCache};
pub use crate::sighash::Prevouts;
#[macro_use]
mod macros;
pub mod raw;
pub mod serialize;
mod error;
pub use self::error::Error;
mod map;
pub use self::map::{Input, Output, TapTree, PsbtSighashType, IncompleteTapTree};
use self::map::Map;
/// Partially signed transaction, commonly referred to as a PSBT.
pub type Psbt = PartiallySignedTransaction;
/// A Partially Signed Transaction.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
pub struct PartiallySignedTransaction {
/// The unsigned transaction, scriptSigs and witnesses for each input must be empty.
pub unsigned_tx: Transaction,
/// The version number of this PSBT. If omitted, the version number is 0.
pub version: u32,
/// A global map from extended public keys to the used key fingerprint and
/// derivation path as defined by BIP 32.
pub xpub: BTreeMap<ExtendedPubKey, KeySource>,
/// Global proprietary key-value pairs.
#[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::btreemap_as_seq_byte_values"))]
pub proprietary: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
/// Unknown global key-value pairs.
#[cfg_attr(feature = "serde", serde(with = "crate::serde_utils::btreemap_as_seq_byte_values"))]
pub unknown: BTreeMap<raw::Key, Vec<u8>>,
/// The corresponding key-value map for each input in the unsigned transaction.
pub inputs: Vec<Input>,
/// The corresponding key-value map for each output in the unsigned transaction.
pub outputs: Vec<Output>,
}
impl PartiallySignedTransaction {
/// Returns an iterator for the funding UTXOs of the psbt
///
/// For each PSBT input that contains UTXO information `Ok` is returned containing that information.
/// The order of returned items is same as the order of inputs.
///
/// ## Errors
///
/// The function returns error when UTXO information is not present or is invalid.
///
/// ## Panics
///
/// The function panics if the length of transaction inputs is not equal to the length of PSBT inputs.
pub fn iter_funding_utxos(&self) -> impl Iterator<Item = Result<&TxOut, Error>> {
assert_eq!(self.inputs.len(), self.unsigned_tx.input.len());
self.unsigned_tx.input.iter().zip(&self.inputs).map(|(tx_input, psbt_input)| {
match (&psbt_input.witness_utxo, &psbt_input.non_witness_utxo) {
(Some(witness_utxo), _) => Ok(witness_utxo),
(None, Some(non_witness_utxo)) => {
let vout = tx_input.previous_output.vout as usize;
non_witness_utxo.output.get(vout).ok_or(Error::PsbtUtxoOutOfbounds)
},
(None, None) => Err(Error::MissingUtxo),
}
})
}
/// Checks that unsigned transaction does not have scriptSig's or witness data.
fn unsigned_tx_checks(&self) -> Result<(), Error> {
for txin in &self.unsigned_tx.input {
if !txin.script_sig.is_empty() {
return Err(Error::UnsignedTxHasScriptSigs);
}
if !txin.witness.is_empty() {
return Err(Error::UnsignedTxHasScriptWitnesses);
}
}
Ok(())
}
/// Creates a PSBT from an unsigned transaction.
///
/// # Errors
///
/// If transactions is not unsigned.
pub fn from_unsigned_tx(tx: Transaction) -> Result<Self, Error> {
let psbt = PartiallySignedTransaction {
inputs: vec![Default::default(); tx.input.len()],
outputs: vec![Default::default(); tx.output.len()],
unsigned_tx: tx,
xpub: Default::default(),
version: 0,
proprietary: Default::default(),
unknown: Default::default(),
};
psbt.unsigned_tx_checks()?;
Ok(psbt)
}
/// Extracts the `Transaction` from a PSBT by filling in the available signature information.
pub fn extract_tx(self) -> Transaction {
let mut tx: Transaction = self.unsigned_tx;
for (vin, psbtin) in tx.input.iter_mut().zip(self.inputs.into_iter()) {
vin.script_sig = psbtin.final_script_sig.unwrap_or_else(Script::new);
vin.witness = psbtin.final_script_witness.unwrap_or_default();
}
tx
}
/// Combines this [`PartiallySignedTransaction`] with `other` PSBT as described by BIP 174.
///
/// In accordance with BIP 174 this function is commutative i.e., `A.combine(B) == B.combine(A)`
pub fn combine(&mut self, other: Self) -> Result<(), Error> {
if self.unsigned_tx != other.unsigned_tx {
return Err(Error::UnexpectedUnsignedTx {
expected: Box::new(self.unsigned_tx.clone()),
actual: Box::new(other.unsigned_tx),
});
}
// BIP 174: The Combiner must remove any duplicate key-value pairs, in accordance with
// the specification. It can pick arbitrarily when conflicts occur.
// Keeping the highest version
self.version = cmp::max(self.version, other.version);
// Merging xpubs
for (xpub, (fingerprint1, derivation1)) in other.xpub {
match self.xpub.entry(xpub) {
btree_map::Entry::Vacant(entry) => {
entry.insert((fingerprint1, derivation1));
},
btree_map::Entry::Occupied(mut entry) => {
// Here in case of the conflict we select the version with algorithm:
// 1) if everything is equal we do nothing
// 2) report an error if
// - derivation paths are equal and fingerprints are not
// - derivation paths are of the same length, but not equal
// - derivation paths has different length, but the shorter one
// is not the strict suffix of the longer one
// 3) choose longest derivation otherwise
let (fingerprint2, derivation2) = entry.get().clone();
if (derivation1 == derivation2 && fingerprint1 == fingerprint2) ||
(derivation1.len() < derivation2.len() && derivation1[..] == derivation2[derivation2.len() - derivation1.len()..])
{
continue
}
else if derivation2[..] == derivation1[derivation1.len() - derivation2.len()..]
{
entry.insert((fingerprint1, derivation1));
continue
}
return Err(Error::CombineInconsistentKeySources(Box::new(xpub)));
}
}
}
self.proprietary.extend(other.proprietary);
self.unknown.extend(other.unknown);
for (self_input, other_input) in self.inputs.iter_mut().zip(other.inputs.into_iter()) {
self_input.combine(other_input);
}
for (self_output, other_output) in self.outputs.iter_mut().zip(other.outputs.into_iter()) {
self_output.combine(other_output);
}
Ok(())
}
/// Attempts to create _all_ the required signatures for this PSBT using `k`.
///
/// **NOTE**: Taproot inputs are, as yet, not supported by this function. We currently only
/// attempt to sign ECDSA inputs.
///
/// If you just want to sign an input with one specific key consider using `sighash_ecdsa`. This
/// function does not support scripts that contain `OP_CODESEPARATOR`.
///
/// # Returns
///
/// Either Ok(SigningKeys) or Err((SigningKeys, SigningErrors)), where
/// - SigningKeys: A map of input index -> pubkey associated with secret key used to sign.
/// - SigningKeys: A map of input index -> the error encountered while attempting to sign.
///
/// If an error is returned some signatures may already have been added to the PSBT. Since
/// `partial_sigs` is a [`BTreeMap`] it is safe to retry, previous sigs will be overwritten.
pub fn sign<C, K>(
&mut self,
k: &K,
secp: &Secp256k1<C>,
) -> Result<SigningKeys, (SigningKeys, SigningErrors)>
where
C: Signing,
K: GetKey,
{
let tx = self.unsigned_tx.clone(); // clone because we need to mutably borrow when signing.
let mut cache = SighashCache::new(&tx);
let mut used = BTreeMap::new();
let mut errors = BTreeMap::new();
for i in 0..self.inputs.len() {
if let Ok(SigningAlgorithm::Ecdsa) = self.signing_algorithm(i) {
match self.bip32_sign_ecdsa(k, i, &mut cache, secp) {
Ok(v) => { used.insert(i, v); },
Err(e) => { errors.insert(i, e); },
}
};
}
if errors.is_empty() {
Ok(used)
} else {
Err((used, errors))
}
}
/// Attempts to create all signatures required by this PSBT's `bip32_derivation` field, adding
/// them to `partial_sigs`.
///
/// # Returns
///
/// - Ok: A list of the public keys used in signing.
/// - Err: Error encountered trying to calculate the sighash AND we had the signing key.
fn bip32_sign_ecdsa<C, K, T>(
&mut self,
k: &K,
input_index: usize,
cache: &mut SighashCache<T>,
secp: &Secp256k1<C>,
) -> Result<Vec<PublicKey>, SignError>
where
C: Signing,
T: Deref<Target=Transaction>,
K: GetKey,
{
let msg_sighash_ty_res = self.sighash_ecdsa(input_index, cache);
let input = &mut self.inputs[input_index]; // Index checked in call to `sighash_ecdsa`.
let mut used = vec![]; // List of pubkeys used to sign the input.
for (pk, key_source) in input.bip32_derivation.iter() {
let sk = if let Ok(Some(sk)) = k.get_key(KeyRequest::Bip32(key_source.clone()), secp) {
sk
} else if let Ok(Some(sk)) = k.get_key(KeyRequest::Pubkey(PublicKey::new(*pk)), secp) {
sk
} else {
continue;
};
// Only return the error if we have a secret key to sign this input.
let (msg, sighash_ty) = match msg_sighash_ty_res {
Err(e) => return Err(e),
Ok((msg, sighash_ty)) => (msg, sighash_ty),
};
let sig = EcdsaSig {
sig: secp.sign_ecdsa(&msg, &sk.inner),
hash_ty: sighash_ty,
};
let pk = sk.public_key(secp);
input.partial_sigs.insert(pk, sig);
used.push(pk);
}
Ok(used)
}
/// Returns the sighash message to sign an ECDSA input along with the sighash type.
///
/// Uses the [`EcdsaSighashType`] from this input if one is specified. If no sighash type is
/// specified uses [`EcdsaSighashType::All`]. This function does not support scripts that
/// contain `OP_CODESEPARATOR`.
pub fn sighash_ecdsa<T: Deref<Target=Transaction>>(
&self,
input_index: usize,
cache: &mut SighashCache<T>,
) -> Result<(Message, EcdsaSighashType), SignError> {
use OutputType::*;
if self.signing_algorithm(input_index)? != SigningAlgorithm::Ecdsa {
return Err(SignError::WrongSigningAlgorithm);
}
let input = self.checked_input(input_index)?;
let utxo = self.spend_utxo(input_index)?;
let spk = &utxo.script_pubkey; // scriptPubkey for input spend utxo.
let hash_ty = input.ecdsa_hash_ty()
.map_err(|_| SignError::InvalidSighashType)?; // Only support standard sighash types.
let sighash = match self.output_type(input_index)? {
Bare => {
cache.legacy_signature_hash(input_index, spk, hash_ty.to_u32())?
},
Sh => {
let script_code = input.redeem_script.as_ref().ok_or(SignError::MissingRedeemScript)?;
cache.legacy_signature_hash(input_index, script_code, hash_ty.to_u32())?
},
Wpkh => {
let script_code = Script::p2wpkh_script_code(spk).ok_or(SignError::NotWpkh)?;
cache.segwit_signature_hash(input_index, &script_code, utxo.value, hash_ty)?
}
ShWpkh => {
let script_code = Script::p2wpkh_script_code(input.redeem_script.as_ref().expect("checked above"))
.ok_or(SignError::NotWpkh)?;
cache.segwit_signature_hash(input_index, &script_code, utxo.value, hash_ty)?
},
Wsh | ShWsh => {
let script_code = input.witness_script.as_ref().ok_or(SignError::MissingWitnessScript)?;
cache.segwit_signature_hash(input_index, script_code, utxo.value, hash_ty)?
},
Tr => {
// This PSBT signing API is WIP, taproot to come shortly.
return Err(SignError::Unsupported);
}
};
Ok((Message::from_slice(&sighash).expect("sighashes are 32 bytes"), hash_ty))
}
/// Returns the spending utxo for this PSBT's input at `input_index`.
pub fn spend_utxo(&self, input_index: usize) -> Result<&TxOut, SignError> {
let input = self.checked_input(input_index)?;
let utxo = if let Some(witness_utxo) = &input.witness_utxo {
witness_utxo
} else if let Some(non_witness_utxo) = &input.non_witness_utxo {
let vout = self.unsigned_tx.input[input_index].previous_output.vout;
&non_witness_utxo.output[vout as usize]
} else {
return Err(SignError::MissingSpendUtxo);
};
Ok(utxo)
}
/// Gets the input at `input_index` after checking that it is a valid index.
fn checked_input(&self, input_index: usize) -> Result<&Input, SignError> {
self.check_index_is_within_bounds(input_index)?;
Ok(&self.inputs[input_index])
}
/// Checks `input_index` is within bounds for the PSBT `inputs` array and
/// for the PSBT `unsigned_tx` `input` array.
fn check_index_is_within_bounds(&self, input_index: usize) -> Result<(), SignError> {
if input_index >= self.inputs.len() {
return Err(SignError::IndexOutOfBounds(input_index, self.inputs.len()));
}
if input_index >= self.unsigned_tx.input.len() {
return Err(SignError::IndexOutOfBounds(input_index, self.unsigned_tx.input.len()));
}
Ok(())
}
/// Returns the algorithm used to sign this PSBT's input at `input_index`.
fn signing_algorithm(&self, input_index: usize) -> Result<SigningAlgorithm, SignError> {
let output_type = self.output_type(input_index)?;
Ok(output_type.signing_algorithm())
}
/// Returns the [`OutputType`] of the spend utxo for this PBST's input at `input_index`.
fn output_type(&self, input_index: usize) -> Result<OutputType, SignError> {
let input = self.checked_input(input_index)?;
let utxo = self.spend_utxo(input_index)?;
let spk = utxo.script_pubkey.clone();
// Anything that is not segwit and is not p2sh is `Bare`.
if !(spk.is_witness_program() || spk.is_p2sh()) {
return Ok(OutputType::Bare);
}
if spk.is_v0_p2wpkh() {
return Ok(OutputType::Wpkh);
}
if spk.is_v0_p2wsh() {
return Ok(OutputType::Wsh);
}
if spk.is_p2sh() {
if input.redeem_script.as_ref().map(|s| s.is_v0_p2wpkh()).unwrap_or(false) {
return Ok(OutputType::ShWpkh);
}
if input.redeem_script.as_ref().map(|x| x.is_v0_p2wsh()).unwrap_or(false) {
return Ok(OutputType::ShWsh);
}
return Ok(OutputType::Sh);
}
if spk.is_v1_p2tr() {
return Ok(OutputType::Tr);
}
// Something is wrong with the input scriptPubkey or we do not know how to sign
// because there has been a new softfork that we do not yet support.
Err(SignError::UnknownOutputType)
}
/// Calculates transaction fee.
///
/// 'Fee' being the amount that will be paid for mining a transaction with the current inputs
/// and outputs i.e., the difference in value of the total inputs and the total outputs.
///
/// ## Errors
///
/// - [`Error::MissingUtxo`] when UTXO information for any input is not present or is invalid.
/// - [`Error::NegativeFee`] if calculated value is negative.
/// - [`Error::FeeOverflow`] if an integer overflow occurs.
pub fn fee(&self) -> Result<Amount, Error> {
let mut inputs: u64 = 0;
for utxo in self.iter_funding_utxos() {
inputs = inputs.checked_add(utxo?.value).ok_or(Error::FeeOverflow)?;
}
let mut outputs: u64 = 0;
for out in &self.unsigned_tx.output {
outputs = outputs.checked_add(out.value).ok_or(Error::FeeOverflow)?;
}
inputs.checked_sub(outputs).map(Amount::from_sat).ok_or(Error::NegativeFee)
}
}
/// Data required to call [`GetKey`] to get the private key to sign an input.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum KeyRequest {
/// Request a private key using the associated public key.
Pubkey(PublicKey),
/// Request a private key using BIP-32 fingerprint and derivation path.
Bip32(KeySource),
}
/// Trait to get a private key from a key request, key is then used to sign an input.
pub trait GetKey {
/// An error occurred while getting the key.
type Error: core::fmt::Debug;
/// Attempts to get the private key for `key_request`.
///
/// # Returns
/// - `Some(key)` if the key is found.
/// - `None` if the key was not found but no error was encountered.
/// - `Err` if an error was encountered while looking for the key.
fn get_key<C: Signing>(&self, key_request: KeyRequest, secp: &Secp256k1<C>) -> Result<Option<PrivateKey>, Self::Error>;
}
impl GetKey for ExtendedPrivKey {
type Error = GetKeyError;
fn get_key<C: Signing>(&self, key_request: KeyRequest, secp: &Secp256k1<C>) -> Result<Option<PrivateKey>, Self::Error> {
match key_request {
KeyRequest::Pubkey(_) => Err(GetKeyError::NotSupported),
KeyRequest::Bip32((fingerprint, path)) => {
let key = if self.fingerprint(secp) == fingerprint {
let k = self.derive_priv(secp, &path)?;
Some(k.to_priv())
} else {
None
};
Ok(key)
}
}
}
}
/// Map of input index -> pubkey associated with secret key used to create signature for that input.
pub type SigningKeys = BTreeMap<usize, Vec<PublicKey>>;
/// Map of input index -> the error encountered while attempting to sign that input.
pub type SigningErrors = BTreeMap<usize, SignError>;
#[rustfmt::skip]
macro_rules! impl_get_key_for_set {
($set:ident) => {
impl GetKey for $set<ExtendedPrivKey> {
type Error = GetKeyError;
fn get_key<C: Signing>(
&self,
key_request: KeyRequest,
secp: &Secp256k1<C>
) -> Result<Option<PrivateKey>, Self::Error> {
match key_request {
KeyRequest::Pubkey(_) => Err(GetKeyError::NotSupported),
KeyRequest::Bip32((fingerprint, path)) => {
for xpriv in self.iter() {
if xpriv.parent_fingerprint == fingerprint {
let k = xpriv.derive_priv(secp, &path)?;
return Ok(Some(k.to_priv()));
}
}
Ok(None)
}
}
}
}}}
impl_get_key_for_set!(BTreeSet);
#[cfg(feature = "std")]
impl_get_key_for_set!(HashSet);
#[rustfmt::skip]
macro_rules! impl_get_key_for_map {
($map:ident) => {
impl GetKey for $map<PublicKey, PrivateKey> {
type Error = GetKeyError;
fn get_key<C: Signing>(
&self,
key_request: KeyRequest,
_: &Secp256k1<C>,
) -> Result<Option<PrivateKey>, Self::Error> {
match key_request {
KeyRequest::Pubkey(pk) => Ok(self.get(&pk).cloned()),
KeyRequest::Bip32(_) => Err(GetKeyError::NotSupported),
}
}
}}}
impl_get_key_for_map!(BTreeMap);
#[cfg(feature = "std")]
impl_get_key_for_map!(HashMap);
/// Errors when getting a key.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[non_exhaustive]
pub enum GetKeyError {
/// A bip32 error.
Bip32(bip32::Error),
/// The GetKey operation is not supported for this key request.
NotSupported,
}
impl fmt::Display for GetKeyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use GetKeyError::*;
match *self {
Bip32(ref e) => write_err!(f, "a bip23 error"; e),
NotSupported => f.write_str("the GetKey operation is not supported for this key request"),
}
}
}
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl std::error::Error for GetKeyError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use GetKeyError::*;
match *self {
NotSupported => None,
Bip32(ref e) => Some(e),
}
}
}
impl From<bip32::Error> for GetKeyError {
fn from(e: bip32::Error) -> Self {
GetKeyError::Bip32(e)
}
}
/// The various output types supported by the Bitcoin network.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum OutputType {
/// An output of type: pay-to-pubkey or pay-to-pubkey-hash.
Bare,
/// A pay-to-witness-pubkey-hash output (P2WPKH).
Wpkh,
/// A pay-to-witness-script-hash output (P2WSH).
Wsh,
/// A nested segwit output, pay-to-witness-pubkey-hash nested in a pay-to-script-hash.
ShWpkh,
/// A nested segwit output, pay-to-witness-script-hash nested in a pay-to-script-hash.
ShWsh,
/// A pay-to-script-hash output excluding wrapped segwit (P2SH).
Sh,
/// A taproot output (P2TR).
Tr,
}
impl OutputType {
/// The signing algorithm used to sign this output type.
pub fn signing_algorithm(&self) -> SigningAlgorithm {
use OutputType::*;
match self {
Bare | Wpkh | Wsh | ShWpkh | ShWsh | Sh => SigningAlgorithm::Ecdsa,
Tr => SigningAlgorithm::Schnorr,
}
}
}
/// Signing algorithms supported by the Bitcoin network.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SigningAlgorithm {
/// The Elliptic Curve Digital Signature Algorithm (see [wikipedia]).
///
/// [wikipedia]: https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm
Ecdsa,
/// The Schnorr signature algorithm (see [wikipedia]).
///
/// [wikipedia]: https://en.wikipedia.org/wiki/Schnorr_signature
Schnorr,
}
/// Errors encountered while calculating the sighash message.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub enum SignError {
/// An ECDSA key-related error occurred.
EcdsaSig(EcdsaSigError),
/// Input index out of bounds (actual index, maximum index allowed).
IndexOutOfBounds(usize, usize),
/// Invalid Sighash type.
InvalidSighashType,
/// Missing input utxo.
MissingInputUtxo,
/// Missing Redeem script.
MissingRedeemScript,
/// Missing spending utxo.
MissingSpendUtxo,
/// Missing witness script.
MissingWitnessScript,
/// Signing algorithm and key type does not match.
MismatchedAlgoKey,
/// Attempted to ECDSA sign an non-ECDSA input.
NotEcdsa,
/// The `scriptPubkey` is not a P2WPKH script.
NotWpkh,
/// Sighash computation error.
SighashComputation(sighash::Error),
/// Unable to determine the output type.
UnknownOutputType,
/// Unable to find key.
KeyNotFound,
/// Attempt to sign an input with the wrong signing algorithm.
WrongSigningAlgorithm,
/// Signing request currently unsupported.
Unsupported
}
impl fmt::Display for SignError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use self::SignError::*;
match *self {
IndexOutOfBounds(ind, len) => {
write!(f, "index {}, psbt input len: {}", ind, len)
}
InvalidSighashType => write!(f, "invalid sighash type"),
MissingInputUtxo => write!(f, "missing input utxo in PBST"),
MissingRedeemScript => write!(f, "missing redeem script"),
MissingSpendUtxo => write!(f, "missing spend utxo in PSBT"),
MissingWitnessScript => write!(f, "missing witness script"),
MismatchedAlgoKey => write!(f, "signing algorithm and key type does not match"),
NotEcdsa => write!(f, "attempted to ECDSA sign an non-ECDSA input"),
NotWpkh => write!(f, "the scriptPubkey is not a P2WPKH script"),
SighashComputation(e) => write!(f, "sighash: {}", e),
EcdsaSig(ref e) => write_err!(f, "ecdsa signature"; e),
UnknownOutputType => write!(f, "unable to determine the output type"),
KeyNotFound => write!(f, "unable to find key"),
WrongSigningAlgorithm => write!(f, "attempt to sign an input with the wrong signing algorithm"),
Unsupported => write!(f, "signing request currently unsupported"),
}
}
}
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl std::error::Error for SignError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use self::SignError::*;
match *self {
IndexOutOfBounds(_, _)
| InvalidSighashType
| MissingInputUtxo
| MissingRedeemScript
| MissingSpendUtxo
| MissingWitnessScript
| MismatchedAlgoKey
| NotEcdsa
| NotWpkh
| UnknownOutputType
| KeyNotFound
| WrongSigningAlgorithm
| Unsupported => None,
EcdsaSig(ref e) => Some(e),
SighashComputation(ref e) => Some(e),
}
}
}
impl From<sighash::Error> for SignError {
fn from(e: sighash::Error) -> Self {
SignError::SighashComputation(e)
}
}
impl From<EcdsaSigError> for SignError {
fn from(e: EcdsaSigError) -> Self {
SignError::EcdsaSig(e)
}
}
#[cfg(feature = "base64")]
mod display_from_str {
use super::PartiallySignedTransaction;
use core::fmt::{Display, Formatter, self};
use core::str::FromStr;
use crate::consensus::encode::{Error, self};
use base64::display::Base64Display;
use bitcoin_internals::write_err;
/// Error encountered during PSBT decoding from Base64 string.
#[derive(Debug)]
#[cfg_attr(docsrs, doc(cfg(feature = "base64")))]
#[non_exhaustive]
pub enum PsbtParseError {
/// Error in internal PSBT data structure.
PsbtEncoding(Error),
/// Error in PSBT Base64 encoding.
Base64Encoding(::base64::DecodeError)
}
impl Display for PsbtParseError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
use self::PsbtParseError::*;
match *self {
PsbtEncoding(ref e) => write_err!(f, "error in internal PSBT data structure"; e),
Base64Encoding(ref e) => write_err!(f, "error in PSBT base64 encoding"; e),
}
}
}
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl std::error::Error for PsbtParseError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use self::PsbtParseError::*;
match self {
PsbtEncoding(e) => Some(e),
Base64Encoding(e) => Some(e),
}
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "base64")))]
impl Display for PartiallySignedTransaction {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}", Base64Display::with_config(&encode::serialize(self), base64::STANDARD))
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "base64")))]
impl FromStr for PartiallySignedTransaction {
type Err = PsbtParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let data = base64::decode(s).map_err(PsbtParseError::Base64Encoding)?;
encode::deserialize(&data).map_err(PsbtParseError::PsbtEncoding)
}
}
}
#[cfg(feature = "base64")]
#[cfg_attr(docsrs, doc(cfg(feature = "base64")))]
pub use self::display_from_str::PsbtParseError;
impl Encodable for PartiallySignedTransaction {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let mut len = 0;
len += b"psbt".consensus_encode(w)?;
len += 0xff_u8.consensus_encode(w)?;
len += self.consensus_encode_map(w)?;
for i in &self.inputs {
len += i.consensus_encode(w)?;
}
for i in &self.outputs {
len += i.consensus_encode(w)?;
}
Ok(len)
}
}
impl Decodable for PartiallySignedTransaction {
fn consensus_decode_from_finite_reader<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
let magic: [u8; 4] = Decodable::consensus_decode(r)?;
if *b"psbt" != magic {
return Err(Error::InvalidMagic.into());
}
if 0xff_u8 != u8::consensus_decode(r)? {
return Err(Error::InvalidSeparator.into());
}
let mut global = PartiallySignedTransaction::consensus_decode_global(r)?;
global.unsigned_tx_checks()?;
let inputs: Vec<Input> = {
let inputs_len: usize = global.unsigned_tx.input.len();
let mut inputs: Vec<Input> = Vec::with_capacity(inputs_len);
for _ in 0..inputs_len {
inputs.push(Decodable::consensus_decode(r)?);
}
inputs
};
let outputs: Vec<Output> = {
let outputs_len: usize = global.unsigned_tx.output.len();
let mut outputs: Vec<Output> = Vec::with_capacity(outputs_len);
for _ in 0..outputs_len {
outputs.push(Decodable::consensus_decode(r)?);
}
outputs
};
global.inputs = inputs;
global.outputs = outputs;
Ok(global)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::blockdata::locktime::absolute;
use crate::hashes::hex::FromHex;
use crate::hashes::{sha256, hash160, Hash, ripemd160};
use crate::hash_types::Txid;
use secp256k1::{Secp256k1, self};
#[cfg(feature = "rand")]
use secp256k1::{All, SecretKey};
use crate::blockdata::script::Script;
use crate::blockdata::transaction::{Transaction, TxIn, TxOut, OutPoint, Sequence};
use crate::network::constants::Network::Bitcoin;
use crate::consensus::encode::{deserialize, serialize, serialize_hex};
use crate::util::bip32::{ChildNumber, ExtendedPrivKey, ExtendedPubKey, KeySource};
use crate::util::psbt::map::{Output, Input};
use crate::util::psbt::raw;
use crate::internal_macros::hex_script;
use std::collections::BTreeMap;
use crate::blockdata::witness::Witness;
#[test]
fn trivial_psbt() {
let psbt = PartiallySignedTransaction {
unsigned_tx: Transaction {
version: 2,
lock_time: absolute::PackedLockTime::ZERO,
input: vec![],
output: vec![],
},
xpub: Default::default(),
version: 0,
proprietary: BTreeMap::new(),
unknown: BTreeMap::new(),
inputs: vec![],
outputs: vec![],
};
assert_eq!(serialize_hex(&psbt), "70736274ff01000a0200000000000000000000");
}
#[test]
fn psbt_uncompressed_key() {
let psbt: PartiallySignedTransaction = hex_psbt!("70736274ff01003302000000010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff000000000000420204bb0d5d0cca36e7b9c80f63bc04c1240babb83bcd2803ef7ac8b6e2af594291daec281e856c98d210c5ab14dfd5828761f8ee7d5f45ca21ad3e4c4b41b747a3a047304402204f67e2afb76142d44fae58a2495d33a3419daa26cd0db8d04f3452b63289ac0f022010762a9fb67e94cc5cad9026f6dc99ff7f070f4278d30fbc7d0c869dd38c7fe70100").unwrap();
assert!(psbt.inputs[0].partial_sigs.len() == 1);
let pk = psbt.inputs[0].partial_sigs.iter().next().unwrap().0;
assert!(!pk.compressed);
}
#[test]
fn serialize_then_deserialize_output() {
let secp = &Secp256k1::new();
let seed = Vec::from_hex("000102030405060708090a0b0c0d0e0f").unwrap();
let mut hd_keypaths: BTreeMap<secp256k1::PublicKey, KeySource> = Default::default();
let mut sk: ExtendedPrivKey = ExtendedPrivKey::new_master(Bitcoin, &seed).unwrap();
let fprint = sk.fingerprint(secp);
let dpath: Vec<ChildNumber> = vec![
ChildNumber::from_normal_idx(0).unwrap(),
ChildNumber::from_normal_idx(1).unwrap(),
ChildNumber::from_normal_idx(2).unwrap(),
ChildNumber::from_normal_idx(4).unwrap(),
ChildNumber::from_normal_idx(42).unwrap(),
ChildNumber::from_hardened_idx(69).unwrap(),
ChildNumber::from_normal_idx(420).unwrap(),
ChildNumber::from_normal_idx(31337).unwrap(),
];
sk = sk.derive_priv(secp, &dpath).unwrap();
let pk = ExtendedPubKey::from_priv(secp, &sk);
hd_keypaths.insert(pk.public_key, (fprint, dpath.into()));
let expected: Output = Output {
redeem_script: Some(hex_script!("76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac")),
witness_script: Some(hex_script!("a9143545e6e33b832c47050f24d3eeb93c9c03948bc787")),
bip32_derivation: hd_keypaths,
..Default::default()
};
let actual: Output = deserialize(&serialize(&expected)).unwrap();
assert_eq!(expected, actual);
}
#[test]
fn serialize_then_deserialize_global() {
let expected = PartiallySignedTransaction {
unsigned_tx: Transaction {
version: 2,
lock_time: absolute::PackedLockTime(1257139),
input: vec![TxIn {
previous_output: OutPoint {
txid: Txid::from_hex(
"f61b1742ca13176464adb3cb66050c00787bb3a4eead37e985f2df1e37718126",
).unwrap(),
vout: 0,
},
script_sig: Script::new(),
sequence: Sequence::ENABLE_LOCKTIME_NO_RBF,
witness: Witness::default(),
}],
output: vec![
TxOut {
value: 99999699,
script_pubkey: hex_script!(
"76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac"
),
},
TxOut {
value: 100000000,