1use std::{fmt, str::FromStr};
2
3use serde::{Deserialize, Deserializer, Serialize, Serializer};
4
5use crate::{hash::sha256, Error, Network, Result};
6
7const PAYLOAD_HEX_LEN: usize = 40;
8const CHECKSUM_LEN: usize = 4;
9
10#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
12pub struct Address(String);
13
14impl Address {
15 pub fn parse(s: &str) -> Result<Self> {
17 Self::parse_for_network(s, Network::Mainnet)
18 }
19
20 pub fn parse_for_network(s: &str, network: Network) -> Result<Self> {
22 let prefix = network.address_prefix();
23 let address_len = prefix.len() + PAYLOAD_HEX_LEN + CHECKSUM_LEN * 2;
24 if s.len() != address_len {
25 return Err(Error::AddressLength);
26 }
27 if !s.starts_with(prefix) {
28 return Err(Error::AddressPrefix);
29 }
30 let (base, checksum_hex) = s.split_at(prefix.len() + PAYLOAD_HEX_LEN);
31 hex::decode(&base[prefix.len()..]).map_err(|_| Error::AddressPayload)?;
32 let got = hex::decode(checksum_hex).map_err(|_| Error::AddressChecksum)?;
33 if got != checksum(base) {
34 return Err(Error::AddressChecksum);
35 }
36 Ok(Self(s.to_owned()))
37 }
38
39 pub(crate) fn from_public_key_bytes(public_key: &[u8]) -> Self {
42 Self::from_public_key_bytes_for_network(public_key, Network::Mainnet)
43 }
44
45 pub(crate) fn from_public_key_bytes_for_network(public_key: &[u8], network: Network) -> Self {
47 let payload = &sha256(public_key)[..20];
48 let base = format!("{}{}", network.address_prefix(), hex::encode(payload));
49 let check = hex::encode(checksum(&base));
50 Self(base + &check)
51 }
52
53 pub fn as_str(&self) -> &str {
55 &self.0
56 }
57}
58
59fn checksum(base: &str) -> [u8; CHECKSUM_LEN] {
60 let second = sha256(&sha256(base.as_bytes()));
61 let mut out = [0u8; CHECKSUM_LEN];
62 out.copy_from_slice(&second[..CHECKSUM_LEN]);
63 out
64}
65
66impl fmt::Display for Address {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 f.write_str(&self.0)
69 }
70}
71
72impl fmt::Debug for Address {
73 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74 write!(f, "Address({})", self.0)
75 }
76}
77
78impl FromStr for Address {
79 type Err = Error;
80 fn from_str(s: &str) -> Result<Self> {
81 Self::parse(s)
82 }
83}
84
85impl AsRef<str> for Address {
86 fn as_ref(&self) -> &str {
87 &self.0
88 }
89}
90
91impl Serialize for Address {
92 fn serialize<S: Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
93 s.serialize_str(&self.0)
94 }
95}
96
97impl<'de> Deserialize<'de> for Address {
98 fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
99 let s = String::deserialize(d)?;
100 Self::parse(&s).map_err(serde::de::Error::custom)
101 }
102}