cashweb_bitcoin/transaction/script/
mod.rs

1//! This module contains the [`Script`] struct which represents a Bitcoin transaction script.
2//! It enjoys [`Encodable`], and provides some utility methods.
3
4pub mod opcodes;
5
6use crate::{var_int::VarInt, Encodable};
7
8use bytes::BufMut;
9
10/// Represents a script.
11#[derive(Clone, Debug, Default, PartialEq, Eq)]
12pub struct Script(pub Vec<u8>);
13
14impl Into<Vec<u8>> for Script {
15    fn into(self) -> Vec<u8> {
16        self.0
17    }
18}
19
20impl From<Vec<u8>> for Script {
21    fn from(raw: Vec<u8>) -> Self {
22        Script(raw)
23    }
24}
25
26impl Script {
27    /// Check whether the script is empty.
28    #[inline]
29    pub fn is_empty(&self) -> bool {
30        self.0.is_empty()
31    }
32
33    /// Length of the script.
34    #[inline]
35    pub fn len(&self) -> usize {
36        self.0.len()
37    }
38
39    /// Length of the script as `VarInt`.
40    #[inline]
41    pub fn len_varint(&self) -> VarInt {
42        VarInt(self.len() as u64)
43    }
44
45    /// Convert the script into the underlying bytes.
46    #[inline]
47    pub fn into_bytes(self) -> Vec<u8> {
48        self.into()
49    }
50
51    /// Converts the script into a byte slice.
52    #[inline]
53    pub fn as_bytes(&self) -> &[u8] {
54        &self.0
55    }
56
57    /// Checks whether the script fits the OP_RETURN pattern.
58    #[inline]
59    pub fn is_op_return(&self) -> bool {
60        !self.0.is_empty() && self.0[0] == opcodes::OP_RETURN
61    }
62
63    /// Checks whether the scripts the P2PKH pattern.
64    #[inline]
65    pub fn is_p2pkh(&self) -> bool {
66        self.0.len() == 25
67            && self.0[0] == opcodes::OP_DUP
68            && self.0[1] == opcodes::OP_HASH160
69            && self.0[2] == opcodes::OP_PUSHBYTES_20
70            && self.0[23] == opcodes::OP_EQUALVERIFY
71            && self.0[24] == opcodes::OP_CHECKSIG
72    }
73}
74
75impl Encodable for Script {
76    #[inline]
77    fn encoded_len(&self) -> usize {
78        self.0.len()
79    }
80
81    #[inline]
82    fn encode_raw<B: BufMut>(&self, buf: &mut B) {
83        buf.put(&self.0[..]);
84    }
85}