1use std::fmt::{self, Debug, Display};
4use std::str::FromStr;
5
6use borsh::{BorshDeserialize, BorshSerialize};
7use serde_with::{DeserializeFromStr, SerializeDisplay};
8use sha2::{Digest, Sha256};
9
10use crate::error::ParseHashError;
11
12#[derive(Clone, Copy, PartialEq, Eq, Hash, Default, SerializeDisplay, DeserializeFromStr)]
14pub struct CryptoHash([u8; 32]);
15
16impl CryptoHash {
17 pub const ZERO: Self = Self([0; 32]);
19
20 pub fn hash(data: &[u8]) -> Self {
22 let result = Sha256::digest(data);
23 let mut bytes = [0u8; 32];
24 bytes.copy_from_slice(&result);
25 Self(bytes)
26 }
27
28 pub const fn from_bytes(bytes: [u8; 32]) -> Self {
30 Self(bytes)
31 }
32
33 pub const fn as_bytes(&self) -> &[u8; 32] {
35 &self.0
36 }
37
38 pub fn to_vec(&self) -> Vec<u8> {
40 self.0.to_vec()
41 }
42
43 pub fn is_zero(&self) -> bool {
45 self.0 == [0u8; 32]
46 }
47}
48
49impl FromStr for CryptoHash {
50 type Err = ParseHashError;
51
52 fn from_str(s: &str) -> Result<Self, Self::Err> {
53 let bytes = bs58::decode(s)
54 .into_vec()
55 .map_err(|e| ParseHashError::InvalidBase58(e.to_string()))?;
56
57 if bytes.len() != 32 {
58 return Err(ParseHashError::InvalidLength(bytes.len()));
59 }
60
61 let mut arr = [0u8; 32];
62 arr.copy_from_slice(&bytes);
63 Ok(Self(arr))
64 }
65}
66
67impl TryFrom<&str> for CryptoHash {
68 type Error = ParseHashError;
69
70 fn try_from(s: &str) -> Result<Self, Self::Error> {
71 s.parse()
72 }
73}
74
75impl TryFrom<&[u8]> for CryptoHash {
76 type Error = ParseHashError;
77
78 fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
79 if bytes.len() != 32 {
80 return Err(ParseHashError::InvalidLength(bytes.len()));
81 }
82 let mut arr = [0u8; 32];
83 arr.copy_from_slice(bytes);
84 Ok(Self(arr))
85 }
86}
87
88impl From<[u8; 32]> for CryptoHash {
89 fn from(bytes: [u8; 32]) -> Self {
90 Self(bytes)
91 }
92}
93
94impl AsRef<[u8]> for CryptoHash {
95 fn as_ref(&self) -> &[u8] {
96 &self.0
97 }
98}
99
100impl Display for CryptoHash {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 write!(f, "{}", bs58::encode(&self.0).into_string())
103 }
104}
105
106impl Debug for CryptoHash {
107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108 write!(f, "CryptoHash({})", self)
109 }
110}
111
112impl BorshSerialize for CryptoHash {
113 fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
114 writer.write_all(&self.0)
115 }
116}
117
118impl BorshDeserialize for CryptoHash {
119 fn deserialize_reader<R: std::io::Read>(reader: &mut R) -> std::io::Result<Self> {
120 let mut bytes = [0u8; 32];
121 reader.read_exact(&mut bytes)?;
122 Ok(Self(bytes))
123 }
124}
125
126#[cfg(test)]
127mod tests {
128 use super::*;
129
130 #[test]
131 fn test_hash() {
132 let hash = CryptoHash::hash(b"hello world");
133 assert!(!hash.is_zero());
134 assert_eq!(hash.as_bytes().len(), 32);
135 }
136
137 #[test]
138 fn test_display_parse_roundtrip() {
139 let hash = CryptoHash::hash(b"test data");
140 let s = hash.to_string();
141 let parsed: CryptoHash = s.parse().unwrap();
142 assert_eq!(hash, parsed);
143 }
144
145 #[test]
146 fn test_zero() {
147 assert!(CryptoHash::ZERO.is_zero());
148 assert!(!CryptoHash::hash(b"x").is_zero());
149 }
150
151 #[test]
152 fn test_from_bytes() {
153 let bytes = [42u8; 32];
154 let hash = CryptoHash::from_bytes(bytes);
155 assert_eq!(hash.as_bytes(), &bytes);
156 }
157
158 #[test]
159 fn test_to_vec() {
160 let hash = CryptoHash::hash(b"test");
161 let vec = hash.to_vec();
162 assert_eq!(vec.len(), 32);
163 assert_eq!(vec.as_slice(), hash.as_bytes());
164 }
165
166 #[test]
167 fn test_from_32_byte_array() {
168 let bytes = [1u8; 32];
169 let hash: CryptoHash = bytes.into();
170 assert_eq!(hash.as_bytes(), &bytes);
171 }
172
173 #[test]
174 fn test_try_from_slice_success() {
175 let bytes = [2u8; 32];
176 let hash = CryptoHash::try_from(bytes.as_slice()).unwrap();
177 assert_eq!(hash.as_bytes(), &bytes);
178 }
179
180 #[test]
181 fn test_try_from_slice_wrong_length() {
182 let bytes = [3u8; 16]; let result = CryptoHash::try_from(bytes.as_slice());
184 assert!(matches!(
185 result,
186 Err(crate::error::ParseHashError::InvalidLength(16))
187 ));
188 }
189
190 #[test]
191 fn test_try_from_str() {
192 let hash = CryptoHash::hash(b"test");
193 let s = hash.to_string();
194 let parsed = CryptoHash::try_from(s.as_str()).unwrap();
195 assert_eq!(hash, parsed);
196 }
197
198 #[test]
199 fn test_as_ref() {
200 let hash = CryptoHash::hash(b"test");
201 let slice: &[u8] = hash.as_ref();
202 assert_eq!(slice.len(), 32);
203 assert_eq!(slice, hash.as_bytes());
204 }
205
206 #[test]
207 fn test_debug_format() {
208 let hash = CryptoHash::ZERO;
209 let debug = format!("{:?}", hash);
210 assert!(debug.starts_with("CryptoHash("));
211 assert!(debug.contains("1111111111")); }
213
214 #[test]
215 fn test_parse_invalid_base58() {
216 let result: Result<CryptoHash, _> = "invalid!@#$%base58".parse();
218 assert!(matches!(
219 result,
220 Err(crate::error::ParseHashError::InvalidBase58(_))
221 ));
222 }
223
224 #[test]
225 fn test_parse_wrong_length() {
226 let result: Result<CryptoHash, _> = "3xRDxw".parse();
228 assert!(matches!(
229 result,
230 Err(crate::error::ParseHashError::InvalidLength(_))
231 ));
232 }
233
234 #[test]
235 fn test_serde_roundtrip() {
236 let hash = CryptoHash::hash(b"serde test");
237 let json = serde_json::to_string(&hash).unwrap();
238 let parsed: CryptoHash = serde_json::from_str(&json).unwrap();
239 assert_eq!(hash, parsed);
240 }
241
242 #[test]
243 fn test_borsh_roundtrip() {
244 let hash = CryptoHash::hash(b"borsh test");
245 let bytes = borsh::to_vec(&hash).unwrap();
246 assert_eq!(bytes.len(), 32);
247 let parsed: CryptoHash = borsh::from_slice(&bytes).unwrap();
248 assert_eq!(hash, parsed);
249 }
250
251 #[test]
252 fn test_hash_deterministic() {
253 let hash1 = CryptoHash::hash(b"same input");
254 let hash2 = CryptoHash::hash(b"same input");
255 assert_eq!(hash1, hash2);
256
257 let hash3 = CryptoHash::hash(b"different input");
258 assert_ne!(hash1, hash3);
259 }
260
261 #[test]
262 fn test_default() {
263 let hash = CryptoHash::default();
264 assert!(hash.is_zero());
265 assert_eq!(hash, CryptoHash::ZERO);
266 }
267
268 #[test]
269 fn test_clone() {
270 let hash1 = CryptoHash::hash(b"clone test");
271 #[allow(clippy::clone_on_copy)]
272 let hash2 = hash1.clone(); assert_eq!(hash1, hash2);
274 }
275
276 #[test]
277 fn test_hash_comparison() {
278 let hash1 = CryptoHash::from_bytes([0u8; 32]);
279 let hash2 = CryptoHash::from_bytes([1u8; 32]);
280 assert_ne!(hash1, hash2);
282 assert_eq!(hash1, CryptoHash::ZERO);
283 }
284}