use bincode::{Decode, Encode};
#[cfg(feature = "json")]
use hex::serde as hex_serde;
#[cfg(feature = "json")]
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
#[cfg(feature = "json")]
use crate::serde::utf8_serde;
#[cfg_attr(feature = "json", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
pub struct Hashlock {
#[cfg_attr(feature = "json", serde(with = "hex_serde"))]
pub hash: [u8; 32],
#[cfg_attr(feature = "json", serde(with = "utf8_serde"))]
pub preimage: Vec<u8>,
}
impl Hashlock {
pub fn verify(&self) -> Result<(), Error> {
let computed = Sha256::digest(&self.preimage);
computed[..]
.ct_eq(&self.hash)
.unwrap_u8()
.eq(&1)
.then_some(())
.ok_or(Error::Mismatch)
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("SHA256(preimage) != hash")]
Mismatch,
}