2023-04-30 23:26:36 +00:00
|
|
|
// SPDX-License-Identifier: CC0-1.0
|
2022-09-16 01:52:57 +00:00
|
|
|
|
|
|
|
//! SHA256t implementation (tagged SHA256).
|
|
|
|
//!
|
|
|
|
|
|
|
|
use core::marker::PhantomData;
|
|
|
|
use core::ops::Index;
|
|
|
|
use core::slice::SliceIndex;
|
2023-02-21 23:25:12 +00:00
|
|
|
use core::{cmp, str};
|
2022-09-16 01:52:57 +00:00
|
|
|
|
2023-05-24 03:29:30 +00:00
|
|
|
use crate::{sha256, FromSliceError};
|
2022-09-16 01:52:57 +00:00
|
|
|
|
|
|
|
type HashEngine = sha256::HashEngine;
|
|
|
|
|
|
|
|
/// Trait representing a tag that can be used as a context for SHA256t hashes.
|
|
|
|
pub trait Tag {
|
|
|
|
/// Returns a hash engine that is pre-tagged and is ready to be used for the data.
|
|
|
|
fn engine() -> sha256::HashEngine;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Output of the SHA256t hash function.
|
|
|
|
#[repr(transparent)]
|
2023-03-23 05:06:56 +00:00
|
|
|
pub struct Hash<T: Tag>([u8; 32], PhantomData<T>);
|
|
|
|
|
|
|
|
#[cfg(feature = "schemars")]
|
|
|
|
impl<T: Tag> schemars::JsonSchema for Hash<T> {
|
|
|
|
fn schema_name() -> String { "Hash".to_owned() }
|
|
|
|
|
|
|
|
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
|
2023-09-28 00:55:33 +00:00
|
|
|
let mut schema: schemars::schema::SchemaObject = <String>::json_schema(gen).into();
|
|
|
|
schema.string = Some(Box::new(schemars::schema::StringValidation {
|
|
|
|
max_length: Some(32 * 2),
|
|
|
|
min_length: Some(32 * 2),
|
|
|
|
pattern: Some("[0-9a-fA-F]+".to_owned()),
|
|
|
|
}));
|
|
|
|
schema.into()
|
2023-03-23 05:06:56 +00:00
|
|
|
}
|
|
|
|
}
|
2022-09-16 01:52:57 +00:00
|
|
|
|
|
|
|
impl<T: Tag> Hash<T> {
|
2023-02-21 23:25:12 +00:00
|
|
|
fn internal_new(arr: [u8; 32]) -> Self { Hash(arr, Default::default()) }
|
2022-09-16 01:52:57 +00:00
|
|
|
|
2023-02-21 23:25:12 +00:00
|
|
|
fn internal_engine() -> HashEngine { T::engine() }
|
2022-09-16 01:52:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: Tag> Copy for Hash<T> {}
|
|
|
|
impl<T: Tag> Clone for Hash<T> {
|
2023-08-25 02:08:56 +00:00
|
|
|
fn clone(&self) -> Self { *self }
|
2022-09-16 01:52:57 +00:00
|
|
|
}
|
|
|
|
impl<T: Tag> PartialEq for Hash<T> {
|
2023-02-21 23:25:12 +00:00
|
|
|
fn eq(&self, other: &Hash<T>) -> bool { self.0 == other.0 }
|
2022-09-16 01:52:57 +00:00
|
|
|
}
|
|
|
|
impl<T: Tag> Eq for Hash<T> {}
|
|
|
|
impl<T: Tag> Default for Hash<T> {
|
2023-02-21 23:25:12 +00:00
|
|
|
fn default() -> Self { Hash([0; 32], PhantomData) }
|
2022-09-16 01:52:57 +00:00
|
|
|
}
|
|
|
|
impl<T: Tag> PartialOrd for Hash<T> {
|
|
|
|
fn partial_cmp(&self, other: &Hash<T>) -> Option<cmp::Ordering> {
|
|
|
|
Some(cmp::Ord::cmp(self, other))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
impl<T: Tag> Ord for Hash<T> {
|
2023-02-21 23:25:12 +00:00
|
|
|
fn cmp(&self, other: &Hash<T>) -> cmp::Ordering { cmp::Ord::cmp(&self.0, &other.0) }
|
2022-09-16 01:52:57 +00:00
|
|
|
}
|
|
|
|
impl<T: Tag> core::hash::Hash for Hash<T> {
|
2023-02-21 23:25:12 +00:00
|
|
|
fn hash<H: core::hash::Hasher>(&self, h: &mut H) { self.0.hash(h) }
|
2022-09-16 01:52:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
crate::internal_macros::hash_trait_impls!(256, true, T: Tag);
|
|
|
|
|
|
|
|
fn from_engine<T: Tag>(e: sha256::HashEngine) -> Hash<T> {
|
|
|
|
use crate::Hash as _;
|
|
|
|
|
2023-01-28 22:47:24 +00:00
|
|
|
Hash::from_byte_array(sha256::Hash::from_engine(e).to_byte_array())
|
2022-09-16 01:52:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Macro used to define a newtype tagged hash.
|
2023-04-02 13:09:48 +00:00
|
|
|
///
|
|
|
|
/// This macro creates two types:
|
|
|
|
///
|
|
|
|
/// * a tag struct
|
|
|
|
/// * a hash wrapper
|
|
|
|
///
|
|
|
|
/// The syntax is:
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// # use bitcoin_hashes::sha256t_hash_newtype;
|
|
|
|
/// sha256t_hash_newtype! {
|
|
|
|
/// /// Optional documentation details here.
|
|
|
|
/// /// Summary is always generated.
|
|
|
|
/// pub struct FooTag = hash_str("foo");
|
|
|
|
///
|
|
|
|
/// /// A foo hash.
|
|
|
|
/// // Direction works just like in case of hash_newtype! macro.
|
|
|
|
/// #[hash_newtype(forward)]
|
|
|
|
/// pub struct FooHash(_);
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// The structs must be defined in this order - tag first, then hash type. `hash_str` marker
|
|
|
|
/// says the midstate should be generated by hashing the supplied string in a way described in
|
|
|
|
/// BIP-341. Alternatively, you can supply `hash_bytes` to hash raw bytes. If you have the midstate
|
|
|
|
/// already pre-computed and prefer **compiler** performance to readability you may use
|
2024-01-05 15:10:52 +00:00
|
|
|
/// `raw(MIDSTATE_BYTES, HASHED_BYTES_LENGTH)` instead.
|
2023-04-02 13:09:48 +00:00
|
|
|
///
|
|
|
|
/// Both visibility modifiers and attributes are optional and passed to inner structs (excluding
|
|
|
|
/// `#[hash_newtype(...)]`). The attributes suffer same compiler performance limitations as in
|
|
|
|
/// [`hash_newtype`] macro.
|
|
|
|
///
|
|
|
|
/// The macro accepts multiple inputs so you can define multiple hash newtypes in one macro call.
|
|
|
|
/// Just make sure to enter the structs in order `Tag0`, `Hash0`, `Tag1`, `Hash1`...
|
|
|
|
///
|
|
|
|
/// [`hash_newtype`]: crate::hash_newtype
|
2022-09-16 01:52:57 +00:00
|
|
|
#[macro_export]
|
|
|
|
macro_rules! sha256t_hash_newtype {
|
2023-04-02 13:09:48 +00:00
|
|
|
($($(#[$($tag_attr:tt)*])* $tag_vis:vis struct $tag:ident = $constructor:tt($($tag_value:tt)+); $(#[$($hash_attr:tt)*])* $hash_vis:vis struct $hash_name:ident($(#[$($field_attr:tt)*])* _);)+) => {
|
|
|
|
$(
|
|
|
|
$crate::sha256t_hash_newtype_tag!($tag_vis, $tag, stringify!($hash_name), $(#[$($tag_attr)*])*);
|
2022-09-16 01:52:57 +00:00
|
|
|
|
|
|
|
impl $crate::sha256t::Tag for $tag {
|
2023-04-02 13:09:48 +00:00
|
|
|
#[inline]
|
2022-09-16 01:52:57 +00:00
|
|
|
fn engine() -> $crate::sha256::HashEngine {
|
2023-04-02 13:09:48 +00:00
|
|
|
const MIDSTATE: ($crate::sha256::Midstate, usize) = $crate::sha256t_hash_newtype_tag_constructor!($constructor, $($tag_value)+);
|
|
|
|
#[allow(unused)]
|
|
|
|
const _LENGTH_CHECK: () = [(); 1][MIDSTATE.1 % 64];
|
|
|
|
$crate::sha256::HashEngine::from_midstate(MIDSTATE.0, MIDSTATE.1)
|
2022-09-16 01:52:57 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-22 08:20:28 +00:00
|
|
|
$crate::hash_newtype! {
|
2023-04-02 13:09:48 +00:00
|
|
|
$(#[$($hash_attr)*])*
|
|
|
|
$hash_vis struct $hash_name($(#[$($field_attr)*])* $crate::sha256t::Hash<$tag>);
|
2023-02-22 08:20:28 +00:00
|
|
|
}
|
2023-04-02 13:09:48 +00:00
|
|
|
)+
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Workaround macros being unavailable in attributes.
|
|
|
|
#[doc(hidden)]
|
|
|
|
#[macro_export]
|
|
|
|
macro_rules! sha256t_hash_newtype_tag {
|
|
|
|
($vis:vis, $tag:ident, $name:expr, $(#[$($attr:meta)*])*) => {
|
|
|
|
#[doc = "The tag used for [`"]
|
|
|
|
#[doc = $name]
|
|
|
|
#[doc = "`]\n\n"]
|
|
|
|
$(#[$($attr)*])*
|
|
|
|
#[derive(Copy, Clone, PartialEq, Eq, Default, PartialOrd, Ord, Hash)]
|
|
|
|
$vis struct $tag;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
#[doc(hidden)]
|
|
|
|
#[macro_export]
|
|
|
|
macro_rules! sha256t_hash_newtype_tag_constructor {
|
|
|
|
(hash_str, $value:expr) => {
|
|
|
|
($crate::sha256::Midstate::hash_tag($value.as_bytes()), 64)
|
|
|
|
};
|
|
|
|
(hash_bytes, $value:expr) => {
|
|
|
|
($crate::sha256::Midstate::hash_tag($value), 64)
|
|
|
|
};
|
|
|
|
(raw, $bytes:expr, $len:expr) => {
|
|
|
|
($crate::sha256::Midstate::from_byte_array($bytes), $len)
|
2022-09-16 01:52:57 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2023-01-21 03:43:48 +00:00
|
|
|
#[cfg(feature = "alloc")]
|
2022-09-16 01:52:57 +00:00
|
|
|
use crate::Hash;
|
2023-02-21 23:25:12 +00:00
|
|
|
use crate::{sha256, sha256t};
|
2022-09-16 01:52:57 +00:00
|
|
|
|
|
|
|
const TEST_MIDSTATE: [u8; 32] = [
|
2023-02-21 23:25:12 +00:00
|
|
|
156, 224, 228, 230, 124, 17, 108, 57, 56, 179, 202, 242, 195, 15, 80, 137, 211, 243, 147,
|
|
|
|
108, 71, 99, 110, 96, 125, 179, 62, 234, 221, 198, 240, 201,
|
2022-09-16 01:52:57 +00:00
|
|
|
];
|
|
|
|
|
|
|
|
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Hash)]
|
|
|
|
pub struct TestHashTag;
|
|
|
|
|
|
|
|
impl sha256t::Tag for TestHashTag {
|
|
|
|
fn engine() -> sha256::HashEngine {
|
|
|
|
// The TapRoot TapLeaf midstate.
|
2023-01-28 22:47:24 +00:00
|
|
|
let midstate = sha256::Midstate::from_byte_array(TEST_MIDSTATE);
|
2022-09-16 01:52:57 +00:00
|
|
|
sha256::HashEngine::from_midstate(midstate, 64)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-28 00:55:33 +00:00
|
|
|
#[cfg(feature = "schemars")]
|
|
|
|
impl schemars::JsonSchema for TestHashTag {
|
|
|
|
fn schema_name() -> String { "Hash".to_owned() }
|
|
|
|
|
|
|
|
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
|
|
|
|
let mut schema: schemars::schema::SchemaObject = <String>::json_schema(gen).into();
|
|
|
|
schema.string = Some(Box::new(schemars::schema::StringValidation {
|
|
|
|
max_length: Some(64 * 2),
|
|
|
|
min_length: Some(64 * 2),
|
|
|
|
pattern: Some("[0-9a-fA-F]+".to_owned()),
|
|
|
|
}));
|
|
|
|
schema.into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-16 01:52:57 +00:00
|
|
|
/// A hash tagged with `$name`.
|
2023-01-21 03:43:48 +00:00
|
|
|
#[cfg(feature = "alloc")]
|
2022-09-16 01:52:57 +00:00
|
|
|
pub type TestHash = sha256t::Hash<TestHashTag>;
|
|
|
|
|
2023-04-02 13:09:48 +00:00
|
|
|
sha256t_hash_newtype! {
|
|
|
|
/// Test detailed explanation.
|
|
|
|
struct NewTypeTag = raw(TEST_MIDSTATE, 64);
|
|
|
|
|
|
|
|
/// A test hash.
|
|
|
|
#[hash_newtype(backward)]
|
|
|
|
struct NewTypeHash(_);
|
|
|
|
}
|
2022-09-16 01:52:57 +00:00
|
|
|
|
|
|
|
#[test]
|
2023-01-21 03:43:48 +00:00
|
|
|
#[cfg(feature = "alloc")]
|
2022-09-16 01:52:57 +00:00
|
|
|
fn test_sha256t() {
|
|
|
|
assert_eq!(
|
2023-01-07 15:39:11 +00:00
|
|
|
TestHash::hash(&[0]).to_string(),
|
2022-09-16 01:52:57 +00:00
|
|
|
"29589d5122ec666ab5b4695070b6debc63881a4f85d88d93ddc90078038213ed"
|
|
|
|
);
|
|
|
|
assert_eq!(
|
2023-01-07 15:39:11 +00:00
|
|
|
NewTypeHash::hash(&[0]).to_string(),
|
2022-09-16 01:52:57 +00:00
|
|
|
"29589d5122ec666ab5b4695070b6debc63881a4f85d88d93ddc90078038213ed"
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|