-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash.rs
161 lines (146 loc) · 5.06 KB
/
hash.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
//! module to provide some handy interfaces atop the hashes so we have
//! the common interfaces for the project to work with.
use alloc::string::String;
use core::hash::{Hash, Hasher};
use core::str::FromStr;
use core::{error, fmt, result};
use crate::chain_crypto::bech32::{self, Bech32};
use crate::error::FromHexErrorWrapper;
use cryptoxide::blake2b::Blake2b;
use cryptoxide::digest::Digest as _;
use cryptoxide::sha3;
use hex::FromHexError;
#[derive(Debug, PartialEq, Clone)]
pub enum Error {
InvalidHashSize(usize, usize),
InvalidHexEncoding(FromHexErrorWrapper),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::InvalidHashSize(sz, expected) => write!(
f,
"invalid hash size, expected {expected} but received {sz} bytes.",
),
Error::InvalidHexEncoding(_) => write!(f, "invalid hex encoding for hash value"),
}
}
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Error::InvalidHashSize(..) => None,
Error::InvalidHexEncoding(err) => Some(err),
}
}
}
impl From<FromHexError> for Error {
fn from(err: FromHexError) -> Self {
Error::InvalidHexEncoding((&err).into())
}
}
pub type Result<T> = result::Result<T, Error>;
/// defines a blake2b object
macro_rules! define_blake2b_new {
($hash_ty:ty) => {
impl $hash_ty {
pub fn new(buf: &[u8]) -> Self {
let mut b2b = Blake2b::new(Self::HASH_SIZE);
let mut out = [0; Self::HASH_SIZE];
b2b.input(buf);
b2b.result(&mut out);
Self::from(out)
}
}
};
}
macro_rules! define_hash_object {
($hash_ty:ty, $constructor:expr, $hash_size:ident, $bech32_hrp:expr) => {
impl $hash_ty {
pub const HASH_SIZE: usize = $hash_size;
pub fn as_hash_bytes(&self) -> &[u8; Self::HASH_SIZE] {
&self.0
}
pub fn try_from_slice(slice: &[u8]) -> Result<Self> {
if slice.len() != Self::HASH_SIZE {
return Err(Error::InvalidHashSize(slice.len(), Self::HASH_SIZE));
}
let mut buf = [0; Self::HASH_SIZE];
buf[0..Self::HASH_SIZE].clone_from_slice(slice);
Ok(Self::from(buf))
}
}
impl AsRef<[u8]> for $hash_ty {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl From<$hash_ty> for [u8; $hash_size] {
fn from(bytes: $hash_ty) -> Self {
bytes.0
}
}
impl<'a> From<&'a $hash_ty> for &'a [u8; $hash_size] {
fn from(bytes: &'a $hash_ty) -> Self {
&bytes.0
}
}
impl From<[u8; Self::HASH_SIZE]> for $hash_ty {
fn from(bytes: [u8; Self::HASH_SIZE]) -> Self {
$constructor(bytes)
}
}
impl Hash for $hash_ty {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.hash(state)
}
}
impl FromStr for $hash_ty {
type Err = Error;
fn from_str(s: &str) -> result::Result<Self, Self::Err> {
let bytes = hex::decode(s)?;
Self::try_from_slice(&bytes)
}
}
impl fmt::Display for $hash_ty {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", hex::encode(self.as_ref()))
}
}
impl fmt::Debug for $hash_ty {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(concat!(stringify!($hash_ty), "(0x"))?;
write!(f, "{}", hex::encode(self.as_ref()))?;
f.write_str(")")
}
}
impl Bech32 for $hash_ty {
const BECH32_HRP: &'static str = $bech32_hrp;
fn try_from_bech32_str(bech32_str: &str) -> bech32::Result<Self> {
let bytes = bech32::try_from_bech32_to_bytes::<Self>(bech32_str)?;
Self::try_from_slice(&bytes).map_err(bech32::Error::data_invalid)
}
fn to_bech32_str(&self) -> String {
bech32::to_bech32_from_bytes::<Self>(self.as_ref())
}
}
};
}
pub const HASH_SIZE_256: usize = 32;
/// Blake2b 256 bits
#[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
pub struct Blake2b256([u8; HASH_SIZE_256]);
define_hash_object!(Blake2b256, Blake2b256, HASH_SIZE_256, "blake2b256");
define_blake2b_new!(Blake2b256);
#[derive(PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
pub struct Sha3_256([u8; HASH_SIZE_256]);
define_hash_object!(Sha3_256, Sha3_256, HASH_SIZE_256, "sha3256");
impl Sha3_256 {
pub fn new(buf: &[u8]) -> Self {
let mut sh3 = sha3::Sha3_256::new();
let mut out = [0; Self::HASH_SIZE];
sh3.input(buf.as_ref());
sh3.result(&mut out);
Self::from(out)
}
}