Skip to main content

bitcoin_primitives/
transaction.rs

1// SPDX-License-Identifier: CC0-1.0
2
3//! Bitcoin transactions.
4//!
5//! A transaction describes a transfer of money. It consumes previously-unspent
6//! transaction outputs and produces new ones, satisfying the condition to spend
7//! the old outputs (typically a digital signature with a specific key must be
8//! provided) and defining the condition to spend the new ones. The use of digital
9//! signatures ensures that coins cannot be spent by unauthorized parties.
10//!
11//! This module provides the structures and functions needed to support transactions.
12
13use core::convert::Infallible;
14use core::fmt;
15#[cfg(feature = "alloc")]
16use core::{cmp, mem};
17
18#[cfg(feature = "arbitrary")]
19use arbitrary::{Arbitrary, Unstructured};
20use encoding::{ArrayEncoder, BytesEncoder, Encodable, Encoder2, UnexpectedEofError};
21#[cfg(feature = "alloc")]
22use encoding::{
23    CompactSizeEncoder, Decodable, Decoder, Decoder2, Decoder3, Encoder, Encoder3, Encoder6,
24    SliceEncoder, VecDecoder, VecDecoderError,
25};
26#[cfg(feature = "alloc")]
27use hashes::sha256d;
28use internals::array::ArrayExt as _;
29use internals::write_err;
30#[cfg(feature = "serde")]
31use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
32#[cfg(all(feature = "hex", feature = "alloc"))]
33use units::parse_int;
34
35#[cfg(feature = "alloc")]
36use crate::amount::{AmountDecoder, AmountEncoder};
37#[cfg(feature = "alloc")]
38use crate::locktime::absolute::{LockTimeDecoder, LockTimeDecoderError, LockTimeEncoder};
39#[cfg(feature = "alloc")]
40use crate::prelude::Vec;
41#[cfg(feature = "alloc")]
42use crate::script::{ScriptEncoder, ScriptPubKeyBufDecoder, ScriptSigBufDecoder};
43#[cfg(feature = "alloc")]
44use crate::sequence::{SequenceDecoder, SequenceEncoder};
45#[cfg(feature = "alloc")]
46use crate::witness::{WitnessDecoder, WitnessDecoderError, WitnessEncoder};
47#[cfg(feature = "alloc")]
48use crate::{absolute, Amount, ScriptPubKeyBuf, ScriptSigBuf, Sequence, Weight, Witness};
49
50#[rustfmt::skip]            // Keep public re-exports separate.
51#[doc(inline)]
52pub use crate::hash_types::{Ntxid, Txid, Wtxid, BlockHashDecoder, TxMerkleNodeDecoder, TxMerkleNodeDecoderError};
53#[doc(no_inline)]
54pub use crate::hash_types::BlockHashDecoderError;
55
56/// Bitcoin transaction.
57///
58/// An authenticated movement of coins.
59///
60/// See [Bitcoin Wiki: Transaction][wiki-transaction] for more information.
61///
62/// [wiki-transaction]: https://en.bitcoin.it/wiki/Transaction
63///
64/// # Bitcoin Core References
65///
66/// * [CTransaction definition](https://github.com/bitcoin/bitcoin/blob/345457b542b6a980ccfbc868af0970a6f91d1b82/src/primitives/transaction.h#L279)
67///
68/// # Serialization notes
69///
70/// If any inputs have nonempty witnesses, the entire transaction is serialized
71/// in the post-BIP-0141 SegWit format which includes a list of witnesses. If all
72/// inputs have empty witnesses, the transaction is serialized in the pre-BIP-0141
73/// format.
74///
75/// There is one major exception to this: to avoid deserialization ambiguity,
76/// if the transaction has no inputs, it is serialized in the BIP-0141 style. Be
77/// aware that this differs from the transaction format in PSBT, which _never_
78/// uses BIP-0141. (Ordinarily there is no conflict, since in PSBT transactions
79/// are always unsigned and therefore their inputs have empty witnesses.)
80///
81/// The specific ambiguity is that SegWit uses the flag bytes `0001` where an old
82/// serializer would read the number of transaction inputs. The old serializer
83/// would interpret this as "no inputs, one output", which means the transaction
84/// is invalid, and simply reject it. SegWit further specifies that this encoding
85/// should *only* be used when some input has a nonempty witness; that is,
86/// witness-less transactions should be encoded in the traditional format.
87///
88/// However, in protocols where transactions may legitimately have 0 inputs, e.g.
89/// when parties are cooperatively funding a transaction, the "00 means SegWit"
90/// heuristic does not work. Since SegWit requires such a transaction to be encoded
91/// in the original transaction format (since it has no inputs and therefore
92/// no input witnesses), a traditionally encoded transaction may have the `0001`
93/// SegWit flag in it, which confuses most SegWit parsers including the one in
94/// Bitcoin Core.
95///
96/// We therefore deviate from the spec by always using the SegWit witness encoding
97/// for 0-input transactions, which results in unambiguously parseable transactions.
98///
99/// # A note on ordering
100///
101/// This type implements `Ord`, even though it contains a locktime, which is not
102/// itself `Ord`. This was done to simplify applications that may need to hold
103/// transactions inside a sorted container. We have ordered the locktimes based
104/// on their representation as a `u32`, which is not a semantically meaningful
105/// order, and therefore the ordering on `Transaction` itself is not semantically
106/// meaningful either.
107///
108/// The ordering is, however, consistent with the ordering present in this library
109/// before this change, so users should not notice any breakage (here) when
110/// transitioning from 0.29 to 0.30.
111#[derive(Clone, PartialEq, Eq, Debug, Hash)]
112#[cfg(feature = "alloc")]
113pub struct Transaction {
114    /// The protocol version, is currently expected to be 1, 2 (BIP-0068) or 3 (BIP-0431).
115    pub version: Version,
116    /// Block height or timestamp. Transaction cannot be included in a block until this height/time.
117    ///
118    /// # Relevant BIPs
119    ///
120    /// * [BIP-0065 OP_CHECKLOCKTIMEVERIFY](https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki)
121    /// * [BIP-0113 Median time-past as endpoint for lock-time calculations](https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki)
122    pub lock_time: absolute::LockTime,
123    /// List of transaction inputs.
124    pub inputs: Vec<TxIn>,
125    /// List of transaction outputs.
126    pub outputs: Vec<TxOut>,
127}
128
129#[cfg(feature = "alloc")]
130impl Transaction {
131    // https://github.com/bitcoin/bitcoin/blob/44b05bf3fef2468783dcebf651654fdd30717e7e/src/policy/policy.h#L27
132    /// Maximum transaction weight for Bitcoin Core 25.0.
133    pub const MAX_STANDARD_WEIGHT: Weight = Weight::from_wu(400_000);
134
135    /// Computes a "normalized TXID" which does not include any signatures.
136    ///
137    /// This function is needed only for legacy (pre-Segwit or P2SH-wrapped segwit version 0)
138    /// applications. This method clears the `script_sig` field of each input, which in Segwit
139    /// transactions is already empty, so for Segwit transactions the ntxid will be equal to the
140    /// txid, and you should simply use the latter.
141    ///
142    /// This gives a way to identify a transaction that is "the same" as another in the sense of
143    /// having the same inputs and outputs.
144    #[doc(alias = "ntxid")]
145    pub fn compute_ntxid(&self) -> Ntxid {
146        let normalized = Self {
147            version: self.version,
148            lock_time: self.lock_time,
149            inputs: self
150                .inputs
151                .iter()
152                .map(|txin| TxIn {
153                    script_sig: ScriptSigBuf::new(),
154                    witness: Witness::default(),
155                    ..*txin
156                })
157                .collect(),
158            outputs: self.outputs.clone(),
159        };
160        Ntxid::from_byte_array(normalized.compute_txid().to_byte_array())
161    }
162
163    /// Computes the [`Txid`].
164    ///
165    /// Hashes the transaction **excluding** the SegWit data (i.e. the marker, flag bytes, and the
166    /// witness fields themselves). For non-SegWit transactions which do not have any SegWit data,
167    /// this will be equal to [`Transaction::compute_wtxid()`].
168    #[doc(alias = "txid")]
169    #[inline]
170    pub fn compute_txid(&self) -> Txid {
171        let hash = hash_transaction(self, false);
172        Txid::from_byte_array(hash.to_byte_array())
173    }
174
175    /// Computes the SegWit version of the transaction id.
176    ///
177    /// Hashes the transaction **including** all SegWit data (i.e. the marker, flag bytes, and the
178    /// witness fields themselves). For non-SegWit transactions which do not have any SegWit data,
179    /// this will be equal to [`Transaction::compute_txid()`].
180    #[doc(alias = "wtxid")]
181    #[inline]
182    pub fn compute_wtxid(&self) -> Wtxid {
183        let hash = hash_transaction(self, self.uses_segwit_serialization());
184        Wtxid::from_byte_array(hash.to_byte_array())
185    }
186
187    /// Returns whether or not to serialize transaction as specified in BIP-0144.
188    // This is duplicated in `bitcoin`, if you change it please do so in both places.
189    #[inline]
190    fn uses_segwit_serialization(&self) -> bool {
191        if self.inputs.iter().any(|input| !input.witness.is_empty()) {
192            return true;
193        }
194        // To avoid serialization ambiguity, no inputs means we use BIP-0141 serialization (see
195        // `Transaction` docs for full explanation).
196        self.inputs.is_empty()
197    }
198
199    /// Checks if this is a coinbase transaction.
200    ///
201    /// The first transaction in the block distributes the mining reward and is called the coinbase
202    /// transaction. It is impossible to check if the transaction is first in the block, so this
203    /// function checks the structure of the transaction instead - the previous output must be
204    /// all-zeros (creates satoshis "out of thin air").
205    #[doc(alias = "is_coin_base")] // method previously had this name
206    pub fn is_coinbase(&self) -> bool {
207        self.inputs.len() == 1 && self.inputs[0].previous_output == OutPoint::COINBASE_PREVOUT
208    }
209}
210
211#[cfg(feature = "alloc")]
212impl cmp::PartialOrd for Transaction {
213    #[inline]
214    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { Some(self.cmp(other)) }
215}
216
217#[cfg(feature = "alloc")]
218impl cmp::Ord for Transaction {
219    fn cmp(&self, other: &Self) -> cmp::Ordering {
220        self.version
221            .cmp(&other.version)
222            .then(self.lock_time.to_consensus_u32().cmp(&other.lock_time.to_consensus_u32()))
223            .then(self.inputs.cmp(&other.inputs))
224            .then(self.outputs.cmp(&other.outputs))
225    }
226}
227
228#[cfg(feature = "alloc")]
229impl From<Transaction> for Txid {
230    #[inline]
231    fn from(tx: Transaction) -> Self { tx.compute_txid() }
232}
233
234#[cfg(feature = "alloc")]
235impl From<&Transaction> for Txid {
236    #[inline]
237    fn from(tx: &Transaction) -> Self { tx.compute_txid() }
238}
239
240#[cfg(feature = "alloc")]
241impl From<Transaction> for Wtxid {
242    #[inline]
243    fn from(tx: Transaction) -> Self { tx.compute_wtxid() }
244}
245
246#[cfg(feature = "alloc")]
247impl From<&Transaction> for Wtxid {
248    #[inline]
249    fn from(tx: &Transaction) -> Self { tx.compute_wtxid() }
250}
251
252/// Trait that abstracts over a transaction identifier i.e., `Txid` and `Wtxid`.
253pub(crate) trait TxIdentifier: AsRef<[u8]> {}
254
255impl TxIdentifier for Txid {}
256impl TxIdentifier for Wtxid {}
257
258// Duplicated in `bitcoin`.
259/// The marker MUST be a 1-byte zero value: 0x00. (BIP-0141)
260#[cfg(feature = "alloc")]
261const SEGWIT_MARKER: u8 = 0x00;
262/// The flag MUST be a 1-byte non-zero value. Currently, 0x01 MUST be used. (BIP-0141)
263#[cfg(feature = "alloc")]
264const SEGWIT_FLAG: u8 = 0x01;
265
266// This is equivalent to consensus encoding but hashes the fields manually.
267#[cfg(feature = "alloc")]
268fn hash_transaction(tx: &Transaction, uses_segwit_serialization: bool) -> sha256d::Hash {
269    use hashes::HashEngine as _;
270
271    let mut enc = sha256d::Hash::engine();
272    enc.input(&tx.version.0.to_le_bytes()); // Same as `encode::emit_i32`.
273
274    if uses_segwit_serialization {
275        // BIP-0141 (SegWit) transaction serialization also includes marker and flag.
276        enc.input(&[SEGWIT_MARKER]);
277        enc.input(&[SEGWIT_FLAG]);
278    }
279
280    // Encode inputs (excluding witness data) with leading compact size encoded int.
281    let input_len = tx.inputs.len();
282    enc.input(crate::compact_size_encode(input_len).as_slice());
283    for input in &tx.inputs {
284        // Encode each input same as we do in `Encodable for TxIn`.
285        enc.input(input.previous_output.txid.as_byte_array());
286        enc.input(&input.previous_output.vout.to_le_bytes());
287
288        let script_sig_bytes = input.script_sig.as_bytes();
289        enc.input(crate::compact_size_encode(script_sig_bytes.len()).as_slice());
290        enc.input(script_sig_bytes);
291
292        enc.input(&input.sequence.0.to_le_bytes());
293    }
294
295    // Encode outputs with leading compact size encoded int.
296    let output_len = tx.outputs.len();
297    enc.input(crate::compact_size_encode(output_len).as_slice());
298    for output in &tx.outputs {
299        // Encode each output same as we do in `Encodable for TxOut`.
300        enc.input(&output.amount.to_sat().to_le_bytes());
301
302        let script_pubkey_bytes = output.script_pubkey.as_bytes();
303        enc.input(crate::compact_size_encode(script_pubkey_bytes.len()).as_slice());
304        enc.input(script_pubkey_bytes);
305    }
306
307    if uses_segwit_serialization {
308        // BIP-0141 (SegWit) transaction serialization also includes the witness data.
309        for input in &tx.inputs {
310            // Same as `Encodable for Witness`.
311            enc.input(crate::compact_size_encode(input.witness.len()).as_slice());
312            for element in &input.witness {
313                enc.input(crate::compact_size_encode(element.len()).as_slice());
314                enc.input(element);
315            }
316        }
317    }
318
319    // Same as `Encodable for absolute::LockTime`.
320    enc.input(&tx.lock_time.to_consensus_u32().to_le_bytes());
321
322    sha256d::Hash::from_engine(enc)
323}
324
325#[cfg(feature = "alloc")]
326type TransactionEncoderInner<'e> = Encoder6<
327    VersionEncoder<'e>,
328    Option<ArrayEncoder<2>>,
329    Encoder2<CompactSizeEncoder, SliceEncoder<'e, TxIn>>,
330    Encoder2<CompactSizeEncoder, SliceEncoder<'e, TxOut>>,
331    Option<WitnessesEncoder<'e>>,
332    LockTimeEncoder<'e>,
333>;
334
335#[cfg(feature = "alloc")]
336encoding::encoder_newtype! {
337    /// The encoder for the [`Transaction`] type.
338    pub struct TransactionEncoder<'e>(TransactionEncoderInner<'e>);
339}
340
341#[cfg(feature = "alloc")]
342impl Encodable for Transaction {
343    type Encoder<'e>
344        = TransactionEncoder<'e>
345    where
346        Self: 'e;
347
348    fn encoder(&self) -> Self::Encoder<'_> {
349        let version = self.version.encoder();
350        let inputs = Encoder2::new(
351            CompactSizeEncoder::new(self.inputs.len()),
352            SliceEncoder::without_length_prefix(self.inputs.as_ref()),
353        );
354        let outputs = Encoder2::new(
355            CompactSizeEncoder::new(self.outputs.len()),
356            SliceEncoder::without_length_prefix(self.outputs.as_ref()),
357        );
358        let lock_time = self.lock_time.encoder();
359
360        if self.uses_segwit_serialization() {
361            let segwit = ArrayEncoder::without_length_prefix([0x00, 0x01]);
362            let witnesses = WitnessesEncoder::new(self.inputs.as_slice());
363            TransactionEncoder::new(Encoder6::new(
364                version,
365                Some(segwit),
366                inputs,
367                outputs,
368                Some(witnesses),
369                lock_time,
370            ))
371        } else {
372            TransactionEncoder::new(Encoder6::new(version, None, inputs, outputs, None, lock_time))
373        }
374    }
375}
376
377#[cfg(all(feature = "hex", feature = "alloc"))]
378impl core::str::FromStr for Transaction {
379    type Err = ParseTransactionError;
380
381    fn from_str(s: &str) -> Result<Self, Self::Err> {
382        crate::hex_codec::HexPrimitive::from_str(s).map_err(ParseTransactionError)
383    }
384}
385
386#[cfg(all(feature = "hex", feature = "alloc"))]
387impl fmt::Display for Transaction {
388    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
389        fmt::Display::fmt(&crate::hex_codec::HexPrimitive(self), f)
390    }
391}
392
393#[cfg(all(feature = "hex", feature = "alloc"))]
394impl fmt::LowerHex for Transaction {
395    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
396        fmt::LowerHex::fmt(&crate::hex_codec::HexPrimitive(self), f)
397    }
398}
399
400#[cfg(all(feature = "hex", feature = "alloc"))]
401impl fmt::UpperHex for Transaction {
402    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
403        fmt::UpperHex::fmt(&crate::hex_codec::HexPrimitive(self), f)
404    }
405}
406
407/// An error that occurs during parsing of a [`Transaction`] from a hex string.
408#[cfg(all(feature = "hex", feature = "alloc"))]
409pub struct ParseTransactionError(crate::ParsePrimitiveError<Transaction>);
410
411#[cfg(all(feature = "hex", feature = "alloc"))]
412impl fmt::Debug for ParseTransactionError {
413    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&self.0, f) }
414}
415
416#[cfg(all(feature = "hex", feature = "alloc"))]
417impl fmt::Display for ParseTransactionError {
418    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&self, f) }
419}
420
421#[cfg(all(feature = "hex", feature = "alloc", feature = "std"))]
422impl std::error::Error for ParseTransactionError {
423    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
424        std::error::Error::source(&self.0)
425    }
426}
427
428/// The decoder for the [`Transaction`] type.
429#[cfg(feature = "alloc")]
430pub struct TransactionDecoder {
431    state: TransactionDecoderState,
432}
433
434#[cfg(feature = "alloc")]
435impl TransactionDecoder {
436    /// Constructs a new [`TransactionDecoder`].
437    pub const fn new() -> Self {
438        Self { state: TransactionDecoderState::Version(VersionDecoder::new()) }
439    }
440}
441
442#[cfg(feature = "alloc")]
443impl Default for TransactionDecoder {
444    fn default() -> Self { Self::new() }
445}
446
447#[cfg(feature = "alloc")]
448#[allow(clippy::too_many_lines)] // TODO: Can we clean this up?
449impl Decoder for TransactionDecoder {
450    type Output = Transaction;
451    type Error = TransactionDecoderError;
452
453    #[inline]
454    fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
455        use {
456            TransactionDecoderError as E, TransactionDecoderErrorInner as Inner,
457            TransactionDecoderState as State,
458        };
459
460        loop {
461            // Attempt to push to the currently-active decoder and return early on success.
462            match &mut self.state {
463                State::Version(decoder) => {
464                    if decoder.push_bytes(bytes)? {
465                        // Still more bytes required.
466                        return Ok(true);
467                    }
468                }
469                State::Inputs(_, _, decoder) =>
470                    if decoder.push_bytes(bytes)? {
471                        return Ok(true);
472                    },
473                State::SegwitFlag(_) =>
474                    if bytes.is_empty() {
475                        return Ok(true);
476                    },
477                State::Outputs(_, _, _, decoder) =>
478                    if decoder.push_bytes(bytes)? {
479                        return Ok(true);
480                    },
481                State::Witnesses(_, _, _, _, decoder) =>
482                    if decoder.push_bytes(bytes)? {
483                        return Ok(true);
484                    },
485                State::LockTime(_, _, _, decoder) =>
486                    if decoder.push_bytes(bytes)? {
487                        return Ok(true);
488                    },
489                State::Done(..) => return Ok(false),
490                State::Errored => panic!("call to push_bytes() after decoder errored"),
491            }
492
493            // If the above failed, end the current decoder and go to the next state.
494            match mem::replace(&mut self.state, State::Errored) {
495                State::Version(decoder) => {
496                    let version = decoder.end()?;
497                    self.state = State::Inputs(version, Attempt::First, VecDecoder::<TxIn>::new());
498                }
499                State::Inputs(version, attempt, decoder) => {
500                    let inputs = decoder.end()?;
501
502                    if Attempt::First == attempt {
503                        if inputs.is_empty() {
504                            self.state = State::SegwitFlag(version);
505                        } else {
506                            self.state = State::Outputs(
507                                version,
508                                inputs,
509                                IsSegwit::No,
510                                VecDecoder::<TxOut>::new(),
511                            );
512                        }
513                    } else {
514                        self.state = State::Outputs(
515                            version,
516                            inputs,
517                            IsSegwit::Yes,
518                            VecDecoder::<TxOut>::new(),
519                        );
520                    }
521                }
522                State::SegwitFlag(version) => {
523                    let segwit_flag = bytes[0];
524                    *bytes = &bytes[1..];
525
526                    if segwit_flag != 1 {
527                        return Err(E(Inner::UnsupportedSegwitFlag(segwit_flag)));
528                    }
529                    self.state = State::Inputs(version, Attempt::Second, VecDecoder::<TxIn>::new());
530                }
531                State::Outputs(version, inputs, is_segwit, decoder) => {
532                    let outputs = decoder.end()?;
533                    // Handle the zero-input case described in the `Transaction` docs.
534                    if is_segwit == IsSegwit::Yes && !inputs.is_empty() {
535                        self.state = State::Witnesses(
536                            version,
537                            inputs,
538                            outputs,
539                            Iteration(0),
540                            WitnessDecoder::new(),
541                        );
542                    } else {
543                        self.state =
544                            State::LockTime(version, inputs, outputs, LockTimeDecoder::new());
545                    }
546                }
547                State::Witnesses(version, mut inputs, outputs, iteration, decoder) => {
548                    let iteration = iteration.0;
549
550                    inputs[iteration].witness = decoder.end()?;
551                    if iteration < inputs.len() - 1 {
552                        self.state = State::Witnesses(
553                            version,
554                            inputs,
555                            outputs,
556                            Iteration(iteration + 1),
557                            WitnessDecoder::new(),
558                        );
559                    } else {
560                        if !inputs.is_empty() && inputs.iter().all(|input| input.witness.is_empty())
561                        {
562                            return Err(E(Inner::NoWitnesses));
563                        }
564                        self.state =
565                            State::LockTime(version, inputs, outputs, LockTimeDecoder::new());
566                    }
567                }
568                State::LockTime(version, inputs, outputs, decoder) => {
569                    let lock_time = decoder.end()?;
570                    self.state = State::Done(Transaction { version, lock_time, inputs, outputs });
571                    return Ok(false);
572                }
573                State::Done(..) => return Ok(false),
574                State::Errored => unreachable!("checked above"),
575            }
576        }
577    }
578
579    #[inline]
580    fn end(self) -> Result<Self::Output, Self::Error> {
581        use {
582            TransactionDecoderError as E, TransactionDecoderErrorInner as Inner,
583            TransactionDecoderState as State,
584        };
585
586        match self.state {
587            State::Version(_) => Err(E(Inner::EarlyEnd("version"))),
588            State::Inputs(..) => Err(E(Inner::EarlyEnd("inputs"))),
589            State::SegwitFlag(..) => Err(E(Inner::EarlyEnd("segwit flag"))),
590            State::Outputs(..) => Err(E(Inner::EarlyEnd("outputs"))),
591            State::Witnesses(..) => Err(E(Inner::EarlyEnd("witnesses"))),
592            State::LockTime(..) => Err(E(Inner::EarlyEnd("locktime"))),
593            State::Done(tx) => {
594                // Reject transactions with no outputs
595                if tx.outputs.is_empty() {
596                    return Err(E(Inner::NoOutputs));
597                }
598                // check for null prevout in non-coinbase txs
599                if tx.inputs.len() > 1 {
600                    for (index, input) in tx.inputs.iter().enumerate() {
601                        if input.previous_output == OutPoint::COINBASE_PREVOUT {
602                            return Err(E(Inner::NullPrevoutInNonCoinbase(index)));
603                        }
604                    }
605                }
606                // check coinbase scriptSig length (must be 2-100 bytes)
607                if tx.is_coinbase() {
608                    let len = tx.inputs[0].script_sig.len();
609                    if len < 2 {
610                        return Err(E(Inner::CoinbaseScriptSigTooSmall(len)));
611                    }
612                    if len > 100 {
613                        return Err(E(Inner::CoinbaseScriptSigTooLarge(len)));
614                    }
615                }
616                // check for duplicate inputs (CVE-2018-17144).
617                let mut outpoints: Vec<_> = tx.inputs.iter().map(|i| i.previous_output).collect();
618                outpoints.sort_unstable();
619                for pair in outpoints.windows(2) {
620                    if pair[0] == pair[1] {
621                        return Err(E(Inner::DuplicateInput(pair[0])));
622                    }
623                }
624                // Check that sum of output values doesn't exceed MAX_MONEY (see CVE-2010-5139)
625                // Note: Individual output values are already validated by Amount::from_sat()
626                // during decoding, so we only need to check the sum here.
627                let mut total_out: u64 = 0;
628                for output in &tx.outputs {
629                    total_out = total_out.saturating_add(output.amount.to_sat());
630                    if total_out > Amount::MAX_MONEY.to_sat() {
631                        return Err(E(Inner::OutputValueSumTooLarge(total_out)));
632                    }
633                }
634                Ok(tx)
635            }
636            State::Errored => panic!("call to end() after decoder errored"),
637        }
638    }
639
640    #[inline]
641    fn read_limit(&self) -> usize {
642        use TransactionDecoderState as State;
643
644        match &self.state {
645            State::Version(decoder) => decoder.read_limit(),
646            State::Inputs(_, _, decoder) => decoder.read_limit(),
647            State::SegwitFlag(_) => 1,
648            State::Outputs(_, _, _, decoder) => decoder.read_limit(),
649            State::Witnesses(_, _, _, _, decoder) => decoder.read_limit(),
650            State::LockTime(_, _, _, decoder) => decoder.read_limit(),
651            State::Done(_) => 0,
652            // `read_limit` is not documented to panic or return an error, so we
653            // return a dummy value if the decoder is in an error state.
654            State::Errored => 0,
655        }
656    }
657}
658
659#[cfg(feature = "alloc")]
660impl Decodable for Transaction {
661    type Decoder = TransactionDecoder;
662    fn decoder() -> Self::Decoder { TransactionDecoder::new() }
663}
664
665/// The state of the transiting decoder.
666#[cfg(feature = "alloc")]
667enum TransactionDecoderState {
668    /// Decoding the transaction version.
669    Version(VersionDecoder),
670    /// Decoding the transaction inputs.
671    Inputs(Version, Attempt, VecDecoder<TxIn>),
672    /// Decoding the segwit flag.
673    SegwitFlag(Version),
674    /// Decoding the transaction outputs.
675    Outputs(Version, Vec<TxIn>, IsSegwit, VecDecoder<TxOut>),
676    /// Decoding the segwit transaction witnesses.
677    Witnesses(Version, Vec<TxIn>, Vec<TxOut>, Iteration, WitnessDecoder),
678    /// Decoding the transaction lock time.
679    LockTime(Version, Vec<TxIn>, Vec<TxOut>, LockTimeDecoder),
680    /// Done decoding the [`Transaction`].
681    Done(Transaction),
682    /// When `end()`ing a sub-decoder, encountered an error which prevented us
683    /// from constructing the next sub-decoder.
684    Errored,
685}
686
687/// Boolean used to track number of times we have attempted to decode the inputs vector.
688#[cfg(feature = "alloc")]
689#[derive(Debug, Copy, Clone, PartialEq, Eq)]
690enum Attempt {
691    /// First time reading inputs.
692    First,
693    /// Second time reading inputs.
694    Second,
695}
696
697/// Boolean used to track whether or not this transaction uses segwit encoding.
698#[cfg(feature = "alloc")]
699#[derive(Debug, Copy, Clone, PartialEq, Eq)]
700enum IsSegwit {
701    /// Yes so uses segwit encoding.
702    Yes,
703    /// No segwit flag, marker, or witnesses.
704    No,
705}
706
707/// How many times we have state transitioned to encoding a witness (zero-based).
708#[cfg(feature = "alloc")]
709#[derive(Debug, Copy, Clone, PartialEq, Eq)]
710struct Iteration(usize);
711
712/// An error consensus decoding a `Transaction`.
713#[cfg(feature = "alloc")]
714#[derive(Debug, Clone, PartialEq, Eq)]
715pub struct TransactionDecoderError(TransactionDecoderErrorInner);
716
717#[cfg(feature = "alloc")]
718#[derive(Debug, Clone, PartialEq, Eq)]
719enum TransactionDecoderErrorInner {
720    /// Error while decoding the `version`.
721    Version(VersionDecoderError),
722    /// We only support segwit flag value 0x01.
723    UnsupportedSegwitFlag(u8),
724    /// Error while decoding the `inputs`.
725    Inputs(VecDecoderError<TxInDecoderError>),
726    /// Error while decoding the `outputs`.
727    Outputs(VecDecoderError<TxOutDecoderError>),
728    /// Error while decoding one of the witnesses.
729    Witness(WitnessDecoderError),
730    /// Non-empty Segwit transaction with no witnesses.
731    NoWitnesses,
732    /// Error while decoding the `lock_time`.
733    LockTime(LockTimeDecoderError),
734    /// Attempt to call `end()` before the transaction was complete. Holds
735    /// a description of the current state.
736    EarlyEnd(&'static str),
737    /// Null prevout in non-coinbase transaction.
738    NullPrevoutInNonCoinbase(usize),
739    /// Coinbase scriptSig too small (must be at least 2 bytes).
740    CoinbaseScriptSigTooSmall(usize),
741    /// Coinbase scriptSig is too large (must be at most 100 bytes).
742    CoinbaseScriptSigTooLarge(usize),
743    /// Transaction has duplicate inputs (this check prevents CVE-2018-17144 ).
744    DuplicateInput(OutPoint),
745    /// Sum of output values exceeds `MAX_MONEY`
746    OutputValueSumTooLarge(u64),
747    /// Transaction has no outputs.
748    NoOutputs,
749}
750
751#[cfg(feature = "alloc")]
752impl From<Infallible> for TransactionDecoderError {
753    fn from(never: Infallible) -> Self { match never {} }
754}
755
756#[cfg(feature = "alloc")]
757impl From<VersionDecoderError> for TransactionDecoderError {
758    fn from(e: VersionDecoderError) -> Self { Self(TransactionDecoderErrorInner::Version(e)) }
759}
760
761#[cfg(feature = "alloc")]
762impl From<VecDecoderError<TxInDecoderError>> for TransactionDecoderError {
763    fn from(e: VecDecoderError<TxInDecoderError>) -> Self {
764        Self(TransactionDecoderErrorInner::Inputs(e))
765    }
766}
767
768#[cfg(feature = "alloc")]
769impl From<VecDecoderError<TxOutDecoderError>> for TransactionDecoderError {
770    fn from(e: VecDecoderError<TxOutDecoderError>) -> Self {
771        Self(TransactionDecoderErrorInner::Outputs(e))
772    }
773}
774
775#[cfg(feature = "alloc")]
776impl From<WitnessDecoderError> for TransactionDecoderError {
777    fn from(e: WitnessDecoderError) -> Self { Self(TransactionDecoderErrorInner::Witness(e)) }
778}
779
780#[cfg(feature = "alloc")]
781impl From<LockTimeDecoderError> for TransactionDecoderError {
782    fn from(e: LockTimeDecoderError) -> Self { Self(TransactionDecoderErrorInner::LockTime(e)) }
783}
784
785#[cfg(feature = "alloc")]
786impl fmt::Display for TransactionDecoderError {
787    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
788        use TransactionDecoderErrorInner as E;
789
790        match self.0 {
791            E::Version(ref e) => write_err!(f, "transaction decoder error"; e),
792            E::UnsupportedSegwitFlag(v) => {
793                write!(f, "we only support segwit flag value 0x01: {}", v)
794            }
795            E::Inputs(ref e) => write_err!(f, "transaction decoder error"; e),
796            E::Outputs(ref e) => write_err!(f, "transaction decoder error"; e),
797            E::Witness(ref e) => write_err!(f, "transaction decoder error"; e),
798            E::NoWitnesses => write!(f, "non-empty Segwit transaction with no witnesses"),
799            E::LockTime(ref e) => write_err!(f, "transaction decoder error"; e),
800            E::EarlyEnd(s) => write!(f, "early end of transaction (still decoding {})", s),
801            E::NullPrevoutInNonCoinbase(index) =>
802                write!(f, "null prevout in non-coinbase transaction at input {}", index),
803            E::CoinbaseScriptSigTooSmall(len) =>
804                write!(f, "coinbase scriptSig too small: {} bytes (min 2)", len),
805            E::CoinbaseScriptSigTooLarge(len) =>
806                write!(f, "coinbase scriptSig too large: {} bytes (max 100)", len),
807            E::DuplicateInput(ref outpoint) =>
808                write!(f, "duplicate input: {:?}:{}", outpoint.txid, outpoint.vout),
809            E::OutputValueSumTooLarge(val) =>
810                write!(f, "sum of output values {} satoshis exceeds MAX_MONEY", val),
811            E::NoOutputs => write!(f, "transaction has no outputs"),
812        }
813    }
814}
815
816#[cfg(feature = "std")]
817#[cfg(feature = "alloc")]
818impl std::error::Error for TransactionDecoderError {
819    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
820        use TransactionDecoderErrorInner as E;
821
822        match self.0 {
823            E::Version(ref e) => Some(e),
824            E::UnsupportedSegwitFlag(_) => None,
825            E::Inputs(ref e) => Some(e),
826            E::Outputs(ref e) => Some(e),
827            E::Witness(ref e) => Some(e),
828            E::NoWitnesses => None,
829            E::LockTime(ref e) => Some(e),
830            E::EarlyEnd(_) => None,
831            E::NullPrevoutInNonCoinbase(_) => None,
832            E::CoinbaseScriptSigTooSmall(_) => None,
833            E::CoinbaseScriptSigTooLarge(_) => None,
834            E::DuplicateInput(_) => None,
835            E::OutputValueSumTooLarge(_) => None,
836            E::NoOutputs => None,
837        }
838    }
839}
840
841/// Bitcoin transaction input.
842///
843/// It contains the location of the previous transaction's output,
844/// that it spends and set of scripts that satisfy its spending
845/// conditions.
846///
847/// # Bitcoin Core References
848///
849/// * [CTxIn definition](https://github.com/bitcoin/bitcoin/blob/345457b542b6a980ccfbc868af0970a6f91d1b82/src/primitives/transaction.h#L65)
850#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
851#[cfg(feature = "alloc")]
852pub struct TxIn {
853    /// The reference to the previous output that is being used as an input.
854    pub previous_output: OutPoint,
855    /// The script which pushes values on the stack which will cause
856    /// the referenced output's script to be accepted.
857    pub script_sig: ScriptSigBuf,
858    /// The sequence number, which suggests to miners which of two
859    /// conflicting transactions should be preferred, or 0xFFFFFFFF
860    /// to ignore this feature. This is generally never used since
861    /// the miner behavior cannot be enforced.
862    pub sequence: Sequence,
863    /// Witness data: an array of byte-arrays.
864    /// Note that this field is *not* (de)serialized with the rest of the `TxIn` in
865    /// Encodable/Decodable, as it is (de)serialized at the end of the full
866    /// Transaction. It *is* (de)serialized with the rest of the `TxIn` in other
867    /// (de)serialization routines.
868    pub witness: Witness,
869}
870
871#[cfg(feature = "alloc")]
872impl TxIn {
873    /// An empty transaction input with the previous output as for a coinbase transaction.
874    ///
875    /// This has a 0-byte scriptSig which is **invalid** per consensus rules
876    /// (coinbase scriptSig must be 2-100 bytes). This is kept for backwards compatibility
877    /// in PSBT workflows where the scriptSig is filled in later.
878    pub const EMPTY_COINBASE: Self = Self {
879        previous_output: OutPoint::COINBASE_PREVOUT,
880        script_sig: ScriptSigBuf::new(),
881        sequence: Sequence::MAX,
882        witness: Witness::new(),
883    };
884}
885
886#[cfg(feature = "alloc")]
887encoding::encoder_newtype! {
888    /// The encoder for the [`TxIn`] type.
889    pub struct TxInEncoder<'e>(
890        Encoder3<OutPointEncoder<'e>, ScriptEncoder<'e>, SequenceEncoder<'e>>
891    );
892}
893
894#[cfg(feature = "alloc")]
895impl Encodable for TxIn {
896    type Encoder<'e>
897        = Encoder3<OutPointEncoder<'e>, ScriptEncoder<'e>, SequenceEncoder<'e>>
898    where
899        Self: 'e;
900
901    fn encoder(&self) -> Self::Encoder<'_> {
902        Encoder3::new(
903            self.previous_output.encoder(),
904            self.script_sig.encoder(),
905            self.sequence.encoder(),
906        )
907    }
908}
909
910/// Encodes the witnesses from a list of inputs.
911#[cfg(feature = "alloc")]
912pub struct WitnessesEncoder<'e> {
913    inputs: &'e [TxIn],
914    /// Encoder for the current witness being encoded.
915    cur_enc: Option<WitnessEncoder<'e>>,
916}
917
918#[cfg(feature = "alloc")]
919impl<'e> WitnessesEncoder<'e> {
920    /// Constructs a new encoder for all witnesses in a list of transaction inputs.
921    pub fn new(inputs: &'e [TxIn]) -> Self {
922        Self { inputs, cur_enc: inputs.first().map(|input| input.witness.encoder()) }
923    }
924}
925
926#[cfg(feature = "alloc")]
927impl Encoder for WitnessesEncoder<'_> {
928    #[inline]
929    fn current_chunk(&self) -> &[u8] {
930        self.cur_enc.as_ref().map(WitnessEncoder::current_chunk).unwrap_or_default()
931    }
932
933    #[inline]
934    fn advance(&mut self) -> bool {
935        let Some(cur) = self.cur_enc.as_mut() else {
936            return false;
937        };
938
939        loop {
940            // On subsequent calls, attempt to advance the current encoder and return
941            // success if this succeeds.
942            if cur.advance() {
943                return true;
944            }
945            // self.inputs guaranteed to be non-empty if cur_enc is non-None.
946            self.inputs = &self.inputs[1..];
947
948            // If advancing the current encoder failed, attempt to move to the next encoder.
949            if let Some(input) = self.inputs.first() {
950                *cur = input.witness.encoder();
951                if !cur.current_chunk().is_empty() {
952                    return true;
953                }
954            } else {
955                self.cur_enc = None; // shortcut the next call to advance()
956                return false;
957            }
958        }
959    }
960}
961
962#[cfg(feature = "alloc")]
963type TxInInnerDecoder = Decoder3<OutPointDecoder, ScriptSigBufDecoder, SequenceDecoder>;
964
965/// The decoder for the [`TxIn`] type.
966#[cfg(feature = "alloc")]
967pub struct TxInDecoder(TxInInnerDecoder);
968
969#[cfg(feature = "alloc")]
970impl Decoder for TxInDecoder {
971    type Output = TxIn;
972    type Error = TxInDecoderError;
973
974    #[inline]
975    fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
976        self.0.push_bytes(bytes).map_err(TxInDecoderError)
977    }
978
979    #[inline]
980    fn end(self) -> Result<Self::Output, Self::Error> {
981        let (previous_output, script_sig, sequence) = self.0.end().map_err(TxInDecoderError)?;
982        Ok(TxIn { previous_output, script_sig, sequence, witness: Witness::default() })
983    }
984
985    #[inline]
986    fn read_limit(&self) -> usize { self.0.read_limit() }
987}
988
989#[cfg(feature = "alloc")]
990impl Decodable for TxIn {
991    type Decoder = TxInDecoder;
992    fn decoder() -> Self::Decoder {
993        TxInDecoder(Decoder3::new(
994            OutPointDecoder::new(),
995            ScriptSigBufDecoder::new(),
996            SequenceDecoder::new(),
997        ))
998    }
999}
1000
1001/// An error consensus decoding a `TxIn`.
1002#[cfg(feature = "alloc")]
1003#[derive(Debug, Clone, PartialEq, Eq)]
1004pub struct TxInDecoderError(<TxInInnerDecoder as Decoder>::Error);
1005
1006#[cfg(feature = "alloc")]
1007impl From<Infallible> for TxInDecoderError {
1008    fn from(never: Infallible) -> Self { match never {} }
1009}
1010
1011#[cfg(feature = "alloc")]
1012impl fmt::Display for TxInDecoderError {
1013    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1014        match &self.0 {
1015            encoding::Decoder3Error::First(ref e) => write_err!(f, "txin decoder error"; e),
1016            encoding::Decoder3Error::Second(ref e) => write_err!(f, "txin decoder error"; e),
1017            encoding::Decoder3Error::Third(ref e) => write_err!(f, "txin decoder error"; e),
1018        }
1019    }
1020}
1021
1022#[cfg(feature = "alloc")]
1023#[cfg(feature = "std")]
1024impl std::error::Error for TxInDecoderError {
1025    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1026        match &self.0 {
1027            encoding::Decoder3Error::First(ref e) => Some(e),
1028            encoding::Decoder3Error::Second(ref e) => Some(e),
1029            encoding::Decoder3Error::Third(ref e) => Some(e),
1030        }
1031    }
1032}
1033
1034/// Bitcoin transaction output.
1035///
1036/// Defines new coins to be created as a result of the transaction,
1037/// along with spending conditions ("script", aka "output script"),
1038/// which an input spending it must satisfy.
1039///
1040/// An output that is not yet spent by an input is called Unspent Transaction Output ("UTXO").
1041///
1042/// # Bitcoin Core References
1043///
1044/// * [CTxOut definition](https://github.com/bitcoin/bitcoin/blob/345457b542b6a980ccfbc868af0970a6f91d1b82/src/primitives/transaction.h#L148)
1045#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
1046#[cfg(feature = "alloc")]
1047pub struct TxOut {
1048    /// The value of the output.
1049    pub amount: Amount,
1050    /// The script which must be satisfied for the output to be spent.
1051    pub script_pubkey: ScriptPubKeyBuf,
1052}
1053
1054#[cfg(feature = "alloc")]
1055encoding::encoder_newtype! {
1056    /// The encoder for the [`TxOut`] type.
1057    pub struct TxOutEncoder<'e>(Encoder2<AmountEncoder<'e>, ScriptEncoder<'e>>);
1058}
1059
1060#[cfg(feature = "alloc")]
1061impl Encodable for TxOut {
1062    type Encoder<'e>
1063        = Encoder2<AmountEncoder<'e>, ScriptEncoder<'e>>
1064    where
1065        Self: 'e;
1066
1067    fn encoder(&self) -> Self::Encoder<'_> {
1068        Encoder2::new(self.amount.encoder(), self.script_pubkey.encoder())
1069    }
1070}
1071
1072#[cfg(feature = "alloc")]
1073type TxOutInnerDecoder = Decoder2<AmountDecoder, ScriptPubKeyBufDecoder>;
1074
1075/// The decoder for the [`TxOut`] type.
1076#[cfg(feature = "alloc")]
1077pub struct TxOutDecoder(TxOutInnerDecoder);
1078
1079#[cfg(feature = "alloc")]
1080impl Decoder for TxOutDecoder {
1081    type Output = TxOut;
1082    type Error = TxOutDecoderError;
1083
1084    #[inline]
1085    fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
1086        self.0.push_bytes(bytes).map_err(TxOutDecoderError)
1087    }
1088
1089    #[inline]
1090    fn end(self) -> Result<Self::Output, Self::Error> {
1091        let (amount, script_pubkey) = self.0.end().map_err(TxOutDecoderError)?;
1092        Ok(TxOut { amount, script_pubkey })
1093    }
1094
1095    #[inline]
1096    fn read_limit(&self) -> usize { self.0.read_limit() }
1097}
1098
1099#[cfg(feature = "alloc")]
1100impl Decodable for TxOut {
1101    type Decoder = TxOutDecoder;
1102    fn decoder() -> Self::Decoder {
1103        TxOutDecoder(Decoder2::new(AmountDecoder::new(), ScriptPubKeyBufDecoder::new()))
1104    }
1105}
1106
1107/// An error consensus decoding a `TxOut`.
1108#[cfg(feature = "alloc")]
1109#[derive(Debug, Clone, PartialEq, Eq)]
1110pub struct TxOutDecoderError(<TxOutInnerDecoder as Decoder>::Error);
1111
1112#[cfg(feature = "alloc")]
1113impl From<Infallible> for TxOutDecoderError {
1114    fn from(never: Infallible) -> Self { match never {} }
1115}
1116
1117#[cfg(feature = "alloc")]
1118impl fmt::Display for TxOutDecoderError {
1119    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1120        match &self.0 {
1121            encoding::Decoder2Error::First(ref e) => write_err!(f, "txout decoder error"; e),
1122            encoding::Decoder2Error::Second(ref e) => write_err!(f, "txout decoder error"; e),
1123        }
1124    }
1125}
1126
1127#[cfg(feature = "std")]
1128impl std::error::Error for TxOutDecoderError {
1129    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1130        match &self.0 {
1131            encoding::Decoder2Error::First(ref e) => Some(e),
1132            encoding::Decoder2Error::Second(ref e) => Some(e),
1133        }
1134    }
1135}
1136
1137/// A reference to a transaction output.
1138///
1139/// # Bitcoin Core References
1140///
1141/// * [COutPoint definition](https://github.com/bitcoin/bitcoin/blob/345457b542b6a980ccfbc868af0970a6f91d1b82/src/primitives/transaction.h#L26)
1142#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
1143pub struct OutPoint {
1144    /// The referenced transaction's txid.
1145    pub txid: Txid,
1146    /// The index of the referenced output in its transaction's vout.
1147    pub vout: u32,
1148}
1149
1150impl OutPoint {
1151    /// The number of bytes that an outpoint contributes to the size of a transaction.
1152    pub const SIZE: usize = 32 + 4; // The serialized lengths of txid and vout.
1153
1154    /// The `OutPoint` used in a coinbase prevout.
1155    ///
1156    /// This is used as the dummy input for coinbase transactions because they don't have any
1157    /// previous outputs. In other words, does not point to a real transaction.
1158    pub const COINBASE_PREVOUT: Self = Self { txid: Txid::COINBASE_PREVOUT, vout: u32::MAX };
1159}
1160
1161encoding::encoder_newtype_exact! {
1162    /// The encoder for the [`OutPoint`] type.
1163    pub struct OutPointEncoder<'e>(Encoder2<BytesEncoder<'e>, ArrayEncoder<4>>);
1164}
1165
1166impl Encodable for OutPoint {
1167    type Encoder<'e>
1168        = OutPointEncoder<'e>
1169    where
1170        Self: 'e;
1171
1172    fn encoder(&self) -> Self::Encoder<'_> {
1173        OutPointEncoder::new(Encoder2::new(
1174            BytesEncoder::without_length_prefix(self.txid.as_byte_array()),
1175            ArrayEncoder::without_length_prefix(self.vout.to_le_bytes()),
1176        ))
1177    }
1178}
1179
1180#[cfg(feature = "hex")]
1181impl fmt::Display for OutPoint {
1182    #[inline]
1183    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1184        write!(f, "{}:{}", self.txid, self.vout)
1185    }
1186}
1187
1188#[cfg(feature = "alloc")]
1189#[cfg(feature = "hex")]
1190impl core::str::FromStr for OutPoint {
1191    type Err = ParseOutPointError;
1192
1193    fn from_str(s: &str) -> Result<Self, Self::Err> {
1194        if s.len() > 75 {
1195            // 64 + 1 + 10
1196            return Err(ParseOutPointError::TooLong);
1197        }
1198        let find = s.find(':');
1199        if find.is_none() || find != s.rfind(':') {
1200            return Err(ParseOutPointError::Format);
1201        }
1202        let colon = find.unwrap();
1203        if colon == 0 || colon == s.len() - 1 {
1204            return Err(ParseOutPointError::Format);
1205        }
1206        Ok(Self {
1207            txid: s[..colon].parse().map_err(ParseOutPointError::Txid)?,
1208            vout: parse_vout(&s[colon + 1..])?,
1209        })
1210    }
1211}
1212
1213/// Parses a string-encoded transaction index (vout).
1214///
1215/// Does not permit leading zeroes or non-digit characters.
1216#[cfg(feature = "alloc")]
1217#[cfg(feature = "hex")]
1218fn parse_vout(s: &str) -> Result<u32, ParseOutPointError> {
1219    if s.len() > 1 {
1220        let first = s.chars().next().unwrap();
1221        if first == '0' || first == '+' {
1222            return Err(ParseOutPointError::VoutNotCanonical);
1223        }
1224    }
1225    parse_int::int_from_str(s).map_err(ParseOutPointError::Vout)
1226}
1227
1228/// The decoder for the [`OutPoint`] type.
1229// 32 for the txid + 4 for the vout
1230pub struct OutPointDecoder(encoding::ArrayDecoder<36>);
1231
1232impl OutPointDecoder {
1233    /// Constructs a new [`OutPoint`] decoder.
1234    pub const fn new() -> Self { Self(encoding::ArrayDecoder::new()) }
1235}
1236
1237impl Default for OutPointDecoder {
1238    fn default() -> Self { Self::new() }
1239}
1240
1241impl encoding::Decoder for OutPointDecoder {
1242    type Output = OutPoint;
1243    type Error = OutPointDecoderError;
1244
1245    #[inline]
1246    fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
1247        self.0.push_bytes(bytes).map_err(OutPointDecoderError)
1248    }
1249
1250    #[inline]
1251    fn end(self) -> Result<Self::Output, Self::Error> {
1252        let encoded = self.0.end().map_err(OutPointDecoderError)?;
1253        let (txid_buf, vout_buf) = encoded.split_array::<32, 4>();
1254
1255        let txid = Txid::from_byte_array(*txid_buf);
1256        let vout = u32::from_le_bytes(*vout_buf);
1257
1258        Ok(OutPoint { txid, vout })
1259    }
1260
1261    #[inline]
1262    fn read_limit(&self) -> usize { self.0.read_limit() }
1263}
1264
1265impl encoding::Decodable for OutPoint {
1266    type Decoder = OutPointDecoder;
1267    fn decoder() -> Self::Decoder { OutPointDecoder::default() }
1268}
1269
1270/// Error while decoding an `OutPoint`.
1271#[derive(Debug, Clone, PartialEq, Eq)]
1272pub struct OutPointDecoderError(UnexpectedEofError);
1273
1274impl core::fmt::Display for OutPointDecoderError {
1275    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1276        write_err!(f, "out point decoder error"; self.0)
1277    }
1278}
1279
1280#[cfg(feature = "std")]
1281impl std::error::Error for OutPointDecoderError {
1282    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
1283}
1284
1285#[cfg(feature = "serde")]
1286impl Serialize for OutPoint {
1287    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1288    where
1289        S: Serializer,
1290    {
1291        if serializer.is_human_readable() {
1292            serializer.collect_str(&self)
1293        } else {
1294            use crate::serde::ser::SerializeStruct as _;
1295
1296            let mut state = serializer.serialize_struct("OutPoint", 2)?;
1297            // serializing as an array was found in the past to break for some serializers so we use
1298            // a slice instead. This causes 8 bytes to be prepended for the length (even though this
1299            // is a bit silly because know the length).
1300            state.serialize_field("txid", self.txid.as_byte_array().as_slice())?;
1301            state.serialize_field("vout", &self.vout.to_le_bytes())?;
1302            state.end()
1303        }
1304    }
1305}
1306
1307#[cfg(feature = "serde")]
1308impl<'de> Deserialize<'de> for OutPoint {
1309    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1310    where
1311        D: Deserializer<'de>,
1312    {
1313        if deserializer.is_human_readable() {
1314            struct StringVisitor;
1315
1316            impl de::Visitor<'_> for StringVisitor {
1317                type Value = OutPoint;
1318
1319                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1320                    formatter.write_str("a string in format 'txid:vout'")
1321                }
1322
1323                fn visit_str<E>(self, value: &str) -> Result<OutPoint, E>
1324                where
1325                    E: de::Error,
1326                {
1327                    value.parse::<OutPoint>().map_err(de::Error::custom)
1328                }
1329            }
1330
1331            deserializer.deserialize_str(StringVisitor)
1332        } else {
1333            #[derive(Deserialize)]
1334            #[serde(field_identifier, rename_all = "lowercase")]
1335            enum Field {
1336                Txid,
1337                Vout,
1338            }
1339
1340            struct OutPointVisitor;
1341
1342            impl<'de> de::Visitor<'de> for OutPointVisitor {
1343                type Value = OutPoint;
1344
1345                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1346                    formatter.write_str("OutPoint struct with fields")
1347                }
1348
1349                fn visit_seq<V>(self, mut seq: V) -> Result<OutPoint, V::Error>
1350                where
1351                    V: de::SeqAccess<'de>,
1352                {
1353                    let txid =
1354                        seq.next_element()?.ok_or_else(|| de::Error::invalid_length(0, &self))?;
1355                    let vout =
1356                        seq.next_element()?.ok_or_else(|| de::Error::invalid_length(1, &self))?;
1357                    Ok(OutPoint { txid, vout })
1358                }
1359
1360                fn visit_map<V>(self, mut map: V) -> Result<OutPoint, V::Error>
1361                where
1362                    V: de::MapAccess<'de>,
1363                {
1364                    let mut txid = None;
1365                    let mut vout = None;
1366
1367                    while let Some(key) = map.next_key()? {
1368                        match key {
1369                            Field::Txid => {
1370                                if txid.is_some() {
1371                                    return Err(de::Error::duplicate_field("txid"));
1372                                }
1373                                let bytes: [u8; 32] = map.next_value()?;
1374                                txid = Some(Txid::from_byte_array(bytes));
1375                            }
1376                            Field::Vout => {
1377                                if vout.is_some() {
1378                                    return Err(de::Error::duplicate_field("vout"));
1379                                }
1380                                let bytes: [u8; 4] = map.next_value()?;
1381                                vout = Some(u32::from_le_bytes(bytes));
1382                            }
1383                        }
1384                    }
1385
1386                    let txid = txid.ok_or_else(|| de::Error::missing_field("txid"))?;
1387                    let vout = vout.ok_or_else(|| de::Error::missing_field("vout"))?;
1388
1389                    Ok(OutPoint { txid, vout })
1390                }
1391            }
1392
1393            const FIELDS: &[&str] = &["txid", "vout"];
1394            deserializer.deserialize_struct("OutPoint", FIELDS, OutPointVisitor)
1395        }
1396    }
1397}
1398
1399/// An error in parsing an [`OutPoint`].
1400#[derive(Debug, Clone, PartialEq, Eq)]
1401#[non_exhaustive]
1402#[cfg(feature = "alloc")]
1403#[cfg(feature = "hex")]
1404pub enum ParseOutPointError {
1405    /// Error in TXID part.
1406    Txid(hex::DecodeFixedLengthBytesError),
1407    /// Error in vout part.
1408    Vout(parse_int::ParseIntError),
1409    /// Error in general format.
1410    Format,
1411    /// Size exceeds max.
1412    TooLong,
1413    /// Vout part is not strictly numeric without leading zeroes.
1414    VoutNotCanonical,
1415}
1416
1417#[cfg(feature = "alloc")]
1418#[cfg(feature = "hex")]
1419impl From<Infallible> for ParseOutPointError {
1420    #[inline]
1421    fn from(never: Infallible) -> Self { match never {} }
1422}
1423
1424#[cfg(feature = "alloc")]
1425#[cfg(feature = "hex")]
1426impl fmt::Display for ParseOutPointError {
1427    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1428        match *self {
1429            Self::Txid(ref e) => write_err!(f, "error parsing TXID"; e),
1430            Self::Vout(ref e) => write_err!(f, "error parsing vout"; e),
1431            Self::Format => write!(f, "OutPoint not in <txid>:<vout> format"),
1432            Self::TooLong => write!(f, "vout should be at most 10 digits"),
1433            Self::VoutNotCanonical => write!(f, "no leading zeroes or + allowed in vout part"),
1434        }
1435    }
1436}
1437
1438#[cfg(feature = "std")]
1439#[cfg(feature = "hex")]
1440impl std::error::Error for ParseOutPointError {
1441    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1442        match self {
1443            Self::Txid(e) => Some(e),
1444            Self::Vout(e) => Some(e),
1445            Self::Format | Self::TooLong | Self::VoutNotCanonical => None,
1446        }
1447    }
1448}
1449
1450/// The transaction version.
1451///
1452/// Currently, as specified by [BIP-0068] and [BIP-0431], version 1, 2, and 3 are considered standard.
1453///
1454/// Standardness of the inner `u32` is not an invariant because you are free to create transactions
1455/// of any version, transactions with non-standard version numbers will not be relayed by the
1456/// Bitcoin network.
1457///
1458/// [BIP-0068]: https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki
1459/// [BIP-0431]: https://github.com/bitcoin/bips/blob/master/bip-0431.mediawiki
1460#[derive(Copy, PartialEq, Eq, Clone, Debug, PartialOrd, Ord, Hash)]
1461#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1462pub struct Version(u32);
1463
1464impl Version {
1465    /// The original Bitcoin transaction version (pre-BIP-0068).
1466    pub const ONE: Self = Self(1);
1467
1468    /// The second Bitcoin transaction version (post-BIP-0068).
1469    pub const TWO: Self = Self(2);
1470
1471    /// The third Bitcoin transaction version (post-BIP-0431).
1472    pub const THREE: Self = Self(3);
1473
1474    /// Constructs a potentially non-standard transaction version.
1475    ///
1476    /// This can accept both standard and non-standard versions.
1477    #[inline]
1478    pub const fn maybe_non_standard(version: u32) -> Self { Self(version) }
1479
1480    /// Returns the inner `u32` value of this `Version`.
1481    #[inline]
1482    pub const fn to_u32(self) -> u32 { self.0 }
1483
1484    /// Returns true if this transaction version number is considered standard.
1485    ///
1486    /// The behavior of this method matches whatever Bitcoin Core considers standard at the time
1487    /// of the release and may change in future versions to accommodate new standard versions.
1488    /// As of Bitcoin Core 28.0 ([release notes](https://bitcoincore.org/en/releases/28.0/)),
1489    /// versions 1, 2, and 3 are considered standard.
1490    #[inline]
1491    pub const fn is_standard(self) -> bool {
1492        self.0 == Self::ONE.0 || self.0 == Self::TWO.0 || self.0 == Self::THREE.0
1493    }
1494}
1495
1496impl fmt::Display for Version {
1497    #[inline]
1498    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
1499}
1500
1501impl fmt::LowerHex for Version {
1502    #[inline]
1503    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(&self.0, f) }
1504}
1505
1506impl fmt::UpperHex for Version {
1507    #[inline]
1508    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::UpperHex::fmt(&self.0, f) }
1509}
1510
1511impl fmt::Octal for Version {
1512    #[inline]
1513    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Octal::fmt(&self.0, f) }
1514}
1515
1516impl fmt::Binary for Version {
1517    #[inline]
1518    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Binary::fmt(&self.0, f) }
1519}
1520
1521impl From<Version> for u32 {
1522    #[inline]
1523    fn from(version: Version) -> Self { version.0 }
1524}
1525
1526encoding::encoder_newtype_exact! {
1527    /// The encoder for the [`Version`] type.
1528    pub struct VersionEncoder<'e>(encoding::ArrayEncoder<4>);
1529}
1530
1531impl encoding::Encodable for Version {
1532    type Encoder<'e> = VersionEncoder<'e>;
1533    fn encoder(&self) -> Self::Encoder<'_> {
1534        VersionEncoder::new(encoding::ArrayEncoder::without_length_prefix(
1535            self.to_u32().to_le_bytes(),
1536        ))
1537    }
1538}
1539
1540/// The decoder for the [`Version`] type.
1541pub struct VersionDecoder(encoding::ArrayDecoder<4>);
1542
1543impl VersionDecoder {
1544    /// Constructs a new [`Version`] decoder.
1545    pub const fn new() -> Self { Self(encoding::ArrayDecoder::new()) }
1546}
1547
1548impl Default for VersionDecoder {
1549    fn default() -> Self { Self::new() }
1550}
1551
1552impl encoding::Decoder for VersionDecoder {
1553    type Output = Version;
1554    type Error = VersionDecoderError;
1555
1556    #[inline]
1557    fn push_bytes(&mut self, bytes: &mut &[u8]) -> Result<bool, Self::Error> {
1558        self.0.push_bytes(bytes).map_err(VersionDecoderError)
1559    }
1560
1561    #[inline]
1562    fn end(self) -> Result<Self::Output, Self::Error> {
1563        let bytes = self.0.end().map_err(VersionDecoderError)?;
1564        let n = u32::from_le_bytes(bytes);
1565        Ok(Version::maybe_non_standard(n))
1566    }
1567
1568    #[inline]
1569    fn read_limit(&self) -> usize { self.0.read_limit() }
1570}
1571
1572impl encoding::Decodable for Version {
1573    type Decoder = VersionDecoder;
1574    fn decoder() -> Self::Decoder { VersionDecoder(encoding::ArrayDecoder::<4>::new()) }
1575}
1576
1577/// An error consensus decoding an `Version`.
1578#[derive(Debug, Clone, PartialEq, Eq)]
1579pub struct VersionDecoderError(encoding::UnexpectedEofError);
1580
1581impl From<Infallible> for VersionDecoderError {
1582    fn from(never: Infallible) -> Self { match never {} }
1583}
1584
1585impl fmt::Display for VersionDecoderError {
1586    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1587        write_err!(f, "version decoder error"; self.0)
1588    }
1589}
1590
1591#[cfg(feature = "std")]
1592impl std::error::Error for VersionDecoderError {
1593    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) }
1594}
1595
1596#[cfg(feature = "arbitrary")]
1597#[cfg(feature = "alloc")]
1598impl<'a> Arbitrary<'a> for Transaction {
1599    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
1600        Ok(Self {
1601            version: Version::arbitrary(u)?,
1602            lock_time: absolute::LockTime::arbitrary(u)?,
1603            inputs: Vec::<TxIn>::arbitrary(u)?,
1604            outputs: Vec::<TxOut>::arbitrary(u)?,
1605        })
1606    }
1607}
1608
1609#[cfg(feature = "arbitrary")]
1610#[cfg(feature = "alloc")]
1611impl<'a> Arbitrary<'a> for TxIn {
1612    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
1613        Ok(Self {
1614            previous_output: OutPoint::arbitrary(u)?,
1615            script_sig: ScriptSigBuf::arbitrary(u)?,
1616            sequence: Sequence::arbitrary(u)?,
1617            witness: Witness::arbitrary(u)?,
1618        })
1619    }
1620}
1621
1622#[cfg(feature = "arbitrary")]
1623#[cfg(feature = "alloc")]
1624impl<'a> Arbitrary<'a> for TxOut {
1625    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
1626        Ok(Self { amount: Amount::arbitrary(u)?, script_pubkey: ScriptPubKeyBuf::arbitrary(u)? })
1627    }
1628}
1629
1630#[cfg(feature = "arbitrary")]
1631impl<'a> Arbitrary<'a> for OutPoint {
1632    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
1633        Ok(Self { txid: Txid::arbitrary(u)?, vout: u32::arbitrary(u)? })
1634    }
1635}
1636
1637#[cfg(feature = "arbitrary")]
1638impl<'a> Arbitrary<'a> for Version {
1639    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
1640        // Equally weight the case of normal version numbers
1641        let choice = u.int_in_range(0..=3)?;
1642        match choice {
1643            0 => Ok(Self::ONE),
1644            1 => Ok(Self::TWO),
1645            2 => Ok(Self::THREE),
1646            _ => Ok(Self(u.arbitrary()?)),
1647        }
1648    }
1649}
1650
1651#[cfg(feature = "alloc")]
1652#[cfg(test)]
1653mod tests {
1654    #[cfg(feature = "hex")]
1655    use alloc::string::ToString;
1656    use alloc::{format, vec};
1657    #[cfg(feature = "hex")]
1658    use core::str::FromStr as _;
1659
1660    use encoding::Encoder as _;
1661    #[cfg(feature = "hex")]
1662    use hex_lit::hex;
1663
1664    use super::*;
1665    #[cfg(all(feature = "alloc", feature = "hex"))]
1666    use crate::absolute::LockTime;
1667
1668    #[test]
1669    #[cfg(feature = "alloc")]
1670    #[cfg(feature = "hex")]
1671    fn transaction_encode_decode_roundtrip() {
1672        // Create two different inputs to avoid duplicate input rejection
1673        let tx_in_1 = segwit_tx_in();
1674        let mut tx_in_2 = segwit_tx_in();
1675        tx_in_2.previous_output.vout = 2;
1676
1677        let tx = Transaction {
1678            version: Version::TWO,
1679            lock_time: absolute::LockTime::ZERO,
1680            inputs: vec![tx_in_1, tx_in_2],
1681            outputs: vec![tx_out(), tx_out()],
1682        };
1683
1684        let encoded = encoding::encode_to_vec(&tx);
1685
1686        let mut decoder = Transaction::decoder();
1687        let mut slice = encoded.as_slice();
1688        decoder.push_bytes(&mut slice).unwrap();
1689        let decoded = decoder.end().unwrap();
1690
1691        assert_eq!(tx, decoded);
1692    }
1693
1694    #[test]
1695    fn sanity_check() {
1696        let version = Version(123);
1697        assert_eq!(version.to_u32(), 123);
1698        assert_eq!(u32::from(version), 123);
1699
1700        assert!(!version.is_standard());
1701        assert!(Version::ONE.is_standard());
1702        assert!(Version::TWO.is_standard());
1703        assert!(Version::THREE.is_standard());
1704    }
1705
1706    #[test]
1707    fn transaction_functions() {
1708        let txin = TxIn {
1709            previous_output: OutPoint {
1710                txid: Txid::from_byte_array([0xAA; 32]), // Arbitrary invalid dummy value.
1711                vout: 0,
1712            },
1713            script_sig: ScriptSigBuf::new(),
1714            sequence: Sequence::MAX,
1715            witness: Witness::new(),
1716        };
1717
1718        let txout = TxOut {
1719            amount: Amount::from_sat(123_456_789).unwrap(),
1720            script_pubkey: ScriptPubKeyBuf::new(),
1721        };
1722
1723        let tx_orig = Transaction {
1724            version: Version::ONE,
1725            lock_time: absolute::LockTime::from_consensus(1_738_968_231), // The time this was written
1726            inputs: vec![txin],
1727            outputs: vec![txout],
1728        };
1729
1730        // Test changing the transaction
1731        let mut tx = tx_orig.clone();
1732        tx.inputs[0].previous_output.txid = Txid::from_byte_array([0xFF; 32]);
1733        tx.outputs[0].amount = Amount::from_sat(987_654_321).unwrap();
1734        assert_eq!(tx.inputs[0].previous_output.txid.to_byte_array(), [0xFF; 32]);
1735        assert_eq!(tx.outputs[0].amount.to_sat(), 987_654_321);
1736
1737        // Test uses_segwit_serialization
1738        assert!(!tx.uses_segwit_serialization());
1739        tx.inputs[0].witness.push(vec![0xAB, 0xCD, 0xEF]);
1740        assert!(tx.uses_segwit_serialization());
1741
1742        // Test partial ord
1743        assert!(tx > tx_orig);
1744    }
1745
1746    #[test]
1747    #[cfg(feature = "hex")]
1748    fn transaction_hex_display() {
1749        let txin = TxIn {
1750            previous_output: OutPoint {
1751                txid: Txid::from_byte_array([0xAA; 32]), // Arbitrary invalid dummy value.
1752                vout: 0,
1753            },
1754            script_sig: ScriptSigBuf::new(),
1755            sequence: Sequence::MAX,
1756            witness: Witness::new(),
1757        };
1758
1759        let txout = TxOut {
1760            amount: Amount::from_sat(123_456_789).unwrap(),
1761            script_pubkey: ScriptPubKeyBuf::new(),
1762        };
1763
1764        let tx_orig = Transaction {
1765            version: Version::ONE,
1766            lock_time: absolute::LockTime::from_consensus(1_765_112_030), // The time this was written
1767            inputs: vec![txin],
1768            outputs: vec![txout],
1769        };
1770
1771        let encoded_tx = "0100000001aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0000000000ffffffff0115cd5b070000000000de783569";
1772        let lower_hex_tx = format!("{:x}", tx_orig);
1773        let upper_hex_tx = format!("{:X}", tx_orig);
1774
1775        // All of these should yield a lowercase hex
1776        assert_eq!(encoded_tx, lower_hex_tx);
1777        assert_eq!(encoded_tx, format!("{}", tx_orig));
1778
1779        // And this should yield uppercase hex
1780        let upper_encoded = encoded_tx
1781            .chars()
1782            .map(|chr| chr.to_ascii_uppercase())
1783            .collect::<alloc::string::String>();
1784        assert_eq!(upper_encoded, upper_hex_tx);
1785    }
1786
1787    #[test]
1788    #[cfg(feature = "hex")]
1789    fn transaction_from_hex_str_round_trip() {
1790        // Create two different inputs to avoid duplicate input rejection
1791        let tx_in_1 = segwit_tx_in();
1792        let mut tx_in_2 = segwit_tx_in();
1793        tx_in_2.previous_output.vout = 2;
1794
1795        // Create a transaction and convert it to a hex string
1796        let tx = Transaction {
1797            version: Version::TWO,
1798            lock_time: absolute::LockTime::ZERO,
1799            inputs: vec![tx_in_1, tx_in_2],
1800            outputs: vec![tx_out(), tx_out()],
1801        };
1802
1803        let lower_hex_tx = format!("{:x}", tx);
1804        let upper_hex_tx = format!("{:X}", tx);
1805
1806        // Parse the hex strings back into transactions
1807        let parsed_lower = Transaction::from_str(&lower_hex_tx).unwrap();
1808        let parsed_upper = Transaction::from_str(&upper_hex_tx).unwrap();
1809
1810        // The parsed transaction should match the originals
1811        assert_eq!(tx, parsed_lower);
1812        assert_eq!(tx, parsed_upper);
1813    }
1814
1815    #[test]
1816    #[cfg(feature = "hex")]
1817    fn transaction_from_hex_str_error() {
1818        use crate::ParsePrimitiveError;
1819
1820        // OddLengthString error
1821        let odd = "abc"; // 3 chars, odd length
1822        let err = Transaction::from_str(odd).unwrap_err();
1823        assert!(matches!(err, ParseTransactionError(ParsePrimitiveError::OddLengthString(..))));
1824
1825        // InvalidChar error
1826        let invalid = "zz";
1827        let err = Transaction::from_str(invalid).unwrap_err();
1828        assert!(matches!(err, ParseTransactionError(ParsePrimitiveError::InvalidChar(..))));
1829
1830        // Decode error
1831        let bad = "deadbeef00"; // arbitrary even-length hex that will fail decoding
1832        let err = Transaction::from_str(bad).unwrap_err();
1833        assert!(matches!(err, ParseTransactionError(ParsePrimitiveError::Decode(..))));
1834    }
1835
1836    #[test]
1837    #[cfg(feature = "hex")]
1838    fn outpoint_from_str() {
1839        // Check format errors
1840        let mut outpoint_str = "0".repeat(64); // No ":"
1841        let outpoint: Result<OutPoint, ParseOutPointError> = outpoint_str.parse();
1842        assert_eq!(outpoint, Err(ParseOutPointError::Format));
1843
1844        outpoint_str.push(':'); // Empty vout
1845        let outpoint: Result<OutPoint, ParseOutPointError> = outpoint_str.parse();
1846        assert_eq!(outpoint, Err(ParseOutPointError::Format));
1847
1848        outpoint_str.push('0'); // Correct format
1849        let outpoint: OutPoint = outpoint_str.parse().unwrap();
1850        assert_eq!(outpoint.txid, Txid::from_byte_array([0; 32]));
1851        assert_eq!(outpoint.vout, 0);
1852
1853        // Check the number of bytes OutPoint contributes to the transaction is equal to SIZE
1854        let outpoint_size = outpoint.txid.as_byte_array().len() + outpoint.vout.to_le_bytes().len();
1855        assert_eq!(outpoint_size, OutPoint::SIZE);
1856    }
1857
1858    #[test]
1859    #[cfg(feature = "hex")]
1860    fn outpoint_from_str_too_long() {
1861        // Check edge case: length exactly 75
1862        let mut outpoint_str = "0".repeat(64);
1863        outpoint_str.push_str(":1234567890");
1864        assert_eq!(outpoint_str.len(), 75);
1865        assert!(outpoint_str.parse::<OutPoint>().is_ok());
1866
1867        // Check TooLong error (length 76)
1868        outpoint_str.push('0');
1869        assert_eq!(outpoint_str.len(), 76);
1870        let outpoint: Result<OutPoint, ParseOutPointError> = outpoint_str.parse();
1871        assert_eq!(outpoint, Err(ParseOutPointError::TooLong));
1872    }
1873
1874    #[test]
1875    #[cfg(feature = "hex")]
1876    fn canonical_vout() {
1877        assert_eq!(parse_vout("0").unwrap(), 0);
1878        assert_eq!(parse_vout("1").unwrap(), 1);
1879        assert!(parse_vout("01").is_err()); // Leading zero not allowed
1880        assert!(parse_vout("+1").is_err()); // Non digits not allowed
1881    }
1882
1883    #[test]
1884    #[cfg(feature = "alloc")]
1885    #[cfg(feature = "hex")]
1886    fn outpoint_display_roundtrip() {
1887        let outpoint_str = "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20:1";
1888        let outpoint: OutPoint = outpoint_str.parse().unwrap();
1889        assert_eq!(format!("{}", outpoint), outpoint_str);
1890    }
1891
1892    #[test]
1893    fn version_display() {
1894        let version = Version(123);
1895        assert_eq!(format!("{}", version), "123");
1896        assert_eq!(format!("{:x}", version), "7b");
1897        assert_eq!(format!("{:#x}", version), "0x7b");
1898        assert_eq!(format!("{:X}", version), "7B");
1899        assert_eq!(format!("{:#X}", version), "0x7B");
1900        assert_eq!(format!("{:o}", version), "173");
1901        assert_eq!(format!("{:#o}", version), "0o173");
1902        assert_eq!(format!("{:b}", version), "1111011");
1903        assert_eq!(format!("{:#b}", version), "0b1111011");
1904    }
1905
1906    // Creates an arbitrary dummy outpoint.
1907    #[cfg(any(feature = "hex", feature = "serde"))]
1908    fn tc_out_point() -> OutPoint {
1909        let s = "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20:1";
1910        s.parse::<OutPoint>().unwrap()
1911    }
1912
1913    #[test]
1914    #[cfg(feature = "serde")]
1915    fn out_point_serde_deserialize_human_readable() {
1916        // `sered` serialization is the same as `Display` but includes quotes.
1917        let ser = "\"0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20:1\"";
1918        let got = serde_json::from_str::<OutPoint>(ser).unwrap();
1919        let want = tc_out_point();
1920
1921        assert_eq!(got, want);
1922    }
1923
1924    #[test]
1925    #[cfg(feature = "serde")]
1926    fn out_point_serde_deserialize_non_human_readable() {
1927        #[rustfmt::skip]
1928        let bytes = [
1929            // Length, prepended by the `serde` infrastructure because we use
1930            // slice serialization instead of array even though we know the length.
1931            32, 0, 0, 0, 0, 0, 0, 0,
1932            // The txid bytes
1933            32, 31, 30, 29, 28, 27, 26, 25,
1934            24, 23, 22, 21, 20, 19, 18, 17,
1935            16, 15, 14, 13, 12, 11, 10, 9,
1936            8, 7, 6, 5, 4, 3, 2, 1,
1937            // The vout
1938            1, 0, 0, 0
1939        ];
1940
1941        let got = bincode::deserialize::<OutPoint>(&bytes).unwrap();
1942        let want = tc_out_point();
1943
1944        assert_eq!(got, want);
1945    }
1946
1947    #[test]
1948    #[cfg(feature = "serde")]
1949    fn out_point_serde_human_readable_rountrips() {
1950        let out_point = tc_out_point();
1951
1952        let ser = serde_json::to_string(&out_point).unwrap();
1953        let got = serde_json::from_str::<OutPoint>(&ser).unwrap();
1954
1955        assert_eq!(got, out_point);
1956    }
1957
1958    #[test]
1959    #[cfg(feature = "serde")]
1960    fn out_point_serde_non_human_readable_rountrips() {
1961        let out_point = tc_out_point();
1962
1963        let ser = bincode::serialize(&out_point).unwrap();
1964        let got = bincode::deserialize::<OutPoint>(&ser).unwrap();
1965
1966        assert_eq!(got, out_point);
1967    }
1968
1969    #[cfg(feature = "alloc")]
1970    fn tx_out() -> TxOut { TxOut { amount: Amount::ONE_SAT, script_pubkey: tc_script_pubkey() } }
1971
1972    #[cfg(any(feature = "hex", feature = "serde"))]
1973    fn segwit_tx_in() -> TxIn {
1974        let bytes = [1u8, 2, 3];
1975        let data = [&bytes[..]];
1976        let witness = Witness::from_iter(data);
1977
1978        TxIn {
1979            previous_output: tc_out_point(),
1980            script_sig: tc_script_sig(),
1981            sequence: Sequence::MAX,
1982            witness,
1983        }
1984    }
1985
1986    #[cfg(feature = "alloc")]
1987    fn tc_script_pubkey() -> ScriptPubKeyBuf {
1988        let script_bytes = vec![1, 2, 3];
1989        ScriptPubKeyBuf::from_bytes(script_bytes)
1990    }
1991
1992    #[cfg(any(feature = "hex", feature = "serde"))]
1993    fn tc_script_sig() -> ScriptSigBuf {
1994        let script_bytes = vec![1, 2, 3];
1995        ScriptSigBuf::from_bytes(script_bytes)
1996    }
1997
1998    #[test]
1999    #[cfg(feature = "alloc")]
2000    #[cfg(feature = "hex")]
2001    fn encode_out_point() {
2002        let out_point = tc_out_point();
2003        let mut encoder = out_point.encoder();
2004
2005        // The txid
2006        assert_eq!(
2007            encoder.current_chunk(),
2008            &[
2009                32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12,
2010                11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
2011            ][..]
2012        );
2013        assert!(encoder.advance());
2014
2015        // The vout
2016        assert_eq!(encoder.current_chunk(), &[1u8, 0, 0, 0][..]);
2017        assert!(!encoder.advance());
2018
2019        // Exhausted
2020        assert!(encoder.current_chunk().is_empty());
2021    }
2022
2023    #[test]
2024    #[cfg(feature = "alloc")]
2025    fn encode_tx_out() {
2026        let out = tx_out();
2027        let mut encoder = out.encoder();
2028
2029        // The amount.
2030        assert_eq!(encoder.current_chunk(), &[1, 0, 0, 0, 0, 0, 0, 0][..]);
2031        assert!(encoder.advance());
2032
2033        // The script pubkey length prefix.
2034        assert_eq!(encoder.current_chunk(), &[3u8][..]);
2035        assert!(encoder.advance());
2036
2037        // The script pubkey data.
2038        assert_eq!(encoder.current_chunk(), &[1u8, 2, 3][..]);
2039        assert!(!encoder.advance());
2040
2041        // Exhausted
2042        assert!(encoder.current_chunk().is_empty());
2043    }
2044
2045    #[test]
2046    #[cfg(feature = "alloc")]
2047    #[cfg(feature = "hex")]
2048    fn encode_tx_in() {
2049        let txin = segwit_tx_in();
2050        let mut encoder = txin.encoder();
2051
2052        // The outpoint (same as tested above).
2053        assert_eq!(
2054            encoder.current_chunk(),
2055            &[
2056                32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12,
2057                11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
2058            ][..]
2059        );
2060        assert!(encoder.advance());
2061        assert_eq!(encoder.current_chunk(), &[1u8, 0, 0, 0][..]);
2062        assert!(encoder.advance());
2063
2064        // The script sig
2065        assert_eq!(encoder.current_chunk(), &[3u8][..]);
2066        assert!(encoder.advance());
2067        assert_eq!(encoder.current_chunk(), &[1u8, 2, 3][..]);
2068        assert!(encoder.advance());
2069
2070        // The sequence
2071        assert_eq!(encoder.current_chunk(), &[0xffu8, 0xff, 0xff, 0xff][..]);
2072        assert!(!encoder.advance());
2073
2074        // Exhausted
2075        assert!(encoder.current_chunk().is_empty());
2076    }
2077
2078    #[test]
2079    #[cfg(all(feature = "alloc", feature = "hex"))]
2080    fn encode_segwit_transaction() {
2081        let tx = Transaction {
2082            version: Version::TWO,
2083            lock_time: LockTime::ZERO,
2084            inputs: vec![segwit_tx_in()],
2085            outputs: vec![tx_out()],
2086        };
2087
2088        let mut encoder = tx.encoder();
2089
2090        // The version
2091        assert_eq!(encoder.current_chunk(), &[2u8, 0, 0, 0][..]);
2092        assert!(encoder.advance());
2093
2094        // The segwit marker and flag
2095        assert_eq!(encoder.current_chunk(), &[0u8, 1][..]);
2096        assert!(encoder.advance());
2097
2098        // The input (same as tested above) but with vec length prefix.
2099        assert_eq!(encoder.current_chunk(), &[1u8][..]);
2100        assert!(encoder.advance());
2101        assert_eq!(
2102            encoder.current_chunk(),
2103            &[
2104                32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12,
2105                11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
2106            ][..]
2107        );
2108        assert!(encoder.advance());
2109        assert_eq!(encoder.current_chunk(), &[1u8, 0, 0, 0][..]);
2110        assert!(encoder.advance());
2111        assert_eq!(encoder.current_chunk(), &[3u8][..]);
2112        assert!(encoder.advance());
2113        assert_eq!(encoder.current_chunk(), &[1u8, 2, 3][..]);
2114        assert!(encoder.advance());
2115        assert_eq!(encoder.current_chunk(), &[0xffu8, 0xff, 0xff, 0xff][..]);
2116        assert!(encoder.advance());
2117
2118        // The output (same as tested above) but with vec length prefix.
2119        assert_eq!(encoder.current_chunk(), &[1u8][..]);
2120        assert!(encoder.advance());
2121        assert_eq!(encoder.current_chunk(), &[1, 0, 0, 0, 0, 0, 0, 0][..]);
2122        assert!(encoder.advance());
2123        assert_eq!(encoder.current_chunk(), &[3u8][..]);
2124        assert!(encoder.advance());
2125        assert_eq!(encoder.current_chunk(), &[1u8, 2, 3][..]);
2126        assert!(encoder.advance());
2127
2128        // The witness
2129        assert_eq!(encoder.current_chunk(), &[1u8][..]);
2130        assert!(encoder.advance());
2131        assert_eq!(encoder.current_chunk(), &[3u8, 1, 2, 3][..]);
2132        assert!(encoder.advance());
2133
2134        // The lock time.
2135        assert_eq!(encoder.current_chunk(), &[0, 0, 0, 0][..]);
2136        assert!(!encoder.advance());
2137
2138        // Exhausted
2139        assert!(encoder.current_chunk().is_empty());
2140    }
2141
2142    #[test]
2143    #[cfg(feature = "alloc")]
2144    #[cfg(feature = "hex")]
2145    fn encode_non_segwit_transaction() {
2146        let mut tx_in = segwit_tx_in();
2147        tx_in.witness = Witness::default();
2148
2149        let tx = Transaction {
2150            version: Version::TWO,
2151            lock_time: LockTime::ZERO,
2152            inputs: vec![tx_in],
2153            outputs: vec![tx_out()],
2154        };
2155
2156        let mut encoder = tx.encoder();
2157
2158        // The version
2159        assert_eq!(encoder.current_chunk(), &[2u8, 0, 0, 0][..]);
2160        assert!(encoder.advance());
2161
2162        // Advance past the optional segwit bytes encoder.
2163        assert!(encoder.advance());
2164
2165        // The input (same as tested above) but with vec length prefix.
2166        assert_eq!(encoder.current_chunk(), &[1u8][..]);
2167        assert!(encoder.advance());
2168        assert_eq!(
2169            encoder.current_chunk(),
2170            &[
2171                32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12,
2172                11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
2173            ][..]
2174        );
2175        assert!(encoder.advance());
2176        assert_eq!(encoder.current_chunk(), &[1u8, 0, 0, 0][..]);
2177        assert!(encoder.advance());
2178        assert_eq!(encoder.current_chunk(), &[3u8][..]);
2179        assert!(encoder.advance());
2180        assert_eq!(encoder.current_chunk(), &[1u8, 2, 3][..]);
2181        assert!(encoder.advance());
2182        assert_eq!(encoder.current_chunk(), &[0xffu8, 0xff, 0xff, 0xff][..]);
2183        assert!(encoder.advance());
2184
2185        // The output (same as tested above) but with vec length prefix.
2186        assert_eq!(encoder.current_chunk(), &[1u8][..]);
2187        assert!(encoder.advance());
2188        assert_eq!(encoder.current_chunk(), &[1, 0, 0, 0, 0, 0, 0, 0][..]);
2189        assert!(encoder.advance());
2190        assert_eq!(encoder.current_chunk(), &[3u8][..]);
2191        assert!(encoder.advance());
2192        assert_eq!(encoder.current_chunk(), &[1u8, 2, 3][..]);
2193        assert!(encoder.advance());
2194
2195        // Advance past the optional witnesses encoder.
2196        assert!(encoder.advance());
2197
2198        // The lock time.
2199        assert_eq!(encoder.current_chunk(), &[0, 0, 0, 0][..]);
2200        assert!(!encoder.advance());
2201
2202        // Exhausted
2203        assert!(encoder.current_chunk().is_empty());
2204    }
2205
2206    // FIXME: Move all these encoding tests to a single file in `primitives/tests/`.
2207    #[test]
2208    #[cfg(feature = "alloc")]
2209    #[cfg(feature = "hex")]
2210    fn encode_block() {
2211        use crate::{
2212            Block, BlockHash, BlockHeader, BlockTime, BlockVersion, CompactTarget, TxMerkleNode,
2213        };
2214
2215        let seconds: u32 = 1_653_195_600; // Arbitrary timestamp: May 22nd, 5am UTC.
2216
2217        let header = BlockHeader {
2218            version: BlockVersion::TWO,
2219            prev_blockhash: BlockHash::from_byte_array([0xab; 32]),
2220            merkle_root: TxMerkleNode::from_byte_array([0xcd; 32]),
2221            time: BlockTime::from(seconds),
2222            bits: CompactTarget::from_consensus(0xbeef),
2223            nonce: 0xcafe,
2224        };
2225
2226        let tx = Transaction {
2227            version: Version::TWO,
2228            lock_time: LockTime::ZERO,
2229            inputs: vec![segwit_tx_in()],
2230            outputs: vec![tx_out()],
2231        };
2232
2233        let block = Block::new_unchecked(header, vec![tx]);
2234        let mut encoder = block.encoder();
2235
2236        // The block header, 6 encoders, 1 chunk per encoder.
2237
2238        // The block version.
2239        assert_eq!(encoder.current_chunk(), &[2u8, 0, 0, 0][..]);
2240        assert!(encoder.advance());
2241        // The previous block's blockhash.
2242        assert_eq!(
2243            encoder.current_chunk(),
2244            &[
2245                171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171,
2246                171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171
2247            ][..]
2248        );
2249        assert!(encoder.advance());
2250        // The merkle root hash.
2251        assert_eq!(
2252            encoder.current_chunk(),
2253            &[
2254                205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205,
2255                205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205
2256            ][..]
2257        );
2258        assert!(encoder.advance());
2259        // The block time.
2260        assert_eq!(encoder.current_chunk(), &[80, 195, 137, 98][..]);
2261        assert!(encoder.advance());
2262        // The target (bits).
2263        assert_eq!(encoder.current_chunk(), &[239, 190, 0, 0][..]);
2264        assert!(encoder.advance());
2265        // The nonce.
2266        assert_eq!(encoder.current_chunk(), &[254, 202, 0, 0][..]);
2267        assert!(encoder.advance());
2268
2269        // The transaction list length prefix.
2270        assert_eq!(encoder.current_chunk(), &[1u8][..]);
2271        assert!(encoder.advance());
2272
2273        // The transaction (same as tested above).
2274
2275        // The version
2276        assert_eq!(encoder.current_chunk(), &[2u8, 0, 0, 0][..]);
2277        assert!(encoder.advance());
2278        // The segwit marker and flag
2279        assert_eq!(encoder.current_chunk(), &[0u8, 1][..]);
2280        assert!(encoder.advance());
2281        // The input (same as tested above) but with vec length prefix.
2282        assert_eq!(encoder.current_chunk(), &[1u8][..]);
2283        assert!(encoder.advance());
2284        assert_eq!(
2285            encoder.current_chunk(),
2286            &[
2287                32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12,
2288                11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
2289            ][..]
2290        );
2291        assert!(encoder.advance());
2292        assert_eq!(encoder.current_chunk(), &[1u8, 0, 0, 0][..]);
2293        assert!(encoder.advance());
2294        assert_eq!(encoder.current_chunk(), &[3u8][..]);
2295        assert!(encoder.advance());
2296        assert_eq!(encoder.current_chunk(), &[1u8, 2, 3][..]);
2297        assert!(encoder.advance());
2298        assert_eq!(encoder.current_chunk(), &[0xffu8, 0xff, 0xff, 0xff][..]);
2299        assert!(encoder.advance());
2300        // The output (same as tested above) but with vec length prefix.
2301        assert_eq!(encoder.current_chunk(), &[1u8][..]);
2302        assert!(encoder.advance());
2303        assert_eq!(encoder.current_chunk(), &[1, 0, 0, 0, 0, 0, 0, 0][..]);
2304        assert!(encoder.advance());
2305        assert_eq!(encoder.current_chunk(), &[3u8][..]);
2306        assert!(encoder.advance());
2307        assert_eq!(encoder.current_chunk(), &[1u8, 2, 3][..]);
2308        assert!(encoder.advance());
2309        // The witness
2310        assert_eq!(encoder.current_chunk(), &[1u8][..]);
2311        assert!(encoder.advance());
2312        assert_eq!(encoder.current_chunk(), &[3u8, 1, 2, 3][..]);
2313        assert!(encoder.advance());
2314        // The lock time.
2315        assert_eq!(encoder.current_chunk(), &[0, 0, 0, 0][..]);
2316        assert!(!encoder.advance());
2317
2318        // Exhausted
2319        assert!(encoder.current_chunk().is_empty());
2320    }
2321
2322    #[test]
2323    #[cfg(all(feature = "alloc", feature = "hex"))]
2324    fn decode_segwit_transaction() {
2325        let tx_bytes = hex!(
2326            "02000000000101595895ea20179de87052b4046dfe6fd515860505d6511a9004cf12a1f93cac7c01000000\
2327            00ffffffff01deb807000000000017a9140f3444e271620c736808aa7b33e370bd87cb5a078702483045022\
2328            100fb60dad8df4af2841adc0346638c16d0b8035f5e3f3753b88db122e70c79f9370220756e6633b17fd271\
2329            0e626347d28d60b0a2d6cbb41de51740644b9fb3ba7751040121028fa937ca8cba2197a37c007176ed89410\
2330            55d3bcb8627d085e94553e62f057dcc00000000"
2331        );
2332        let mut decoder = Transaction::decoder();
2333        let mut slice = tx_bytes.as_slice();
2334        decoder.push_bytes(&mut slice).unwrap();
2335        let tx = decoder.end().unwrap();
2336
2337        // Attempt various truncations
2338        for i in [1, 10, 20, 50, 100, tx_bytes.len() / 2, tx_bytes.len()] {
2339            let mut decoder = Transaction::decoder();
2340            let mut slice = &tx_bytes[..tx_bytes.len() - i];
2341            // push_bytes will not fail because the data is not invalid, just truncated
2342            decoder.push_bytes(&mut slice).unwrap();
2343            // ...but end() will fail because we will be in some incomplete state
2344            decoder.end().unwrap_err();
2345        }
2346
2347        // All these tests aren't really needed because if they fail, the hash check at the end
2348        // will also fail. But these will show you where the failure is so I'll leave them in.
2349        assert_eq!(tx.version, Version::TWO);
2350        assert_eq!(tx.inputs.len(), 1);
2351        // In particular this one is easy to get backward -- in bitcoin hashes are encoded
2352        // as little-endian 256-bit numbers rather than as data strings.
2353        assert_eq!(
2354            format!("{:x}", tx.inputs[0].previous_output.txid),
2355            "7cac3cf9a112cf04901a51d605058615d56ffe6d04b45270e89d1720ea955859".to_string()
2356        );
2357        assert_eq!(tx.inputs[0].previous_output.vout, 1);
2358        assert_eq!(tx.outputs.len(), 1);
2359        assert_eq!(tx.lock_time, absolute::LockTime::ZERO);
2360
2361        assert_eq!(
2362            format!("{:x}", tx.compute_txid()),
2363            "f5864806e3565c34d1b41e716f72609d00b55ea5eac5b924c9719a842ef42206".to_string()
2364        );
2365        assert_eq!(
2366            format!("{:x}", tx.compute_wtxid()),
2367            "80b7d8a82d5d5bf92905b06f2014dd699e03837ca172e3a59d51426ebbe3e7f5".to_string()
2368        );
2369    }
2370
2371    #[test]
2372    #[cfg(all(feature = "alloc", feature = "hex"))]
2373    fn decode_nonsegwit_transaction() {
2374        let tx_bytes = hex!("0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000");
2375
2376        let mut decoder = Transaction::decoder();
2377        let mut slice = tx_bytes.as_slice();
2378        decoder.push_bytes(&mut slice).unwrap();
2379        let tx = decoder.end().unwrap();
2380
2381        // All these tests aren't really needed because if they fail, the hash check at the end
2382        // will also fail. But these will show you where the failure is so I'll leave them in.
2383        assert_eq!(tx.version, Version::ONE);
2384        assert_eq!(tx.inputs.len(), 1);
2385        // In particular this one is easy to get backward -- in bitcoin hashes are encoded
2386        // as little-endian 256-bit numbers rather than as data strings.
2387        assert_eq!(
2388            format!("{:x}", tx.inputs[0].previous_output.txid),
2389            "ce9ea9f6f5e422c6a9dbcddb3b9a14d1c78fab9ab520cb281aa2a74a09575da1".to_string()
2390        );
2391        assert_eq!(tx.inputs[0].previous_output.vout, 1);
2392        assert_eq!(tx.outputs.len(), 1);
2393        assert_eq!(tx.lock_time, absolute::LockTime::ZERO);
2394
2395        assert_eq!(
2396            format!("{:x}", tx.compute_txid()),
2397            "a6eab3c14ab5272a58a5ba91505ba1a4b6d7a3a9fcbd187b6cd99a7b6d548cb7".to_string()
2398        );
2399        assert_eq!(
2400            format!("{:x}", tx.compute_wtxid()),
2401            "a6eab3c14ab5272a58a5ba91505ba1a4b6d7a3a9fcbd187b6cd99a7b6d548cb7".to_string()
2402        );
2403    }
2404
2405    #[test]
2406    #[cfg(all(feature = "alloc", feature = "hex"))]
2407    fn decode_segwit_without_witnesses_errors() {
2408        // A SegWit-serialized transaction with 1 input but no witnesses for any input.
2409        let tx_bytes = hex!(
2410            "02000000\
2411             0001\
2412             01\
2413             0000000000000000000000000000000000000000000000000000000000000000\
2414             00000000\
2415             00\
2416             ffffffff\
2417             01\
2418             0100000000000000\
2419             00\
2420             00\
2421             00000000"
2422        );
2423
2424        let mut slice = tx_bytes.as_slice();
2425        let err = Transaction::decoder()
2426            .push_bytes(&mut slice)
2427            .expect_err("segwit tx with no witnesses should error");
2428
2429        assert_eq!(err, TransactionDecoderError(TransactionDecoderErrorInner::NoWitnesses));
2430    }
2431
2432    #[test]
2433    #[cfg(feature = "alloc")]
2434    fn decode_zero_inputs() {
2435        // Test transaction with no inputs (but with one output to satisfy validation).
2436        let block: u32 = 741_521;
2437        let original_tx = Transaction {
2438            version: Version::ONE,
2439            lock_time: absolute::LockTime::from_height(block).expect("valid height"),
2440            inputs: vec![],
2441            outputs: vec![TxOut { amount: Amount::ONE_SAT, script_pubkey: ScriptPubKeyBuf::new() }],
2442        };
2443
2444        let encoded = encoding::encode_to_vec(&original_tx);
2445        let decoded_tx = encoding::decode_from_slice(&encoded).unwrap();
2446
2447        assert_eq!(original_tx, decoded_tx);
2448    }
2449
2450    #[test]
2451    #[cfg(all(feature = "alloc", feature = "hex"))]
2452    fn reject_null_prevout_in_non_coinbase_transaction() {
2453        // Test vector taken from Bitcoin Core tx_invalid.json
2454        // https://github.com/bitcoin/bitcoin/blob/master/src/test/data/tx_invalid.json#L64
2455        // "Null txin, but without being a coinbase (because there are two inputs)"
2456        let tx_bytes = hex!("01000000020000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff00010000000000000000000000000000000000000000000000000000000000000000000000ffffffff010000000000000000015100000000");
2457
2458        let mut decoder = Transaction::decoder();
2459        let mut slice = tx_bytes.as_slice();
2460        decoder.push_bytes(&mut slice).unwrap();
2461        let err = decoder.end().expect_err("null prevout in non-coinbase tx should be rejected");
2462
2463        assert_eq!(
2464            err,
2465            TransactionDecoderError(TransactionDecoderErrorInner::NullPrevoutInNonCoinbase(0))
2466        );
2467    }
2468
2469    #[test]
2470    #[cfg(all(feature = "alloc", feature = "hex"))]
2471    fn reject_coinbase_scriptsig_too_small() {
2472        // Test vector taken from Bitcoin Core tx_invalid.json
2473        // https://github.com/bitcoin/bitcoin/blob/master/src/test/data/tx_invalid.json#L57
2474        // "Coinbase of size 1"
2475        let tx_bytes = hex!("01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0151ffffffff010000000000000000015100000000");
2476
2477        let mut decoder = Transaction::decoder();
2478        let mut slice = tx_bytes.as_slice();
2479        decoder.push_bytes(&mut slice).unwrap();
2480        let err = decoder.end().expect_err("coinbase with 1-byte scriptSig should be rejected");
2481
2482        assert_eq!(
2483            err,
2484            TransactionDecoderError(TransactionDecoderErrorInner::CoinbaseScriptSigTooSmall(1))
2485        );
2486    }
2487
2488    #[test]
2489    #[cfg(all(feature = "alloc", feature = "hex"))]
2490    fn reject_coinbase_scriptsig_too_large() {
2491        // Test vector taken from Bitcoin Core tx_invalid.json:
2492        // https://github.com/bitcoin/bitcoin/blob/master/src/test/data/tx_invalid.json#L62
2493        // "Coinbase of size 101"
2494        let tx_bytes = hex!("01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff655151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151ffffffff010000000000000000015100000000");
2495
2496        let mut decoder = Transaction::decoder();
2497        let mut slice = tx_bytes.as_slice();
2498        decoder.push_bytes(&mut slice).unwrap();
2499        let err = decoder.end().expect_err("coinbase with 101-byte scriptSig should be rejected");
2500
2501        assert_eq!(
2502            err,
2503            TransactionDecoderError(TransactionDecoderErrorInner::CoinbaseScriptSigTooLarge(101))
2504        );
2505    }
2506
2507    #[test]
2508    #[cfg(all(feature = "alloc", feature = "hex"))]
2509    fn accept_coinbase_scriptsig_min_valid() {
2510        // boundary test: 2 bytes is the minimum valid length
2511        let tx_bytes = hex!("01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff025151ffffffff010000000000000000015100000000");
2512
2513        let mut decoder = Transaction::decoder();
2514        let mut slice = tx_bytes.as_slice();
2515        decoder.push_bytes(&mut slice).unwrap();
2516        let tx = decoder.end().expect("coinbase with 2-byte scriptSig should be accepted");
2517
2518        assert_eq!(tx.inputs[0].script_sig.len(), 2);
2519    }
2520
2521    #[test]
2522    #[cfg(all(feature = "alloc", feature = "hex"))]
2523    fn accept_coinbase_scriptsig_max_valid() {
2524        // boundary test: 100 bytes is the maximum valid length
2525        let tx_bytes = hex!("01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff6451515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151515151ffffffff010000000000000000015100000000");
2526
2527        let mut decoder = Transaction::decoder();
2528        let mut slice = tx_bytes.as_slice();
2529        decoder.push_bytes(&mut slice).unwrap();
2530        let tx = decoder.end().expect("coinbase with 100-byte scriptSig should be accepted");
2531
2532        assert_eq!(tx.inputs[0].script_sig.len(), 100);
2533    }
2534
2535    #[test]
2536    #[cfg(all(feature = "alloc", feature = "hex"))]
2537    fn reject_duplicate_inputs() {
2538        // Test vector from Bitcoin Core tx_invalid.json:
2539        // https://github.com/bitcoin/bitcoin/blob/master/src/test/data/tx_invalid.json#L50
2540        // Transaction has two inputs both spending the same outpoint
2541        let tx_bytes = hex!("01000000020001000000000000000000000000000000000000000000000000000000000000000000006c47304402204bb1197053d0d7799bf1b30cd503c44b58d6240cccbdc85b6fe76d087980208f02204beeed78200178ffc6c74237bb74b3f276bbb4098b5605d814304fe128bf1431012321039e8815e15952a7c3fada1905f8cf55419837133bd7756c0ef14fc8dfe50c0deaacffffffff0001000000000000000000000000000000000000000000000000000000000000000000006c47304402202306489afef52a6f62e90bf750bbcdf40c06f5c6b138286e6b6b86176bb9341802200dba98486ea68380f47ebb19a7df173b99e6bc9c681d6ccf3bde31465d1f16b3012321039e8815e15952a7c3fada1905f8cf55419837133bd7756c0ef14fc8dfe50c0deaacffffffff010000000000000000015100000000");
2542
2543        let mut decoder = Transaction::decoder();
2544        let mut slice = tx_bytes.as_slice();
2545        decoder.push_bytes(&mut slice).unwrap();
2546        let err = decoder.end().expect_err("transaction with duplicate inputs should be rejected");
2547
2548        let expected_outpoint = OutPoint {
2549            txid: Txid::from_byte_array([
2550                0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2551                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2552                0x00, 0x00, 0x00, 0x00,
2553            ]),
2554            vout: 0,
2555        };
2556        assert_eq!(
2557            err,
2558            TransactionDecoderError(TransactionDecoderErrorInner::DuplicateInput(
2559                expected_outpoint
2560            ))
2561        );
2562    }
2563
2564    #[test]
2565    #[cfg(all(feature = "alloc", feature = "hex"))]
2566    fn reject_output_value_sum_too_large() {
2567        // Test vector taken from Bitcoin Core tx_invalid.json
2568        // https://github.com/bitcoin/bitcoin/blob/master/src/test/data/tx_invalid.json#L48
2569        // "MAX_MONEY output + 1 output" (sum exceeds MAX_MONEY)
2570        let tx_bytes = hex!("01000000010001000000000000000000000000000000000000000000000000000000000000000000006d483045022027deccc14aa6668e78a8c9da3484fbcd4f9dcc9bb7d1b85146314b21b9ae4d86022100d0b43dece8cfb07348de0ca8bc5b86276fa88f7f2138381128b7c36ab2e42264012321029bb13463ddd5d2cc05da6e84e37536cb9525703cfd8f43afdb414988987a92f6acffffffff020040075af075070001510001000000000000015100000000");
2571
2572        let mut decoder = Transaction::decoder();
2573        let mut slice = tx_bytes.as_slice();
2574        decoder.push_bytes(&mut slice).unwrap();
2575        let err = decoder.end().expect_err("sum of output values > MAX_MONEY should be rejected");
2576
2577        match err.0 {
2578            TransactionDecoderErrorInner::OutputValueSumTooLarge(_) => (),
2579            e => panic!("unexpected error: {:?}", e),
2580        }
2581    }
2582
2583    #[test]
2584    #[cfg(all(feature = "alloc", feature = "hex"))]
2585    fn accept_output_value_sum_equal_to_max_money() {
2586        let tx_bytes = hex!("01000000010001000000000000000000000000000000000000000000000000000000000000000000006d483045022027deccc14aa6668e78a8c9da3484fbcd4f9dcc9bb7d1b85146314b21b9ae4d86022100d0b43dece8cfb07348de0ca8bc5b86276fa88f7f2138381128b7c36ab2e42264012321029bb13463ddd5d2cc05da6e84e37536cb9525703cfd8f43afdb414988987a92f6acffffffff020080c6a47e8d0300015100c040b571e80300015100000000");
2587
2588        let mut decoder = Transaction::decoder();
2589        let mut slice = tx_bytes.as_slice();
2590        decoder.push_bytes(&mut slice).unwrap();
2591        let tx = decoder.end().expect("sum of output values == MAX_MONEY should be accepted");
2592
2593        let total: u64 = tx.outputs.iter().map(|o| o.amount.to_sat()).sum();
2594        assert_eq!(total, Amount::MAX_MONEY.to_sat());
2595    }
2596
2597    #[test]
2598    #[cfg(all(feature = "alloc", feature = "hex"))]
2599    fn reject_output_value_greater_than_max_money() {
2600        // Test vector taken from Bitcoin Core tx_invalid.json
2601        // https://github.com/bitcoin/bitcoin/blob/master/src/test/data/tx_invalid.json#L44
2602        // "MAX_MONEY + 1 output"
2603        let tx_bytes = hex!("01000000010001000000000000000000000000000000000000000000000000000000000000000000006e493046022100e1eadba00d9296c743cb6ecc703fd9ddc9b3cd12906176a226ae4c18d6b00796022100a71aef7d2874deff681ba6080f1b278bac7bb99c61b08a85f4311970ffe7f63f012321030c0588dc44d92bdcbf8e72093466766fdc265ead8db64517b0c542275b70fffbacffffffff010140075af0750700015100000000");
2604
2605        let mut decoder = Transaction::decoder();
2606        let mut slice = tx_bytes.as_slice();
2607        let result = decoder.push_bytes(&mut slice);
2608        assert!(result.is_err(), "output value > MAX_MONEY should be rejected during decoding");
2609    }
2610
2611    #[test]
2612    #[cfg(all(feature = "alloc", feature = "hex"))]
2613    fn reject_transaction_with_no_outputs() {
2614        // Test vector taken from Bitcoin Core tx_invalid.json
2615        // https://github.com/bitcoin/bitcoin/blob/master/src/test/data/tx_invalid.json#L36
2616        // "No outputs"
2617        let tx_bytes = hex!("01000000010001000000000000000000000000000000000000000000000000000000000000000000006d483045022100f16703104aab4e4088317c862daec83440242411b039d14280e03dd33b487ab802201318a7be236672c5c56083eb7a5a195bc57a40af7923ff8545016cd3b571e2a601232103c40e5d339df3f30bf753e7e04450ae4ef76c9e45587d1d993bdc4cd06f0651c7acffffffff0000000000");
2618
2619        let mut decoder = Transaction::decoder();
2620        let mut slice = tx_bytes.as_slice();
2621        decoder.push_bytes(&mut slice).unwrap();
2622        let err = decoder.end().unwrap_err();
2623        assert_eq!(err, TransactionDecoderError(TransactionDecoderErrorInner::NoOutputs));
2624    }
2625}