Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions crates/common/types/transaction.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use std::{cmp::min, fmt::Display};

use crate::{errors::EcdsaError, utils::keccak};
use crate::{
errors::EcdsaError,
utils::{HashBuffer, keccak},
};
use bytes::Bytes;
use ethereum_types::{Address, H256, Signature, U256};
use ethrex_crypto::keccak::keccak_hash;
Expand Down Expand Up @@ -1362,7 +1365,9 @@ impl Transaction {
if let Transaction::PrivilegedL2Transaction(tx) = self {
return tx.get_privileged_hash().unwrap_or_default();
}
crate::utils::keccak(self.encode_canonical_to_vec())
let mut hasher = HashBuffer::new();
self.encode_canonical(&mut hasher);
H256::from_slice(&hasher.finalize())
}

pub fn hash(&self) -> H256 {
Expand Down
79 changes: 78 additions & 1 deletion crates/common/utils.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::H256;
use bytes::{Buf, BufMut};
use ethereum_types::U256;
use ethrex_crypto::keccak::keccak_hash;
use ethrex_crypto::keccak::{Keccak256, keccak_hash};
use hex::FromHexError;

pub const ZERO_U256: U256 = U256([0, 0, 0, 0]);
Expand Down Expand Up @@ -79,6 +80,82 @@ pub fn truncate_array<const N: usize, const M: usize>(data: [u8; N]) -> [u8; M]
res
}

/// A buffer to hash the data passed by the trait BufMut, to avoid creating a temporary (Vec) buffer when hashing for example RLP encoded transactions.
pub struct HashBuffer {
hasher: Keccak256,
}

impl Default for HashBuffer {
fn default() -> Self {
Self::new()
}
}

impl HashBuffer {
#[inline]
pub fn new() -> Self {
Self {
hasher: Keccak256::new(),
}
}

#[inline]
pub fn finalize(self) -> [u8; 32] {
self.hasher.finalize()
}
}

unsafe impl BufMut for HashBuffer {
#[inline]
fn remaining_mut(&self) -> usize {
usize::MAX
}

unsafe fn advance_mut(&mut self, _cnt: usize) {
unreachable!("advance_mut should not be called on HashBuffer")
}

fn chunk_mut(&mut self) -> &mut bytes::buf::UninitSlice {
unreachable!("chunk_mut should not be called on HashBuffer")
}

#[inline]
fn put_u8(&mut self, n: u8) {
self.hasher.update([n]);
}

#[inline]
fn put_slice(&mut self, src: &[u8]) {
self.hasher.update(src);
}

#[inline]
fn put_bytes(&mut self, val: u8, mut cnt: usize) {
let chunk = [val; 64];

while cnt >= 64 {
self.hasher.update(chunk);
cnt -= 64;
}

if cnt > 0 {
self.hasher.update(&chunk[..cnt]);
}
}

#[inline]
fn put<T: Buf>(&mut self, mut src: T)
where
Self: Sized,
{
while src.has_remaining() {
let chunk = src.chunk();
self.hasher.update(chunk);
src.advance(chunk.len());
}
}
}

#[cfg(test)]
mod test {
use ethereum_types::U256;
Expand Down
Loading