aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/account.rs4
-rw-r--r--src/account/address.rs134
-rw-r--r--src/account/signature.rs60
-rw-r--r--src/cmd/hash.rs89
-rw-r--r--src/hdk.rs6
-rw-r--r--src/serialization.rs288
-rw-r--r--src/transaction/accesslist.rs12
-rw-r--r--src/transaction/eip1559.rs30
-rw-r--r--src/transaction/eip2930.rs27
-rw-r--r--src/transaction/legacy.rs22
-rw-r--r--src/typeddata.rs39
11 files changed, 213 insertions, 498 deletions
diff --git a/src/account.rs b/src/account.rs
index 7cf21bb..2dde76e 100644
--- a/src/account.rs
+++ b/src/account.rs
@@ -1,14 +1,14 @@
//! Module implementing `secp256k1` private key.
-mod address;
mod prehashed;
mod public;
mod signature;
use self::prehashed::Prehashed;
-pub use self::{address::Address, public::PublicKey, signature::Signature};
+pub use self::{public::PublicKey, signature::Signature};
use crate::hash;
use anyhow::Result;
+use ethaddr::Address;
use k256::{
ecdsa::{signature::DigestSigner as _, SigningKey},
SecretKey,
diff --git a/src/account/address.rs b/src/account/address.rs
deleted file mode 100644
index 1f3383c..0000000
--- a/src/account/address.rs
+++ /dev/null
@@ -1,134 +0,0 @@
-use crate::{hash, serialization};
-use hex::FromHexError;
-use serde::Deserialize;
-use std::{
- fmt::{self, Debug, Display, Formatter},
- ops::{Deref, DerefMut},
- str::{self, FromStr},
-};
-
-/// An Ethereum public address.
-#[derive(Copy, Clone, Default, Deserialize, Eq, Ord, PartialEq, PartialOrd)]
-#[serde(transparent)]
-pub struct Address(#[serde(with = "serialization::bytearray")] pub [u8; 20]);
-
-impl Address {
- /// Creates an address from a slice.
- ///
- /// # Panics
- ///
- /// This method panics if the length of the slice is not 20 bytes.
- pub fn from_slice(slice: &[u8]) -> Self {
- let mut address = Self::default();
- address.as_mut().copy_from_slice(slice);
- address
- }
-}
-
-impl Debug for Address {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- struct DisplayAsDebug<T>(T);
-
- impl<T> Debug for DisplayAsDebug<T>
- where
- T: Display,
- {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- self.0.fmt(f)
- }
- }
-
- f.debug_tuple("Address")
- .field(&DisplayAsDebug(self))
- .finish()
- }
-}
-
-impl Display for Address {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- let mut buf = *b"0x0000000000000000000000000000000000000000";
- let addr = &mut buf[2..];
- hex::encode_to_slice(self, addr).expect("error decoding hex");
-
- let digest = hash::keccak256(&addr);
- for i in 0..addr.len() {
- let byte = digest[i / 2];
- let nibble = 0xf & if i % 2 == 0 { byte >> 4 } else { byte };
- if nibble >= 8 {
- addr[i] = addr[i].to_ascii_uppercase();
- }
- }
-
- f.write_str(unsafe { str::from_utf8_unchecked(&buf) })
- }
-}
-
-impl AsRef<[u8]> for Address {
- fn as_ref(&self) -> &[u8] {
- &self.0
- }
-}
-
-impl AsMut<[u8]> for Address {
- fn as_mut(&mut self) -> &mut [u8] {
- &mut self.0
- }
-}
-
-impl Deref for Address {
- type Target = [u8; 20];
-
- fn deref(&self) -> &Self::Target {
- &self.0
- }
-}
-
-impl DerefMut for Address {
- fn deref_mut(&mut self) -> &mut Self::Target {
- &mut self.0
- }
-}
-
-impl FromStr for Address {
- type Err = FromHexError;
-
- fn from_str(s: &str) -> Result<Self, Self::Err> {
- let mut address = Self::default();
- let s = s.strip_prefix("0x").unwrap_or(s);
- hex::decode_to_slice(s, address.as_mut())?;
- Ok(address)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use serde_json::json;
-
- #[test]
- fn checksum_address() {
- for s in &[
- "0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1",
- "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
- ] {
- let address = s.parse::<Address>().unwrap();
- assert_eq!(address.to_string(), *s);
- }
- }
-
- #[test]
- fn deserialize_address() {
- assert_eq!(
- serde_json::from_value::<Address>(json!("0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"))
- .unwrap(),
- Address([0xee; 20]),
- )
- }
-
- #[test]
- fn deserialize_address_requires_0x_prefix() {
- let without_prefix = "EeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
- assert!(without_prefix.parse::<Address>().is_ok());
- assert!(serde_json::from_value::<Address>(json!(without_prefix)).is_err());
- }
-}
diff --git a/src/account/signature.rs b/src/account/signature.rs
index 5afa0ca..550ac3d 100644
--- a/src/account/signature.rs
+++ b/src/account/signature.rs
@@ -1,8 +1,15 @@
//! Module containing signature data model.
+use anyhow::bail;
use ethnum::{AsU256 as _, U256};
-use k256::ecdsa::recoverable;
-use std::fmt::{self, Display, Formatter};
+use k256::ecdsa::{
+ self,
+ recoverable::{self, Id},
+};
+use std::{
+ fmt::{self, Display, Formatter},
+ str::FromStr,
+};
/// A secp256k1 signature.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -33,6 +40,17 @@ impl Signature {
pub fn s(&self) -> U256 {
U256::from_be_bytes(self.0.s().to_bytes().into())
}
+
+ /// Creates a signature from its raw parts.
+ pub fn from_parts(y_parity: u8, r: [u8; 32], s: [u8; 32]) -> Self {
+ Self(
+ recoverable::Signature::new(
+ &ecdsa::Signature::from_scalars(r, s).unwrap(),
+ Id::new(y_parity).unwrap(),
+ )
+ .unwrap(),
+ )
+ }
}
impl Display for Signature {
@@ -47,25 +65,31 @@ impl Display for Signature {
}
}
+impl FromStr for Signature {
+ type Err = anyhow::Error;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ let mut signature = [0; 65];
+ hex::decode_to_slice(s, &mut signature)?;
+
+ let v = signature[64];
+ let y_parity = match v {
+ 27 => 0,
+ 28 => 1,
+ _ => bail!("invalid V-value, must be 27 or 28 but got {v}"),
+ };
+
+ Ok(Self::from_parts(
+ y_parity,
+ signature[0..32].try_into().unwrap(),
+ signature[32..64].try_into().unwrap(),
+ ))
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
- use k256::ecdsa::{self, recoverable::Id};
-
- impl Signature {
- /// Creates a signature from its raw parts.
- ///
- /// Convinience method used for testing.
- pub fn from_parts(y_parity: u8, r: [u8; 32], s: [u8; 32]) -> Self {
- Self(
- recoverable::Signature::new(
- &ecdsa::Signature::from_scalars(r, s).unwrap(),
- Id::new(y_parity).unwrap(),
- )
- .unwrap(),
- )
- }
- }
#[test]
fn replay_protection() {
diff --git a/src/cmd/hash.rs b/src/cmd/hash.rs
index 4c8a9b8..74c4e07 100644
--- a/src/cmd/hash.rs
+++ b/src/cmd/hash.rs
@@ -3,18 +3,95 @@
use crate::cmd;
use anyhow::Result;
use clap::Parser;
-use hdwallet::hash;
+use hdwallet::{
+ account::Signature, hash, message::EthereumMessage, transaction::Transaction,
+ typeddata::TypedData,
+};
use std::path::PathBuf;
#[derive(Debug, Parser)]
pub struct Options {
- /// Path to the data to hash. Use `-` for standard in.
- #[clap(name = "DATA", default_value = "-")]
- data: PathBuf,
+ #[clap(subcommand)]
+ input: Input,
+}
+
+#[derive(Debug, Parser)]
+#[clap(rename_all = "lowercase")]
+enum Input {
+ /// Hash an Ethereum transaction.
+ Transaction {
+ /// Path to transaction to hash in JSON format.
+ #[clap(name = "TRANSACTION")]
+ transaction: PathBuf,
+
+ /// Signature for the transaction.
+ #[clap(short, long)]
+ signature: Option<Signature>,
+ },
+
+ /// Hash an Ethereum message.
+ Message {
+ /// Path to the message to hash in the "eth_sign" scheme. This message
+ /// will be prefixed with "\x19Ethereum Signed Message:\n" and its
+ /// length before hashing.
+ #[clap(name = "MESSAGE")]
+ message: PathBuf,
+ },
+
+ /// Hash EIP-712 typed data.
+ TypedData {
+ /// Path to the EIP-712 typed data in JSON format.
+ #[clap(name = "TYPEDDATA")]
+ typed_data: PathBuf,
+
+ /// Only compute the struct hash of the main message without mixing in
+ /// the domain separator.
+ #[clap(short, long)]
+ message_hash: bool,
+ },
+
+ /// Hash raw data.
+ Data {
+ /// Path to the data to hash. Use `-` for standard in.
+ #[clap(name = "DATA")]
+ data: PathBuf,
+ },
}
pub fn run(options: Options) -> Result<()> {
- let data = cmd::read_input(&options.data)?;
- println!("0x{}", hex::encode(hash::keccak256(data)));
+ let hash = match options.input {
+ Input::Transaction {
+ transaction,
+ signature,
+ } => {
+ let transaction =
+ serde_json::from_slice::<Transaction>(&cmd::read_input(&transaction)?)?;
+ match signature {
+ Some(signature) => hash::keccak256(transaction.encode(signature)),
+ None => transaction.signing_message(),
+ }
+ }
+ Input::Message { message } => {
+ let message = EthereumMessage(cmd::read_input(&message)?);
+ message.signing_message()
+ }
+ Input::TypedData {
+ typed_data,
+ message_hash,
+ } => {
+ let typed_data = serde_json::from_slice::<TypedData>(&cmd::read_input(&typed_data)?)?;
+ if message_hash {
+ typed_data.message_hash()
+ } else {
+ typed_data.signing_message()
+ }
+ }
+ Input::Data { data } => {
+ let data = cmd::read_input(&data)?;
+ hash::keccak256(data)
+ }
+ };
+ println!("0x{}", hex::encode(hash));
+
Ok(())
}
diff --git a/src/hdk.rs b/src/hdk.rs
index daf4a9d..2be1e44 100644
--- a/src/hdk.rs
+++ b/src/hdk.rs
@@ -65,8 +65,8 @@ fn derive_slice(seed: &[u8], path: &Path) -> Result<PrivateKey> {
#[cfg(test)]
mod tests {
use super::*;
- use crate::{account::Address, ganache::DETERMINISTIC_MNEMONIC, mnemonic::Mnemonic};
- use hex_literal::hex;
+ use crate::{ganache::DETERMINISTIC_MNEMONIC, mnemonic::Mnemonic};
+ use ethaddr::address;
#[test]
fn ganache_deterministic_mnemonic() {
@@ -76,7 +76,7 @@ mod tests {
let account = derive(mnemonic.seed(""), &path).unwrap();
assert_eq!(
account.address(),
- Address(hex!("90F8bf6A479f320ead074411a4B0e7944Ea8c9C1")),
+ address!("0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1"),
);
}
}
diff --git a/src/serialization.rs b/src/serialization.rs
index f306d30..4d5e6d2 100644
--- a/src/serialization.rs
+++ b/src/serialization.rs
@@ -5,214 +5,24 @@ use serde_json::{Map, Value};
/// A JSON object.
pub type JsonObject = Map<String, Value>;
-/// `I256` serialization methods.
-pub mod i256 {
- use ethnum::{AsI256 as _, I256, U256};
- use serde::de::{self, Deserializer, Visitor};
- use std::fmt::{self, Formatter};
-
- struct I256Visitor;
-
- impl<'de> Visitor<'de> for I256Visitor {
- type Value = I256;
-
- fn expecting(&self, f: &mut Formatter) -> fmt::Result {
- f.write_str("number, decimal string or '0x-' prefixed hexadecimal string")
- }
-
- fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
- where
- E: de::Error,
- {
- Ok(v.as_i256())
- }
-
- fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
- where
- E: de::Error,
- {
- Ok(v.as_i256())
- }
-
- fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E>
- where
- E: de::Error,
- {
- Ok(v.as_i256())
- }
-
- fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
- where
- E: de::Error,
- {
- Ok(v.as_i256())
- }
-
- fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E>
- where
- E: de::Error,
- {
- if !(0.0..(1_u64 << 24) as _).contains(&v.abs()) {
- return Err(de::Error::custom(
- "invalid conversion from single precision floating point \
- number outside of valid integer range (-2^24, 2^24)",
- ));
- }
-
- self.visit_f64(v as _)
- }
-
- fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
- where
- E: de::Error,
- {
- if v.fract() != 0. {
- return Err(de::Error::custom(
- "invalid conversion from floating point number \
- with fractional part to 256-bit integer",
- ));
- }
- if !(0.0..(1_u64 << 53) as _).contains(&v.abs()) {
- return Err(de::Error::custom(
- "invalid conversion from double precision floating point \
- number outside of valid integer range (-2^53, 2^53)",
- ));
- }
-
- Ok(v.as_i256())
- }
-
- fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
- where
- E: de::Error,
- {
- let (u, neg) = match v.strip_prefix('-') {
- Some(v) => (v, true),
- None => (v, false),
- };
- let (src, radix) = match u.strip_prefix("0x") {
- Some(u) => (u, 16),
- None => (u, 10),
- };
- let value = U256::from_str_radix(src, radix)
- .map_err(de::Error::custom)?
- .as_i256();
- match (neg, value) {
- (true, I256::MIN) => Ok(value),
- (true, v) if v > 0 => Ok(v.wrapping_neg()),
- (true, I256::ZERO) => Err(de::Error::custom("negative zero is invalid")),
- (true, _) => Err(de::Error::custom("number too small to fit in target type")),
- (false, v) if v >= 0 => Ok(v),
- (false, _) => Err(de::Error::custom("number too big to fit in target type")),
- }
- }
- }
-
- pub fn deserialize<'de, D>(deserializer: D) -> Result<I256, D::Error>
+/// Permisive deserialization for optional 256-bit integer types.
+pub mod numopt {
+ use ethnum::serde::permissive::Permissive;
+ use serde::{Deserialize, Deserializer};
+
+ #[derive(Deserialize)]
+ #[serde(transparent)]
+ struct Helper<T>(#[serde(with = "ethnum::serde::permissive")] T)
where
- D: Deserializer<'de>,
- {
- deserializer.deserialize_any(I256Visitor)
- }
-}
-
-/// `U256` serialization methods.
-pub mod u256 {
- use ethnum::{AsU256 as _, U256};
- use serde::de::{self, Deserializer, Visitor};
- use std::fmt::{self, Formatter};
-
- struct U256Visitor;
-
- impl<'de> Visitor<'de> for U256Visitor {
- type Value = U256;
-
- fn expecting(&self, f: &mut Formatter) -> fmt::Result {
- f.write_str("number, decimal string or '0x-' prefixed hexadecimal string")
- }
-
- fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
- where
- E: de::Error,
- {
- Ok(v.as_u256())
- }
-
- fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
- where
- E: de::Error,
- {
- Ok(v.as_u256())
- }
-
- fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E>
- where
- E: de::Error,
- {
- if !(0.0..(1_u64 << 24) as _).contains(&v) {
- return Err(de::Error::custom(
- "invalid conversion from single precision floating point \
- number outside of valid integer range [0, 2^24)",
- ));
- }
-
- self.visit_f64(v as _)
- }
-
- fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
- where
- E: de::Error,
- {
- if v.fract() != 0. {
- return Err(de::Error::custom(
- "invalid conversion from floating point number \
- with fractional part to 256-bit integer",
- ));
- }
- if !(0.0..(1_u64 << 53) as _).contains(&v) {
- return Err(de::Error::custom(
- "invalid conversion from double precision floating point \
- number outside of valid integer range [0, 2^53)",
- ));
- }
+ T: Permissive;
- Ok(v.as_u256())
- }
-
- fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
- where
- E: de::Error,
- {
- let (src, radix) = match v.strip_prefix("0x") {
- Some(v) => (v, 16),
- None => (v, 10),
- };
- U256::from_str_radix(src, radix).map_err(de::Error::custom)
- }
- }
-
- pub fn deserialize<'de, D>(deserializer: D) -> Result<U256, D::Error>
+ pub fn deserialize<'de, T, D>(deserializer: D) -> Result<Option<T>, D::Error>
where
+ T: Permissive,
D: Deserializer<'de>,
{
- deserializer.deserialize_any(U256Visitor)
- }
-
- pub mod option {
- use super::*;
- use serde::Deserialize;
-
- #[derive(Deserialize)]
- #[serde(transparent)]
- struct Helper(#[serde(with = "super")] U256);
-
- pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<U256>, D::Error>
- where
- D: Deserializer<'de>,
- {
- let option = Option::deserialize(deserializer)?;
- Ok(option.map(|Helper(v)| v))
- }
+ let option = Option::deserialize(deserializer)?;
+ Ok(option.map(|Helper(v)| v))
}
}
@@ -257,75 +67,3 @@ pub mod bytearray {
Ok(value)
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use ethnum::{I256, U256};
-
- macro_rules! assert_deserializes_to {
- ($m:ident: $v:expr => $x:expr) => {{
- use ::serde::de::{value::Error, IntoDeserializer};
- let v = $m::deserialize(IntoDeserializer::<Error>::into_deserializer($v)).unwrap();
- assert_eq!(v, $x);
- }};
- }
-
- macro_rules! assert_deserializes_err {
- ($m:ident: $v:expr) => {{
- use ::serde::de::{value::Error, IntoDeserializer};
- let v = $m::deserialize(IntoDeserializer::<Error>::into_deserializer($v));
- assert!(v.is_err());
- }};
- }
-
- #[test]
- fn i256_deserialization() {
- assert_deserializes_to!(i256: -42_i64 => I256::new(-42));
- assert_deserializes_to!(i256: 42_u64 => I256::new(42));
-
- assert_deserializes_to!(i256: -1337_i128 => I256::new(-1337));
- assert_deserializes_to!(i256: 1337_u128 => I256::new(1337));
-
- assert_deserializes_to!(i256: 100.0_f32 => I256::new(100));
- assert_deserializes_err!(i256: 4.2_f32);
- assert_deserializes_err!(i256: 16777216.0_f32);
-
- assert_deserializes_to!(i256: -100.0_f64 => I256::new(-100));
- assert_deserializes_err!(i256: -13.37_f64);
- assert_deserializes_err!(i256: 9007199254740992.0_f32);
-
- assert_deserializes_to!(i256: "-1" => I256::new(-1));
- assert_deserializes_to!(i256: "1000" => I256::new(1000));
- assert_deserializes_to!(i256: "0x42" => I256::new(0x42));
- assert_deserializes_to!(i256: "-0x2a" => I256::new(-42));
-
- assert_deserializes_to!(i256: "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" => I256::MAX);
- assert_deserializes_err!(i256: "0x8000000000000000000000000000000000000000000000000000000000000000");
- assert_deserializes_to!(i256: "-0x8000000000000000000000000000000000000000000000000000000000000000" => I256::MIN);
- assert_deserializes_err!(i256: "-0x8000000000000000000000000000000000000000000000000000000000000001");
-
- assert_deserializes_err!(i256: "-0");
- assert_deserializes_err!(i256: "-0x0");
- }
-
- #[test]
- fn u256_deserialization() {
- assert_deserializes_to!(u256: 42_u64 => U256::new(42));
- assert_deserializes_to!(u256: 1337_u128 => U256::new(1337));
-
- assert_deserializes_to!(u256: 100.0_f32 => U256::new(100));
- assert_deserializes_err!(u256: 4.2_f32);
- assert_deserializes_err!(u256: 16777216.0_f32);
-
- assert_deserializes_to!(u256: 100.0_f64 => U256::new(100));
- assert_deserializes_err!(u256: 13.37_f64);
- assert_deserializes_err!(u256: 9007199254740992.0_f32);
-
- assert_deserializes_to!(u256: "1000" => U256::new(1000));
- assert_deserializes_to!(u256: "0x42" => U256::new(0x42));
-
- assert_deserializes_to!(u256: "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" => U256::MAX);
- assert_deserializes_err!(u256: "0x10000000000000000000000000000000000000000000000000000000000000000");
- }
-}
diff --git a/src/transaction/accesslist.rs b/src/transaction/accesslist.rs
index 507b73e..0147350 100644
--- a/src/transaction/accesslist.rs
+++ b/src/transaction/accesslist.rs
@@ -1,7 +1,8 @@
//! Module with EIP-2930 access list type definition with RLP encoding and JSON
//! serialization implementation.
-use crate::{account::Address, serialization, transaction::rlp};
+use crate::{serialization, transaction::rlp};
+use ethaddr::Address;
use serde::Deserialize;
/// An Ethereum virtual machine storage slot.
@@ -36,6 +37,7 @@ impl AccessList {
#[cfg(test)]
mod tests {
use super::*;
+ use ethaddr::address;
use hex_literal::hex;
use serde_json::json;
@@ -55,7 +57,7 @@ mod tests {
.unwrap(),
AccessList(vec![
(
- Address(hex!("de0b295669a9fd93d5f28d9ec85e40f4cb697bae")),
+ address!("0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe"),
vec![
StorageSlot(hex!(
"0000000000000000000000000000000000000000000000000000000000000003"
@@ -66,7 +68,7 @@ mod tests {
]
),
(
- Address(hex!("bb9bc244d798123fde783fcc1c72d3bb8c189413")),
+ address!("0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413"),
vec![]
)
]),
@@ -78,7 +80,7 @@ mod tests {
assert_eq!(
AccessList(vec![
(
- Address(hex!("de0b295669a9fd93d5f28d9ec85e40f4cb697bae")),
+ address!("0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe"),
vec![
StorageSlot(hex!(
"0000000000000000000000000000000000000000000000000000000000000003"
@@ -89,7 +91,7 @@ mod tests {
]
),
(
- Address(hex!("bb9bc244d798123fde783fcc1c72d3bb8c189413")),
+ address!("0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413"),
vec![]
)
])
diff --git a/src/transaction/eip1559.rs b/src/transaction/eip1559.rs
index 765ce97..f93b931 100644
--- a/src/transaction/eip1559.rs
+++ b/src/transaction/eip1559.rs
@@ -1,11 +1,9 @@
//! EIp-1559 Ethereum transaction with base gas pricing type definition and RLP encoding.
use crate::{
- account::{Address, Signature},
- serialization,
- transaction::accesslist::AccessList,
- transaction::rlp,
+ account::Signature, serialization, transaction::accesslist::AccessList, transaction::rlp,
};
+use ethaddr::Address;
use ethnum::U256;
use serde::Deserialize;
@@ -13,28 +11,25 @@ use serde::Deserialize;
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct Eip1559Transaction {
/// The chain ID for the transaction.
- #[serde(rename = "chainId")]
- #[serde(with = "serialization::u256")]
+ #[serde(rename = "chainId", with = "ethnum::serde::permissive")]
pub chain_id: U256,
/// The nonce for the transaction.
- #[serde(with = "serialization::u256")]
+ #[serde(with = "ethnum::serde::permissive")]
pub nonce: U256,
/// The maximum priority fee in Wei for the transaction.
- #[serde(rename = "maxPriorityFeePerGas")]
- #[serde(with = "serialization::u256")]
+ #[serde(rename = "maxPriorityFeePerGas", with = "ethnum::serde::permissive")]
pub max_priority_fee_per_gas: U256,
/// The maximum gas price in Wei for the transaction.
- #[serde(rename = "maxFeePerGas")]
- #[serde(with = "serialization::u256")]
+ #[serde(rename = "maxFeePerGas", with = "ethnum::serde::permissive")]
pub max_fee_per_gas: U256,
/// The gas limit for the transaction.
- #[serde(with = "serialization::u256")]
+ #[serde(with = "ethnum::serde::permissive")]
pub gas: U256,
/// The target address for the transaction. This can also be `None` to
/// indicate a contract creation transaction.
pub to: Option<Address>,
/// The amount of Ether to send with the transaction.
- #[serde(with = "serialization::u256")]
+ #[serde(with = "ethnum::serde::permissive")]
pub value: U256,
/// The calldata to use for the transaction.
#[serde(with = "serialization::bytes")]
@@ -81,6 +76,7 @@ impl Eip1559Transaction {
mod tests {
use super::*;
use crate::transaction::accesslist::StorageSlot;
+ use ethaddr::address;
use ethnum::AsU256 as _;
use hex_literal::hex;
use serde_json::json;
@@ -119,7 +115,7 @@ mod tests {
let deserialized = serde_json::from_value::<Eip1559Transaction>(tx).unwrap();
assert_eq!(
deserialized.to.unwrap(),
- Address(hex!("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef")),
+ address!("0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF"),
);
assert_eq!(
deserialized.access_list,
@@ -136,7 +132,7 @@ mod tests {
max_priority_fee_per_gas: 28e9.as_u256(),
max_fee_per_gas: 42e9.as_u256(),
gas: 30_000.as_u256(),
- to: Some(Address(hex!("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"))),
+ to: Some(address!("0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF")),
value: 13.37e18.as_u256(),
data: vec![],
access_list: AccessList::default(),
@@ -164,7 +160,7 @@ mod tests {
.to_vec(),
access_list: AccessList(vec![
(
- Address(hex!("1111111111111111111111111111111111111111")),
+ address!("0x1111111111111111111111111111111111111111"),
vec![
StorageSlot(hex!(
"a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0"
@@ -175,7 +171,7 @@ mod tests {
],
),
(
- Address(hex!("2222222222222222222222222222222222222222")),
+ address!("0x2222222222222222222222222222222222222222"),
vec![],
),
]),
diff --git a/src/transaction/eip2930.rs b/src/transaction/eip2930.rs
index 4a8bcf8..5cd0f02 100644
--- a/src/transaction/eip2930.rs
+++ b/src/transaction/eip2930.rs
@@ -1,11 +1,9 @@
//! EIp-2930 Ethereum transaction with access list type definition and RLP encoding.
use crate::{
- account::{Address, Signature},
- serialization,
- transaction::accesslist::AccessList,
- transaction::rlp,
+ account::Signature, serialization, transaction::accesslist::AccessList, transaction::rlp,
};
+use ethaddr::Address;
use ethnum::U256;
use serde::Deserialize;
@@ -13,24 +11,22 @@ use serde::Deserialize;
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct Eip2930Transaction {
/// The chain ID for the transaction.
- #[serde(rename = "chainId")]
- #[serde(with = "serialization::u256")]
+ #[serde(rename = "chainId", with = "ethnum::serde::permissive")]
pub chain_id: U256,
/// The nonce for the transaction.
- #[serde(with = "serialization::u256")]
+ #[serde(with = "ethnum::serde::permissive")]
pub nonce: U256,
/// The gas price in Wei for the transaction.
- #[serde(rename = "gasPrice")]
- #[serde(with = "serialization::u256")]
+ #[serde(rename = "gasPrice", with = "ethnum::serde::permissive")]
pub gas_price: U256,
/// The gas limit for the transaction.
- #[serde(with = "serialization::u256")]
+ #[serde(with = "ethnum::serde::permissive")]
pub gas: U256,
/// The target address for the transaction. This can also be `None` to
/// indicate a contract creation transaction.
pub to: Option<Address>,
/// The amount of Ether to send with the transaction.
- #[serde(with = "serialization::u256")]
+ #[serde(with = "ethnum::serde::permissive")]
pub value: U256,
/// The calldata to use for the transaction.
#[serde(with = "serialization::bytes")]
@@ -75,6 +71,7 @@ impl Eip2930Transaction {
mod tests {
use super::*;
use crate::transaction::accesslist::StorageSlot;
+ use ethaddr::address;
use ethnum::AsU256 as _;
use hex_literal::hex;
use serde_json::json;
@@ -110,7 +107,7 @@ mod tests {
.unwrap()
.to
.unwrap(),
- Address(hex!("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef")),
+ address!("0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF"),
);
}
@@ -122,7 +119,7 @@ mod tests {
nonce: 66.as_u256(),
gas_price: 42e9.as_u256(),
gas: 30_000.as_u256(),
- to: Some(Address(hex!("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"))),
+ to: Some(address!("0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF")),
value: 13.37e18.as_u256(),
data: vec![],
access_list: AccessList::default(),
@@ -149,7 +146,7 @@ mod tests {
.to_vec(),
access_list: AccessList(vec![
(
- Address(hex!("1111111111111111111111111111111111111111")),
+ address!("0x1111111111111111111111111111111111111111"),
vec![
StorageSlot(hex!(
"a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0"
@@ -160,7 +157,7 @@ mod tests {
],
),
(
- Address(hex!("2222222222222222222222222222222222222222")),
+ address!("0x2222222222222222222222222222222222222222"),
vec![],
),
]),
diff --git a/src/transaction/legacy.rs b/src/transaction/legacy.rs
index 9e0f9bc..231d9f8 100644
--- a/src/transaction/legacy.rs
+++ b/src/transaction/legacy.rs
@@ -1,10 +1,7 @@
//! Legacy Ethereum transaction type definition and RLP encoding.
-use crate::{
- account::{Address, Signature},
- serialization,
- transaction::rlp,
-};
+use crate::{account::Signature, serialization, transaction::rlp};
+use ethaddr::Address;
use ethnum::U256;
use serde::Deserialize;
@@ -12,25 +9,25 @@ use serde::Deserialize;
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct LegacyTransaction {
/// The nonce for the transaction.
- #[serde(with = "serialization::u256")]
+ #[serde(with = "ethnum::serde::permissive")]
pub nonce: U256,
/// The gas price in Wei for the transaction.
- #[serde(rename = "gasPrice", with = "serialization::u256")]
+ #[serde(rename = "gasPrice", with = "ethnum::serde::permissive")]
pub gas_price: U256,
/// The gas limit for the transaction.
- #[serde(with = "serialization::u256")]
+ #[serde(with = "ethnum::serde::permissive")]
pub gas: U256,
/// The target address for the transaction. This can also be `None` to
/// indicate a contract creation transaction.
pub to: Option<Address>,
/// The amount of Ether to send with the transaction.
- #[serde(with = "serialization::u256")]
+ #[serde(with = "ethnum::serde::permissive")]
pub value: U256,
/// The calldata to use for the transaction.
#[serde(with = "serialization::bytes")]
pub data: Vec<u8>,
/// Optional chain ID for the transaction.
- #[serde(default, rename = "chainId", with = "serialization::u256::option")]
+ #[serde(default, rename = "chainId", with = "serialization::numopt")]
pub chain_id: Option<U256>,
}
@@ -59,6 +56,7 @@ impl LegacyTransaction {
#[cfg(test)]
mod tests {
use super::*;
+ use ethaddr::address;
use ethnum::AsU256 as _;
use hex_literal::hex;
use serde_json::json;
@@ -92,7 +90,7 @@ mod tests {
.unwrap()
.to
.unwrap(),
- Address(hex!("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef")),
+ address!("0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF"),
);
}
@@ -104,7 +102,7 @@ mod tests {
nonce: 66.as_u256(),
gas_price: 42e9.as_u256(),
gas: 30_000.as_u256(),
- to: Some(Address(hex!("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"))),
+ to: Some(address!("0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF")),
value: 13.37e18.as_u256(),
data: vec![],
}
diff --git a/src/typeddata.rs b/src/typeddata.rs
index ec9c1f3..fe252a4 100644
--- a/src/typeddata.rs
+++ b/src/typeddata.rs
@@ -1,12 +1,12 @@
//! Module for hashing EIP-712 typed data.
use crate::{
- account::Address,
hash,
serialization::{self, JsonObject},
};
use anyhow::{bail, ensure, Context as _, Result};
-use ethnum::U256;
+use ethaddr::Address;
+use ethnum::{serde::permissive, I256, U256};
use serde::{
de::{self, Deserializer},
Deserialize,
@@ -21,6 +21,8 @@ use std::{
/// EIP-712 typed data.
pub struct TypedData {
digest: [u8; 32],
+ domain_separator: [u8; 32],
+ message_hash: [u8; 32],
}
impl TypedData {
@@ -30,6 +32,16 @@ impl TypedData {
pub fn signing_message(&self) -> [u8; 32] {
self.digest
}
+
+ /// Returns the 32-byte hash of the typed data domain.
+ pub fn domain_separator(&self) -> [u8; 32] {
+ self.domain_separator
+ }
+
+ /// Returns the 32-byte hash of the typed data message.
+ pub fn message_hash(&self) -> [u8; 32] {
+ self.message_hash
+ }
}
impl<'de> Deserialize<'de> for TypedData {
@@ -37,10 +49,9 @@ impl<'de> Deserialize<'de> for TypedData {
where
D: Deserializer<'de>,
{
- let blob = TypedDataBlob::deserialize(deserializer)?;
- Ok(Self {
- digest: blob.digest().map_err(de::Error::custom)?,
- })
+ TypedDataBlob::deserialize(deserializer)?
+ .compute()
+ .map_err(de::Error::custom)
}
}
@@ -54,7 +65,7 @@ struct TypedDataBlob {
}
impl TypedDataBlob {
- fn digest(self) -> Result<[u8; 32]> {
+ fn compute(self) -> Result<TypedData> {
self.verify_domain_type()?;
let TypedDataBlob {
@@ -70,7 +81,13 @@ impl TypedDataBlob {
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);
- Ok(hash::keccak256(buffer))
+ let digest = hash::keccak256(buffer);
+
+ Ok(TypedData {
+ digest,
+ domain_separator,
+ message_hash,
+ })
}
fn verify_domain_type(&self) -> Result<()> {
@@ -87,7 +104,7 @@ impl TypedDataBlob {
!domain_type.members.is_empty(),
"EIP-712 domain must have at least one member"
);
- domain_type.members.iter().try_fold(
+ let _ = domain_type.members.iter().try_fold(
DOMAIN_MEMBERS.iter(),
|mut allowed_members, member| {
let (_, kind) = allowed_members
@@ -195,7 +212,7 @@ impl Types {
}
}
MemberKind::Uint(n) => {
- let value = serialization::u256::deserialize(value)?;
+ let value = permissive::deserialize::<U256, _>(value)?;
ensure!(
value.leading_zeros() + n >= 256,
"value {:#x} overflows uint{}",
@@ -205,7 +222,7 @@ impl Types {
value.to_be_bytes()
}
MemberKind::Int(n) => {
- let value = serialization::i256::deserialize(value)?;
+ let value = permissive::deserialize::<I256, _>(value)?;
ensure!(
value.unsigned_abs().leading_zeros() + n >= 256,
"value {:#x} overflows int{}",