Skip to main content

ton_net/
address.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: 2026 Nirapod Labs
3
4//! TON account addresses: parsing the raw and user-friendly forms.
5
6use crate::codec::{base64_decode, crc16, decode_hex};
7use crate::Error;
8
9/// The tag byte of a user-friendly address, with neither flag set.
10const ADDRESS_TAG: u8 = 0x11;
11
12/// The tag bit marking an address as usable only on a test network.
13const TEST_ONLY: u8 = 0x80;
14
15/// The tag bit marking an address as non-bounceable.
16const NON_BOUNCEABLE: u8 = 0x40;
17
18/// A TON account address: a workchain id and a 256-bit account id.
19///
20/// Parses both the raw `workchain:hex` form and the user-friendly base64 form. The
21/// address carries no balance or state.
22///
23/// Two addresses are equal when they name the same account. The user-friendly form also
24/// carries a bounceable and a test-only flag, which say how a message to the account
25/// should be sent and which network it belongs to rather than which account it is, so
26/// they are readable but do not enter into equality. The raw form carries neither, and an
27/// address parsed from it reports the defaults: bounceable, and not test-only.
28#[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    /// Parses an address from a string.
38    ///
39    /// Accepts the raw form, for example `-1:3333...3333`, and the user-friendly base64
40    /// form, for example `Ef8z...`. A raw address is a workchain, a colon, and 64 hex
41    /// digits. A user-friendly address is 36 base64 bytes whose CRC16 checksum is
42    /// verified.
43    ///
44    /// # Errors
45    ///
46    /// Returns [`Error::Address`] if the string is not a valid address in either form, or
47    /// if a user-friendly address fails its checksum.
48    ///
49    /// # Examples
50    ///
51    /// ```
52    /// use ton_net::Address;
53    /// let a = Address::parse(
54    ///     "-1:3333333333333333333333333333333333333333333333333333333333333333",
55    /// )?;
56    /// assert_eq!(a.workchain(), -1);
57    /// # Ok::<(), ton_net::Error>(())
58    /// ```
59    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        // tag (1) ++ workchain (1) ++ account id (32) ++ crc16 (2)
85        // Held as an array rather than a length-checked vector, so every field below is a
86        // constant range the compiler settles rather than a bound taken on trust.
87        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        // The checksum covers the tag, so it validates whatever tag the string carries
99        // rather than the ones the format defines. Reading the tag is what keeps this
100        // from accepting a string every other TON implementation refuses.
101        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        // The workchain byte is a signed 8-bit value: 0x00 is workchain 0, 0xff is -1.
109        #[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    /// Returns the workchain id.
125    #[must_use]
126    pub fn workchain(&self) -> i32 {
127        self.workchain
128    }
129
130    /// Returns the 32-byte account id.
131    #[must_use]
132    pub fn account_id(&self) -> &[u8; 32] {
133        &self.account_id
134    }
135
136    /// Whether a failed message to this address should be returned to its sender.
137    ///
138    /// A hint about sending, not part of the account's identity. True for an address
139    /// parsed from the raw form, which does not carry the flag.
140    #[must_use]
141    pub fn is_bounceable(&self) -> bool {
142        self.bounceable
143    }
144
145    /// Whether the address was written for a test network.
146    ///
147    /// Which network a client is on is decided by its [`Config`](crate::Config), not by
148    /// an address, so this is not enforced anywhere: a test-only address read against
149    /// mainnet gets a correct answer about a mainnet account, which is almost certainly
150    /// not the account the caller meant. A caller that cares checks this.
151    #[must_use]
152    pub fn is_test_only(&self) -> bool {
153        self.test_only
154    }
155}
156
157impl PartialEq for Address {
158    /// Equal when they name the same account. The sending hints are not the account.
159    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        // The reference implementation packs 0:fcb91a...2260 to this address.
198        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        // The elector, in both forms, is one address.
209        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        // The elector's address with its last base64 digit changed.
219        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        // Forty-eight base64 characters carry exactly the thirty-six bytes an address
226        // needs, with nothing left over. A forty-ninth adds six bits and no byte, so
227        // without a canonical decoder it would spell the same address a second way and
228        // any caller holding a list of addresses as strings could be walked past it.
229        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        // The checksum covers the tag, so a string carrying any tag at all checksums
243        // correctly and the checksum alone cannot refuse one. The elector's address,
244        // repacked under each tag the format defines and two it does not.
245        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            // The flags describe how to send, not which account, so they leave the
264            // address equal to the same account written any other way.
265            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    /// Packs bytes as URL-safe base64, for building the tagged addresses above.
283    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}