cashweb_bitcoin/transaction/
outpoint.rs

1//! This module contains the [`Outpoint`] struct which represents a Bitcoin transaction outpoint.
2//! It enjoys [`Encodable`] and [`Decodable`].
3
4use bytes::{Buf, BufMut};
5use thiserror::Error;
6
7use crate::{Decodable, Encodable};
8
9/// Represents an outpoint.
10#[derive(Clone, Debug, Default, PartialEq, Eq)]
11#[allow(missing_docs)]
12pub struct Outpoint {
13    pub tx_id: [u8; 32],
14    pub vout: u32,
15}
16
17impl Encodable for Outpoint {
18    #[inline]
19    fn encoded_len(&self) -> usize {
20        32 + 4
21    }
22
23    #[inline]
24    fn encode_raw<B: BufMut>(&self, buf: &mut B) {
25        buf.put(&self.tx_id[..]);
26        buf.put_u32_le(self.vout);
27    }
28}
29
30/// Error associated with [`Outpoint`] deserialization.
31#[derive(Clone, Debug, PartialEq, Eq, Error)]
32#[error("outpoint too short")]
33pub struct DecodeError;
34
35impl Decodable for Outpoint {
36    type Error = DecodeError;
37
38    #[inline]
39    fn decode<B: Buf>(buf: &mut B) -> Result<Self, Self::Error> {
40        if buf.remaining() < 32 + 4 {
41            return Err(DecodeError);
42        }
43        let mut tx_id = [0; 32];
44        buf.copy_to_slice(&mut tx_id);
45        let vout = buf.get_u32_le();
46
47        Ok(Outpoint { tx_id, vout })
48    }
49}