1use crate::codec::{base64_decode, crc16, decode_hex};
7use crate::Error;
8
9const ADDRESS_TAG: u8 = 0x11;
11
12const TEST_ONLY: u8 = 0x80;
14
15const NON_BOUNCEABLE: u8 = 0x40;
17
18#[derive(Debug, Clone)]
29pub struct Address {
30 workchain: i32,
31 account_id: [u8; 32],
32 bounceable: bool,
33 test_only: bool,
34}
35
36impl Address {
37 pub fn parse(s: &str) -> Result<Self, Error> {
60 if let Some((workchain, account)) = s.split_once(':') {
61 return Self::parse_raw(s, workchain, account);
62 }
63 Self::parse_user_friendly(s)
64 }
65
66 fn parse_raw(whole: &str, workchain: &str, account: &str) -> Result<Self, Error> {
67 let workchain: i32 = workchain
68 .parse()
69 .map_err(|_| Error::Address(format!("invalid workchain in `{whole}`")))?;
70 let account_id: [u8; 32] = decode_hex(account)
71 .and_then(|bytes| bytes.try_into().ok())
72 .ok_or_else(|| {
73 Error::Address(format!("account id is not 32 hex bytes in `{whole}`"))
74 })?;
75 Ok(Self {
76 workchain,
77 account_id,
78 bounceable: true,
79 test_only: false,
80 })
81 }
82
83 fn parse_user_friendly(s: &str) -> Result<Self, Error> {
84 let raw: [u8; 36] = base64_decode(s)
88 .and_then(|bytes| <[u8; 36]>::try_from(bytes).ok())
89 .ok_or_else(|| Error::Address(format!("not a 36-byte user-friendly address: `{s}`")))?;
90
91 let stored = [raw[34], raw[35]];
92 if crc16(&raw[..34]).to_be_bytes() != stored {
93 return Err(Error::Address(format!(
94 "address checksum mismatch in `{s}`"
95 )));
96 }
97
98 let tag = raw[0];
102 if tag & !(TEST_ONLY | NON_BOUNCEABLE) != ADDRESS_TAG {
103 return Err(Error::Address(format!(
104 "unknown address tag {tag:#04x} in `{s}`"
105 )));
106 }
107
108 #[allow(
110 clippy::cast_possible_wrap,
111 reason = "the workchain byte is meant as signed: 0x00 is 0 and 0xff is -1, so reinterpreting its bit pattern as i8 is the intended decode, not an accident"
112 )]
113 let workchain = i32::from(raw[1] as i8);
114 let mut account_id = [0u8; 32];
115 account_id.copy_from_slice(&raw[2..34]);
116 Ok(Self {
117 workchain,
118 account_id,
119 bounceable: tag & NON_BOUNCEABLE == 0,
120 test_only: tag & TEST_ONLY != 0,
121 })
122 }
123
124 #[must_use]
126 pub fn workchain(&self) -> i32 {
127 self.workchain
128 }
129
130 #[must_use]
132 pub fn account_id(&self) -> &[u8; 32] {
133 &self.account_id
134 }
135
136 #[must_use]
141 pub fn is_bounceable(&self) -> bool {
142 self.bounceable
143 }
144
145 #[must_use]
152 pub fn is_test_only(&self) -> bool {
153 self.test_only
154 }
155}
156
157impl PartialEq for Address {
158 fn eq(&self, other: &Self) -> bool {
160 self.workchain == other.workchain && self.account_id == other.account_id
161 }
162}
163
164impl Eq for Address {}
165
166impl std::hash::Hash for Address {
167 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
168 self.workchain.hash(state);
169 self.account_id.hash(state);
170 }
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176
177 fn hex(bytes: &[u8]) -> String {
178 use std::fmt::Write as _;
179
180 bytes.iter().fold(String::new(), |mut hex, b| {
181 let _ = write!(hex, "{b:02x}");
182 hex
183 })
184 }
185
186 #[test]
187 fn parses_the_raw_form() {
188 let a =
189 Address::parse("-1:3333333333333333333333333333333333333333333333333333333333333333")
190 .unwrap();
191 assert_eq!(a.workchain(), -1);
192 assert_eq!(a.account_id(), &[0x33; 32]);
193 }
194
195 #[test]
196 fn parses_a_real_user_friendly_address() {
197 let a = Address::parse("EQD8uRo6OBbQ97jCx2EIuKm8Wmt6Vb15-KsQHFLbKSMiYM0w").unwrap();
199 assert_eq!(a.workchain(), 0);
200 assert_eq!(
201 hex(a.account_id()),
202 "fcb91a3a3816d0f7b8c2c76108b8a9bc5a6b7a55bd79f8ab101c52db29232260"
203 );
204 }
205
206 #[test]
207 fn the_raw_and_user_friendly_forms_agree() {
208 let raw =
210 Address::parse("-1:3333333333333333333333333333333333333333333333333333333333333333")
211 .unwrap();
212 let friendly = Address::parse("Ef8zMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzM0vF").unwrap();
213 assert_eq!(raw, friendly);
214 }
215
216 #[test]
217 fn rejects_a_corrupted_checksum() {
218 let corrupted = "Ef8zMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzM0vG";
220 assert!(matches!(Address::parse(corrupted), Err(Error::Address(_))));
221 }
222
223 #[test]
224 fn one_account_has_one_user_friendly_spelling() {
225 let real = "EQD8uRo6OBbQ97jCx2EIuKm8Wmt6Vb15-KsQHFLbKSMiYM0w";
230 assert!(Address::parse(real).is_ok());
231 for extra in ["A", "z", "9", "-", "_", "=", "=A"] {
232 let padded = format!("{real}{extra}");
233 assert!(
234 matches!(Address::parse(&padded), Err(Error::Address(_))),
235 "`{padded}` parsed as an address"
236 );
237 }
238 }
239
240 #[test]
241 fn an_address_tag_is_read_rather_than_assumed() {
242 let account = [0x33; 32];
246 let packed = |tag: u8| {
247 let mut raw = vec![tag, 0xff];
248 raw.extend_from_slice(&account);
249 raw.extend_from_slice(&crc16(&raw).to_be_bytes());
250 base64_encode(&raw)
251 };
252
253 for (tag, bounceable, test_only) in [
254 (0x11, true, false),
255 (0x51, false, false),
256 (0x91, true, true),
257 (0xd1, false, true),
258 ] {
259 let address = Address::parse(&packed(tag)).expect("a tag the format defines");
260 assert_eq!(address.workchain(), -1);
261 assert_eq!(address.is_bounceable(), bounceable);
262 assert_eq!(address.is_test_only(), test_only);
263 assert_eq!(
266 address,
267 Address::parse(
268 "-1:3333333333333333333333333333333333333333333333333333333333333333"
269 )
270 .unwrap()
271 );
272 }
273
274 for tag in [0x00, 0xff, 0x12, 0x21] {
275 assert!(
276 matches!(Address::parse(&packed(tag)), Err(Error::Address(_))),
277 "tag {tag:#04x} was accepted"
278 );
279 }
280 }
281
282 fn base64_encode(bytes: &[u8]) -> String {
284 const ALPHABET: &[u8; 64] =
285 b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
286 let mut out = String::new();
287 for chunk in bytes.chunks(3) {
288 let mut block = [0u8; 3];
289 block[..chunk.len()].copy_from_slice(chunk);
290 let n = u32::from_be_bytes([0, block[0], block[1], block[2]]);
291 let digits = chunk.len() * 8 / 6 + 1;
292 for i in 0..4 {
293 if i < digits {
294 out.push(ALPHABET[((n >> (18 - i * 6)) & 63) as usize] as char);
295 } else {
296 out.push('=');
297 }
298 }
299 }
300 out
301 }
302
303 #[test]
304 fn rejects_a_non_numeric_workchain() {
305 assert!(matches!(
306 Address::parse("zz:3333333333333333333333333333333333333333333333333333333333333333"),
307 Err(Error::Address(_))
308 ));
309 }
310
311 #[test]
312 fn rejects_a_short_account_id() {
313 assert!(matches!(Address::parse("0:3333"), Err(Error::Address(_))));
314 }
315}