Skip to main content

ton_net/
config.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: 2026 Nirapod Labs
3
4//! The network config: the liteservers a client can reach.
5
6use serde::Deserialize;
7
8use crate::codec::base64_decode;
9use crate::{BlockIdExt, Error};
10
11/// How far behind the local clock a proven head may be, by default.
12///
13/// Ten minutes. The bound has to cover two things at once: a server serving a block it
14/// has been sitting on, and the walk's own duration, since a cold sync targets a head it
15/// read at the start and takes a couple of minutes to reach it. A tighter bound would
16/// refuse an honest cold sync on a slow link, which is why this is generous and
17/// [`Config::with_max_head_age`] exists for a caller who knows better.
18const DEFAULT_MAX_HEAD_AGE: u32 = 600;
19
20/// The public network parameters a client needs to reach TON.
21///
22/// A config lists the liteservers to connect to and names the block a client anchors its
23/// trust at. It holds only public data and never a secret. The DHT section a config also
24/// carries is not read.
25#[derive(Debug, Clone)]
26pub struct Config {
27    liteservers: Vec<LiteServer>,
28    init_block: Option<BlockIdExt>,
29    max_head_age: u32,
30}
31
32/// One liteserver: an address ready to dial and its public key.
33#[derive(Debug, Clone)]
34pub struct LiteServer {
35    pub(crate) addr: String,
36    pub(crate) key: [u8; 32],
37}
38
39impl Config {
40    /// Returns a config for TON mainnet from a bundled snapshot, taken 2026-07-21.
41    ///
42    /// The snapshot is a point-in-time copy of the public mainnet config and can go stale
43    /// as liteservers rotate. To use a current server list, fetch `global.config.json` and
44    /// pass it to [`Config::from_json`].
45    ///
46    /// Read that sentence narrowly, because the file carries two things whose trust
47    /// requirements are opposite. The liteserver list needs none: every answer a server
48    /// gives is checked against a proof, so a hostile one can stall or lie and the lie is
49    /// refused. The [`init_block`](Self::init_block) is the other case. It is the anchor
50    /// every later proof is measured against, so a fetched one moves this client's root of
51    /// trust to whoever served it, and every proof then verifies cleanly against whatever
52    /// chain that party invented. Fetching a config therefore trusts the source for the
53    /// anchor as well as for the servers, which is a different decision from refreshing a
54    /// server list and worth making deliberately.
55    ///
56    /// The bundled [`init_block`](Self::init_block) is at masterchain sequence number
57    /// 46894135, which is where a first sync starts walking. That block is what the network
58    /// publishes rather than one this library chose, and the further it recedes the
59    /// longer a first sync takes, so refreshing this snapshot belongs to cutting a
60    /// release rather than to housekeeping.
61    ///
62    /// # Panics
63    ///
64    /// Panics if the bundled snapshot fails to parse. It cannot in a released build: a
65    /// test in this module parses this exact checked-in file, so a failure here would mean
66    /// the snapshot and the test that guards it have already gone out of sync before this
67    /// ever ran.
68    #[must_use]
69    // Whether the checked-in snapshot parses is settled before a caller ever runs, and a
70    // test in this module holds it there. Returning a Result would put a failure no
71    // caller can cause, and none can act on, into the first call most programs make.
72    #[expect(clippy::expect_used, reason = "a checked-in file, held by a test")]
73    pub fn mainnet() -> Self {
74        Self::from_json(include_str!("mainnet.config.json"))
75            .expect("the bundled mainnet config parses")
76    }
77
78    /// Parses a config from the TON `global.config.json` format.
79    ///
80    /// Reads the liteserver list and the validator section's init block; the rest is
81    /// ignored. Each liteserver's `ip` is a signed 32-bit integer in that format, decoded
82    /// here to dotted-quad form, and a block's shard is a signed 64-bit integer decoded
83    /// to the prefix mask a block identity uses.
84    ///
85    /// A config with no init block parses. It leaves a client without a starting point
86    /// for a cold sync, which is a failure at [`crate::Client::sync`] rather than here,
87    /// because a caller supplying their own anchor never needs one.
88    ///
89    /// # Errors
90    ///
91    /// Returns [`Error::Config`] if the JSON is malformed, has no liteserver list, a
92    /// liteserver has an unsupported key type or a key that is not 32 bytes, or the init
93    /// block's hashes are not 32 base64 bytes.
94    pub fn from_json(json: &str) -> Result<Self, Error> {
95        let raw: RawConfig =
96            serde_json::from_str(json).map_err(|e| Error::Config(e.to_string()))?;
97        if raw.liteservers.is_empty() {
98            return Err(Error::Config("config has no liteservers".to_string()));
99        }
100
101        let mut liteservers = Vec::with_capacity(raw.liteservers.len());
102        for server in raw.liteservers {
103            if server.id.key_type != "pub.ed25519" {
104                return Err(Error::Config(format!(
105                    "unsupported liteserver key type `{}`",
106                    server.id.key_type
107                )));
108            }
109            let key: [u8; 32] = base64_decode(&server.id.key)
110                .and_then(|bytes| bytes.try_into().ok())
111                .ok_or_else(|| {
112                    Error::Config("liteserver key is not 32 base64 bytes".to_string())
113                })?;
114
115            #[allow(
116                clippy::cast_possible_truncation,
117                clippy::cast_sign_loss,
118                reason = "ip is a signed 32-bit integer that serde_json widens to i64; casting back to u32 takes its low 32 bits as the address octets, which is the intended bit-for-bit reinterpretation"
119            )]
120            let octets = (server.ip as u32).to_be_bytes();
121            let addr = format!(
122                "{}.{}.{}.{}:{}",
123                octets[0], octets[1], octets[2], octets[3], server.port
124            );
125            liteservers.push(LiteServer { addr, key });
126        }
127
128        let init_block = match raw.validator.and_then(|validator| validator.init_block) {
129            Some(block) => {
130                #[allow(
131                    clippy::cast_sign_loss,
132                    reason = "shard is TON's signed 64-bit prefix mask; BlockIdExt stores its bit pattern as u64, so the masterchain's top bit becomes 0x8000_0000_0000_0000 rather than a negative number"
133                )]
134                let shard = block.shard as u64;
135                Some(BlockIdExt::new(
136                    block.workchain,
137                    shard,
138                    block.seqno,
139                    hash(&block.root_hash, "init block root hash")?,
140                    hash(&block.file_hash, "init block file hash")?,
141                ))
142            }
143            None => None,
144        };
145
146        Ok(Self {
147            liteservers,
148            init_block,
149            max_head_age: DEFAULT_MAX_HEAD_AGE,
150        })
151    }
152
153    /// The block a client anchors its trust at before it has proved anything.
154    ///
155    /// This is the `validator.init_block` field of the TON config format, and it is the
156    /// only thing a verified read takes on trust from the chain's side of the world. A
157    /// caller who wants a different root of trust changes it here or hands their own
158    /// block to [`Client::connect_from`](crate::Client::connect_from).
159    ///
160    /// It is not the only trusted input. The other is the local clock, which is the one
161    /// thing separating a current block from a genuine old one replayed: see
162    /// [`max_head_age`](Self::max_head_age).
163    #[must_use]
164    pub fn init_block(&self) -> Option<&BlockIdExt> {
165        self.init_block.as_ref()
166    }
167
168    /// Sets how far behind the local clock a proven head may be, in seconds.
169    ///
170    /// A liteserver can serve a real block that is old, and nothing in a proof says when
171    /// it was served, so a block's own generation time against the local clock is the
172    /// only freshness signal there is. Setting this to zero refuses every head, which is
173    /// a way to say the check is not wanted only if the caller means it.
174    #[must_use]
175    pub fn with_max_head_age(mut self, seconds: u32) -> Self {
176        self.max_head_age = seconds;
177        self
178    }
179
180    /// How far behind the local clock a proven head may be, in seconds.
181    #[must_use]
182    pub fn max_head_age(&self) -> u32 {
183        self.max_head_age
184    }
185
186    /// The parsed liteservers, in config order.
187    pub(crate) fn liteservers(&self) -> &[LiteServer] {
188        &self.liteservers
189    }
190}
191
192/// Decodes a 32-byte hash from the base64 the config format writes it in.
193fn hash(encoded: &str, what: &'static str) -> Result<[u8; 32], Error> {
194    base64_decode(encoded)
195        .and_then(|bytes| bytes.try_into().ok())
196        .ok_or_else(|| Error::Config(format!("{what} is not 32 base64 bytes")))
197}
198
199#[derive(Deserialize)]
200struct RawConfig {
201    liteservers: Vec<RawLiteServer>,
202    validator: Option<RawValidator>,
203}
204
205#[derive(Deserialize)]
206struct RawValidator {
207    init_block: Option<RawBlockId>,
208}
209
210#[derive(Deserialize)]
211struct RawBlockId {
212    workchain: i32,
213    /// Written as a signed 64-bit integer, so the masterchain shard arrives negative.
214    shard: i64,
215    seqno: u32,
216    root_hash: String,
217    file_hash: String,
218}
219
220#[derive(Deserialize)]
221struct RawLiteServer {
222    ip: i64,
223    port: u16,
224    id: RawId,
225}
226
227#[derive(Deserialize)]
228struct RawId {
229    #[serde(rename = "@type")]
230    key_type: String,
231    key: String,
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237
238    fn hex(bytes: &[u8]) -> String {
239        use std::fmt::Write as _;
240
241        bytes.iter().fold(String::new(), |mut hex, b| {
242            let _ = write!(hex, "{b:02x}");
243            hex
244        })
245    }
246
247    const KEY: &str = "n4VDnSCUuSpjnCyUk9e3QOOd6o0ItSWYbTnW3Wnn8wk=";
248
249    #[test]
250    fn mainnet_parses_and_leads_with_the_proven_server() {
251        let config = Config::mainnet();
252        assert!(!config.liteservers().is_empty());
253        assert_eq!(config.liteservers()[0].addr, "5.9.10.47:19949");
254    }
255
256    #[test]
257    fn mainnet_names_the_block_a_first_sync_starts_from() {
258        // The one input a verified read rests on, so it is worth pinning here rather than
259        // trusting whatever the bundled file happens to say. These are the values the
260        // public mainnet config published on 2026-07-21.
261        let config = Config::mainnet();
262        let init = config
263            .init_block()
264            .expect("the snapshot names an init block");
265        assert_eq!(init.workchain, -1);
266        assert_eq!(init.shard, 0x8000_0000_0000_0000);
267        assert_eq!(init.seqno, 46_894_135);
268        assert_eq!(
269            hex(&init.root_hash),
270            "3048e69a12cf946ebc99b4cf9ca61c3ff4b3fcc88c4015763ac01204ecc1bf9f"
271        );
272        assert_eq!(
273            hex(&init.file_hash),
274            "bbdac0b4543e9141449ceb37c3c63ba6e9cc4e2c904d77f56d17e44acf1d1bed"
275        );
276    }
277
278    #[test]
279    fn the_freshness_bound_has_a_default_and_can_be_set() {
280        let config = Config::mainnet();
281        assert_eq!(config.max_head_age(), DEFAULT_MAX_HEAD_AGE);
282        assert_eq!(config.with_max_head_age(30).max_head_age(), 30);
283    }
284
285    #[test]
286    fn from_json_reads_an_init_block() {
287        // The shard arrives as a negative signed 64-bit integer in this format, which is
288        // the masterchain's prefix mask read as signed.
289        let json = format!(
290            r#"{{"liteservers":[{{"ip":84478511,"port":19949,"id":{{"@type":"pub.ed25519","key":"{KEY}"}}}}],
291                "validator":{{"init_block":{{"workchain":-1,"shard":-9223372036854775808,"seqno":7,
292                "root_hash":"{KEY}","file_hash":"{KEY}"}}}}}}"#
293        );
294        let config = Config::from_json(&json).unwrap();
295        let init = config.init_block().expect("an init block");
296        assert_eq!(init.workchain, -1);
297        assert_eq!(init.shard, 0x8000_0000_0000_0000);
298        assert_eq!(init.seqno, 7);
299    }
300
301    #[test]
302    fn from_json_accepts_a_config_with_no_init_block() {
303        // A caller who brings their own anchor never needs one, so this parses and the
304        // absence surfaces later, at the sync that would have needed it.
305        let json = format!(
306            r#"{{"liteservers":[{{"ip":84478511,"port":19949,"id":{{"@type":"pub.ed25519","key":"{KEY}"}}}}]}}"#
307        );
308        assert!(Config::from_json(&json).unwrap().init_block().is_none());
309    }
310
311    #[test]
312    fn from_json_rejects_an_init_block_hash_that_is_not_32_bytes() {
313        let json = format!(
314            r#"{{"liteservers":[{{"ip":84478511,"port":19949,"id":{{"@type":"pub.ed25519","key":"{KEY}"}}}}],
315                "validator":{{"init_block":{{"workchain":-1,"shard":-9223372036854775808,"seqno":7,
316                "root_hash":"AAAA","file_hash":"{KEY}"}}}}}}"#
317        );
318        assert!(matches!(Config::from_json(&json), Err(Error::Config(_))));
319    }
320
321    #[test]
322    fn from_json_reads_a_liteserver() {
323        let json = format!(
324            r#"{{"liteservers":[{{"ip":84478511,"port":19949,"id":{{"@type":"pub.ed25519","key":"{KEY}"}}}}]}}"#
325        );
326        let config = Config::from_json(&json).unwrap();
327        assert_eq!(config.liteservers().len(), 1);
328        assert_eq!(config.liteservers()[0].addr, "5.9.10.47:19949");
329        assert_eq!(
330            hex(&config.liteservers()[0].key),
331            "9f85439d2094b92a639c2c9493d7b740e39dea8d08b525986d39d6dd69e7f309"
332        );
333    }
334
335    #[test]
336    fn from_json_decodes_a_negative_ip() {
337        // 192.168.0.1 is a negative signed int32 in the TON config format.
338        let json = format!(
339            r#"{{"liteservers":[{{"ip":-1062731775,"port":1,"id":{{"@type":"pub.ed25519","key":"{KEY}"}}}}]}}"#
340        );
341        let config = Config::from_json(&json).unwrap();
342        assert_eq!(config.liteservers()[0].addr, "192.168.0.1:1");
343    }
344
345    #[test]
346    fn from_json_ignores_the_other_config_sections() {
347        // The real global.config.json carries dht, validator, and per-server fields this
348        // release does not read. Parsing must ignore them, not fail on them.
349        let json = format!(
350            r#"{{"@type":"config.global","dht":{{"k":1}},"liteservers":[{{"ip":84478511,"port":19949,"extra":true,"id":{{"@type":"pub.ed25519","key":"{KEY}"}}}}],"validator":{{"zero_state":{{"workchain":-1}}}}}}"#
351        );
352        let config = Config::from_json(&json).unwrap();
353        assert_eq!(config.liteservers().len(), 1);
354        assert_eq!(config.liteservers()[0].addr, "5.9.10.47:19949");
355    }
356
357    #[test]
358    fn from_json_rejects_an_unsupported_key_type() {
359        let json = format!(
360            r#"{{"liteservers":[{{"ip":84478511,"port":19949,"id":{{"@type":"pub.unknown","key":"{KEY}"}}}}]}}"#
361        );
362        assert!(matches!(Config::from_json(&json), Err(Error::Config(_))));
363    }
364
365    #[test]
366    fn from_json_rejects_malformed_json() {
367        assert!(matches!(
368            Config::from_json("{not json"),
369            Err(Error::Config(_))
370        ));
371    }
372
373    #[test]
374    fn from_json_rejects_an_empty_liteserver_list() {
375        assert!(matches!(
376            Config::from_json(r#"{"liteservers":[]}"#),
377            Err(Error::Config(_))
378        ));
379    }
380}