alloy_primitives/bits/
address.rs

1use crate::{FixedBytes, aliases::U160, utils::keccak256};
2use alloc::{
3    borrow::Borrow,
4    string::{String, ToString},
5};
6use core::{fmt, mem::MaybeUninit, str};
7
8/// Error type for address checksum validation.
9#[derive(Clone, Copy, Debug)]
10pub enum AddressError {
11    /// Error while decoding hex.
12    Hex(hex::FromHexError),
13
14    /// Invalid ERC-55 checksum.
15    InvalidChecksum,
16}
17
18impl From<hex::FromHexError> for AddressError {
19    #[inline]
20    fn from(value: hex::FromHexError) -> Self {
21        Self::Hex(value)
22    }
23}
24
25impl core::error::Error for AddressError {
26    #[inline]
27    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
28        match self {
29            #[cfg(any(feature = "std", not(feature = "hex-compat")))]
30            Self::Hex(err) => Some(err),
31            _ => None,
32        }
33    }
34}
35
36impl fmt::Display for AddressError {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        match self {
39            Self::Hex(err) => err.fmt(f),
40            Self::InvalidChecksum => f.write_str("Bad address checksum"),
41        }
42    }
43}
44
45wrap_fixed_bytes!(
46    // we implement Display with the checksum, so we don't derive it
47    extra_derives: [],
48    /// An Ethereum address, 20 bytes in length.
49    ///
50    /// This type is separate from [`FixedBytes<20>`]
51    /// and is declared with the [`wrap_fixed_bytes!`] macro. This allows us
52    /// to implement address-specific functionality.
53    ///
54    /// The main difference with the generic [`FixedBytes`] implementation is that
55    /// [`Display`] formats the address using its [EIP-55] checksum
56    /// ([`to_checksum`]).
57    /// Use [`Debug`] to display the raw bytes without the checksum.
58    ///
59    /// [EIP-55]: https://eips.ethereum.org/EIPS/eip-55
60    /// [`Debug`]: fmt::Debug
61    /// [`Display`]: fmt::Display
62    /// [`to_checksum`]: Address::to_checksum
63    ///
64    /// # Examples
65    ///
66    /// Parsing and formatting:
67    ///
68    /// ```
69    /// use alloy_primitives::{address, Address};
70    ///
71    /// let checksummed = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045";
72    /// let expected = address!("0xd8da6bf26964af9d7eed9e03e53415d37aa96045");
73    /// let address = Address::parse_checksummed(checksummed, None).expect("valid checksum");
74    /// assert_eq!(address, expected);
75    ///
76    /// // Format the address with the checksum
77    /// assert_eq!(address.to_string(), checksummed);
78    /// assert_eq!(address.to_checksum(None), checksummed);
79    ///
80    /// // Format the compressed checksummed address
81    /// assert_eq!(format!("{address:#}"), "0xd8dA…6045");
82    ///
83    /// // Format the address without the checksum
84    /// assert_eq!(format!("{address:?}"), "0xd8da6bf26964af9d7eed9e03e53415d37aa96045");
85    /// ```
86    #[cfg_attr(feature = "rkyv", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
87    #[cfg_attr(feature = "rkyv", rkyv(derive(Copy, Clone, Hash, PartialEq, Eq)))]
88    pub struct Address<20>;
89);
90
91impl From<U160> for Address {
92    #[inline]
93    fn from(value: U160) -> Self {
94        Self(FixedBytes(value.to_be_bytes()))
95    }
96}
97
98impl From<Address> for U160 {
99    #[inline]
100    fn from(value: Address) -> Self {
101        Self::from_be_bytes(value.0.0)
102    }
103}
104
105impl fmt::Display for Address {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        let checksum = self.to_checksum_buffer(None);
108        let checksum = checksum.as_str();
109        if f.alternate() {
110            // If the alternate flag is set, use middle-out compression
111            // "0x" + first 4 bytes + "…" + last 4 bytes
112            f.write_str(&checksum[..6])?;
113            f.write_str("…")?;
114            f.write_str(&checksum[38..])
115        } else {
116            f.write_str(checksum)
117        }
118    }
119}
120
121impl Address {
122    /// Creates an Ethereum address from an EVM word's upper 20 bytes
123    /// (`word[12..]`).
124    ///
125    /// # Examples
126    ///
127    /// ```
128    /// # use alloy_primitives::{address, b256, Address};
129    /// let word = b256!("0x000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa96045");
130    /// assert_eq!(Address::from_word(word), address!("0xd8da6bf26964af9d7eed9e03e53415d37aa96045"));
131    /// ```
132    #[inline]
133    #[must_use]
134    pub fn from_word(word: FixedBytes<32>) -> Self {
135        Self(FixedBytes(word[12..].try_into().unwrap()))
136    }
137
138    /// Left-pads the address to 32 bytes (EVM word size).
139    ///
140    /// # Examples
141    ///
142    /// ```
143    /// # use alloy_primitives::{address, b256, Address};
144    /// assert_eq!(
145    ///     address!("0xd8da6bf26964af9d7eed9e03e53415d37aa96045").into_word(),
146    ///     b256!("0x000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa96045"),
147    /// );
148    /// ```
149    #[inline]
150    #[must_use]
151    pub fn into_word(&self) -> FixedBytes<32> {
152        let mut word = [0; 32];
153        word[12..].copy_from_slice(self.as_slice());
154        FixedBytes(word)
155    }
156
157    /// Parse an Ethereum address, verifying its [EIP-55] checksum.
158    ///
159    /// You can optionally specify an [EIP-155 chain ID] to check the address
160    /// using [EIP-1191].
161    ///
162    /// [EIP-55]: https://eips.ethereum.org/EIPS/eip-55
163    /// [EIP-155 chain ID]: https://eips.ethereum.org/EIPS/eip-155
164    /// [EIP-1191]: https://eips.ethereum.org/EIPS/eip-1191
165    ///
166    /// # Errors
167    ///
168    /// This method returns an error if the provided string does not match the
169    /// expected checksum.
170    ///
171    /// # Examples
172    ///
173    /// ```
174    /// # use alloy_primitives::{address, Address};
175    /// let checksummed = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045";
176    /// let address = Address::parse_checksummed(checksummed, None).unwrap();
177    /// let expected = address!("0xd8da6bf26964af9d7eed9e03e53415d37aa96045");
178    /// assert_eq!(address, expected);
179    /// ```
180    pub fn parse_checksummed<S: AsRef<str>>(
181        s: S,
182        chain_id: Option<u64>,
183    ) -> Result<Self, AddressError> {
184        fn parse_checksummed(s: &str, chain_id: Option<u64>) -> Result<Address, AddressError> {
185            // checksummed addresses always start with the "0x" prefix
186            if !s.starts_with("0x") {
187                return Err(AddressError::Hex(hex::FromHexError::InvalidStringLength));
188            }
189
190            let address: Address = s.parse()?;
191            if s == address.to_checksum_buffer(chain_id).as_str() {
192                Ok(address)
193            } else {
194                Err(AddressError::InvalidChecksum)
195            }
196        }
197
198        parse_checksummed(s.as_ref(), chain_id)
199    }
200
201    /// Encodes an Ethereum address to its [EIP-55] checksum into a heap-allocated string.
202    ///
203    /// You can optionally specify an [EIP-155 chain ID] to encode the address
204    /// using [EIP-1191].
205    ///
206    /// [EIP-55]: https://eips.ethereum.org/EIPS/eip-55
207    /// [EIP-155 chain ID]: https://eips.ethereum.org/EIPS/eip-155
208    /// [EIP-1191]: https://eips.ethereum.org/EIPS/eip-1191
209    ///
210    /// # Examples
211    ///
212    /// ```
213    /// # use alloy_primitives::{address, Address};
214    /// let address = address!("0xd8da6bf26964af9d7eed9e03e53415d37aa96045");
215    ///
216    /// let checksummed: String = address.to_checksum(None);
217    /// assert_eq!(checksummed, "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045");
218    ///
219    /// let checksummed: String = address.to_checksum(Some(1));
220    /// assert_eq!(checksummed, "0xD8Da6bf26964Af9d7EEd9e03e53415d37AA96045");
221    /// ```
222    #[inline]
223    #[must_use]
224    pub fn to_checksum(&self, chain_id: Option<u64>) -> String {
225        self.to_checksum_buffer(chain_id).as_str().into()
226    }
227
228    /// Encodes an Ethereum address to its [EIP-55] checksum into the given buffer.
229    ///
230    /// For convenience, the buffer is returned as a `&mut str`, as the bytes
231    /// are guaranteed to be valid UTF-8.
232    ///
233    /// You can optionally specify an [EIP-155 chain ID] to encode the address
234    /// using [EIP-1191].
235    ///
236    /// [EIP-55]: https://eips.ethereum.org/EIPS/eip-55
237    /// [EIP-155 chain ID]: https://eips.ethereum.org/EIPS/eip-155
238    /// [EIP-1191]: https://eips.ethereum.org/EIPS/eip-1191
239    ///
240    /// # Panics
241    ///
242    /// Panics if `buf` is not exactly 42 bytes long.
243    ///
244    /// # Examples
245    ///
246    /// ```
247    /// # use alloy_primitives::{address, Address};
248    /// let address = address!("0xd8da6bf26964af9d7eed9e03e53415d37aa96045");
249    /// let mut buf = [0; 42];
250    ///
251    /// let checksummed: &mut str = address.to_checksum_raw(&mut buf, None);
252    /// assert_eq!(checksummed, "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045");
253    ///
254    /// let checksummed: &mut str = address.to_checksum_raw(&mut buf, Some(1));
255    /// assert_eq!(checksummed, "0xD8Da6bf26964Af9d7EEd9e03e53415d37AA96045");
256    /// ```
257    #[inline]
258    #[must_use]
259    pub fn to_checksum_raw<'a>(&self, buf: &'a mut [u8], chain_id: Option<u64>) -> &'a mut str {
260        let buf: &mut [u8; 42] = buf.try_into().expect("buffer must be exactly 42 bytes long");
261        self.to_checksum_inner(buf, chain_id);
262        // SAFETY: All bytes in the buffer are valid UTF-8.
263        unsafe { str::from_utf8_unchecked_mut(buf) }
264    }
265
266    /// Encodes an Ethereum address to its [EIP-55] checksum into a stack-allocated buffer.
267    ///
268    /// You can optionally specify an [EIP-155 chain ID] to encode the address
269    /// using [EIP-1191].
270    ///
271    /// [EIP-55]: https://eips.ethereum.org/EIPS/eip-55
272    /// [EIP-155 chain ID]: https://eips.ethereum.org/EIPS/eip-155
273    /// [EIP-1191]: https://eips.ethereum.org/EIPS/eip-1191
274    ///
275    /// # Examples
276    ///
277    /// ```
278    /// # use alloy_primitives::{address, Address, AddressChecksumBuffer};
279    /// let address = address!("0xd8da6bf26964af9d7eed9e03e53415d37aa96045");
280    ///
281    /// let mut buffer: AddressChecksumBuffer = address.to_checksum_buffer(None);
282    /// assert_eq!(buffer.as_str(), "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045");
283    ///
284    /// let checksummed: &str = buffer.format(&address, Some(1));
285    /// assert_eq!(checksummed, "0xD8Da6bf26964Af9d7EEd9e03e53415d37AA96045");
286    /// ```
287    #[inline]
288    pub fn to_checksum_buffer(&self, chain_id: Option<u64>) -> AddressChecksumBuffer {
289        // SAFETY: The buffer is initialized by `format`.
290        let mut buf = unsafe { AddressChecksumBuffer::new() };
291        buf.format(self, chain_id);
292        buf
293    }
294
295    // https://eips.ethereum.org/EIPS/eip-55
296    // > In English, convert the address to hex, but if the `i`th digit is a letter (ie. it’s one of
297    // > `abcdef`) print it in uppercase if the `4*i`th bit of the hash of the lowercase hexadecimal
298    // > address is 1 otherwise print it in lowercase.
299    //
300    // https://eips.ethereum.org/EIPS/eip-1191
301    // > [...] If the chain id passed to the function belongs to a network that opted for using this
302    // > checksum variant, prefix the address with the chain id and the `0x` separator before
303    // > calculating the hash. [...]
304    #[allow(clippy::wrong_self_convention)]
305    fn to_checksum_inner(&self, buf: &mut [u8; 42], chain_id: Option<u64>) {
306        buf[0] = b'0';
307        buf[1] = b'x';
308        hex::encode_to_slice(self, &mut buf[2..]).unwrap();
309
310        let mut hasher = crate::Keccak256::new();
311        match chain_id {
312            Some(chain_id) => {
313                hasher.update(itoa::Buffer::new().format(chain_id).as_bytes());
314                // Clippy suggests an unnecessary copy.
315                #[allow(clippy::needless_borrows_for_generic_args)]
316                hasher.update(&*buf);
317            }
318            None => hasher.update(&buf[2..]),
319        }
320        let hash = hasher.finalize();
321
322        for (i, out) in buf[2..].iter_mut().enumerate() {
323            // This is made branchless for easier vectorization.
324            // Get the i-th nibble of the hash.
325            let hash_nibble = (hash[i / 2] >> (4 * (1 - i % 2))) & 0xf;
326            // Make the character ASCII uppercase if it's a hex letter and the hash nibble is >= 8.
327            // We can use a simpler comparison for checking if the character is a hex letter because
328            // we know `out` is a hex-encoded character (`b'0'..=b'9' | b'a'..=b'f'`).
329            *out ^= 0b0010_0000 * ((*out >= b'a') & (hash_nibble >= 8)) as u8;
330        }
331    }
332
333    /// Computes the `create` address for this address and nonce:
334    ///
335    /// `keccak256(rlp([sender, nonce]))[12:]`
336    ///
337    /// # Examples
338    ///
339    /// ```
340    /// # use alloy_primitives::{address, Address};
341    /// let sender = address!("0xb20a608c624Ca5003905aA834De7156C68b2E1d0");
342    ///
343    /// let expected = address!("0x00000000219ab540356cBB839Cbe05303d7705Fa");
344    /// assert_eq!(sender.create(0), expected);
345    ///
346    /// let expected = address!("0xe33c6e89e69d085897f98e92b06ebd541d1daa99");
347    /// assert_eq!(sender.create(1), expected);
348    /// ```
349    #[cfg(feature = "rlp")]
350    #[inline]
351    #[must_use]
352    pub fn create(&self, nonce: u64) -> Self {
353        use alloy_rlp::{EMPTY_LIST_CODE, EMPTY_STRING_CODE, Encodable};
354
355        // max u64 encoded length is `1 + u64::BYTES`
356        const MAX_LEN: usize = 1 + (1 + 20) + 9;
357
358        let len = 22 + nonce.length();
359        debug_assert!(len <= MAX_LEN);
360
361        let mut out = [0u8; MAX_LEN];
362
363        // list header
364        // minus 1 to account for the list header itself
365        out[0] = EMPTY_LIST_CODE + len as u8 - 1;
366
367        // address header + address
368        out[1] = EMPTY_STRING_CODE + 20;
369        out[2..22].copy_from_slice(self.as_slice());
370
371        // nonce
372        nonce.encode(&mut &mut out[22..]);
373
374        let hash = keccak256(&out[..len]);
375        Self::from_word(hash)
376    }
377
378    /// Computes the `CREATE2` address of a smart contract as specified in
379    /// [EIP-1014]:
380    ///
381    /// `keccak256(0xff ++ address ++ salt ++ keccak256(init_code))[12:]`
382    ///
383    /// The `init_code` is the code that, when executed, produces the runtime
384    /// bytecode that will be placed into the state, and which typically is used
385    /// by high level languages to implement a ‘constructor’.
386    ///
387    /// [EIP-1014]: https://eips.ethereum.org/EIPS/eip-1014
388    ///
389    /// # Examples
390    ///
391    /// ```
392    /// # use alloy_primitives::{address, b256, bytes, Address};
393    /// let address = address!("0x8ba1f109551bD432803012645Ac136ddd64DBA72");
394    /// let salt = b256!("0x7c5ea36004851c764c44143b1dcb59679b11c9a68e5f41497f6cf3d480715331");
395    /// let init_code = bytes!("6394198df16000526103ff60206004601c335afa6040516060f3");
396    /// let expected = address!("0x533ae9d683B10C02EbDb05471642F85230071FC3");
397    /// assert_eq!(address.create2_from_code(salt, init_code), expected);
398    /// ```
399    #[must_use]
400    pub fn create2_from_code<S, C>(&self, salt: S, init_code: C) -> Self
401    where
402        // not `AsRef` because `[u8; N]` does not implement `AsRef<[u8; N]>`
403        S: Borrow<[u8; 32]>,
404        C: AsRef<[u8]>,
405    {
406        self._create2(salt.borrow(), &keccak256(init_code.as_ref()).0)
407    }
408
409    /// Computes the `CREATE2` address of a smart contract as specified in
410    /// [EIP-1014], taking the pre-computed hash of the init code as input:
411    ///
412    /// `keccak256(0xff ++ address ++ salt ++ init_code_hash)[12:]`
413    ///
414    /// The `init_code` is the code that, when executed, produces the runtime
415    /// bytecode that will be placed into the state, and which typically is used
416    /// by high level languages to implement a ‘constructor’.
417    ///
418    /// [EIP-1014]: https://eips.ethereum.org/EIPS/eip-1014
419    ///
420    /// # Examples
421    ///
422    /// ```
423    /// # use alloy_primitives::{address, b256, Address};
424    /// let address = address!("0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f");
425    /// let salt = b256!("0x2b2f5776e38002e0c013d0d89828fdb06fee595ea2d5ed4b194e3883e823e350");
426    /// let init_code_hash =
427    ///     b256!("0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f");
428    /// let expected = address!("0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852");
429    /// assert_eq!(address.create2(salt, init_code_hash), expected);
430    /// ```
431    #[must_use]
432    pub fn create2<S, H>(&self, salt: S, init_code_hash: H) -> Self
433    where
434        // not `AsRef` because `[u8; N]` does not implement `AsRef<[u8; N]>`
435        S: Borrow<[u8; 32]>,
436        H: Borrow<[u8; 32]>,
437    {
438        self._create2(salt.borrow(), init_code_hash.borrow())
439    }
440
441    // non-generic inner function
442    fn _create2(&self, salt: &[u8; 32], init_code_hash: &[u8; 32]) -> Self {
443        // note: creating a temporary buffer and copying everything over performs
444        // much better than calling `Keccak::update` multiple times
445        let mut bytes = [0; 85];
446        bytes[0] = 0xff;
447        bytes[1..21].copy_from_slice(self.as_slice());
448        bytes[21..53].copy_from_slice(salt);
449        bytes[53..85].copy_from_slice(init_code_hash);
450        let hash = keccak256(bytes);
451        Self::from_word(hash)
452    }
453
454    /// Computes the address created by the `EOFCREATE` opcode, where `self` is the sender.
455    ///
456    /// The address is calculated as `keccak256(0xff || sender32 || salt)[12:]`, where sender32 is
457    /// the sender address left-padded to 32 bytes with zeros.
458    ///
459    /// See [EIP-7620](https://eips.ethereum.org/EIPS/eip-7620) for more details.
460    ///
461    /// <div class="warning">
462    /// This function's stability is not guaranteed. It may change in the future as the EIP is
463    /// not yet accepted.
464    /// </div>
465    ///
466    /// # Examples
467    ///
468    /// ```
469    /// # use alloy_primitives::{address, b256, Address};
470    /// let address = address!("0xb20a608c624Ca5003905aA834De7156C68b2E1d0");
471    /// let salt = b256!("0x7c5ea36004851c764c44143b1dcb59679b11c9a68e5f41497f6cf3d480715331");
472    /// // Create an address using CREATE_EOF
473    /// let eof_address = address.create_eof(salt);
474    /// ```
475    #[must_use]
476    #[doc(alias = "eof_create")]
477    pub fn create_eof<S>(&self, salt: S) -> Self
478    where
479        // not `AsRef` because `[u8; N]` does not implement `AsRef<[u8; N]>`
480        S: Borrow<[u8; 32]>,
481    {
482        self._create_eof(salt.borrow())
483    }
484
485    // non-generic inner function
486    fn _create_eof(&self, salt: &[u8; 32]) -> Self {
487        let mut buffer = [0; 65];
488        buffer[0] = 0xff;
489        // 1..13 is zero pad (already initialized to 0)
490        buffer[13..33].copy_from_slice(self.as_slice());
491        buffer[33..].copy_from_slice(salt);
492        Self::from_word(keccak256(buffer))
493    }
494
495    /// Instantiate by hashing public key bytes.
496    ///
497    /// # Panics
498    ///
499    /// If the input is not exactly 64 bytes
500    pub fn from_raw_public_key(pubkey: &[u8]) -> Self {
501        assert_eq!(pubkey.len(), 64, "raw public key must be 64 bytes");
502        let digest = keccak256(pubkey);
503        Self::from_slice(&digest[12..])
504    }
505
506    /// Converts an ECDSA verifying key to its corresponding Ethereum address.
507    #[inline]
508    #[cfg(feature = "k256")]
509    #[doc(alias = "from_verifying_key")]
510    pub fn from_public_key(pubkey: &k256::ecdsa::VerifyingKey) -> Self {
511        use k256::elliptic_curve::sec1::ToEncodedPoint;
512        let affine: &k256::AffinePoint = pubkey.as_ref();
513        let encoded = affine.to_encoded_point(false);
514        Self::from_raw_public_key(&encoded.as_bytes()[1..])
515    }
516
517    /// Converts an ECDSA signing key to its corresponding Ethereum address.
518    #[inline]
519    #[cfg(feature = "k256")]
520    #[doc(alias = "from_signing_key")]
521    pub fn from_private_key(private_key: &k256::ecdsa::SigningKey) -> Self {
522        Self::from_public_key(private_key.verifying_key())
523    }
524}
525
526/// Stack-allocated buffer for efficiently computing address checksums.
527///
528/// See [`Address::to_checksum_buffer`] for more information.
529#[must_use]
530#[allow(missing_copy_implementations)]
531#[derive(Clone)]
532pub struct AddressChecksumBuffer(MaybeUninit<[u8; 42]>);
533
534impl fmt::Debug for AddressChecksumBuffer {
535    #[inline]
536    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
537        self.as_str().fmt(f)
538    }
539}
540
541impl fmt::Display for AddressChecksumBuffer {
542    #[inline]
543    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
544        self.as_str().fmt(f)
545    }
546}
547
548impl AddressChecksumBuffer {
549    /// Creates a new buffer.
550    ///
551    /// # Safety
552    ///
553    /// The buffer must be initialized with [`format`](Self::format) before use.
554    /// Prefer [`Address::to_checksum_buffer`] instead.
555    #[inline]
556    pub const unsafe fn new() -> Self {
557        Self(MaybeUninit::uninit())
558    }
559
560    /// Calculates the checksum of an address into the buffer.
561    ///
562    /// See [`Address::to_checksum_buffer`] for more information.
563    #[inline]
564    pub fn format(&mut self, address: &Address, chain_id: Option<u64>) -> &mut str {
565        address.to_checksum_inner(unsafe { self.0.assume_init_mut() }, chain_id);
566        self.as_mut_str()
567    }
568
569    /// Returns the checksum of a formatted address.
570    #[inline]
571    pub const fn as_str(&self) -> &str {
572        unsafe { str::from_utf8_unchecked(self.0.assume_init_ref()) }
573    }
574
575    /// Returns the checksum of a formatted address.
576    #[inline]
577    pub const fn as_mut_str(&mut self) -> &mut str {
578        unsafe { str::from_utf8_unchecked_mut(self.0.assume_init_mut()) }
579    }
580
581    /// Returns the checksum of a formatted address.
582    #[inline]
583    #[allow(clippy::inherent_to_string_shadow_display)]
584    pub fn to_string(&self) -> String {
585        self.as_str().to_string()
586    }
587
588    /// Returns the backing buffer.
589    #[inline]
590    pub const fn into_inner(self) -> [u8; 42] {
591        unsafe { self.0.assume_init() }
592    }
593}
594
595#[cfg(test)]
596mod tests {
597    use super::*;
598    use crate::hex;
599
600    #[test]
601    fn parse() {
602        let expected = hex!("0102030405060708090a0b0c0d0e0f1011121314");
603        assert_eq!(
604            "0102030405060708090a0b0c0d0e0f1011121314".parse::<Address>().unwrap().into_array(),
605            expected
606        );
607        assert_eq!(
608            "0x0102030405060708090a0b0c0d0e0f1011121314".parse::<Address>().unwrap(),
609            expected
610        );
611    }
612
613    // https://eips.ethereum.org/EIPS/eip-55
614    #[test]
615    fn checksum() {
616        let addresses = [
617            // All caps
618            "0x52908400098527886E0F7030069857D2E4169EE7",
619            "0x8617E340B3D01FA5F11F306F4090FD50E238070D",
620            // All Lower
621            "0xde709f2102306220921060314715629080e2fb77",
622            "0x27b1fdb04752bbc536007a920d24acb045561c26",
623            // Normal
624            "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed",
625            "0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359",
626            "0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB",
627            "0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb",
628        ];
629        for addr in addresses {
630            let parsed1: Address = addr.parse().unwrap();
631            let parsed2 = Address::parse_checksummed(addr, None).unwrap();
632            assert_eq!(parsed1, parsed2);
633            assert_eq!(parsed2.to_checksum(None), addr);
634        }
635    }
636
637    // https://eips.ethereum.org/EIPS/eip-1191
638    #[test]
639    fn checksum_chain_id() {
640        let eth_mainnet = [
641            "0x27b1fdb04752bbc536007a920d24acb045561c26",
642            "0x3599689E6292b81B2d85451025146515070129Bb",
643            "0x42712D45473476b98452f434e72461577D686318",
644            "0x52908400098527886E0F7030069857D2E4169EE7",
645            "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed",
646            "0x6549f4939460DE12611948b3f82b88C3C8975323",
647            "0x66f9664f97F2b50F62D13eA064982f936dE76657",
648            "0x8617E340B3D01FA5F11F306F4090FD50E238070D",
649            "0x88021160C5C792225E4E5452585947470010289D",
650            "0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb",
651            "0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB",
652            "0xde709f2102306220921060314715629080e2fb77",
653            "0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359",
654        ];
655        let rsk_mainnet = [
656            "0x27b1FdB04752BBc536007A920D24ACB045561c26",
657            "0x3599689E6292B81B2D85451025146515070129Bb",
658            "0x42712D45473476B98452f434E72461577d686318",
659            "0x52908400098527886E0F7030069857D2E4169ee7",
660            "0x5aaEB6053f3e94c9b9a09f33669435E7ef1bEAeD",
661            "0x6549F4939460DE12611948B3F82B88C3C8975323",
662            "0x66F9664f97f2B50F62d13EA064982F936de76657",
663            "0x8617E340b3D01Fa5f11f306f4090fd50E238070D",
664            "0x88021160c5C792225E4E5452585947470010289d",
665            "0xD1220A0Cf47c7B9BE7a2e6ba89F429762E7B9adB",
666            "0xDBF03B407c01E7CD3cBea99509D93F8Dddc8C6FB",
667            "0xDe709F2102306220921060314715629080e2FB77",
668            "0xFb6916095cA1Df60bb79ce92cE3EA74c37c5d359",
669        ];
670        let rsk_testnet = [
671            "0x27B1FdB04752BbC536007a920D24acB045561C26",
672            "0x3599689e6292b81b2D85451025146515070129Bb",
673            "0x42712D45473476B98452F434E72461577D686318",
674            "0x52908400098527886E0F7030069857D2e4169EE7",
675            "0x5aAeb6053F3e94c9b9A09F33669435E7EF1BEaEd",
676            "0x6549f4939460dE12611948b3f82b88C3c8975323",
677            "0x66f9664F97F2b50f62d13eA064982F936DE76657",
678            "0x8617e340b3D01fa5F11f306F4090Fd50e238070d",
679            "0x88021160c5C792225E4E5452585947470010289d",
680            "0xd1220a0CF47c7B9Be7A2E6Ba89f429762E7b9adB",
681            "0xdbF03B407C01E7cd3cbEa99509D93f8dDDc8C6fB",
682            "0xDE709F2102306220921060314715629080e2Fb77",
683            "0xFb6916095CA1dF60bb79CE92ce3Ea74C37c5D359",
684        ];
685        for (addresses, chain_id) in [(eth_mainnet, 1), (rsk_mainnet, 30), (rsk_testnet, 31)] {
686            // EIP-1191 test cases treat mainnet as "not adopted"
687            let id = if chain_id == 1 { None } else { Some(chain_id) };
688            for addr in addresses {
689                let parsed1: Address = addr.parse().unwrap();
690                let parsed2 = Address::parse_checksummed(addr, id).unwrap();
691                assert_eq!(parsed1, parsed2);
692                assert_eq!(parsed2.to_checksum(id), addr);
693            }
694        }
695    }
696
697    // https://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed
698    #[test]
699    #[cfg(feature = "rlp")]
700    fn create() {
701        let from = "0x6ac7ea33f8831ea9dcc53393aaa88b25a785dbf0".parse::<Address>().unwrap();
702        for (nonce, expected) in [
703            "0xcd234a471b72ba2f1ccf0a70fcaba648a5eecd8d",
704            "0x343c43a37d37dff08ae8c4a11544c718abb4fcf8",
705            "0xf778b86fa74e846c4f0a1fbd1335fe81c00a0c91",
706            "0xfffd933a0bc612844eaf0c6fe3e5b8e9b6c1d19c",
707        ]
708        .into_iter()
709        .enumerate()
710        {
711            let address = from.create(nonce as u64);
712            assert_eq!(address, expected.parse::<Address>().unwrap());
713        }
714    }
715
716    #[test]
717    #[cfg(all(feature = "rlp", feature = "arbitrary"))]
718    #[cfg_attr(miri, ignore = "doesn't run in isolation and would take too long")]
719    fn create_correctness() {
720        fn create_slow(address: &Address, nonce: u64) -> Address {
721            use alloy_rlp::Encodable;
722
723            let mut out = vec![];
724
725            alloy_rlp::Header { list: true, payload_length: address.length() + nonce.length() }
726                .encode(&mut out);
727            address.encode(&mut out);
728            nonce.encode(&mut out);
729
730            Address::from_word(keccak256(out))
731        }
732
733        proptest::proptest!(|(address: Address, nonce: u64)| {
734            proptest::prop_assert_eq!(address.create(nonce), create_slow(&address, nonce));
735        });
736    }
737
738    // https://eips.ethereum.org/EIPS/eip-1014
739    #[test]
740    fn create2() {
741        let tests = [
742            (
743                "0000000000000000000000000000000000000000",
744                "0000000000000000000000000000000000000000000000000000000000000000",
745                "00",
746                "0x4D1A2e2bB4F88F0250f26Ffff098B0b30B26BF38",
747            ),
748            (
749                "deadbeef00000000000000000000000000000000",
750                "0000000000000000000000000000000000000000000000000000000000000000",
751                "00",
752                "0xB928f69Bb1D91Cd65274e3c79d8986362984fDA3",
753            ),
754            (
755                "deadbeef00000000000000000000000000000000",
756                "000000000000000000000000feed000000000000000000000000000000000000",
757                "00",
758                "0xD04116cDd17beBE565EB2422F2497E06cC1C9833",
759            ),
760            (
761                "0000000000000000000000000000000000000000",
762                "0000000000000000000000000000000000000000000000000000000000000000",
763                "deadbeef",
764                "0x70f2b2914A2a4b783FaEFb75f459A580616Fcb5e",
765            ),
766            (
767                "00000000000000000000000000000000deadbeef",
768                "00000000000000000000000000000000000000000000000000000000cafebabe",
769                "deadbeef",
770                "0x60f3f640a8508fC6a86d45DF051962668E1e8AC7",
771            ),
772            (
773                "00000000000000000000000000000000deadbeef",
774                "00000000000000000000000000000000000000000000000000000000cafebabe",
775                "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
776                "0x1d8bfDC5D46DC4f61D6b6115972536eBE6A8854C",
777            ),
778            (
779                "0000000000000000000000000000000000000000",
780                "0000000000000000000000000000000000000000000000000000000000000000",
781                "",
782                "0xE33C0C7F7df4809055C3ebA6c09CFe4BaF1BD9e0",
783            ),
784        ];
785        for (from, salt, init_code, expected) in tests {
786            let from = from.parse::<Address>().unwrap();
787
788            let salt = hex::decode(salt).unwrap();
789            let salt: [u8; 32] = salt.try_into().unwrap();
790
791            let init_code = hex::decode(init_code).unwrap();
792            let init_code_hash = keccak256(&init_code);
793
794            let expected = expected.parse::<Address>().unwrap();
795
796            assert_eq!(expected, from.create2(salt, init_code_hash));
797            assert_eq!(expected, from.create2_from_code(salt, init_code));
798        }
799    }
800
801    #[test]
802    fn create_eof() {
803        // Test cases with (from_address, salt, expected_result)
804        let tests = [
805            (
806                "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
807                "0000000000000000000000000000000000000000000000000000000000000000",
808                "02b6826e9392ee6bf6479e413c570846ab0107ec",
809            ),
810            (
811                "0000000000000000000000000000000000000000",
812                "0000000000000000000000000000000000000000000000000000000000000000",
813                "47f3f8F550f58348651C4c3E8cCD414b35d2E9fC",
814            ),
815            (
816                "deadbeef00000000000000000000000000000000",
817                "0000000000000000000000000000000000000000000000000000000000000000",
818                "D146E87a5EA438103eF31cB75B432EecF0c855cc",
819            ),
820        ];
821
822        for (from, salt, expected) in tests {
823            let from = from.parse::<Address>().unwrap();
824
825            let salt = hex::decode(salt).unwrap();
826            let salt: [u8; 32] = salt.try_into().unwrap();
827
828            let expected = expected.parse::<Address>().unwrap();
829
830            assert_eq!(expected, from.create_eof(salt));
831        }
832    }
833
834    #[test]
835    fn test_raw_public_key_to_address() {
836        let addr = "0Ac1dF02185025F65202660F8167210A80dD5086".parse::<Address>().unwrap();
837
838        let pubkey_bytes = hex::decode("76698beebe8ee5c74d8cc50ab84ac301ee8f10af6f28d0ffd6adf4d6d3b9b762d46ca56d3dad2ce13213a6f42278dabbb53259f2d92681ea6a0b98197a719be3").unwrap();
839
840        assert_eq!(Address::from_raw_public_key(&pubkey_bytes), addr);
841    }
842}