bitcoin_cash/
pubkey.rs

1use crate::{BitcoinByteArray, BitcoinDataType, ByteArray, DataType, Op};
2
3#[derive(Clone, Copy)]
4pub struct Pubkey([u8; 33]);
5
6impl Pubkey {
7    pub fn from_slice(slice: &[u8]) -> Self {
8        let mut pubkey = [0; 33];
9        pubkey.copy_from_slice(slice);
10        Pubkey(pubkey)
11    }
12
13    pub fn from_slice_checked(slice: &[u8]) -> Option<Self> {
14        let mut pubkey = [0; 33];
15        if slice.len() != pubkey.len() {
16            return None;
17        }
18        pubkey.copy_from_slice(slice);
19        Some(Pubkey(pubkey))
20    }
21
22    pub fn new(pubkey: [u8; 33]) -> Self {
23        Pubkey(pubkey)
24    }
25
26    pub fn as_slice(&self) -> &[u8] {
27        &self.0
28    }
29
30    pub fn as_byte_array(&self) -> ByteArray {
31        ByteArray::from_slice_unnamed(&self.0)
32    }
33}
34
35impl std::fmt::Debug for Pubkey {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
37        write!(f, "Pubkey({})", hex::encode(&self.0[..]))
38    }
39}
40
41impl Default for Pubkey {
42    fn default() -> Self {
43        Pubkey([0; 33])
44    }
45}
46
47impl BitcoinDataType for Pubkey {
48    type Type = BitcoinByteArray;
49    fn to_data(&self) -> Self::Type {
50        BitcoinByteArray(self.as_byte_array())
51    }
52    fn to_pushop(&self) -> Op {
53        self.as_byte_array().into()
54    }
55    fn to_data_type(&self) -> DataType {
56        DataType::ByteArray(Some(self.0.len()))
57    }
58}