tempo_commonware_node/consensus/
digest.rs

1//! [`Digest`] is a wrapper around [`B256`] to use eth block hash in commonware simplex.
2
3use std::ops::Deref;
4
5use alloy_primitives::B256;
6use commonware_codec::{FixedSize, Read, ReadExt as _, Write};
7use commonware_utils::{Array, Span};
8
9/// Wrapper around [`B256`] to use it in places requiring [`commonware_cryptography::Digest`].
10#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
11#[repr(transparent)]
12pub struct Digest(pub(crate) B256);
13
14impl Array for Digest {}
15
16impl AsRef<[u8]> for Digest {
17    fn as_ref(&self) -> &[u8] {
18        self.0.as_ref()
19    }
20}
21
22impl Deref for Digest {
23    type Target = [u8];
24
25    fn deref(&self) -> &Self::Target {
26        self.0.deref()
27    }
28}
29
30impl commonware_cryptography::Digest for Digest {
31    /// Generate a random digest.
32    ///
33    /// # Note
34    ///
35    /// One-to-one copy of [`commonware_cryptography::Digest`]
36    /// for [`commonware_cryptography::sha256::Digest`].
37    fn random<R: rand::RngCore + rand::CryptoRng>(rng: &mut R) -> Self {
38        let mut array = B256::ZERO;
39        rng.fill_bytes(&mut *array);
40        Self(array)
41    }
42}
43
44impl FixedSize for Digest {
45    const SIZE: usize = 32;
46}
47
48impl std::fmt::Display for Digest {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        self.0.fmt(f)
51    }
52}
53
54impl Read for Digest {
55    type Cfg = ();
56
57    fn read_cfg(
58        buf: &mut impl bytes::Buf,
59        _cfg: &Self::Cfg,
60    ) -> Result<Self, commonware_codec::Error> {
61        let array = <[u8; 32]>::read(buf)?;
62        Ok(Self(B256::new(array)))
63    }
64}
65
66impl Span for Digest {}
67
68impl Write for Digest {
69    fn write(&self, buf: &mut impl bytes::BufMut) {
70        self.0.write(buf)
71    }
72}