aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/account.rs25
-rw-r--r--src/account/signature.rs24
-rw-r--r--src/cmd/hash.rs12
-rw-r--r--src/cmd/sign.rs15
-rw-r--r--src/hash.rs18
-rw-r--r--src/lib.rs1
-rw-r--r--src/message.rs10
-rw-r--r--src/mnemonic.rs15
-rw-r--r--src/transaction.rs7
-rw-r--r--src/typeddata.rs50
10 files changed, 83 insertions, 94 deletions
diff --git a/src/account.rs b/src/account.rs
index f862853..f3340aa 100644
--- a/src/account.rs
+++ b/src/account.rs
@@ -4,9 +4,9 @@ mod public;
mod signature;
pub use self::{public::PublicKey, signature::Signature};
-use crate::hash;
use anyhow::Result;
use ethaddr::Address;
+use ethdigest::Digest;
use k256::{
ecdsa::{hazmat::SignPrimitive, SigningKey},
SecretKey,
@@ -40,9 +40,9 @@ impl PrivateKey {
// an uncompressed point) and the subsequent bytes are the coordinates
// we want. So discard the first byte for the address calculation.
debug_assert_eq!(encoded[0], 0x04);
- let hash = hash::keccak256(&encoded[1..]);
+ let digest = Digest::of(&encoded[1..]);
- Address::from_slice(&hash[12..])
+ Address::from_slice(&digest[12..])
}
/// Returns the private key's 32 byte secret.
@@ -51,15 +51,15 @@ impl PrivateKey {
}
/// Generate a signature for the specified message.
- pub fn sign(&self, message: [u8; 32]) -> Signature {
+ pub fn sign(&self, message: Digest) -> Signature {
self.try_sign(message).expect("signature operation failed")
}
/// Generate a signature for the specified message.
- pub fn try_sign(&self, message: [u8; 32]) -> Result<Signature> {
+ pub fn try_sign(&self, message: Digest) -> Result<Signature> {
let (signature, recovery_id) = SigningKey::from(&self.0)
.as_nonzero_scalar()
- .try_sign_prehashed_rfc6979::<Sha256>(&message.into(), b"")?;
+ .try_sign_prehashed_rfc6979::<Sha256>(&message.0.into(), b"")?;
Ok(Signature(signature, recovery_id.unwrap()))
}
}
@@ -74,26 +74,27 @@ impl Debug for PrivateKey {
mod tests {
use super::*;
use crate::ganache::DETERMINISTIC_PRIVATE_KEY;
- use hex_literal::hex;
+ use ethaddr::address;
+ use ethnum::uint;
#[test]
fn ganache_determinitic_address() {
let key = PrivateKey::new(DETERMINISTIC_PRIVATE_KEY).unwrap();
assert_eq!(
- *key.address(),
- hex!("90F8bf6A479f320ead074411a4B0e7944Ea8c9C1"),
+ key.address(),
+ address!("90F8bf6A479f320ead074411a4B0e7944Ea8c9C1"),
);
}
#[test]
fn ganache_deterministic_signature() {
let key = PrivateKey::new(DETERMINISTIC_PRIVATE_KEY).unwrap();
- let message = hash::keccak256(b"\x19Ethereum Signed Message:\n12Hello World!");
+ let message = Digest::of(b"\x19Ethereum Signed Message:\n12Hello World!");
assert_eq!(
key.sign(message),
Signature::from_parts(
- hex!("408790f153cbfa2722fc708a57d97a43b24429724cf060df7c915d468c43bd84"),
- hex!("61c96aac95ce37d7a31087b6634f4a3ea439a9f704b5c818584fa2a32fa83859"),
+ uint!("0x408790f153cbfa2722fc708a57d97a43b24429724cf060df7c915d468c43bd84"),
+ uint!("0x61c96aac95ce37d7a31087b6634f4a3ea439a9f704b5c818584fa2a32fa83859"),
1,
),
);
diff --git a/src/account/signature.rs b/src/account/signature.rs
index ba3b959..dbc47d6 100644
--- a/src/account/signature.rs
+++ b/src/account/signature.rs
@@ -43,9 +43,9 @@ impl Signature {
/// # Panics
///
/// Panics on invalid signature parts.
- pub fn from_parts(r: [u8; 32], s: [u8; 32], y_parity: u8) -> Self {
+ pub fn from_parts(r: U256, s: U256, y_parity: u8) -> Self {
Self(
- ecdsa::Signature::from_scalars(r, s).unwrap(),
+ ecdsa::Signature::from_scalars(r.to_be_bytes(), s.to_be_bytes()).unwrap(),
y_parity.try_into().unwrap(),
)
}
@@ -77,10 +77,13 @@ impl FromStr for Signature {
_ => bail!("invalid V-value, must be 27 or 28 but got {v}"),
};
- Ok(Self::from_parts(
- signature[0..32].try_into().unwrap(),
- signature[32..64].try_into().unwrap(),
- y_parity,
+ Ok(Self(
+ ecdsa::Signature::from_scalars(
+ <[u8; 32]>::try_from(&signature[0..32])?,
+ <[u8; 32]>::try_from(&signature[32..64])?,
+ )
+ .unwrap(),
+ y_parity.try_into()?,
))
}
}
@@ -88,16 +91,21 @@ impl FromStr for Signature {
#[cfg(test)]
mod tests {
use super::*;
+ use ethnum::uint;
#[test]
fn replay_protection() {
- let signature = Signature::from_parts([1; 32], [2; 32], 0);
+ let signature = Signature::from_parts(U256::new(1), U256::new(2), 0);
assert_eq!(signature.v(Some(U256::new(1))), U256::new(37));
}
#[test]
fn signature_to_string() {
- let signature = Signature::from_parts([1; 32], [2; 32], 0);
+ let signature = Signature::from_parts(
+ uint!("0x0101010101010101010101010101010101010101010101010101010101010101"),
+ uint!("0x0202020202020202020202020202020202020202020202020202020202020202"),
+ 0,
+ );
assert_eq!(
signature.to_string(),
"0x0101010101010101010101010101010101010101010101010101010101010101\
diff --git a/src/cmd/hash.rs b/src/cmd/hash.rs
index 4a93d3a..1235d9f 100644
--- a/src/cmd/hash.rs
+++ b/src/cmd/hash.rs
@@ -3,9 +3,9 @@
use crate::cmd;
use anyhow::Result;
use clap::Parser;
+use ethdigest::Digest;
use hdwallet::{
- account::Signature, hash, message::EthereumMessage, transaction::Transaction,
- typeddata::TypedData,
+ account::Signature, message::EthereumMessage, transaction::Transaction, typeddata::TypedData,
};
use std::path::PathBuf;
@@ -59,7 +59,7 @@ enum Input {
}
pub fn run(options: Options) -> Result<()> {
- let hash = match options.input {
+ let digest = match options.input {
Input::Transaction {
transaction,
signature,
@@ -67,7 +67,7 @@ pub fn run(options: Options) -> Result<()> {
let transaction =
serde_json::from_slice::<Transaction>(&cmd::read_input(&transaction)?)?;
match signature {
- Some(signature) => hash::keccak256(transaction.encode(signature)),
+ Some(signature) => Digest::of(transaction.encode(signature)),
None => transaction.signing_message(),
}
}
@@ -88,10 +88,10 @@ pub fn run(options: Options) -> Result<()> {
}
Input::Data { data } => {
let data = cmd::read_input(&data)?;
- hash::keccak256(data)
+ Digest::of(data)
}
};
- println!("0x{}", hex::encode(hash));
+ println!("{digest}");
Ok(())
}
diff --git a/src/cmd/sign.rs b/src/cmd/sign.rs
index d3005ea..75cc2bc 100644
--- a/src/cmd/sign.rs
+++ b/src/cmd/sign.rs
@@ -1,14 +1,15 @@
//! Module implementing the `sign` subcommand for generating ECDSA signatures.
use crate::cmd::{self, AccountOptions};
-use anyhow::{ensure, Context as _, Result};
+use anyhow::{ensure, Result};
use clap::Parser;
+use ethdigest::Digest;
use hdwallet::{
message::EthereumMessage,
transaction::{LegacyTransaction, Transaction},
typeddata::TypedData,
};
-use std::{convert::TryInto, path::PathBuf};
+use std::path::PathBuf;
#[derive(Debug, Parser)]
pub struct Options {
@@ -58,8 +59,8 @@ enum Input {
/// Sign a raw data.
Raw {
/// The 32 byte message to sign specified as a hexadecimal string.
- #[clap(name = "BYTES", value_parser = permissive_hex_digest)]
- message: [u8; 32],
+ #[clap(name = "BYTES")]
+ message: Digest,
},
}
@@ -101,9 +102,3 @@ pub fn run(options: Options) -> Result<()> {
}
Ok(())
}
-
-fn permissive_hex_digest(s: &str) -> Result<[u8; 32]> {
- cmd::permissive_hex(s)?[..]
- .try_into()
- .context("message for signing must be exactly 32 bytes long")
-}
diff --git a/src/hash.rs b/src/hash.rs
deleted file mode 100644
index b3091d2..0000000
--- a/src/hash.rs
+++ /dev/null
@@ -1,18 +0,0 @@
-//! Module implementing various hashing utilities.
-
-use sha2::{Digest as _, Sha256};
-use sha3::Keccak256;
-
-/// Returns the Keccak-256 hash of the specified input.
-pub fn keccak256(data: impl AsRef<[u8]>) -> [u8; 32] {
- let mut hasher = Keccak256::new();
- hasher.update(data.as_ref());
- hasher.finalize().into()
-}
-
-/// Returns the SHA256 hash of the specified input.
-pub fn sha256(data: impl AsRef<[u8]>) -> [u8; 32] {
- let mut hasher = Sha256::new();
- hasher.update(data.as_ref());
- hasher.finalize().into()
-}
diff --git a/src/lib.rs b/src/lib.rs
index ba715bd..7bd9d5f 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -5,7 +5,6 @@
//! these derived keys for signing various messages relative to Ethereum.
pub mod account;
-pub mod hash;
pub mod hdk;
pub mod message;
pub mod mnemonic;
diff --git a/src/message.rs b/src/message.rs
index 1c0d594..449a16e 100644
--- a/src/message.rs
+++ b/src/message.rs
@@ -1,6 +1,6 @@
//! Ethereum message for signing.
-use crate::hash;
+use ethdigest::Digest;
use std::io::Write as _;
/// A message to be signed with an Ethereum specific prefix.
@@ -11,13 +11,13 @@ where
T: AsRef<[u8]>,
{
/// Computes the 32-byte message used for ECDSA signing with a private key.
- pub fn signing_message(&self) -> [u8; 32] {
+ pub fn signing_message(&self) -> Digest {
digest(self.0.as_ref())
}
}
/// Computes the Ethereum-specific digest for a message.
-fn digest(data: &[u8]) -> [u8; 32] {
+fn digest(data: &[u8]) -> Digest {
let mut buffer = Vec::with_capacity(46 + data.len());
buffer.extend_from_slice(b"\x19Ethereum Signed Message:\n");
// Display implementation for `usize` should not error when writing to an
@@ -27,7 +27,7 @@ fn digest(data: &[u8]) -> [u8; 32] {
write!(buffer, "{}", data.len()).expect("unexpected error writing number");
buffer.extend_from_slice(data);
- hash::keccak256(buffer)
+ Digest::of(buffer)
}
#[cfg(test)]
@@ -38,7 +38,7 @@ mod tests {
fn computes_digest() {
assert_eq!(
digest(b"hello world!"),
- hash::keccak256(b"\x19Ethereum Signed Message:\n12hello world!"),
+ Digest::of(b"\x19Ethereum Signed Message:\n12hello world!"),
);
}
}
diff --git a/src/mnemonic.rs b/src/mnemonic.rs
index bd9e108..a9420c4 100644
--- a/src/mnemonic.rs
+++ b/src/mnemonic.rs
@@ -4,12 +4,11 @@ mod language;
mod wordlist;
pub use self::{language::Language, wordlist::WORD_COUNT};
-use crate::{hash, rand};
+use crate::rand;
use anyhow::{ensure, Context as _, Result};
use hmac::Hmac;
-use sha2::Sha512;
+use sha2::{Digest as _, Sha256, Sha512};
use std::{
- convert::TryInto,
fmt::{self, Display, Formatter},
mem,
ops::Deref,
@@ -49,7 +48,7 @@ impl Mnemonic {
let (seed, hash) = buf.split_at_mut(len);
rand::get_entropy(&mut *seed)?;
- hash[..32].copy_from_slice(&hash::sha256(seed));
+ hash_seed(seed, hash);
buf
};
@@ -94,7 +93,7 @@ impl Mnemonic {
debug_assert_eq!(len * 8 + bit_offset, words.len() * WORD_BITS);
debug_assert_eq!(byte_offset, len);
- hash[..32].copy_from_slice(&hash::sha256(seed));
+ hash_seed(seed, hash);
let checksum_mask = (1 << bit_offset) - 1;
ensure!(
@@ -209,6 +208,12 @@ fn mnemonic_to_byte_length(len: usize) -> Result<usize> {
Ok((len * WORD_BITS * 32 / 33) / 8)
}
+fn hash_seed(seed: &[u8], hash: &mut [u8]) {
+ let mut hasher = Sha256::new();
+ hasher.update(seed);
+ hasher.finalize_into((&mut hash[..32]).into());
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/transaction.rs b/src/transaction.rs
index cbc0e4f..5635766 100644
--- a/src/transaction.rs
+++ b/src/transaction.rs
@@ -10,7 +10,8 @@ mod rlp;
pub use self::{
eip1559::Eip1559Transaction, eip2930::Eip2930Transaction, legacy::LegacyTransaction,
};
-use crate::{account::Signature, hash, serialization::JsonObject};
+use crate::{account::Signature, serialization::JsonObject};
+use ethdigest::Digest;
use serde::{
de::{self, Deserializer},
Deserialize,
@@ -26,8 +27,8 @@ pub enum Transaction {
impl Transaction {
/// Returns the RLP encoded transaction with an optional signature.
- pub fn signing_message(&self) -> [u8; 32] {
- hash::keccak256(self.rlp_encode(None))
+ pub fn signing_message(&self) -> Digest {
+ Digest::of(self.rlp_encode(None))
}
/// Returns the 32-byte message used for signing.
diff --git a/src/typeddata.rs b/src/typeddata.rs
index 35ecdd6..84bae2b 100644
--- a/src/typeddata.rs
+++ b/src/typeddata.rs
@@ -1,11 +1,9 @@
//! Module for hashing EIP-712 typed data.
-use crate::{
- hash,
- serialization::{self, JsonObject},
-};
+use crate::serialization::{self, JsonObject};
use anyhow::{bail, ensure, Context as _, Result};
use ethaddr::Address;
+use ethdigest::Digest;
use ethnum::{serde::permissive, I256, U256};
use serde::{
de::{self, Deserializer},
@@ -20,26 +18,26 @@ use std::{
/// EIP-712 typed data.
pub struct TypedData {
- digest: [u8; 32],
- domain_separator: [u8; 32],
- message_hash: [u8; 32],
+ digest: Digest,
+ domain_separator: Digest,
+ message_hash: Digest,
}
impl TypedData {
/// Returns the 32-byte message to be used for siging the typed data.
///
/// This is the EIP-712 digest of the typed data.
- pub fn signing_message(&self) -> [u8; 32] {
+ pub fn signing_message(&self) -> Digest {
self.digest
}
/// Returns the 32-byte hash of the typed data domain.
- pub fn domain_separator(&self) -> [u8; 32] {
+ pub fn domain_separator(&self) -> Digest {
self.domain_separator
}
/// Returns the 32-byte hash of the typed data message.
- pub fn message_hash(&self) -> [u8; 32] {
+ pub fn message_hash(&self) -> Digest {
self.message_hash
}
}
@@ -79,9 +77,9 @@ impl TypedDataBlob {
let mut buffer = [0; 66];
buffer[0..2].copy_from_slice(b"\x19\x01");
- buffer[2..34].copy_from_slice(&domain_separator);
- buffer[34..66].copy_from_slice(&message_hash);
- let digest = hash::keccak256(buffer);
+ buffer[2..34].copy_from_slice(domain_separator.as_slice());
+ buffer[34..66].copy_from_slice(message_hash.as_slice());
+ let digest = Digest::of(buffer);
Ok(TypedData {
digest,
@@ -127,10 +125,10 @@ impl TypedDataBlob {
struct Types(HashMap<String, Vec<Member>>);
impl Types {
- fn struct_hash(&self, kind: &str, mut data: JsonObject) -> Result<[u8; 32]> {
+ fn struct_hash(&self, kind: &str, mut data: JsonObject) -> Result<Digest> {
let type_definition = self.type_definition(kind)?;
let mut buffer = vec![0_u8; 32 * (1 + type_definition.members.len())];
- buffer[0..32].copy_from_slice(&self.type_hash(kind)?);
+ buffer[0..32].copy_from_slice(self.type_hash(kind)?.as_slice());
for (i, member) in type_definition.members.iter().enumerate() {
buffer[(i + 1) * 32..][..32].copy_from_slice(
&self.encode_value(
@@ -147,7 +145,7 @@ impl Types {
"additional unspecified {kind} properties: {}",
data.keys().cloned().collect::<Vec<_>>().join(", "),
);
- Ok(hash::keccak256(&buffer))
+ Ok(Digest::of(buffer))
}
fn encode_type(&self, kind: &str) -> Result<String> {
@@ -172,9 +170,9 @@ impl Types {
Ok(buffer)
}
- fn type_hash(&self, kind: &str) -> Result<[u8; 32]> {
+ fn type_hash(&self, kind: &str) -> Result<Digest> {
let encoded_type = self.encode_type(kind)?;
- Ok(hash::keccak256(encoded_type))
+ Ok(Digest::of(encoded_type))
}
fn type_definition<'a>(&'a self, kind: &'a str) -> Result<TypeDefinition<'a>> {
@@ -204,7 +202,7 @@ impl Types {
.copy_from_slice(&bytes);
buffer
}
- None => hash::keccak256(&bytes),
+ None => Digest::of(&bytes).0,
}
}
MemberKind::Uint(n) => {
@@ -234,13 +232,13 @@ impl Types {
buffer[12..].copy_from_slice(&*address);
buffer
}
- MemberKind::String => hash::keccak256(&*Cow::<str>::deserialize(value)?),
+ MemberKind::String => Digest::of(&*Cow::<str>::deserialize(value)?).0,
MemberKind::Struct(inner) => {
let value = match value {
Value::Object(value) => value,
value => bail!("expected JSON object but got '{value}'"),
};
- self.struct_hash(inner, value)?
+ *self.struct_hash(inner, value)?
}
MemberKind::Array(inner, size) => {
let value = match value {
@@ -259,7 +257,7 @@ impl Types {
for (i, element) in value.into_iter().enumerate() {
buffer[(i * 32)..][..32].copy_from_slice(&self.encode_value(inner, element)?);
}
- hash::keccak256(&buffer)
+ Digest::of(&buffer).0
}
})
}
@@ -281,7 +279,7 @@ impl<'a> TypeDefinition<'a> {
impl Display for TypeDefinition<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}(", self.kind)?;
- if let Some(first_member) = self.members.get(0) {
+ if let Some(first_member) = self.members.first() {
write!(f, "{first_member}")?;
}
for member in self.members.get(1..).into_iter().flatten() {
@@ -390,7 +388,7 @@ impl<'de> Deserialize<'de> for MemberKind {
#[cfg(test)]
mod tests {
use super::*;
- use hex_literal::hex;
+ use ethdigest::digest;
use maplit::hashmap;
use serde_json::json;
@@ -438,7 +436,7 @@ mod tests {
.unwrap();
assert_eq!(
typed_data.signing_message(),
- hex!("be609aee343fb3c4b28e1df9e632fca64fcfaede20f02e86244efddf30957bd2"),
+ digest!("be609aee343fb3c4b28e1df9e632fca64fcfaede20f02e86244efddf30957bd2"),
);
}
@@ -499,7 +497,7 @@ mod tests {
.unwrap();
assert_eq!(
typed_data.signing_message(),
- hex!("a150d6fdc3fe189531a29808ccdd2808005c24274de09187af619f69377221a1"),
+ digest!("a150d6fdc3fe189531a29808ccdd2808005c24274de09187af619f69377221a1"),
);
}