Skip to main content

ferogram_mtproto/
message.rs

1// Copyright (c) Ankit Chaubey <ankitchaubey.dev@gmail.com>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3//
4// ferogram: async Telegram MTProto client in Rust
5// https://github.com/ankit-chaubey/ferogram
6//
7// If you use or modify this code, keep this notice at the top of your file
8// and include the LICENSE-MIT or LICENSE-APACHE file from this repository:
9// https://github.com/ankit-chaubey/ferogram
10
11use std::sync::atomic::{AtomicU32, Ordering};
12use std::time::{SystemTime, UNIX_EPOCH};
13
14/// Process-wide monotonically increasing counter for plaintext message IDs.
15///
16/// A global atomic ensures msg_id monotonicity across concurrent sessions.
17static GLOBAL_MSG_COUNTER: AtomicU32 = AtomicU32::new(1);
18
19/// A 64-bit MTProto message identifier.
20///
21/// Per the spec: the lower 32 bits are derived from the current Unix time;
22/// the upper 32 bits are a monotonically increasing counter within the second.
23/// The least significant two bits must be zero for client messages.
24#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
25pub struct MessageId(pub u64);
26
27impl MessageId {
28    /// Generate a new message ID using the system clock and a global counter.
29    ///
30    /// MTProto msg_id layout:
31    ///   bits 63–32: Unix timestamp in seconds (upper 32 bits)
32    ///   bits 31–2:  intra-second sequencing counter (lower 30 bits, × 4)
33    ///   bits 1–0:   must be 0b00 for client messages
34    ///
35    pub(crate) fn generate(_counter: u32) -> Self {
36        let unix_secs = SystemTime::now()
37            .duration_since(UNIX_EPOCH)
38            .unwrap_or_default()
39            .as_secs();
40        // Global atomic: wrapping_add ensures monotonicity across concurrent sessions.
41        let counter = GLOBAL_MSG_COUNTER.fetch_add(1, Ordering::Relaxed);
42        // upper 32 bits = seconds, lower 30 bits = counter × 4 (bits 1-0 = 0b00)
43        let id = (unix_secs << 32) | (u64::from(counter) << 2);
44        Self(id)
45    }
46}
47
48/// A framed MTProto message ready to be sent.
49#[derive(Debug)]
50pub struct Message {
51    /// Unique identifier for this message.
52    pub id: MessageId,
53    /// Session-scoped sequence number (even for content-unrelated, odd for content-related).
54    pub seq_no: i32,
55    /// The serialized TL body (constructor ID + fields).
56    pub body: Vec<u8>,
57}
58
59impl Message {
60    /// Construct a new plaintext message (used before key exchange).
61    pub fn plaintext(id: MessageId, seq_no: i32, body: Vec<u8>) -> Self {
62        Self { id, seq_no, body }
63    }
64
65    /// Serialize the message into the plaintext wire format:
66    ///
67    /// ```text
68    /// auth_key_id:long  (0 for plaintext)
69    /// message_id:long
70    /// message_data_length:int
71    /// message_data:bytes
72    /// ```
73    pub fn to_plaintext_bytes(&self) -> Vec<u8> {
74        let mut buf = Vec::with_capacity(8 + 8 + 4 + self.body.len());
75        buf.extend(0i64.to_le_bytes()); // auth_key_id = 0
76        buf.extend(self.id.0.to_le_bytes()); // message_id
77        buf.extend((self.body.len() as u32).to_le_bytes()); // length
78        buf.extend(&self.body);
79        buf
80    }
81}