Skip to content
This repository has been archived by the owner on Sep 4, 2024. It is now read-only.

Commit

Permalink
Rename HashEngine structs to Engine
Browse files Browse the repository at this point in the history
Currently we use the same name for the hash engine trait and the structs
in each module. There is no real additional information in, for example,
`sha256::HashEngine` compared to `sha256::Engine`. Use the more terse
`Engine` and remove the overloading of the term.
  • Loading branch information
tcharding committed May 14, 2024
1 parent 5ebfa0f commit bf5393d
Show file tree
Hide file tree
Showing 12 changed files with 140 additions and 139 deletions.
35 changes: 18 additions & 17 deletions src/hmac.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use core::{fmt, ops, str};

use hex::DisplayHex;

use crate::FromSliceError;
use crate::{FromSliceError, HashEngine};

/// A hash computed from a RFC 2104 HMAC. Parameterized by the size of the underlying hash function.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
Expand All @@ -22,7 +22,7 @@ impl<const N: usize> Hash<N> {
/// Returns a hash engine that is ready to be used for the data.
pub fn engine<E>() -> E
where
E: crate::HashEngine<Digest = [u8; N]>,
E: HashEngine<Digest = [u8; N]>,
{
E::new()
}
Expand All @@ -32,7 +32,7 @@ impl<const N: usize> Hash<N> {
/// This is equivalent to calling `Hash::from_byte_array(engine.finalize())`.
pub fn from_engine<E>(engine: E) -> Self
where
E: crate::HashEngine<Digest = [u8; N]>,
E: HashEngine<Digest = [u8; N]>,
{
let digest = engine.finalize();
Self::from_byte_array(digest)
Expand Down Expand Up @@ -183,7 +183,7 @@ impl<'de, const N: usize> crate::serde::Deserialize<'de> for Hash<N> {
}

/// Pair of underlying hash midstates which represent the current state of an `HashEngine`.
pub struct MidState<E: crate::HashEngine> {
pub struct MidState<E: HashEngine> {
/// Midstate of the inner hash engine
pub inner: E::Midstate,
/// Midstate of the outer hash engine
Expand All @@ -192,32 +192,32 @@ pub struct MidState<E: crate::HashEngine> {

/// Pair of underlying hash engines, used for the inner and outer hash of HMAC.
#[derive(Clone)]
pub struct HashEngine<E: crate::HashEngine> {
pub struct Engine<E: HashEngine> {
iengine: E,
oengine: E,
}

impl<E: crate::HashEngine> Default for HashEngine<E> {
fn default() -> Self { HashEngine::new(&[]) }
impl<E: HashEngine> Default for Engine<E> {
fn default() -> Self { Engine::new(&[]) }
}

impl<E: crate::HashEngine> HashEngine<E> {
impl<E: HashEngine> Engine<E> {
/// Constructs a new keyed HMAC from `key`.
///
/// We only support hash engines whose internal block sizes are ≤ 128 bytes.
///
/// # Panics
///
/// Larger block sizes will result in a panic.
pub fn new(key: &[u8]) -> HashEngine<E> {
pub fn new(key: &[u8]) -> Engine<E> {
debug_assert!(E::BLOCK_SIZE <= 128);

let mut ipad = [0x36u8; 128];
let mut opad = [0x5cu8; 128];
let mut ret = HashEngine { iengine: E::default(), oengine: E::default() };
let mut ret = Engine { iengine: E::default(), oengine: E::default() };

if key.len() > E::BLOCK_SIZE {
let hash = <E as crate::HashEngine>::hash(key);
let hash = <E as HashEngine>::hash(key);
for (b_i, b_h) in ipad.iter_mut().zip(hash.as_ref()) {
*b_i ^= *b_h;
}
Expand All @@ -239,7 +239,7 @@ impl<E: crate::HashEngine> HashEngine<E> {
}
}

impl<E: crate::HashEngine> crate::HashEngine for HashEngine<E> {
impl<E: HashEngine> HashEngine for Engine<E> {
type Digest = E::Digest;
type Midstate = Midstate<E>;
const BLOCK_SIZE: usize = E::BLOCK_SIZE;
Expand All @@ -264,7 +264,7 @@ impl<E: crate::HashEngine> crate::HashEngine for HashEngine<E> {

#[inline]
fn from_midstate(midstate: Midstate<E>, length: usize) -> Self {
HashEngine {
Engine {
iengine: E::from_midstate(midstate.inner, length),
oengine: E::from_midstate(midstate.outer, length),
}
Expand All @@ -274,7 +274,7 @@ impl<E: crate::HashEngine> crate::HashEngine for HashEngine<E> {
/// Pair of underlying hash engine midstates which represent the current state of an `HashEngine`.
// TODO: Use derives?
//#[derive(Copy, Clone, PartialEq, Eq, Default, PartialOrd, Ord, Hash)]
pub struct Midstate<E: crate::HashEngine> {
pub struct Midstate<E: HashEngine> {
/// Midstate of the inner hash engine.
pub inner: E::Midstate,
/// Midstate of the outer hash engine.
Expand Down Expand Up @@ -402,7 +402,7 @@ mod tests {
];

for test in tests {
let mut engine = HashEngine::<sha256::HashEngine>::new(&test.key);
let mut engine = Engine::<sha256::Engine>::new(&test.key);
engine.input(&test.input);
let hash = engine.finalize();
assert_eq!(&hash[..], &test.output[..]);
Expand All @@ -413,9 +413,10 @@ mod tests {
#[cfg(feature = "serde")]
#[test]
fn hmac_sha512_serde() {
use crate::hmac;
use serde_test::{assert_tokens, Configure, Token};

use crate::hmac;

#[rustfmt::skip]
static HASH_BYTES: [u8; 64] = [
0x8b, 0x41, 0xe1, 0xb7, 0x8a, 0xd1, 0x15, 0x21,
Expand Down Expand Up @@ -445,7 +446,7 @@ mod tests {
use super::*;
use crate::sha256;

let engine: HashEngine<sha256::HashEngine> = Default::default();
let engine: Engine<sha256::Engine> = Default::default();
let hmac = Hash::from_engine(engine);
let hint = hmac.0.iter().size_hint().1;

Expand Down
43 changes: 21 additions & 22 deletions src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,57 +7,56 @@

use bitcoin_io::impl_write;

use crate::{hmac, ripemd160, sha1, sha256, sha256t, sha512, siphash24, HashEngine as _};
use crate::{hmac, ripemd160, sha1, sha256, sha256t, sha512, siphash24, HashEngine};

impl_write!(
sha1::HashEngine,
|us: &mut sha1::HashEngine, buf| {
sha1::Engine,
|us: &mut sha1::Engine, buf| {
us.input(buf);
Ok(buf.len())
},
|_us| { Ok(()) }
);

impl_write!(
sha256::HashEngine,
|us: &mut sha256::HashEngine, buf| {
sha256::Engine,
|us: &mut sha256::Engine, buf| {
us.input(buf);
Ok(buf.len())
},
|_us| { Ok(()) }
);

impl_write!(
sha512::HashEngine,
|us: &mut sha512::HashEngine, buf| {
sha512::Engine,
|us: &mut sha512::Engine, buf| {
us.input(buf);
Ok(buf.len())
},
|_us| { Ok(()) }
);

impl_write!(
ripemd160::HashEngine,
|us: &mut ripemd160::HashEngine, buf| {
ripemd160::Engine,
|us: &mut ripemd160::Engine, buf| {
us.input(buf);
Ok(buf.len())
},
|_us| { Ok(()) }
);

impl_write!(
siphash24::HashEngine,
|us: &mut siphash24::HashEngine, buf| {
siphash24::Engine,
|us: &mut siphash24::Engine, buf| {
us.input(buf);
Ok(buf.len())
},
|_us| { Ok(()) }
);

impl<E: crate::HashEngine> bitcoin_io::Write for hmac::HashEngine<E> {
impl<E: HashEngine> bitcoin_io::Write for hmac::Engine<E> {
#[inline]
fn write(&mut self, buf: &[u8]) -> Result<usize, bitcoin_io::Error> {
use crate::HashEngine as _;
self.input(buf);
Ok(buf.len())
}
Expand All @@ -67,7 +66,7 @@ impl<E: crate::HashEngine> bitcoin_io::Write for hmac::HashEngine<E> {
}

#[cfg(feature = "std")]
impl<E: crate::HashEngine> std::io::Write for hmac::HashEngine<E> {
impl<E: HashEngine> std::io::Write for hmac::Engine<E> {
#[inline]
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.input(buf);
Expand All @@ -79,8 +78,8 @@ impl<E: crate::HashEngine> std::io::Write for hmac::HashEngine<E> {
}

impl_write!(
sha256t::HashEngine<T>,
|us: &mut sha256t::HashEngine<T>, buf| {
sha256t::Engine<T>,
|us: &mut sha256t::Engine<T>, buf| {
us.input(buf);
Ok(buf.len())
},
Expand All @@ -98,17 +97,17 @@ mod tests {
($mod:ident, $exp_empty:expr, $exp_256:expr, $exp_64k:expr,) => {
#[test]
fn $mod() {
let mut engine = $mod::HashEngine::new();
let mut engine = $mod::Engine::new();
engine.write_all(&[]).unwrap();
let hash = $mod::Hash::from_engine(engine);
assert_eq!(format!("{}", hash), $exp_empty);

let mut engine = $mod::HashEngine::new();
let mut engine = $mod::Engine::new();
engine.write_all(&[1; 256]).unwrap();
let hash = $mod::Hash::from_engine(engine);
assert_eq!(format!("{}", hash), $exp_256);

let mut engine = $mod::HashEngine::new();
let mut engine = $mod::Engine::new();
engine.write_all(&[99; 64000]).unwrap();
let hash = $mod::Hash::from_engine(engine);
assert_eq!(format!("{}", hash), $exp_64k);
Expand Down Expand Up @@ -151,21 +150,21 @@ mod tests {

#[test]
fn hmac() {
let mut engine = hmac::HashEngine::<sha256::HashEngine>::new(&[0xde, 0xad, 0xbe, 0xef]);
let mut engine = hmac::Engine::<sha256::Engine>::new(&[0xde, 0xad, 0xbe, 0xef]);
engine.write_all(&[]).unwrap();
assert_eq!(
format!("{}", hmac::Hash::from_engine(engine)),
"bf5515149cf797955c4d3194cca42472883281951697c8375d9d9b107f384225"
);

let mut engine = hmac::HashEngine::<sha256::HashEngine>::new(&[0xde, 0xad, 0xbe, 0xef]);
let mut engine = hmac::Engine::<sha256::Engine>::new(&[0xde, 0xad, 0xbe, 0xef]);
engine.write_all(&[1; 256]).unwrap();
assert_eq!(
format!("{}", hmac::Hash::from_engine(engine)),
"59c9aca10c81c73cb4c196d94db741b6bf2050e0153d5a45f2526bff34675ac5"
);

let mut engine = hmac::HashEngine::<sha256::HashEngine>::new(&[0xde, 0xad, 0xbe, 0xef]);
let mut engine = hmac::Engine::<sha256::Engine>::new(&[0xde, 0xad, 0xbe, 0xef]);
engine.write_all(&[99; 64000]).unwrap();
assert_eq!(
format!("{}", hmac::Hash::from_engine(engine)),
Expand Down
4 changes: 2 additions & 2 deletions src/internal_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,12 +162,12 @@ macro_rules! hash_type {
}

/// Returns a hash engine that is ready to be used for data.
pub fn engine() -> HashEngine { HashEngine::new() }
pub fn engine() -> Engine { Engine::new() }

/// Creates a `Hash` from an `engine`.
///
/// This is equivalent to calling `Hash::from_byte_array(engine.finalize())`.
pub fn from_engine(engine: HashEngine) -> Self {
pub fn from_engine(engine: Engine) -> Self {
let digest = engine.finalize();
Self(digest)
}
Expand Down
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
//! #[cfg(std)]
//! # fn main() -> std::io::Result<()> {
//! let mut reader: &[u8] = b"hello"; // in real code, this could be a `File` or `TcpStream`
//! let mut engine = sha256::HashEngine::default();
//! let mut engine = sha256::Engine::default();
//! std::io::copy(&mut reader, &mut engine)?;
//! let hash = sha256::Hash::from_engine(engine);
//! # Ok(())
Expand All @@ -58,7 +58,7 @@
//! let mut part1: &[u8] = b"hello";
//! let mut part2: &[u8] = b" ";
//! let mut part3: &[u8] = b"world";
//! let mut engine = sha256::HashEngine::default();
//! let mut engine = sha256::Engine::default();
//! engine.write_all(part1)?;
//! engine.write_all(part2)?;
//! engine.write_all(part3)?;
Expand Down
18 changes: 9 additions & 9 deletions src/ripemd160.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use core::str;

use crate::HashEngine as _;
use crate::HashEngine;

crate::internal_macros::hash_type! {
160,
Expand All @@ -15,23 +15,23 @@ const BLOCK_SIZE: usize = 64;

/// Engine to compute RIPEMD160 hash function.
#[derive(Clone)]
pub struct HashEngine {
pub struct Engine {
buffer: [u8; BLOCK_SIZE],
h: [u32; 5],
length: usize,
}

impl Default for HashEngine {
impl Default for Engine {
fn default() -> Self {
HashEngine {
Engine {
h: [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0],
length: 0,
buffer: [0; BLOCK_SIZE],
}
}
}

impl crate::HashEngine for HashEngine {
impl HashEngine for Engine {
type Digest = [u8; 20];
type Midstate = [u8; 20];
const BLOCK_SIZE: usize = BLOCK_SIZE;
Expand Down Expand Up @@ -87,15 +87,15 @@ impl crate::HashEngine for HashEngine {
}

#[inline]
fn from_midstate(midstate: Self::Midstate, length: usize) -> HashEngine {
fn from_midstate(midstate: Self::Midstate, length: usize) -> Engine {
assert!(length % BLOCK_SIZE == 0, "length is no multiple of the block size");

let mut ret = [0; 5];
for (ret_val, midstate_bytes) in ret.iter_mut().zip(midstate[..].chunks_exact(4)) {
*ret_val = u32::from_be_bytes(midstate_bytes.try_into().expect("4 byte slice"));
}

HashEngine { buffer: [0; BLOCK_SIZE], h: ret, length }
Engine { buffer: [0; BLOCK_SIZE], h: ret, length }
}
}

Expand Down Expand Up @@ -224,7 +224,7 @@ macro_rules! process_block(
});
);

impl HashEngine {
impl Engine {
fn process_block(&mut self) {
debug_assert_eq!(self.buffer.len(), BLOCK_SIZE);

Expand Down Expand Up @@ -504,7 +504,7 @@ mod tests {
);

// Hash through engine, checking that we can input byte by byte
let mut engine = ripemd160::HashEngine::new();
let mut engine = ripemd160::Engine::new();
for ch in test.input.as_bytes() {
engine.input(&[*ch]);
}
Expand Down
Loading

0 comments on commit bf5393d

Please sign in to comment.