aboutsummaryrefslogtreecommitdiff
path: root/src/account/address.rs
blob: 1f3383c1d27f0547dbcb1887fd1bf18a4617b4e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
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());
    }
}