hashes: Strongly type the hash160::HashEngine

Currently we are using a type alias for the `hash160::HashEngine`.

Type alias' allow for potential mixing of types, a `hash160::HashEngine`
struct can better serve our users with not much additional complexity or
maintenance burden.

As we did for the `sha256d::HashEngine`, add a new wrapper type
`hash160::HashEngine` that replaces the current type alias.
This commit is contained in:
Tobin C. Harding 2024-07-09 13:19:15 +10:00
parent d5dd54a489
commit 51010777bf
No known key found for this signature in database
GPG Key ID: 40BF9E4C269D6607
3 changed files with 36 additions and 7 deletions

View File

@ -34,7 +34,7 @@ use core::str::FromStr;
use bech32::primitives::gf32::Fe32;
use bech32::primitives::hrp::Hrp;
use hashes::{sha256, HashEngine};
use hashes::{hash160, HashEngine};
use secp256k1::{Secp256k1, Verification, XOnlyPublicKey};
use crate::consensus::Params;
@ -878,11 +878,11 @@ impl FromStr for Address<NetworkUnchecked> {
}
/// Convert a byte array of a pubkey hash into a segwit redeem hash
fn segwit_redeem_hash(pubkey_hash: PubkeyHash) -> crate::hashes::hash160::Hash {
let mut sha_engine = sha256::Hash::engine();
fn segwit_redeem_hash(pubkey_hash: PubkeyHash) -> hash160::Hash {
let mut sha_engine = hash160::Hash::engine();
sha_engine.input(&[0, 20]);
sha_engine.input(pubkey_hash.as_ref());
crate::hashes::hash160::Hash::from_engine(sha_engine)
hash160::Hash::from_engine(sha_engine)
}
#[cfg(test)]

View File

@ -18,10 +18,30 @@ crate::internal_macros::hash_type! {
"Output of the Bitcoin HASH160 hash function. (RIPEMD160(SHA256))"
}
type HashEngine = sha256::HashEngine;
/// Engine to compute HASH160 hash function.
#[derive(Clone)]
pub struct HashEngine(sha256::HashEngine);
impl HashEngine {
/// Creates a new HASH160 hash engine.
pub const fn new() -> Self { Self(sha256::HashEngine::new()) }
}
impl Default for HashEngine {
fn default() -> Self { Self::new() }
}
impl crate::HashEngine for HashEngine {
type MidState = sha256::Midstate;
fn midstate(&self) -> Self::MidState { self.0.midstate() }
const BLOCK_SIZE: usize = 64; // Same as sha256::HashEngine::BLOCK_SIZE;
fn input(&mut self, data: &[u8]) { self.0.input(data) }
fn n_bytes_hashed(&self) -> usize { self.0.n_bytes_hashed() }
}
fn from_engine(e: HashEngine) -> Hash {
let sha2 = sha256::Hash::from_engine(e);
let sha2 = sha256::Hash::from_engine(e.0);
let rmd = ripemd160::Hash::hash(&sha2[..]);
let mut ret = [0; 20];

View File

@ -6,7 +6,16 @@
use bitcoin_io::impl_write;
use crate::{hmac, ripemd160, sha1, sha256, sha256d, sha512, siphash24, HashEngine};
use crate::{hash160, hmac, ripemd160, sha1, sha256, sha256d, sha512, siphash24, HashEngine};
impl_write!(
hash160::HashEngine,
|us: &mut hash160::HashEngine, buf| {
us.input(buf);
Ok(buf.len())
},
|_us| { Ok(()) }
);
impl_write!(
sha1::HashEngine,