aboutsummaryrefslogtreecommitdiff
path: root/src/account
diff options
context:
space:
mode:
Diffstat (limited to 'src/account')
-rw-r--r--src/account/address.rs134
-rw-r--r--src/account/signature.rs60
2 files changed, 42 insertions, 152 deletions
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() {