1use serde::Deserialize;
7
8use crate::codec::base64_decode;
9use crate::{BlockIdExt, Error};
10
11const DEFAULT_MAX_HEAD_AGE: u32 = 600;
19
20#[derive(Debug, Clone)]
26pub struct Config {
27 liteservers: Vec<LiteServer>,
28 init_block: Option<BlockIdExt>,
29 max_head_age: u32,
30}
31
32#[derive(Debug, Clone)]
34pub struct LiteServer {
35 pub(crate) addr: String,
36 pub(crate) key: [u8; 32],
37}
38
39impl Config {
40 #[must_use]
69 #[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 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 #[must_use]
164 pub fn init_block(&self) -> Option<&BlockIdExt> {
165 self.init_block.as_ref()
166 }
167
168 #[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 #[must_use]
182 pub fn max_head_age(&self) -> u32 {
183 self.max_head_age
184 }
185
186 pub(crate) fn liteservers(&self) -> &[LiteServer] {
188 &self.liteservers
189 }
190}
191
192fn 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 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 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 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 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 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 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}