1use std::{fmt, ops::Deref, str::FromStr};
2
3use base64::{Engine as _, engine::general_purpose};
4use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
5use thiserror::Error;
6
7pub(crate) fn deserialize_optional_non_null<'de, D, T>(
9 deserializer: D,
10) -> Result<Option<T>, D::Error>
11where
12 D: Deserializer<'de>,
13 T: Deserialize<'de>,
14{
15 T::deserialize(deserializer).map(Some)
16}
17
18#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
20pub struct EmptyObject;
21
22impl Serialize for EmptyObject {
23 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
24 where
25 S: Serializer,
26 {
27 use serde::ser::SerializeMap as _;
28
29 serializer.serialize_map(Some(0))?.end()
30 }
31}
32
33impl<'de> Deserialize<'de> for EmptyObject {
34 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
35 where
36 D: Deserializer<'de>,
37 {
38 let fields =
39 std::collections::BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
40 if fields.is_empty() {
41 Ok(Self)
42 } else {
43 Err(de::Error::custom("object must not contain properties"))
44 }
45 }
46}
47
48#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
50pub enum ValueError {
51 #[error("client id must be exactly 64 lowercase hexadecimal characters")]
53 InvalidClientId,
54 #[error("network id must be a stringified integer")]
56 InvalidNetworkId,
57 #[error("decimal string must contain one or more ASCII digits")]
59 InvalidDecimalString,
60 #[error("value must be a canonical decimal string in the unsigned 64-bit range")]
62 InvalidUint64String,
63 #[error("value must be valid standard or URL-safe base64")]
65 InvalidBase64,
66 #[error("trace id must use the canonical UUID text shape")]
68 InvalidTraceId,
69 #[error("URL must be an absolute HTTPS URL with a host")]
71 InvalidHttpsUrl,
72 #[error("array must contain at least one element")]
74 EmptyArray,
75}
76
77#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
79pub struct ClientId([u8; 32]);
80
81impl ClientId {
82 #[must_use]
84 pub const fn from_bytes(bytes: [u8; 32]) -> Self {
85 Self(bytes)
86 }
87
88 #[must_use]
90 pub const fn to_bytes(self) -> [u8; 32] {
91 self.0
92 }
93}
94
95impl fmt::Debug for ClientId {
96 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
97 fmt::Display::fmt(self, formatter)
98 }
99}
100
101impl fmt::Display for ClientId {
102 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
103 formatter.write_str(&hex::encode(self.0))
104 }
105}
106
107impl FromStr for ClientId {
108 type Err = ValueError;
109
110 fn from_str(value: &str) -> Result<Self, Self::Err> {
111 if value.len() != 64
112 || !value
113 .as_bytes()
114 .iter()
115 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(byte))
116 {
117 return Err(ValueError::InvalidClientId);
118 }
119
120 let mut bytes = [0_u8; 32];
121 hex::decode_to_slice(value, &mut bytes).map_err(|_| ValueError::InvalidClientId)?;
122 Ok(Self(bytes))
123 }
124}
125
126impl Serialize for ClientId {
127 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
128 where
129 S: Serializer,
130 {
131 serializer.serialize_str(&self.to_string())
132 }
133}
134
135impl<'de> Deserialize<'de> for ClientId {
136 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
137 where
138 D: Deserializer<'de>,
139 {
140 let value = String::deserialize(deserializer)?;
141 Self::from_str(&value).map_err(de::Error::custom)
142 }
143}
144
145macro_rules! validated_string {
146 ($name:ident, $validator:ident, $error:expr, $docs:literal) => {
147 #[doc = $docs]
148 #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
149 pub struct $name(String);
150
151 impl $name {
152 #[must_use]
154 pub fn as_str(&self) -> &str {
155 &self.0
156 }
157
158 #[must_use]
160 pub fn into_string(self) -> String {
161 self.0
162 }
163 }
164
165 impl TryFrom<String> for $name {
166 type Error = ValueError;
167
168 fn try_from(value: String) -> Result<Self, Self::Error> {
169 if $validator(&value) {
170 Ok(Self(value))
171 } else {
172 Err($error)
173 }
174 }
175 }
176
177 impl TryFrom<&str> for $name {
178 type Error = ValueError;
179
180 fn try_from(value: &str) -> Result<Self, Self::Error> {
181 Self::try_from(value.to_owned())
182 }
183 }
184
185 impl fmt::Display for $name {
186 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
187 formatter.write_str(self.as_str())
188 }
189 }
190
191 impl AsRef<str> for $name {
192 fn as_ref(&self) -> &str {
193 self.as_str()
194 }
195 }
196
197 impl Deref for $name {
198 type Target = str;
199
200 fn deref(&self) -> &Self::Target {
201 self.as_str()
202 }
203 }
204
205 impl Serialize for $name {
206 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
207 where
208 S: Serializer,
209 {
210 serializer.serialize_str(self.as_str())
211 }
212 }
213
214 impl<'de> Deserialize<'de> for $name {
215 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
216 where
217 D: Deserializer<'de>,
218 {
219 let value = String::deserialize(deserializer)?;
220 Self::try_from(value).map_err(de::Error::custom)
221 }
222 }
223 };
224}
225
226fn valid_network_id(value: &str) -> bool {
227 let digits = value.strip_prefix('-').unwrap_or(value);
228 !digits.is_empty() && digits.as_bytes().iter().all(u8::is_ascii_digit)
229}
230
231fn valid_decimal(value: &str) -> bool {
232 !value.is_empty() && value.as_bytes().iter().all(u8::is_ascii_digit)
233}
234
235fn decode_base64(value: &str) -> Result<Vec<u8>, ValueError> {
236 let has_standard = value.bytes().any(|byte| matches!(byte, b'+' | b'/'));
237 let has_url_safe = value.bytes().any(|byte| matches!(byte, b'-' | b'_'));
238 if has_standard && has_url_safe {
239 return Err(ValueError::InvalidBase64);
240 }
241
242 let padded = value.ends_with('=');
243 let decoded = match (has_url_safe, padded) {
244 (true, true) => general_purpose::URL_SAFE.decode(value),
245 (true, false) => general_purpose::URL_SAFE_NO_PAD.decode(value),
246 (false, true) => general_purpose::STANDARD.decode(value),
247 (false, false) => general_purpose::STANDARD_NO_PAD.decode(value),
248 };
249 decoded.map_err(|_| ValueError::InvalidBase64)
250}
251
252fn valid_base64(value: &str) -> bool {
253 decode_base64(value).is_ok()
254}
255
256fn valid_trace_id(value: &str) -> bool {
257 let mut parts = value.split('-');
258 let lengths = [8_usize, 4, 4, 4, 12];
259 for expected in lengths {
260 let Some(part) = parts.next() else {
261 return false;
262 };
263 if part.len() != expected || !part.as_bytes().iter().all(u8::is_ascii_hexdigit) {
264 return false;
265 }
266 }
267 parts.next().is_none()
268}
269
270fn valid_https_url(value: &str) -> bool {
271 url::Url::parse(value).is_ok_and(|url| url.scheme() == "https" && url.has_host())
272}
273
274validated_string!(
275 NetworkId,
276 valid_network_id,
277 ValueError::InvalidNetworkId,
278 "A TON network `global_id` encoded as the opaque stringified-integer wire value."
279);
280
281#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
283pub struct Uint64String(u64);
284
285impl Uint64String {
286 #[must_use]
288 pub const fn get(self) -> u64 {
289 self.0
290 }
291}
292
293impl From<u64> for Uint64String {
294 fn from(value: u64) -> Self {
295 Self(value)
296 }
297}
298
299impl TryFrom<&str> for Uint64String {
300 type Error = ValueError;
301
302 fn try_from(value: &str) -> Result<Self, Self::Error> {
303 let parsed = value
304 .parse::<u64>()
305 .map_err(|_| ValueError::InvalidUint64String)?;
306 if parsed.to_string() != value {
307 return Err(ValueError::InvalidUint64String);
308 }
309 Ok(Self(parsed))
310 }
311}
312
313impl fmt::Display for Uint64String {
314 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
315 write!(formatter, "{}", self.0)
316 }
317}
318
319impl Serialize for Uint64String {
320 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
321 where
322 S: Serializer,
323 {
324 serializer.serialize_str(&self.to_string())
325 }
326}
327
328impl<'de> Deserialize<'de> for Uint64String {
329 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
330 where
331 D: Deserializer<'de>,
332 {
333 let value = String::deserialize(deserializer)?;
334 Self::try_from(value.as_str()).map_err(de::Error::custom)
335 }
336}
337validated_string!(
338 DecimalString,
339 valid_decimal,
340 ValueError::InvalidDecimalString,
341 "A non-negative integer in the decimal-string wire representation."
342);
343validated_string!(
344 Base64Value,
345 valid_base64,
346 ValueError::InvalidBase64,
347 "A validated standard or URL-safe base64 wire value."
348);
349validated_string!(
350 TraceId,
351 valid_trace_id,
352 ValueError::InvalidTraceId,
353 "A UUID-shaped trace identifier accepted by the TON Connect bridge schema."
354);
355validated_string!(
356 HttpsUrl,
357 valid_https_url,
358 ValueError::InvalidHttpsUrl,
359 "An absolute HTTPS URL with a host."
360);
361
362impl HttpsUrl {
363 pub fn parsed(&self) -> Result<url::Url, ValueError> {
365 url::Url::parse(self.as_str()).map_err(|_| ValueError::InvalidHttpsUrl)
366 }
367}
368
369impl Base64Value {
370 pub fn decode(&self) -> Result<Vec<u8>, ValueError> {
372 decode_base64(self.as_str())
373 }
374}
375
376#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
378#[serde(transparent)]
379pub struct NonEmptyVec<T>(Vec<T>);
380
381impl<T> NonEmptyVec<T> {
382 #[must_use]
384 pub fn as_slice(&self) -> &[T] {
385 &self.0
386 }
387
388 #[must_use]
390 pub fn into_vec(self) -> Vec<T> {
391 self.0
392 }
393
394 #[must_use]
396 pub fn map<U, F>(self, map: F) -> NonEmptyVec<U>
397 where
398 F: FnMut(T) -> U,
399 {
400 NonEmptyVec(self.0.into_iter().map(map).collect())
401 }
402
403 #[must_use]
405 pub fn map_ref<'a, U, F>(&'a self, map: F) -> NonEmptyVec<U>
406 where
407 F: FnMut(&'a T) -> U,
408 {
409 NonEmptyVec(self.0.iter().map(map).collect())
410 }
411}
412
413impl<T> TryFrom<Vec<T>> for NonEmptyVec<T> {
414 type Error = ValueError;
415
416 fn try_from(values: Vec<T>) -> Result<Self, Self::Error> {
417 if values.is_empty() {
418 Err(ValueError::EmptyArray)
419 } else {
420 Ok(Self(values))
421 }
422 }
423}
424
425impl<'de, T> Deserialize<'de> for NonEmptyVec<T>
426where
427 T: Deserialize<'de>,
428{
429 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
430 where
431 D: Deserializer<'de>,
432 {
433 let values = Vec::<T>::deserialize(deserializer)?;
434 Self::try_from(values).map_err(de::Error::custom)
435 }
436}
437
438#[cfg(test)]
439mod tests {
440 use proptest::prelude::*;
441
442 use super::*;
443
444 #[test]
445 fn empty_object_rejects_every_property() {
446 assert!(serde_json::to_string(&EmptyObject).is_ok_and(|value| value == "{}"));
447 assert!(serde_json::from_str::<EmptyObject>("{}").is_ok());
448 assert!(serde_json::from_str::<EmptyObject>(r#"{"future":true}"#).is_err());
449 }
450
451 #[test]
452 fn client_id_requires_canonical_lowercase_hex() {
453 let canonical = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
454 let client = ClientId::from_str(canonical).expect("canonical client id");
455 assert_eq!(format!("{client:?}"), canonical);
456 assert!(ClientId::from_str(&canonical.to_uppercase()).is_err());
457 assert!(ClientId::from_str("00").is_err());
458 }
459
460 #[test]
461 fn validated_string_views_and_non_empty_conversion_are_lossless() -> Result<(), ValueError> {
462 let url = HttpsUrl::try_from("https://app.example/path")?;
463 assert_eq!(url.to_string(), "https://app.example/path");
464 assert_eq!(url.as_ref(), "https://app.example/path");
465 assert_eq!(&*url, "https://app.example/path");
466 assert_eq!(url.clone().into_string(), "https://app.example/path");
467 assert_eq!(url.parsed()?.host_str(), Some("app.example"));
468
469 let values = NonEmptyVec::try_from(vec![1_u8, 2, 3])?;
470 assert_eq!(values.into_vec(), vec![1, 2, 3]);
471 Ok(())
472 }
473
474 #[test]
475 fn network_id_preserves_every_schema_valid_global_id_verbatim() {
476 for original in ["-239", "-0", "00", "2147483648", "999999999999999999999"] {
477 assert_eq!(
478 NetworkId::try_from(original).map(NetworkId::into_string),
479 Ok(original.to_owned())
480 );
481 }
482 assert!(NetworkId::try_from("+3").is_err());
483 assert!(NetworkId::try_from("-").is_err());
484 assert!(NetworkId::try_from("").is_err());
485 assert!(NetworkId::try_from("12x").is_err());
486 }
487
488 #[test]
489 fn base64_accepts_both_protocol_alphabets() {
490 assert!(Base64Value::try_from("+/8=").is_ok());
491 assert!(Base64Value::try_from("-_8").is_ok());
492 assert!(Base64Value::try_from("+/8_").is_err());
493 assert!(Base64Value::try_from("a==").is_err());
494 }
495
496 #[test]
499 fn decodes_all_applicable_typescript_base64_vectors() -> Result<(), ValueError> {
500 let text = "test=string example: { a: \"_b&%\" }";
501 let encoded = Base64Value::try_from("dGVzdD1zdHJpbmcgZXhhbXBsZTogeyBhOiAiX2ImJSIgfQ==")?;
502 assert_eq!(encoded.decode()?, text.as_bytes());
503
504 let object =
505 Base64Value::try_from("eyJhIjoiMTIzJiQlLT0iLCJiIjpbMSwyXSwiYyI6eyJ4IjpudWxsfX0=")?;
506 assert_eq!(
507 object.decode()?,
508 br#"{"a":"123&$%-=","b":[1,2],"c":{"x":null}}"#
509 );
510
511 let bytes = [
512 186, 172, 126, 137, 246, 202, 196, 52, 232, 0, 13, 167, 173, 31, 102, 124, 154, 83,
513 137, 111, 255, 109, 138, 217, 10, 134, 120, 9, 141, 24, 133, 33,
514 ];
515 let encoded = general_purpose::STANDARD.encode(bytes);
516 assert_eq!(Base64Value::try_from(encoded)?.decode()?, bytes);
517
518 for normalized_by_sdk in ["te6ccAA-", "AQ", "AQI", "AQID"] {
519 assert!(
520 Base64Value::try_from(normalized_by_sdk).is_ok(),
521 "rejected {normalized_by_sdk}"
522 );
523 }
524 assert!(Base64Value::try_from("te6cc-_").is_err());
527 Ok(())
528 }
529
530 #[test]
531 fn non_empty_vec_rejects_empty_json_array() {
532 let result = serde_json::from_str::<NonEmptyVec<String>>("[]");
533 assert!(result.is_err());
534 }
535
536 proptest! {
537 #[test]
538 fn every_client_id_has_a_canonical_json_round_trip(bytes in any::<[u8; 32]>()) {
539 let original = ClientId::from_bytes(bytes);
540 let encoded = serde_json::to_string(&original);
541 let decoded = encoded.and_then(|json| serde_json::from_str::<ClientId>(&json));
542 prop_assert_eq!(decoded.ok(), Some(original));
543 }
544
545 #[test]
546 fn every_non_empty_ascii_digit_sequence_is_a_decimal_string(
547 digits in proptest::collection::vec(b'0'..=b'9', 1..512)
548 ) {
549 let text = digits.into_iter().map(char::from).collect::<String>();
550 let value = DecimalString::try_from(text.clone());
551 prop_assert_eq!(value.map(DecimalString::into_string), Ok(text));
552 }
553 }
554}