zebra_chain/block/
hash.rs

1use std::{fmt, io, sync::Arc};
2
3use hex::{FromHex, ToHex};
4use serde::{Deserialize, Serialize};
5
6use crate::serialization::{
7    sha256d, ReadZcashExt, SerializationError, ZcashDeserialize, ZcashSerialize,
8};
9
10use super::Header;
11
12#[cfg(any(test, feature = "proptest-impl"))]
13use proptest_derive::Arbitrary;
14
15/// A hash of a block, used to identify blocks and link blocks into a chain. ⛓️
16///
17/// Technically, this is the (SHA256d) hash of a block *header*, but since the
18/// block header includes the Merkle root of the transaction Merkle tree, it
19/// binds the entire contents of the block and is used to identify entire blocks.
20///
21/// Note: Zebra displays transaction and block hashes in big-endian byte-order,
22/// following the u256 convention set by Bitcoin and zcashd.
23#[derive(Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
24#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary, Default))]
25pub struct Hash(pub [u8; 32]);
26
27impl Hash {
28    /// Return the hash bytes in big-endian byte-order suitable for printing out byte by byte.
29    ///
30    /// Zebra displays transaction and block hashes in big-endian byte-order,
31    /// following the u256 convention set by Bitcoin and zcashd.
32    pub fn bytes_in_display_order(&self) -> [u8; 32] {
33        let mut reversed_bytes = self.0;
34        reversed_bytes.reverse();
35        reversed_bytes
36    }
37
38    /// Convert bytes in big-endian byte-order into a [`block::Hash`](crate::block::Hash).
39    ///
40    /// Zebra displays transaction and block hashes in big-endian byte-order,
41    /// following the u256 convention set by Bitcoin and zcashd.
42    pub fn from_bytes_in_display_order(bytes_in_display_order: &[u8; 32]) -> Hash {
43        let mut internal_byte_order = *bytes_in_display_order;
44        internal_byte_order.reverse();
45
46        Hash(internal_byte_order)
47    }
48}
49
50impl fmt::Display for Hash {
51    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52        f.write_str(&self.encode_hex::<String>())
53    }
54}
55
56impl fmt::Debug for Hash {
57    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
58        f.debug_tuple("block::Hash")
59            .field(&self.encode_hex::<String>())
60            .finish()
61    }
62}
63
64impl ToHex for &Hash {
65    fn encode_hex<T: FromIterator<char>>(&self) -> T {
66        self.bytes_in_display_order().encode_hex()
67    }
68
69    fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
70        self.bytes_in_display_order().encode_hex_upper()
71    }
72}
73
74impl ToHex for Hash {
75    fn encode_hex<T: FromIterator<char>>(&self) -> T {
76        (&self).encode_hex()
77    }
78
79    fn encode_hex_upper<T: FromIterator<char>>(&self) -> T {
80        (&self).encode_hex_upper()
81    }
82}
83
84impl FromHex for Hash {
85    type Error = <[u8; 32] as FromHex>::Error;
86
87    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
88        let hash = <[u8; 32]>::from_hex(hex)?;
89
90        Ok(Self::from_bytes_in_display_order(&hash))
91    }
92}
93
94impl From<[u8; 32]> for Hash {
95    fn from(bytes: [u8; 32]) -> Self {
96        Self(bytes)
97    }
98}
99
100impl<'a> From<&'a Header> for Hash {
101    fn from(block_header: &'a Header) -> Self {
102        let mut hash_writer = sha256d::Writer::default();
103        block_header
104            .zcash_serialize(&mut hash_writer)
105            .expect("Sha256dWriter is infallible");
106        Self(hash_writer.finish())
107    }
108}
109
110impl From<Header> for Hash {
111    // The borrow is actually needed to use From<&Header>
112    #[allow(clippy::needless_borrow)]
113    fn from(block_header: Header) -> Self {
114        (&block_header).into()
115    }
116}
117
118impl From<&Arc<Header>> for Hash {
119    // The borrow is actually needed to use From<&Header>
120    #[allow(clippy::needless_borrow)]
121    fn from(block_header: &Arc<Header>) -> Self {
122        block_header.as_ref().into()
123    }
124}
125
126impl From<Arc<Header>> for Hash {
127    // The borrow is actually needed to use From<&Header>
128    #[allow(clippy::needless_borrow)]
129    fn from(block_header: Arc<Header>) -> Self {
130        block_header.as_ref().into()
131    }
132}
133
134impl ZcashSerialize for Hash {
135    fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), io::Error> {
136        writer.write_all(&self.0)?;
137        Ok(())
138    }
139}
140
141impl ZcashDeserialize for Hash {
142    fn zcash_deserialize<R: io::Read>(mut reader: R) -> Result<Self, SerializationError> {
143        Ok(Hash(reader.read_32_bytes()?))
144    }
145}
146
147impl std::str::FromStr for Hash {
148    type Err = SerializationError;
149    fn from_str(s: &str) -> Result<Self, Self::Err> {
150        Ok(Self::from_hex(s)?)
151    }
152}