1use alloc::format;
4use alloc::string::String;
5use core::fmt;
6use core::str::FromStr;
7
8use ripemd::Ripemd160;
9use sha3::{Digest, Sha3_256};
10
11use crate::base32;
12use crate::hex::{self, ParseHexError};
13use crate::key::PublicKey;
14use crate::network::NetworkIdentifier;
15
16#[derive(Clone, Copy, PartialEq, Eq, Hash)]
19pub struct Address(pub [u8; 24]);
20
21impl Address {
22 pub const SIZE: usize = 24;
23 pub const ENCODED_SIZE: usize = 39;
25 const CHECKSUM_SIZE: usize = 3;
26
27 pub fn from_public_key(public_key: &PublicKey, network: NetworkIdentifier) -> Self {
28 let public_key_hash = Sha3_256::digest(public_key.0);
29 let mut address = [0; Self::SIZE];
30 address[0] = network.0;
31 address[1..21].copy_from_slice(&Ripemd160::digest(public_key_hash));
32 let checksum_begin = Self::SIZE - Self::CHECKSUM_SIZE;
33 let checksum = Sha3_256::digest(&address[..checksum_begin]);
34 address[checksum_begin..].copy_from_slice(&checksum[..Self::CHECKSUM_SIZE]);
35 Self(address)
36 }
37
38 pub fn network(&self) -> NetworkIdentifier {
39 NetworkIdentifier(self.0[0])
40 }
41
42 pub fn has_valid_checksum(&self) -> bool {
45 let checksum_begin = Self::SIZE - Self::CHECKSUM_SIZE;
46 Sha3_256::digest(&self.0[..checksum_begin])[..Self::CHECKSUM_SIZE]
47 == self.0[checksum_begin..]
48 }
49
50 pub fn from_hex(text: &str) -> Result<Self, ParseAddressError> {
53 let address = Self(hex::decode(text).map_err(ParseAddressError::InvalidHex)?);
54 if !address.has_valid_checksum() {
55 return Err(ParseAddressError::InvalidChecksum);
56 }
57 Ok(address)
58 }
59
60 pub fn to_hex(&self) -> String {
62 hex::encode(&self.0)
63 }
64}
65
66impl fmt::Display for Address {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 let mut padded = [0; Self::SIZE + 1];
71 padded[..Self::SIZE].copy_from_slice(&self.0);
72 let mut encoded = base32::encode(&padded);
73 encoded.pop();
74 f.write_str(&encoded)
75 }
76}
77
78impl fmt::Debug for Address {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 write!(f, "Address({self})")
81 }
82}
83
84impl FromStr for Address {
87 type Err = ParseAddressError;
88
89 fn from_str(text: &str) -> Result<Self, Self::Err> {
90 let length = text.chars().count();
91 if length != Self::ENCODED_SIZE {
92 return Err(ParseAddressError::InvalidLength(length));
93 }
94 let padded = base32::decode(&format!("{text}A")).map_err(|(index, character)| {
95 ParseAddressError::InvalidCharacter { index, character }
96 })?;
97 if padded[Self::SIZE] != 0 {
99 return Err(ParseAddressError::NonCanonical);
100 }
101 let address = Self(padded[..Self::SIZE].try_into().expect("24 bytes"));
102 if !address.has_valid_checksum() {
103 return Err(ParseAddressError::InvalidChecksum);
104 }
105 Ok(address)
106 }
107}
108
109#[derive(Debug, Clone, PartialEq, Eq)]
110pub enum ParseAddressError {
111 InvalidLength(usize),
113 InvalidCharacter {
115 index: usize,
116 character: char,
117 },
118 NonCanonical,
120 InvalidChecksum,
121 InvalidHex(ParseHexError),
123}
124
125impl fmt::Display for ParseAddressError {
126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127 match self {
128 Self::InvalidLength(length) => {
129 write!(
130 f,
131 "アドレスは {} 文字のはずが {length} 文字でした",
132 Address::ENCODED_SIZE
133 )
134 }
135 Self::InvalidCharacter { index, character } => {
136 write!(
137 f,
138 "{index} 文字目の {character:?} は Base32 の文字ではありません"
139 )
140 }
141 Self::NonCanonical => write!(f, "最後の文字が正規の書き方になっていません"),
142 Self::InvalidChecksum => write!(f, "チェックサムが合いません"),
143 Self::InvalidHex(error) => write!(f, "アドレスの16進として読めません: {error}"),
144 }
145 }
146}
147
148impl core::error::Error for ParseAddressError {}
149
150#[cfg(test)]
151mod tests {
152 use super::*;
153 use crate::hex;
154
155 const BLOCK_2_SIGNER: &str = "79AF37ED4A98EF6C79F8C26992EA55ECEF74865827A1BBB602374C8F4F13DA07";
158 const BLOCK_2_BENEFICIARY: &str = "68C32AB1A8FC9D5024A43787788879FE6D42A5490A614170";
159 const BLOCK_2_BENEFICIARY_ENCODED: &str = "NDBSVMNI7SOVAJFEG6DXRCDZ7ZWUFJKJBJQUC4A";
161
162 fn block_2_beneficiary() -> Address {
163 Address::from_public_key(&BLOCK_2_SIGNER.parse().unwrap(), NetworkIdentifier::MAINNET)
164 }
165
166 #[test]
167 fn derives_the_beneficiary_of_mainnet_block_2_from_its_signer() {
168 let address = block_2_beneficiary();
169 assert_eq!(address.0, hex::decode(BLOCK_2_BENEFICIARY).unwrap());
170 assert_eq!(address.network(), NetworkIdentifier::MAINNET);
171 assert!(address.has_valid_checksum());
172 }
173
174 #[test]
175 fn round_trips_through_hex() {
176 let address = block_2_beneficiary();
177 assert_eq!(address.to_hex(), BLOCK_2_BENEFICIARY);
178 assert_eq!(Address::from_hex(BLOCK_2_BENEFICIARY), Ok(address));
179 assert_eq!(
180 Address::from_hex(&BLOCK_2_BENEFICIARY.to_lowercase()),
181 Ok(address)
182 );
183 let mut changed = BLOCK_2_BENEFICIARY.to_owned();
185 changed.replace_range(46.., "71");
186 assert_eq!(
187 Address::from_hex(&changed),
188 Err(ParseAddressError::InvalidChecksum)
189 );
190 assert!(matches!(
191 Address::from_hex(BLOCK_2_BENEFICIARY_ENCODED),
192 Err(ParseAddressError::InvalidHex(_))
193 ));
194 }
195
196 #[test]
197 fn round_trips_through_base32() {
198 let address = block_2_beneficiary();
199 assert_eq!(address.to_string(), BLOCK_2_BENEFICIARY_ENCODED);
200 assert_eq!(BLOCK_2_BENEFICIARY_ENCODED.parse(), Ok(address));
201 }
202
203 #[test]
204 fn network_changes_the_whole_address() {
205 let public_key = BLOCK_2_SIGNER.parse().unwrap();
206 let mainnet = Address::from_public_key(&public_key, NetworkIdentifier::MAINNET);
207 let testnet = Address::from_public_key(&public_key, NetworkIdentifier::TESTNET);
208 assert!(testnet.to_string().starts_with('T'));
209 assert_eq!(mainnet.0[1..21], testnet.0[1..21]);
211 assert_ne!(mainnet.0[21..], testnet.0[21..]);
212 }
213
214 #[test]
215 fn rejects_wrong_length() {
216 assert_eq!(
217 BLOCK_2_BENEFICIARY_ENCODED[..38].parse::<Address>(),
218 Err(ParseAddressError::InvalidLength(38))
219 );
220 }
221
222 #[test]
223 fn rejects_lower_case() {
224 assert_eq!(
225 BLOCK_2_BENEFICIARY_ENCODED
226 .to_lowercase()
227 .parse::<Address>(),
228 Err(ParseAddressError::InvalidCharacter {
229 index: 0,
230 character: 'n'
231 })
232 );
233 }
234
235 #[test]
236 fn rejects_a_mistyped_character() {
237 let mistyped = BLOCK_2_BENEFICIARY_ENCODED.replacen("NDBS", "NDBT", 1);
238 assert_eq!(
239 mistyped.parse::<Address>(),
240 Err(ParseAddressError::InvalidChecksum)
241 );
242 }
243
244 #[test]
245 fn rejects_bits_beyond_the_24_bytes() {
246 let mut text = BLOCK_2_BENEFICIARY_ENCODED.to_string();
248 text.pop();
249 text.push('B');
250 assert_eq!(
251 text.parse::<Address>(),
252 Err(ParseAddressError::NonCanonical)
253 );
254 }
255}