#![allow(clippy::needless_borrow)]
use amplify::{Slice32, Wrapper};
use bitcoin_hashes::hex::FromHex;
use bitcoin_hashes::{hex, sha256, sha256t, Error, Hash, HashEngine};
#[cfg(feature = "serde")]
use serde_with::{As, DisplayFromStr};
#[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<Tag>
where
Self: Sized + Wrapper<Inner = sha256t::Hash<Tag>>,
Tag: sha256t::Tag + 'static,
{
fn hash(msg: impl AsRef<[u8]>) -> Self {
Self::from_inner(sha256t::Hash::hash(msg.as_ref()))
}
fn from_hash(hash: impl Hash<Inner = [u8; 32]>) -> Self {
Self::from_inner(sha256t::Hash::from_inner(hash.into_inner()))
}
fn from_hex(hex: &str) -> Result<Self, hex::Error> {
Ok(Self::from_inner(sha256t::Hash::from_hex(hex)?))
}
fn from_bytes(slice: impl AsRef<[u8]>) -> Result<Self, Error> {
sha256t::Hash::from_slice(slice.as_ref()).map(Self::from_inner)
}
fn from_array(array: [u8; 32]) -> Self {
Self::from_inner(sha256t::Hash::from_inner(array))
}
fn from_engine(engine: sha256::HashEngine) -> Self {
Self::from_inner(sha256t::Hash::from_engine(engine))
}
fn as_slice(&self) -> &[u8] { self.as_inner().as_inner() }
fn into_array(self) -> [u8; 32] { self.into_inner().into_inner() }
fn into_sha356t(self) -> sha256t::Hash<Tag> { self.into_inner() }
fn into_sha256(self) -> sha256::Hash {
sha256::Hash::from_inner(self.into_inner().into_inner())
}
fn to_vec(self) -> Vec<u8> { self.into_array().to_vec() }
}
impl<H, Tag> TaggedHash<Tag> for H
where
H: Wrapper<Inner = sha256t::Hash<Tag>>,
Tag: sha256t::Tag + 'static,
{
}