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