1use 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] #[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#[derive(Clone, PartialEq, Eq, Debug, Hash)]
112#[cfg(feature = "alloc")]
113pub struct Transaction {
114 pub version: Version,
116 pub lock_time: absolute::LockTime,
123 pub inputs: Vec<TxIn>,
125 pub outputs: Vec<TxOut>,
127}
128
129#[cfg(feature = "alloc")]
130impl Transaction {
131 pub const MAX_STANDARD_WEIGHT: Weight = Weight::from_wu(400_000);
134
135 #[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 #[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 #[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 #[inline]
190 fn uses_segwit_serialization(&self) -> bool {
191 if self.inputs.iter().any(|input| !input.witness.is_empty()) {
192 return true;
193 }
194 self.inputs.is_empty()
197 }
198
199 #[doc(alias = "is_coin_base")] 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
252pub(crate) trait TxIdentifier: AsRef<[u8]> {}
254
255impl TxIdentifier for Txid {}
256impl TxIdentifier for Wtxid {}
257
258#[cfg(feature = "alloc")]
261const SEGWIT_MARKER: u8 = 0x00;
262#[cfg(feature = "alloc")]
264const SEGWIT_FLAG: u8 = 0x01;
265
266#[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()); if uses_segwit_serialization {
275 enc.input(&[SEGWIT_MARKER]);
277 enc.input(&[SEGWIT_FLAG]);
278 }
279
280 let input_len = tx.inputs.len();
282 enc.input(crate::compact_size_encode(input_len).as_slice());
283 for input in &tx.inputs {
284 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 let output_len = tx.outputs.len();
297 enc.input(crate::compact_size_encode(output_len).as_slice());
298 for output in &tx.outputs {
299 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 for input in &tx.inputs {
310 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 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 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#[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#[cfg(feature = "alloc")]
430pub struct TransactionDecoder {
431 state: TransactionDecoderState,
432}
433
434#[cfg(feature = "alloc")]
435impl TransactionDecoder {
436 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)] impl 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 match &mut self.state {
463 State::Version(decoder) => {
464 if decoder.push_bytes(bytes)? {
465 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 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 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 if tx.outputs.is_empty() {
596 return Err(E(Inner::NoOutputs));
597 }
598 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 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 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 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 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#[cfg(feature = "alloc")]
667enum TransactionDecoderState {
668 Version(VersionDecoder),
670 Inputs(Version, Attempt, VecDecoder<TxIn>),
672 SegwitFlag(Version),
674 Outputs(Version, Vec<TxIn>, IsSegwit, VecDecoder<TxOut>),
676 Witnesses(Version, Vec<TxIn>, Vec<TxOut>, Iteration, WitnessDecoder),
678 LockTime(Version, Vec<TxIn>, Vec<TxOut>, LockTimeDecoder),
680 Done(Transaction),
682 Errored,
685}
686
687#[cfg(feature = "alloc")]
689#[derive(Debug, Copy, Clone, PartialEq, Eq)]
690enum Attempt {
691 First,
693 Second,
695}
696
697#[cfg(feature = "alloc")]
699#[derive(Debug, Copy, Clone, PartialEq, Eq)]
700enum IsSegwit {
701 Yes,
703 No,
705}
706
707#[cfg(feature = "alloc")]
709#[derive(Debug, Copy, Clone, PartialEq, Eq)]
710struct Iteration(usize);
711
712#[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 Version(VersionDecoderError),
722 UnsupportedSegwitFlag(u8),
724 Inputs(VecDecoderError<TxInDecoderError>),
726 Outputs(VecDecoderError<TxOutDecoderError>),
728 Witness(WitnessDecoderError),
730 NoWitnesses,
732 LockTime(LockTimeDecoderError),
734 EarlyEnd(&'static str),
737 NullPrevoutInNonCoinbase(usize),
739 CoinbaseScriptSigTooSmall(usize),
741 CoinbaseScriptSigTooLarge(usize),
743 DuplicateInput(OutPoint),
745 OutputValueSumTooLarge(u64),
747 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#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
851#[cfg(feature = "alloc")]
852pub struct TxIn {
853 pub previous_output: OutPoint,
855 pub script_sig: ScriptSigBuf,
858 pub sequence: Sequence,
863 pub witness: Witness,
869}
870
871#[cfg(feature = "alloc")]
872impl TxIn {
873 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 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#[cfg(feature = "alloc")]
912pub struct WitnessesEncoder<'e> {
913 inputs: &'e [TxIn],
914 cur_enc: Option<WitnessEncoder<'e>>,
916}
917
918#[cfg(feature = "alloc")]
919impl<'e> WitnessesEncoder<'e> {
920 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 if cur.advance() {
943 return true;
944 }
945 self.inputs = &self.inputs[1..];
947
948 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; return false;
957 }
958 }
959 }
960}
961
962#[cfg(feature = "alloc")]
963type TxInInnerDecoder = Decoder3<OutPointDecoder, ScriptSigBufDecoder, SequenceDecoder>;
964
965#[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#[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#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
1046#[cfg(feature = "alloc")]
1047pub struct TxOut {
1048 pub amount: Amount,
1050 pub script_pubkey: ScriptPubKeyBuf,
1052}
1053
1054#[cfg(feature = "alloc")]
1055encoding::encoder_newtype! {
1056 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#[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#[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#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
1143pub struct OutPoint {
1144 pub txid: Txid,
1146 pub vout: u32,
1148}
1149
1150impl OutPoint {
1151 pub const SIZE: usize = 32 + 4; pub const COINBASE_PREVOUT: Self = Self { txid: Txid::COINBASE_PREVOUT, vout: u32::MAX };
1159}
1160
1161encoding::encoder_newtype_exact! {
1162 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 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#[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
1228pub struct OutPointDecoder(encoding::ArrayDecoder<36>);
1231
1232impl OutPointDecoder {
1233 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#[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 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#[derive(Debug, Clone, PartialEq, Eq)]
1401#[non_exhaustive]
1402#[cfg(feature = "alloc")]
1403#[cfg(feature = "hex")]
1404pub enum ParseOutPointError {
1405 Txid(hex::DecodeFixedLengthBytesError),
1407 Vout(parse_int::ParseIntError),
1409 Format,
1411 TooLong,
1413 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#[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 pub const ONE: Self = Self(1);
1467
1468 pub const TWO: Self = Self(2);
1470
1471 pub const THREE: Self = Self(3);
1473
1474 #[inline]
1478 pub const fn maybe_non_standard(version: u32) -> Self { Self(version) }
1479
1480 #[inline]
1482 pub const fn to_u32(self) -> u32 { self.0 }
1483
1484 #[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 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
1540pub struct VersionDecoder(encoding::ArrayDecoder<4>);
1542
1543impl VersionDecoder {
1544 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#[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 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 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]), 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), inputs: vec![txin],
1727 outputs: vec![txout],
1728 };
1729
1730 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 assert!(!tx.uses_segwit_serialization());
1739 tx.inputs[0].witness.push(vec![0xAB, 0xCD, 0xEF]);
1740 assert!(tx.uses_segwit_serialization());
1741
1742 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]), 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), 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 assert_eq!(encoded_tx, lower_hex_tx);
1777 assert_eq!(encoded_tx, format!("{}", tx_orig));
1778
1779 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 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 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 let parsed_lower = Transaction::from_str(&lower_hex_tx).unwrap();
1808 let parsed_upper = Transaction::from_str(&upper_hex_tx).unwrap();
1809
1810 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 let odd = "abc"; let err = Transaction::from_str(odd).unwrap_err();
1823 assert!(matches!(err, ParseTransactionError(ParsePrimitiveError::OddLengthString(..))));
1824
1825 let invalid = "zz";
1827 let err = Transaction::from_str(invalid).unwrap_err();
1828 assert!(matches!(err, ParseTransactionError(ParsePrimitiveError::InvalidChar(..))));
1829
1830 let bad = "deadbeef00"; 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 let mut outpoint_str = "0".repeat(64); let outpoint: Result<OutPoint, ParseOutPointError> = outpoint_str.parse();
1842 assert_eq!(outpoint, Err(ParseOutPointError::Format));
1843
1844 outpoint_str.push(':'); let outpoint: Result<OutPoint, ParseOutPointError> = outpoint_str.parse();
1846 assert_eq!(outpoint, Err(ParseOutPointError::Format));
1847
1848 outpoint_str.push('0'); 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 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 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 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()); assert!(parse_vout("+1").is_err()); }
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 #[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 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 32, 0, 0, 0, 0, 0, 0, 0,
1932 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 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 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 assert_eq!(encoder.current_chunk(), &[1u8, 0, 0, 0][..]);
2017 assert!(!encoder.advance());
2018
2019 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 assert_eq!(encoder.current_chunk(), &[1, 0, 0, 0, 0, 0, 0, 0][..]);
2031 assert!(encoder.advance());
2032
2033 assert_eq!(encoder.current_chunk(), &[3u8][..]);
2035 assert!(encoder.advance());
2036
2037 assert_eq!(encoder.current_chunk(), &[1u8, 2, 3][..]);
2039 assert!(!encoder.advance());
2040
2041 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 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 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 assert_eq!(encoder.current_chunk(), &[0xffu8, 0xff, 0xff, 0xff][..]);
2072 assert!(!encoder.advance());
2073
2074 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 assert_eq!(encoder.current_chunk(), &[2u8, 0, 0, 0][..]);
2092 assert!(encoder.advance());
2093
2094 assert_eq!(encoder.current_chunk(), &[0u8, 1][..]);
2096 assert!(encoder.advance());
2097
2098 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 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 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 assert_eq!(encoder.current_chunk(), &[0, 0, 0, 0][..]);
2136 assert!(!encoder.advance());
2137
2138 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 assert_eq!(encoder.current_chunk(), &[2u8, 0, 0, 0][..]);
2160 assert!(encoder.advance());
2161
2162 assert!(encoder.advance());
2164
2165 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 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 assert!(encoder.advance());
2197
2198 assert_eq!(encoder.current_chunk(), &[0, 0, 0, 0][..]);
2200 assert!(!encoder.advance());
2201
2202 assert!(encoder.current_chunk().is_empty());
2204 }
2205
2206 #[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; 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 assert_eq!(encoder.current_chunk(), &[2u8, 0, 0, 0][..]);
2240 assert!(encoder.advance());
2241 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 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 assert_eq!(encoder.current_chunk(), &[80, 195, 137, 98][..]);
2261 assert!(encoder.advance());
2262 assert_eq!(encoder.current_chunk(), &[239, 190, 0, 0][..]);
2264 assert!(encoder.advance());
2265 assert_eq!(encoder.current_chunk(), &[254, 202, 0, 0][..]);
2267 assert!(encoder.advance());
2268
2269 assert_eq!(encoder.current_chunk(), &[1u8][..]);
2271 assert!(encoder.advance());
2272
2273 assert_eq!(encoder.current_chunk(), &[2u8, 0, 0, 0][..]);
2277 assert!(encoder.advance());
2278 assert_eq!(encoder.current_chunk(), &[0u8, 1][..]);
2280 assert!(encoder.advance());
2281 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 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 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 assert_eq!(encoder.current_chunk(), &[0, 0, 0, 0][..]);
2316 assert!(!encoder.advance());
2317
2318 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 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 decoder.push_bytes(&mut slice).unwrap();
2343 decoder.end().unwrap_err();
2345 }
2346
2347 assert_eq!(tx.version, Version::TWO);
2350 assert_eq!(tx.inputs.len(), 1);
2351 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 assert_eq!(tx.version, Version::ONE);
2384 assert_eq!(tx.inputs.len(), 1);
2385 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 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 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 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 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 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 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 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 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 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 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 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}