From 25cb3d3539306a075cf434bfe947e98e16a19a66 Mon Sep 17 00:00:00 2001 From: Elichai Turkel Date: Wed, 8 Apr 2020 15:01:47 +0300 Subject: [PATCH] Remove alloc when hashing for Bitcoin message signing format --- src/util/misc.rs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/util/misc.rs b/src/util/misc.rs index 2ee4fb0c..5a925e34 100644 --- a/src/util/misc.rs +++ b/src/util/misc.rs @@ -16,9 +16,9 @@ //! //! Various utility functions -use hashes::{sha256d, Hash}; +use hashes::{sha256d, Hash, HashEngine}; use blockdata::opcodes; -use consensus::encode; +use consensus::{encode, Encodable}; static MSG_SIGN_PREFIX: &[u8] = b"\x18Bitcoin Signed Message:\n"; @@ -59,14 +59,15 @@ pub fn script_find_and_remove(haystack: &mut Vec, needle: &[u8]) -> usize { /// Hash message for signature using Bitcoin's message signing format pub fn signed_msg_hash(msg: &str) -> sha256d::Hash { - sha256d::Hash::hash( - &[ - MSG_SIGN_PREFIX, - &encode::serialize(&encode::VarInt(msg.len() as u64)), - msg.as_bytes(), - ] - .concat(), - ) + let msg_len = encode::VarInt(msg.len() as u64); + + // TODO: Sanity assert that consensus_encode returned length matches the hashed length in the hasher. + let mut engine = sha256d::Hash::engine(); + engine.input(MSG_SIGN_PREFIX); + msg_len.consensus_encode(&mut engine).unwrap(); + engine.input(msg.as_bytes()); + + sha256d::Hash::from_engine(engine) } #[cfg(test)]