Skip to main content

merkle_tree/
hash.rs

1use std::{
2    fmt,
3    ops::{Deref, DerefMut},
4    str::FromStr,
5};
6
7use hex::FromHexError;
8use sha2::Digest;
9
10#[derive(Debug, Clone, PartialEq, Eq, Default)]
11pub struct Hash(pub Vec<u8>);
12pub type Data = Hash;
13
14/// Which side to put Hash on when concatinating proof hashes
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub enum HashDirection {
17    Left,
18    Right,
19}
20
21pub fn hash_data<T: AsRef<[u8]>>(data: &T) -> Hash {
22    sha2::Sha256::digest(data.as_ref()).to_vec().into()
23}
24
25pub fn hash_concat<T: AsRef<[u8]>>(h1: &T, h2: &T) -> Hash {
26    hash_data(&[h1.as_ref(), h2.as_ref()].concat())
27}
28
29impl FromStr for Hash {
30    type Err = FromHexError;
31
32    fn from_str(data: &str) -> Result<Self, Self::Err> {
33        Ok(Hash(hex::decode(data)?))
34    }
35}
36
37impl fmt::Display for Hash {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        write!(f, "{}", hex::encode(&self.0))
40    }
41}
42
43impl Deref for Hash {
44    type Target = Vec<u8>;
45    fn deref(&self) -> &Self::Target {
46        &self.0
47    }
48}
49
50impl DerefMut for Hash {
51    fn deref_mut(&mut self) -> &mut Self::Target {
52        &mut self.0
53    }
54}
55
56impl AsRef<[u8]> for Hash {
57    fn as_ref(&self) -> &[u8] {
58        &self.0
59    }
60}
61
62impl From<Vec<u8>> for Hash {
63    fn from(value: Vec<u8>) -> Self {
64        Self(value)
65    }
66}