use amplify::Wrapper;
use bitcoin_hashes::hex::FromHex;
use bitcoin_hashes::{hex, sha256, sha256t, Error, Hash, HashEngine};
#[cfg(feature = "serde")]
use serde_with::{As, DisplayFromStr};
use crate::Slice32;
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate", transparent)
)]
#[derive(
Wrapper,
Clone,
Copy,
PartialEq,
Eq,
PartialOrd,
Ord,
Hash,
Debug,
Display,
From,
)]
#[display(LowerHex)]
#[wrapper(FromStr, LowerHex, UpperHex)]
pub struct Midstate(
#[cfg_attr(feature = "serde", serde(with = "As::<DisplayFromStr>"))]
Slice32,
);
impl Midstate {
pub fn with(tag: impl AsRef<[u8]>) -> Self {
let mut engine = sha256::Hash::engine();
let tag_hash = sha256::Hash::hash(tag.as_ref());
engine.input(&tag_hash[..]);
engine.input(&tag_hash[..]);
Self::from_inner(engine.midstate().into_inner().into())
}
}
pub trait TaggedHash<'a, T>
where
Self: Wrapper<Inner = sha256t::Hash<T>>,
T: 'a + sha256t::Tag,
{
fn hash(msg: impl AsRef<[u8]>) -> Self
where
Self: Sized,
{
Self::from_inner(sha256t::Hash::hash(msg.as_ref()))
}
fn from_hash<X>(hash: X) -> Self
where
Self: Sized,
X: Hash<Inner = [u8; 32]>,
{
Self::from_inner(sha256t::Hash::from_inner(hash.into_inner()))
}
fn from_slice(slice: &[u8]) -> Result<Self, Error>
where
Self: Sized,
{
sha256t::Hash::from_slice(slice).map(Self::from_inner)
}
fn as_slice(&'a self) -> &'a [u8; 32] {
self.as_inner().as_inner()
}
fn from_hex(hex: &str) -> Result<Self, hex::Error>
where
Self: Sized,
{
Ok(Self::from_inner(sha256t::Hash::from_hex(hex)?))
}
}
impl<'a, U, T> TaggedHash<'a, T> for U
where
U: Wrapper<Inner = sha256t::Hash<T>>,
T: 'a + sha256t::Tag,
{
}