/
transaction.rs
2027 lines (1868 loc) · 204 KB
/
transaction.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
// Rust Bitcoin Library
// Written in 2014 by
// Andrew Poelstra <apoelstra@wpsoftware.net>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//
//! Bitcoin transactions.
//!
//! A transaction describes a transfer of money. It consumes previously-unspent
//! transaction outputs and produces new ones, satisfying the condition to spend
//! the old outputs (typically a digital signature with a specific key must be
//! provided) and defining the condition to spend the new ones. The use of digital
//! signatures ensures that coins cannot be spent by unauthorized parties.
//!
//! This module provides the structures and functions needed to support transactions.
//!
use crate::prelude::*;
use crate::io;
use core::{fmt, str, default::Default};
use core::convert::TryFrom;
use crate::hashes::{self, Hash, sha256d};
use crate::hashes::hex::FromHex;
use crate::util::endian;
use crate::blockdata::constants::{WITNESS_SCALE_FACTOR, MAX_SEQUENCE};
#[cfg(feature="bitcoinconsensus")] use crate::blockdata::script;
use crate::blockdata::script::Script;
use crate::blockdata::witness::Witness;
use crate::consensus::{encode, Decodable, Encodable};
use crate::hash_types::{Sighash, Txid, Wtxid};
use crate::VarInt;
use crate::util::sighash::UINT256_ONE;
#[cfg(doc)]
use crate::util::sighash::SchnorrSighashType;
/// A reference to a transaction output.
///
/// ### Bitcoin Core References
///
/// * [COutPoint definition](https://github.com/bitcoin/bitcoin/blob/345457b542b6a980ccfbc868af0970a6f91d1b82/src/primitives/transaction.h#L26)
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct OutPoint {
/// The referenced transaction's txid.
pub txid: Txid,
/// The index of the referenced output in its transaction's vout.
pub vout: u32,
}
serde_struct_human_string_impl!(OutPoint, "an OutPoint", txid, vout);
impl OutPoint {
/// Creates a new [`OutPoint`].
#[inline]
pub fn new(txid: Txid, vout: u32) -> OutPoint {
OutPoint { txid, vout }
}
/// Creates a "null" `OutPoint`.
///
/// This value is used for coinbase transactions because they don't have any previous outputs.
#[inline]
pub fn null() -> OutPoint {
OutPoint {
txid: Default::default(),
vout: u32::max_value(),
}
}
/// Checks if an `OutPoint` is "null".
///
/// # Examples
///
/// ```rust
/// use bitcoin::blockdata::constants::genesis_block;
/// use bitcoin::network::constants::Network;
///
/// let block = genesis_block(Network::Bitcoin);
/// let tx = &block.txdata[0];
///
/// // Coinbase transactions don't have any previous output.
/// assert!(tx.input[0].previous_output.is_null());
/// ```
#[inline]
pub fn is_null(&self) -> bool {
*self == OutPoint::null()
}
}
impl Default for OutPoint {
fn default() -> Self {
OutPoint::null()
}
}
impl fmt::Display for OutPoint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}:{}", self.txid, self.vout)
}
}
/// An error in parsing an OutPoint.
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub enum ParseOutPointError {
/// Error in TXID part.
Txid(hashes::hex::Error),
/// Error in vout part.
Vout(::core::num::ParseIntError),
/// Error in general format.
Format,
/// Size exceeds max.
TooLong,
/// Vout part is not strictly numeric without leading zeroes.
VoutNotCanonical,
}
impl fmt::Display for ParseOutPointError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ParseOutPointError::Txid(ref e) => write_err!(f, "error parsing TXID"; e),
ParseOutPointError::Vout(ref e) => write_err!(f, "error parsing vout"; e),
ParseOutPointError::Format => write!(f, "OutPoint not in <txid>:<vout> format"),
ParseOutPointError::TooLong => write!(f, "vout should be at most 10 digits"),
ParseOutPointError::VoutNotCanonical => write!(f, "no leading zeroes or + allowed in vout part"),
}
}
}
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl std::error::Error for ParseOutPointError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use self::ParseOutPointError::*;
match self {
Txid(e) => Some(e),
Vout(e) => Some(e),
Format | TooLong | VoutNotCanonical => None,
}
}
}
/// Parses a string-encoded transaction index (vout).
/// Does not permit leading zeroes or non-digit characters.
fn parse_vout(s: &str) -> Result<u32, ParseOutPointError> {
if s.len() > 1 {
let first = s.chars().next().unwrap();
if first == '0' || first == '+' {
return Err(ParseOutPointError::VoutNotCanonical);
}
}
s.parse().map_err(ParseOutPointError::Vout)
}
impl ::core::str::FromStr for OutPoint {
type Err = ParseOutPointError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.len() > 75 { // 64 + 1 + 10
return Err(ParseOutPointError::TooLong);
}
let find = s.find(':');
if find == None || find != s.rfind(':') {
return Err(ParseOutPointError::Format);
}
let colon = find.unwrap();
if colon == 0 || colon == s.len() - 1 {
return Err(ParseOutPointError::Format);
}
Ok(OutPoint {
txid: Txid::from_hex(&s[..colon]).map_err(ParseOutPointError::Txid)?,
vout: parse_vout(&s[colon+1..])?,
})
}
}
/// Bitcoin transaction input.
///
/// It contains the location of the previous transaction's output,
/// that it spends and set of scripts that satisfy its spending
/// conditions.
///
/// ### Bitcoin Core References
///
/// * [CTxIn definition](https://github.com/bitcoin/bitcoin/blob/345457b542b6a980ccfbc868af0970a6f91d1b82/src/primitives/transaction.h#L65)
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
pub struct TxIn {
/// The reference to the previous output that is being used an an input.
pub previous_output: OutPoint,
/// The script which pushes values on the stack which will cause
/// the referenced output's script to be accepted.
pub script_sig: Script,
/// The sequence number, which suggests to miners which of two
/// conflicting transactions should be preferred, or 0xFFFFFFFF
/// to ignore this feature. This is generally never used since
/// the miner behaviour cannot be enforced.
pub sequence: Sequence,
/// Witness data: an array of byte-arrays.
/// Note that this field is *not* (de)serialized with the rest of the TxIn in
/// Encodable/Decodable, as it is (de)serialized at the end of the full
/// Transaction. It *is* (de)serialized with the rest of the TxIn in other
/// (de)serialization routines.
pub witness: Witness
}
impl Default for TxIn {
fn default() -> TxIn {
TxIn {
previous_output: OutPoint::default(),
script_sig: Script::new(),
sequence: Sequence::MAX,
witness: Witness::default(),
}
}
}
/// Bitcoin transaction input sequence number.
///
/// The sequence field is used for:
/// - Indicating whether absolute lock-time (specified in `lock_time` field of [`Transaction`])
/// are enabled.
/// - Indicating and encoding [BIP-68] relative lock-times.
/// - Indicating whether a transcation opts-in to [BIP-125] replace-by-fee.
///
/// Note that transactions spending an output with `OP_CHECKLOCKTIMEVERIFY`MUST NOT use
/// `Sequence::MAX` for the corresponding input. [BIP-65]
///
/// [BIP-65]: <https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki>
/// [BIP-68]: <https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki>
/// [BIP-125]: <https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki>
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
pub struct Sequence(pub u32);
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
/// An error in creating relative lock-times.
pub enum RelativeLockTimeError {
/// The input was too large
IntegerOverflow(u32)
}
impl Sequence {
/// The maximum allowable sequence number.
///
/// This sequence number disables lock-time and replace-by-fee.
pub const MAX: Self = Sequence(MAX_SEQUENCE);
/// Zero value sequence.
///
/// This sequence number enables replace-by-fee and lock-time.
pub const ZERO: Self = Sequence(0);
/// The sequence number that enables absolute lock-time but disables replace-by-fee
/// and relative lock-time.
pub const ENABLE_LOCKTIME_NO_RBF: Self = Sequence::MIN_NO_RBF;
/// The sequence number that enables replace-by-fee and absolute lock-time but
/// disables relative lock-time.
pub const ENABLE_RBF_NO_LOCKTIME: Self = Sequence(0xFFFFFFFD);
/// The lowest sequence number that does not opt-in for replace-by-fee.
///
/// A transaction is considered to have opted in to replacement of itself
/// if any of it's inputs have a `Sequence` number less than this value
/// (Explicit Signalling [BIP-125]).
///
/// [BIP-125]: <https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki]>
const MIN_NO_RBF: Self = Sequence(0xFFFFFFFE);
/// BIP-68 relative lock-time disable flag mask
const LOCK_TIME_DISABLE_FLAG_MASK: u32 = 0x80000000;
/// BIP-68 relative lock-time type flag mask
const LOCK_TYPE_MASK: u32 = 0x00400000;
/// Retuns `true` if the sequence number indicates that the transaction is finalised.
///
/// The sequence number being equal to 0xffffffff on all txin sequences indicates
/// that the transaction is finalised.
#[inline]
pub fn is_final(&self) -> bool {
*self == Sequence::MAX
}
/// Returns true if the transaction opted-in to BIP125 replace-by-fee.
///
/// Replace by fee is signaled by the sequence being less than 0xfffffffe which is checked by this method.
#[inline]
pub fn is_rbf(&self) -> bool {
*self < Sequence::MIN_NO_RBF
}
/// Returns `true` if the sequence has a relative lock-time.
#[inline]
pub fn is_relative_lock_time(&self) -> bool {
self.0 & Sequence::LOCK_TIME_DISABLE_FLAG_MASK == 0
}
/// Returns `true` if the sequence number encodes a block based relative lock-time.
#[inline]
pub fn is_height_locked(&self) -> bool {
self.is_relative_lock_time() & (self.0 & Sequence::LOCK_TYPE_MASK == 0)
}
/// Returns `true` if the sequene number encodes a time interval based relative lock-time.
#[inline]
pub fn is_time_locked(&self) -> bool {
self.is_relative_lock_time() & (self.0 & Sequence::LOCK_TYPE_MASK > 0)
}
/// Create a relative lock-time using block height.
#[inline]
pub fn from_height(height: u16) -> Self {
Sequence(u32::from(height))
}
/// Create a relative lock-time using time intervals where each interval is equivalent
/// to 512 seconds.
///
/// Encoding finer granularity of time for relative lock-times is not supported in Bitcoin
#[inline]
pub fn from_512_second_intervals(intervals: u16) -> Self {
Sequence(u32::from(intervals) | Sequence::LOCK_TYPE_MASK)
}
/// Create a relative lock-time from seconds, converting the seconds into 512 second
/// interval with floor division.
///
/// Will return an error if the input cannot be encoded in 16 bits.
#[inline]
pub fn from_seconds_floor(seconds: u32) -> Result<Self, RelativeLockTimeError> {
if let Ok(interval) = u16::try_from(seconds / 512) {
Ok(Sequence::from_512_second_intervals(interval))
} else {
Err(RelativeLockTimeError::IntegerOverflow(seconds))
}
}
/// Create a relative lock-time from seconds, converting the seconds into 512 second
/// interval with ceiling division.
///
/// Will return an error if the input cannot be encoded in 16 bits.
#[inline]
pub fn from_seconds_ceil(seconds: u32) -> Result<Self, RelativeLockTimeError> {
if let Ok(interval) = u16::try_from((seconds + 511) / 512) {
Ok(Sequence::from_512_second_intervals(interval))
} else {
Err(RelativeLockTimeError::IntegerOverflow(seconds))
}
}
/// Returns `true` if the sequence number enables absolute lock-time ([`Transaction::lock_time`]).
#[inline]
pub fn enables_absolute_lock_time(&self) -> bool {
!self.is_final()
}
/// Create a sequence from a u32 value.
#[inline]
pub fn from_consensus(n: u32) -> Self {
Sequence(n)
}
/// Returns the inner 32bit integer value of Sequence.
#[inline]
pub fn to_consensus_u32(&self) -> u32 {
self.0
}
}
impl Default for Sequence {
/// The default value of sequence is 0xffffffff.
fn default() -> Self {
Sequence::MAX
}
}
impl From<Sequence> for u32 {
fn from(sequence: Sequence) -> u32 {
sequence.0
}
}
impl fmt::Display for Sequence {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl fmt::LowerHex for Sequence {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(&self.0, f)
}
}
impl fmt::UpperHex for Sequence {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::UpperHex::fmt(&self.0, f)
}
}
impl fmt::Display for RelativeLockTimeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Self::IntegerOverflow(val) => write!(f, "input of {} was too large", val)
}
}
}
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl std::error::Error for RelativeLockTimeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::IntegerOverflow(_) => None
}
}
}
/// Bitcoin transaction output.
///
/// Defines new coins to be created as a result of the transaction,
/// along with spending conditions ("script", aka "output script"),
/// which an input spending it must satisfy.
///
/// An output that is not yet spent by an input is called Unspent Transaction Output ("UTXO").
///
/// ### Bitcoin Core References
///
/// * [CTxOut definition](https://github.com/bitcoin/bitcoin/blob/345457b542b6a980ccfbc868af0970a6f91d1b82/src/primitives/transaction.h#L148)
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
pub struct TxOut {
/// The value of the output, in satoshis.
pub value: u64,
/// The script which must be satisfied for the output to be spent.
pub script_pubkey: Script
}
// This is used as a "null txout" in consensus signing code.
impl Default for TxOut {
fn default() -> TxOut {
TxOut { value: 0xffffffffffffffff, script_pubkey: Script::new() }
}
}
/// Result of [`Transaction::encode_signing_data_to`].
///
/// This type forces the caller to handle SIGHASH_SINGLE bug case.
///
/// This corner case can't be expressed using standard `Result`,
/// in a way that is both convenient and not-prone to accidental
/// mistakes (like calling `.expect("writer never fails")`).
#[must_use]
pub enum EncodeSigningDataResult<E> {
/// Input data is an instance of `SIGHASH_SINGLE` bug
SighashSingleBug,
/// Operation performed normally.
WriteResult(Result<(), E>),
}
impl<E> EncodeSigningDataResult<E> {
/// Checks for SIGHASH_SINGLE bug returning error if the writer failed.
///
/// This method is provided for easy and correct handling of the result because
/// SIGHASH_SINGLE bug is a special case that must not be ignored nor cause panicking.
/// Since the data is usually written directly into a hasher which never fails,
/// the recommended pattern to handle this is:
///
/// ```rust
/// # use bitcoin::consensus::deserialize;
/// # use bitcoin::{Transaction, Sighash};
/// # use bitcoin_hashes::{Hash, hex::FromHex};
/// # let mut writer = Sighash::engine();
/// # let input_index = 0;
/// # let script_pubkey = bitcoin::Script::new();
/// # let sighash_u32 = 0u32;
/// # const SOME_TX: &'static str = "0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000";
/// # let raw_tx = Vec::from_hex(SOME_TX).unwrap();
/// # let tx: Transaction = deserialize(&raw_tx).unwrap();
/// if tx.encode_signing_data_to(&mut writer, input_index, &script_pubkey, sighash_u32)
/// .is_sighash_single_bug()
/// .expect("writer can't fail") {
/// // use a hash value of "1", instead of computing the actual hash due to SIGHASH_SINGLE bug
/// }
/// ```
pub fn is_sighash_single_bug(self) -> Result<bool, E> {
match self {
EncodeSigningDataResult::SighashSingleBug => Ok(true),
EncodeSigningDataResult::WriteResult(Ok(())) => Ok(false),
EncodeSigningDataResult::WriteResult(Err(e)) => Err(e),
}
}
/// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
/// contained [`Err`] value, leaving an [`Ok`] value untouched.
///
/// Like [`Result::map_err`].
pub fn map_err<E2, F>(self, f: F) -> EncodeSigningDataResult<E2> where F: FnOnce(E) -> E2 {
match self {
EncodeSigningDataResult::SighashSingleBug => EncodeSigningDataResult::SighashSingleBug,
EncodeSigningDataResult::WriteResult(Err(e)) => EncodeSigningDataResult::WriteResult(Err(f(e))),
EncodeSigningDataResult::WriteResult(Ok(o)) => EncodeSigningDataResult::WriteResult(Ok(o)),
}
}
}
/// Bitcoin transaction.
///
/// An authenticated movement of coins.
///
/// See [Bitcoin Wiki: Transaction][wiki-transaction] for more information.
///
/// [wiki-transaction]: https://en.bitcoin.it/wiki/Transaction
///
/// ### Bitcoin Core References
///
/// * [CTtransaction definition](https://github.com/bitcoin/bitcoin/blob/345457b542b6a980ccfbc868af0970a6f91d1b82/src/primitives/transaction.h#L279)
///
/// ### Serialization notes
///
/// If any inputs have nonempty witnesses, the entire transaction is serialized
/// in the post-BIP141 Segwit format which includes a list of witnesses. If all
/// inputs have empty witnesses, the transaction is serialized in the pre-BIP141
/// format.
///
/// There is one major exception to this: to avoid deserialization ambiguity,
/// if the transaction has no inputs, it is serialized in the BIP141 style. Be
/// aware that this differs from the transaction format in PSBT, which _never_
/// uses BIP141. (Ordinarily there is no conflict, since in PSBT transactions
/// are always unsigned and therefore their inputs have empty witnesses.)
///
/// The specific ambiguity is that Segwit uses the flag bytes `0001` where an old
/// serializer would read the number of transaction inputs. The old serializer
/// would interpret this as "no inputs, one output", which means the transaction
/// is invalid, and simply reject it. Segwit further specifies that this encoding
/// should *only* be used when some input has a nonempty witness; that is,
/// witness-less transactions should be encoded in the traditional format.
///
/// However, in protocols where transactions may legitimately have 0 inputs, e.g.
/// when parties are cooperatively funding a transaction, the "00 means Segwit"
/// heuristic does not work. Since Segwit requires such a transaction be encoded
/// in the original transaction format (since it has no inputs and therefore
/// no input witnesses), a traditionally encoded transaction may have the `0001`
/// Segwit flag in it, which confuses most Segwit parsers including the one in
/// Bitcoin Core.
///
/// We therefore deviate from the spec by always using the Segwit witness encoding
/// for 0-input transactions, which results in unambiguously parseable transactions.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
pub struct Transaction {
/// The protocol version, is currently expected to be 1 or 2 (BIP 68).
pub version: i32,
/// Block number before which this transaction is valid, or 0 for valid immediately.
pub lock_time: u32,
/// List of transaction inputs.
pub input: Vec<TxIn>,
/// List of transaction outputs.
pub output: Vec<TxOut>,
}
impl Transaction {
/// Computes a "normalized TXID" which does not include any signatures.
/// This gives a way to identify a transaction that is "the same" as
/// another in the sense of having same inputs and outputs.
pub fn ntxid(&self) -> sha256d::Hash {
let cloned_tx = Transaction {
version: self.version,
lock_time: self.lock_time,
input: self.input.iter().map(|txin| TxIn { script_sig: Script::new(), witness: Witness::default(), .. *txin }).collect(),
output: self.output.clone(),
};
cloned_tx.txid().into()
}
/// Computes the txid. For non-segwit transactions this will be identical
/// to the output of `wtxid()`, but for segwit transactions,
/// this will give the correct txid (not including witnesses) while `wtxid`
/// will also hash witnesses.
pub fn txid(&self) -> Txid {
let mut enc = Txid::engine();
self.version.consensus_encode(&mut enc).expect("engines don't error");
self.input.consensus_encode(&mut enc).expect("engines don't error");
self.output.consensus_encode(&mut enc).expect("engines don't error");
self.lock_time.consensus_encode(&mut enc).expect("engines don't error");
Txid::from_engine(enc)
}
/// Computes SegWit-version of the transaction id (wtxid). For transaction with the witness
/// data this hash includes witness, for pre-witness transaction it is equal to the normal
/// value returned by txid() function.
pub fn wtxid(&self) -> Wtxid {
let mut enc = Wtxid::engine();
self.consensus_encode(&mut enc).expect("engines don't error");
Wtxid::from_engine(enc)
}
/// Encodes the signing data from which a signature hash for a given input index with a given
/// sighash flag can be computed.
///
/// To actually produce a scriptSig, this hash needs to be run through an ECDSA signer, the
/// [`EcdsaSighashType`] appended to the resulting sig, and a script written around this, but
/// this is the general (and hard) part.
///
/// The `sighash_type` supports an arbitrary `u32` value, instead of just [`EcdsaSighashType`],
/// because internally 4 bytes are being hashed, even though only the lowest byte is appended to
/// signature in a transaction.
///
/// # Warning
///
/// - Does NOT attempt to support OP_CODESEPARATOR. In general this would require evaluating
/// `script_pubkey` to determine which separators get evaluated and which don't, which we don't
/// have the information to determine.
/// - Does NOT handle the sighash single bug (see "Return type" section)
///
/// # Return type
///
/// This function can't handle the SIGHASH_SINGLE bug internally, so it returns [`EncodeSigningDataResult`]
/// that must be handled by the caller (see [`EncodeSigningDataResult::is_sighash_single_bug`]).
///
/// # Panics
///
/// If `input_index` is out of bounds (greater than or equal to `self.input.len()`).
pub fn encode_signing_data_to<Write: io::Write, U: Into<u32>>(
&self,
writer: Write,
input_index: usize,
script_pubkey: &Script,
sighash_type: U,
) -> EncodeSigningDataResult<io::Error> {
let sighash_type: u32 = sighash_type.into();
assert!(input_index < self.input.len()); // Panic on OOB
if self.is_invalid_use_of_sighash_single(sighash_type, input_index) {
// We cannot correctly handle the SIGHASH_SINGLE bug here because usage of this function
// will result in the data written to the writer being hashed, however the correct
// handling of the SIGHASH_SINGLE bug is to return the 'one array' - either implement
// this behaviour manually or use `signature_hash()`.
return EncodeSigningDataResult::SighashSingleBug;
}
fn encode_signing_data_to_inner<Write: io::Write>(
self_: &Transaction,
mut writer: Write,
input_index: usize,
script_pubkey: &Script,
sighash_type: u32,
) -> Result<(), io::Error> {
let (sighash, anyone_can_pay) = EcdsaSighashType::from_consensus(sighash_type).split_anyonecanpay_flag();
// Build tx to sign
let mut tx = Transaction {
version: self_.version,
lock_time: self_.lock_time,
input: vec![],
output: vec![],
};
// Add all inputs necessary..
if anyone_can_pay {
tx.input = vec![TxIn {
previous_output: self_.input[input_index].previous_output,
script_sig: script_pubkey.clone(),
sequence: self_.input[input_index].sequence,
witness: Witness::default(),
}];
} else {
tx.input = Vec::with_capacity(self_.input.len());
for (n, input) in self_.input.iter().enumerate() {
tx.input.push(TxIn {
previous_output: input.previous_output,
script_sig: if n == input_index { script_pubkey.clone() } else { Script::new() },
sequence: if n != input_index && (sighash == EcdsaSighashType::Single || sighash == EcdsaSighashType::None) { Sequence::ZERO } else { input.sequence },
witness: Witness::default(),
});
}
}
// ..then all outputs
tx.output = match sighash {
EcdsaSighashType::All => self_.output.clone(),
EcdsaSighashType::Single => {
let output_iter = self_.output.iter()
.take(input_index + 1) // sign all outputs up to and including this one, but erase
.enumerate() // all of them except for this one
.map(|(n, out)| if n == input_index { out.clone() } else { TxOut::default() });
output_iter.collect()
}
EcdsaSighashType::None => vec![],
_ => unreachable!()
};
// hash the result
tx.consensus_encode(&mut writer)?;
let sighash_arr = endian::u32_to_array_le(sighash_type);
sighash_arr.consensus_encode(&mut writer)?;
Ok(())
}
EncodeSigningDataResult::WriteResult(
encode_signing_data_to_inner(
self,
writer,
input_index,
script_pubkey,
sighash_type
)
)
}
/// Computes a signature hash for a given input index with a given sighash flag.
///
/// To actually produce a scriptSig, this hash needs to be run through an ECDSA signer, the
/// [`EcdsaSighashType`] appended to the resulting sig, and a script written around this, but
/// this is the general (and hard) part.
///
/// The `sighash_type` supports an arbitrary `u32` value, instead of just [`EcdsaSighashType`],
/// because internally 4 bytes are being hashed, even though only the lowest byte is appended to
/// signature in a transaction.
///
/// This function correctly handles the sighash single bug by returning the 'one array'. The
/// sighash single bug becomes exploitable when one tries to sign a transaction with
/// `SIGHASH_SINGLE` and there is not a corresponding output with the same index as the input.
///
/// # Warning
///
/// Does NOT attempt to support OP_CODESEPARATOR. In general this would require evaluating
/// `script_pubkey` to determine which separators get evaluated and which don't, which we don't
/// have the information to determine.
///
/// # Panics
///
/// If `input_index` is out of bounds (greater than or equal to `self.input.len()`).
pub fn signature_hash(
&self,
input_index: usize,
script_pubkey: &Script,
sighash_u32: u32
) -> Sighash {
if self.is_invalid_use_of_sighash_single(sighash_u32, input_index) {
return Sighash::from_inner(UINT256_ONE);
}
let mut engine = Sighash::engine();
if self.encode_signing_data_to(&mut engine, input_index, script_pubkey, sighash_u32)
.is_sighash_single_bug()
.expect("engines don't error") {
return Sighash::from_slice(&UINT256_ONE).expect("const-size array");
}
Sighash::from_engine(engine)
}
fn is_invalid_use_of_sighash_single(&self, sighash: u32, input_index: usize) -> bool {
let ty = EcdsaSighashType::from_consensus(sighash);
ty == EcdsaSighashType::Single && input_index >= self.output.len()
}
/// Returns the "weight" of this transaction, as defined by BIP141.
#[inline]
#[deprecated(since = "0.28.0", note = "Please use `transaction::weight` instead.")]
pub fn get_weight(&self) -> usize {
self.weight()
}
/// Returns the "weight" of this transaction, as defined by BIP141.
///
/// For transactions with an empty witness, this is simply the consensus-serialized size times
/// four. For transactions with a witness, this is the non-witness consensus-serialized size
/// multiplied by three plus the with-witness consensus-serialized size.
#[inline]
pub fn weight(&self) -> usize {
self.scaled_size(WITNESS_SCALE_FACTOR)
}
/// Returns the regular byte-wise consensus-serialized size of this transaction.
#[inline]
#[deprecated(since = "0.28.0", note = "Please use `transaction::size` instead.")]
pub fn get_size(&self) -> usize {
self.size()
}
/// Returns the regular byte-wise consensus-serialized size of this transaction.
#[inline]
pub fn size(&self) -> usize {
self.scaled_size(1)
}
/// Returns the "virtual size" (vsize) of this transaction.
#[inline]
#[deprecated(since = "0.28.0", note = "Please use `transaction::vsize` instead.")]
pub fn get_vsize(&self) -> usize {
self.vsize()
}
/// Returns the "virtual size" (vsize) of this transaction.
///
/// Will be `ceil(weight / 4.0)`. Note this implements the virtual size as per [`BIP141`], which
/// is different to what is implemented in Bitcoin Core. The computation should be the same for
/// any remotely sane transaction, and a standardness-rule-correct version is available in the
/// [`policy`] module.
///
/// [`BIP141`]: https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki
/// [`policy`]: ../policy/mod.rs.html
#[inline]
pub fn vsize(&self) -> usize {
let weight = self.weight();
(weight + WITNESS_SCALE_FACTOR - 1) / WITNESS_SCALE_FACTOR
}
/// Returns the size of this transaction excluding the witness data.
#[deprecated(since = "0.28.0", note = "Please use `transaction::strippedsize` instead.")]
pub fn get_strippedsize(&self) -> usize {
self.strippedsize()
}
/// Returns the size of this transaction excluding the witness data.
pub fn strippedsize(&self) -> usize {
let mut input_size = 0;
for input in &self.input {
input_size += 32 + 4 + 4 + // outpoint (32+4) + nSequence
VarInt(input.script_sig.len() as u64).len() +
input.script_sig.len();
}
let mut output_size = 0;
for output in &self.output {
output_size += 8 + // value
VarInt(output.script_pubkey.len() as u64).len() +
output.script_pubkey.len();
}
let non_input_size =
// version:
4 +
// count varints:
VarInt(self.input.len() as u64).len() +
VarInt(self.output.len() as u64).len() +
output_size +
// lock_time
4;
non_input_size + input_size
}
/// Internal utility function for size/weight functions.
fn scaled_size(&self, scale_factor: usize) -> usize {
let mut input_weight = 0;
let mut inputs_with_witnesses = 0;
for input in &self.input {
input_weight += scale_factor*(32 + 4 + 4 + // outpoint (32+4) + nSequence
VarInt(input.script_sig.len() as u64).len() +
input.script_sig.len());
if !input.witness.is_empty() {
inputs_with_witnesses += 1;
input_weight += input.witness.serialized_len();
}
}
let mut output_size = 0;
for output in &self.output {
output_size += 8 + // value
VarInt(output.script_pubkey.len() as u64).len() +
output.script_pubkey.len();
}
let non_input_size =
// version:
4 +
// count varints:
VarInt(self.input.len() as u64).len() +
VarInt(self.output.len() as u64).len() +
output_size +
// lock_time
4;
if inputs_with_witnesses == 0 {
non_input_size * scale_factor + input_weight
} else {
non_input_size * scale_factor + input_weight + self.input.len() - inputs_with_witnesses + 2
}
}
/// Shorthand for [`Self::verify_with_flags`] with flag [`bitcoinconsensus::VERIFY_ALL`].
#[cfg(feature="bitcoinconsensus")]
#[cfg_attr(docsrs, doc(cfg(feature = "bitcoinconsensus")))]
pub fn verify<S>(&self, spent: S) -> Result<(), script::Error>
where
S: FnMut(&OutPoint) -> Option<TxOut>
{
self.verify_with_flags(spent, ::bitcoinconsensus::VERIFY_ALL)
}
/// Verify that this transaction is able to spend its inputs.
/// The `spent` closure should not return the same [`TxOut`] twice!
#[cfg(feature="bitcoinconsensus")]
#[cfg_attr(docsrs, doc(cfg(feature = "bitcoinconsensus")))]
pub fn verify_with_flags<S, F>(&self, mut spent: S, flags: F) -> Result<(), script::Error>
where
S: FnMut(&OutPoint) -> Option<TxOut>,
F: Into<u32>
{
let tx = encode::serialize(&*self);
let flags: u32 = flags.into();
for (idx, input) in self.input.iter().enumerate() {
if let Some(output) = spent(&input.previous_output) {
output.script_pubkey.verify_with_flags(idx, crate::Amount::from_sat(output.value), tx.as_slice(), flags)?;
} else {
return Err(script::Error::UnknownSpentOutput(input.previous_output));
}
}
Ok(())
}
/// Is this a coin base transaction?
pub fn is_coin_base(&self) -> bool {
self.input.len() == 1 && self.input[0].previous_output.is_null()
}
/// Returns `true` if the transaction itself opted in to be BIP-125-replaceable (RBF). This
/// **does not** cover the case where a transaction becomes replaceable due to ancestors being
/// RBF.
pub fn is_explicitly_rbf(&self) -> bool {
self.input.iter().any(|input| input.sequence.is_rbf())
}
}
impl_consensus_encoding!(TxOut, value, script_pubkey);
impl Encodable for OutPoint {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let len = self.txid.consensus_encode(w)?;
Ok(len + self.vout.consensus_encode(w)?)
}
}
impl Decodable for OutPoint {
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
Ok(OutPoint {
txid: Decodable::consensus_decode(r)?,
vout: Decodable::consensus_decode(r)?,
})
}
}
impl Encodable for TxIn {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let mut len = 0;
len += self.previous_output.consensus_encode(w)?;
len += self.script_sig.consensus_encode(w)?;
len += self.sequence.consensus_encode(w)?;
Ok(len)
}
}
impl Decodable for TxIn {
#[inline]
fn consensus_decode_from_finite_reader<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
Ok(TxIn {
previous_output: Decodable::consensus_decode_from_finite_reader(r)?,
script_sig: Decodable::consensus_decode_from_finite_reader(r)?,
sequence: Decodable::consensus_decode_from_finite_reader(r)?,
witness: Witness::default(),
})
}
}
impl Encodable for Sequence {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
self.0.consensus_encode(w)
}
}
impl Decodable for Sequence {
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
Decodable::consensus_decode(r).map(Sequence)
}
}
impl Encodable for Transaction {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let mut len = 0;
len += self.version.consensus_encode(w)?;
// To avoid serialization ambiguity, no inputs means we use BIP141 serialization (see
// `Transaction` docs for full explanation).
let mut have_witness = self.input.is_empty();
for input in &self.input {
if !input.witness.is_empty() {
have_witness = true;
break;
}
}
if !have_witness {
len += self.input.consensus_encode(w)?;
len += self.output.consensus_encode(w)?;
} else {
len += 0u8.consensus_encode(w)?;
len += 1u8.consensus_encode(w)?;
len += self.input.consensus_encode(w)?;