stratus/eth/primitives/
hash.rs1use std::fmt::Display;
2use std::str::FromStr;
3
4use alloy_primitives::B256;
5use anyhow::anyhow;
6use display_json::DebugAsJson;
7use fake::Dummy;
8use fake::Faker;
9
10#[derive(DebugAsJson, Clone, Copy, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
11#[serde(transparent)]
12pub struct Hash(pub B256);
13
14impl Hash {
15 pub const ZERO: Hash = Hash(B256::ZERO);
16
17 pub const fn new(bytes: [u8; 32]) -> Self {
19 Self(B256::new(bytes))
20 }
21}
22
23impl Display for Hash {
24 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25 write!(f, "{}", const_hex::encode_prefixed(self.0))
26 }
27}
28
29impl Dummy<Faker> for Hash {
30 fn dummy_with_rng<R: rand::Rng + ?Sized>(_: &Faker, rng: &mut R) -> Self {
31 B256::random_with(rng).into()
32 }
33}
34
35impl AsRef<[u8]> for Hash {
36 fn as_ref(&self) -> &[u8] {
37 self.0.as_ref()
38 }
39}
40
41impl FromStr for Hash {
46 type Err = anyhow::Error;
47
48 fn from_str(s: &str) -> anyhow::Result<Self> {
49 match B256::from_str(s) {
50 Ok(parsed) => Ok(Self(parsed)),
51 Err(e) => {
52 tracing::warn!(reason = ?e, value = %s, "failed to parse hash");
53 Err(anyhow!("Failed to parse field 'hash' with value '{}'", s.to_owned()))
54 }
55 }
56 }
57}
58
59impl From<B256> for Hash {
60 fn from(value: B256) -> Self {
61 Self(value)
62 }
63}
64
65impl From<[u8; 32]> for Hash {
66 fn from(value: [u8; 32]) -> Self {
67 Self(B256::from(value))
68 }
69}
70
71impl From<Hash> for B256 {
76 fn from(value: Hash) -> Self {
77 value.0
78 }
79}