Skip to main content

ferogram_e2e/
tl.rs

1/*
2 * Copyright (c) 2026 Ankit Chaubey <ankitchaubey.dev@gmail.com>
3 * https://github.com/ankit-chaubey
4 *
5 * Project: ferogram
6 * Website: https://ferogram.dev
7 *
8 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
9 * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
10 * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
11 * This file may not be copied, modified, or distributed except according
12 * to those terms.
13 */
14
15//! Inner TL layer of Telegram secret chats.
16//!
17//! These types live inside the encrypted `data` field of `messages.sendEncrypted`.
18//! They are not part of the outer MTProto TL schema, so they are serialized and
19//! parsed by hand here rather than by `ferogram-tl-types`.
20
21use rand::Rng;
22
23use crate::error::E2eError;
24
25// Constructor IDs from the secret chat TL schema (https://core.telegram.org/schema/end-to-end).
26
27/// Constructor ID of `decryptedMessage` (layer 73 and above).
28pub const ID_DECRYPTED_MESSAGE: u32 = 0x91cc4674;
29
30/// Constructor ID of `decryptedMessage` before layer 73.
31pub const ID_DECRYPTED_MESSAGE_OLD: u32 = 0x36b091de;
32
33/// Constructor ID of `decryptedMessageService` (layer 17 and above).
34pub const ID_DECRYPTED_MESSAGE_SERVICE: u32 = 0x73164160;
35
36/// Constructor ID of `decryptedMessageService` (layer 8).
37pub const ID_DECRYPTED_MESSAGE_SERVICE8: u32 = 0xaa48327d;
38
39/// Constructor ID of `decryptedMessageLayer`, the wrapper around every message from layer 17 on.
40pub const ID_DECRYPTED_MESSAGE_LAYER: u32 = 0x1be31789;
41
42/// Constructor ID of `decryptedMessageActionNotifyLayer`.
43pub const ID_ACTION_NOTIFY_LAYER: u32 = 0xf3048883;
44
45/// Constructor ID of `decryptedMessageActionRequestKey`.
46pub const ID_ACTION_REQUEST_KEY: u32 = 0xf3c9611b;
47
48/// Constructor ID of `decryptedMessageActionAcceptKey`.
49pub const ID_ACTION_ACCEPT_KEY: u32 = 0x6fe1735b;
50
51/// Constructor ID of `decryptedMessageActionAbortKey`.
52pub const ID_ACTION_ABORT_KEY: u32 = 0xdd05ec6b;
53
54/// Constructor ID of `decryptedMessageActionCommitKey`.
55pub const ID_ACTION_COMMIT_KEY: u32 = 0xec2e0b9b;
56
57/// Constructor ID of `decryptedMessageActionNoop`.
58pub const ID_ACTION_NOOP: u32 = 0xa82fdd63;
59
60/// Constructor ID of `decryptedMessageActionSetMessageTTL`.
61pub const ID_ACTION_SET_TTL: u32 = 0xa1733aec;
62
63/// Constructor ID of `decryptedMessageActionResend`.
64pub const ID_ACTION_RESEND: u32 = 0x511110b0;
65
66/// Constructor ID of `decryptedMessageActionReadMessages` (parsed only).
67pub const ID_ACTION_READ_MESSAGES: u32 = 0x0c4f40be;
68
69/// Constructor ID of `decryptedMessageActionDeleteMessages` (parsed only).
70pub const ID_ACTION_DELETE_MESSAGES: u32 = 0x65614304;
71
72/// Constructor ID of `decryptedMessageActionScreenshotMessages` (parsed only).
73pub const ID_ACTION_SCREENSHOT_MESSAGES: u32 = 0x8ac1f475;
74
75/// Constructor ID of `decryptedMessageActionFlushHistory` (parsed only).
76pub const ID_ACTION_FLUSH_HISTORY: u32 = 0x6719e45c;
77
78/// Constructor ID of `decryptedMessageActionTyping` (parsed only).
79pub const ID_ACTION_TYPING: u32 = 0xccb27641;
80
81/// Constructor ID of `decryptedMessageMediaEmpty`.
82pub const ID_MEDIA_EMPTY: u32 = 0x089f5c4a;
83
84/// Constructor ID of `decryptedMessageMediaVenue` (layer 45).
85pub const ID_MEDIA_VENUE: u32 = 0x8a0df56f;
86
87/// Constructor ID of `decryptedMessageMediaPhoto` (layer 45 and above).
88pub const ID_MEDIA_PHOTO: u32 = 0xf1fa8d78;
89
90/// Constructor ID of `decryptedMessageMediaPhoto` (layer 8).
91pub const ID_MEDIA_PHOTO_OLD: u32 = 0x32798a8c;
92
93/// Constructor ID of `decryptedMessageMediaDocument` (layer 143 and above).
94pub const ID_MEDIA_DOCUMENT: u32 = 0x6abd9782;
95
96/// Constructor ID of `decryptedMessageMediaDocument` (layer 8).
97pub const ID_MEDIA_DOCUMENT_OLD: u32 = 0xb095434b;
98
99/// Constructor ID of `decryptedMessageMediaGeoPoint`.
100pub const ID_MEDIA_GEO: u32 = 0x35480a59;
101
102/// Constructor ID of `decryptedMessageMediaContact`.
103pub const ID_MEDIA_CONTACT: u32 = 0x588a0a97;
104
105/// Constructor ID of `decryptedMessageMediaAudio` (layer 8).
106pub const ID_MEDIA_AUDIO_L8: u32 = 0x6080758f;
107
108/// Constructor ID of `decryptedMessageMediaAudio` (layer 17).
109pub const ID_MEDIA_AUDIO_L17: u32 = 0x57e0a9cb;
110
111/// Constructor ID of `decryptedMessageMediaVideo` (layer 8).
112pub const ID_MEDIA_VIDEO_L8: u32 = 0x4cee6ef3;
113
114/// Constructor ID of `decryptedMessageMediaVideo` (layer 17).
115pub const ID_MEDIA_VIDEO_L17: u32 = 0x524a415d;
116
117/// Constructor ID of `decryptedMessageMediaVideo` (layer 45).
118pub const ID_MEDIA_VIDEO_L45: u32 = 0x970c8c0e;
119
120/// Constructor ID of `documentAttributeImageSize`.
121pub const ID_ATTR_IMAGE_SIZE: u32 = 0x6c37c15c;
122
123/// Constructor ID of `documentAttributeAnimated`.
124pub const ID_ATTR_ANIMATED: u32 = 0x11b58939;
125
126/// Constructor ID of `documentAttributeSticker` as used in secret chats (layer 17 and above).
127pub const ID_ATTR_STICKER: u32 = 0x3a556302;
128
129/// Constructor ID of `documentAttributeVideo`.
130pub const ID_ATTR_VIDEO: u32 = 0x0ef02ce6;
131
132/// Constructor ID of `documentAttributeAudio`.
133pub const ID_ATTR_AUDIO: u32 = 0x9852f9c6;
134
135/// Constructor ID of `documentAttributeFilename`.
136pub const ID_ATTR_FILENAME: u32 = 0x15590068;
137
138/// TL `vector` constructor ID.
139const TL_VECTOR: u32 = 0x1cb5c415;
140
141/// A service action carried inside a `decryptedMessageService`.
142#[derive(Debug, Clone)]
143pub enum DecryptedAction {
144    /// Announces the sender's supported layer.
145    NotifyLayer {
146        /// Highest layer the sender supports.
147        layer: i32,
148    },
149    /// Starts a key re-exchange.
150    RequestKey {
151        /// Identifier of this exchange.
152        exchange_id: i64,
153        /// Sender's DH public value `g_a`.
154        g_a: Vec<u8>,
155    },
156    /// Accepts a key re-exchange.
157    AcceptKey {
158        /// Identifier of this exchange.
159        exchange_id: i64,
160        /// Sender's DH public value `g_b`.
161        g_b: Vec<u8>,
162        /// Fingerprint of the key that results from the exchange.
163        key_fingerprint: i64,
164    },
165    /// Aborts a key re-exchange.
166    AbortKey {
167        /// Identifier of the aborted exchange.
168        exchange_id: i64,
169    },
170    /// Commits to the new key after a successful re-exchange.
171    CommitKey {
172        /// Identifier of this exchange.
173        exchange_id: i64,
174        /// Fingerprint of the new key.
175        key_fingerprint: i64,
176    },
177    /// Does nothing; used to acknowledge sequence numbers.
178    Noop,
179    /// Sets the self-destruct timer for following messages.
180    SetTtl {
181        /// New TTL in seconds (0 disables it).
182        ttl_seconds: i32,
183    },
184    /// Asks the peer to resend messages in a sequence-number range.
185    Resend {
186        /// First raw sequence number to resend.
187        start_seq_no: i32,
188        /// Last raw sequence number to resend.
189        end_seq_no: i32,
190    },
191    /// The peer read these messages. Parsed only, never sent.
192    ReadMessages {
193        /// `random_id`s of the messages that were read.
194        random_ids: Vec<i64>,
195    },
196    /// The peer deleted these messages. Parsed only, never sent.
197    DeleteMessages {
198        /// `random_id`s of the deleted messages.
199        random_ids: Vec<i64>,
200    },
201    /// The peer took a screenshot of these messages. Parsed only, never sent.
202    ScreenshotMessages {
203        /// `random_id`s of the captured messages.
204        random_ids: Vec<i64>,
205    },
206    /// The peer cleared the chat history. Parsed only, never sent.
207    FlushHistory,
208    /// The peer is typing or doing another chat action. Parsed only, never sent.
209    Typing {
210        /// Constructor ID of the `SendMessageAction` the peer reported.
211        action_ctor: u32,
212    },
213    /// An action this crate does not know.
214    Unknown {
215        /// Its constructor ID.
216        ctor: u32,
217    },
218}
219
220/// Document attributes carried inside `DecryptedMedia::Document`.
221#[derive(Debug, Clone)]
222pub enum DocumentAttribute {
223    /// Image dimensions in pixels.
224    ImageSize {
225        /// Width.
226        w: i32,
227        /// Height.
228        h: i32,
229    },
230    /// The document is an animation (GIF).
231    Animated,
232    /// The document is a sticker.
233    Sticker {
234        /// Emoji the sticker represents.
235        alt: String,
236    },
237    /// Video metadata.
238    Video {
239        /// Duration in seconds.
240        duration: i32,
241        /// Width in pixels.
242        w: i32,
243        /// Height in pixels.
244        h: i32,
245    },
246    /// Audio metadata.
247    Audio {
248        /// Duration in seconds.
249        duration: i32,
250        /// Track title, if present.
251        title: Option<String>,
252        /// Performer, if present.
253        performer: Option<String>,
254    },
255    /// Original file name.
256    FileName {
257        /// The file name.
258        file_name: String,
259    },
260    /// An attribute this crate does not know.
261    Unknown {
262        /// Its constructor ID.
263        ctor: u32,
264    },
265}
266
267/// Media payload of a decrypted message.
268///
269/// For `Photo` and `Document`, `key` and `iv` are the one-time AES-256-IGE key and
270/// IV (32 bytes each, fully used by IGE) of the separately uploaded encrypted file.
271#[derive(Debug, Clone)]
272pub enum DecryptedMedia {
273    /// No media.
274    Empty,
275    /// A photo.
276    Photo {
277        /// JPEG thumbnail bytes.
278        thumb: Vec<u8>,
279        /// Thumbnail width.
280        thumb_w: i32,
281        /// Thumbnail height.
282        thumb_h: i32,
283        /// Photo width in pixels.
284        w: i32,
285        /// Photo height in pixels.
286        h: i32,
287        /// Size of the plaintext file in bytes.
288        size: i32,
289        /// File encryption key (32 bytes).
290        key: Vec<u8>,
291        /// File encryption IV (32 bytes).
292        iv: Vec<u8>,
293        /// Caption.
294        caption: String,
295    },
296    /// A generic document.
297    Document {
298        /// Thumbnail bytes.
299        thumb: Vec<u8>,
300        /// Thumbnail width.
301        thumb_w: i32,
302        /// Thumbnail height.
303        thumb_h: i32,
304        /// MIME type.
305        mime_type: String,
306        /// Size of the plaintext file in bytes.
307        size: i64,
308        /// File encryption key (32 bytes).
309        key: Vec<u8>,
310        /// File encryption IV (32 bytes).
311        iv: Vec<u8>,
312        /// Document attributes.
313        attributes: Vec<DocumentAttribute>,
314        /// Caption.
315        caption: String,
316    },
317    /// A location.
318    GeoPoint {
319        /// Latitude.
320        lat: f64,
321        /// Longitude.
322        long: f64,
323    },
324    /// A shared contact.
325    Contact {
326        /// Phone number.
327        phone_number: String,
328        /// First name.
329        first_name: String,
330        /// Last name.
331        last_name: String,
332        /// Telegram user id of the contact.
333        user_id: i32,
334    },
335    /// A media type this crate does not know.
336    Unknown {
337        /// Its constructor ID.
338        ctor: u32,
339    },
340}
341
342/// A decrypted message as carried inside [`DecryptedMessageLayer`].
343#[derive(Debug, Clone)]
344pub enum DecryptedMessage {
345    /// A text message, optionally with media.
346    Text {
347        /// Client-generated unique id.
348        random_id: i64,
349        /// Self-destruct timer in seconds (0 = none).
350        ttl: i32,
351        /// Message text.
352        message: String,
353        /// Attached media.
354        media: DecryptedMedia,
355    },
356    /// A service message carrying an action.
357    Service {
358        /// Client-generated unique id.
359        random_id: i64,
360        /// The action.
361        action: DecryptedAction,
362    },
363    /// An unrecognized constructor. The raw bytes are kept for logging and are
364    /// not forwarded to the caller.
365    Unknown {
366        /// Its constructor ID.
367        ctor: u32,
368        /// The undecoded bytes.
369        raw: Vec<u8>,
370    },
371}
372
373/// The outer wrapper of every secret chat message (layer 17 and above).
374#[derive(Debug, Clone)]
375pub struct DecryptedMessageLayer {
376    /// Random filler (15, 19 or 23 bytes) that varies the payload length.
377    pub random_bytes: Vec<u8>,
378    /// Layer the sender uses.
379    pub layer: i32,
380    /// Number of messages the sender has received, as a wire sequence number.
381    pub in_seq_no: i32,
382    /// Number of messages the sender has sent, as a wire sequence number.
383    pub out_seq_no: i32,
384    /// The wrapped message.
385    pub message: DecryptedMessage,
386}
387
388fn write_u32(buf: &mut Vec<u8>, v: u32) {
389    buf.extend_from_slice(&v.to_le_bytes());
390}
391fn write_i32(buf: &mut Vec<u8>, v: i32) {
392    buf.extend_from_slice(&v.to_le_bytes());
393}
394fn write_i64(buf: &mut Vec<u8>, v: i64) {
395    buf.extend_from_slice(&v.to_le_bytes());
396}
397
398fn write_bytes(buf: &mut Vec<u8>, data: &[u8]) {
399    let len = data.len();
400    if len < 254 {
401        buf.push(len as u8);
402        buf.extend_from_slice(data);
403        let pad = (4 - (1 + len) % 4) % 4;
404        for _ in 0..pad {
405            buf.push(0);
406        }
407    } else {
408        buf.push(0xfe);
409        buf.push((len & 0xff) as u8);
410        buf.push(((len >> 8) & 0xff) as u8);
411        buf.push(((len >> 16) & 0xff) as u8);
412        buf.extend_from_slice(data);
413        let pad = (4 - (4 + len) % 4) % 4;
414        for _ in 0..pad {
415            buf.push(0);
416        }
417    }
418}
419
420fn write_string(buf: &mut Vec<u8>, s: &str) {
421    write_bytes(buf, s.as_bytes());
422}
423
424fn need(data: &[u8], offset: usize, n: usize) -> Result<(), E2eError> {
425    if offset + n > data.len() {
426        Err(E2eError::TlDeserializationFailed)
427    } else {
428        Ok(())
429    }
430}
431
432fn read_u32(data: &[u8], offset: &mut usize) -> Result<u32, E2eError> {
433    need(data, *offset, 4)?;
434    let mut b = [0u8; 4];
435    b.copy_from_slice(&data[*offset..*offset + 4]);
436    *offset += 4;
437    Ok(u32::from_le_bytes(b))
438}
439
440fn read_i32(data: &[u8], offset: &mut usize) -> Result<i32, E2eError> {
441    Ok(read_u32(data, offset)? as i32)
442}
443
444fn read_i64(data: &[u8], offset: &mut usize) -> Result<i64, E2eError> {
445    need(data, *offset, 8)?;
446    let mut b = [0u8; 8];
447    b.copy_from_slice(&data[*offset..*offset + 8]);
448    *offset += 8;
449    Ok(i64::from_le_bytes(b))
450}
451
452fn read_f64(data: &[u8], offset: &mut usize) -> Result<f64, E2eError> {
453    need(data, *offset, 8)?;
454    let mut b = [0u8; 8];
455    b.copy_from_slice(&data[*offset..*offset + 8]);
456    *offset += 8;
457    Ok(f64::from_le_bytes(b))
458}
459
460fn read_bytes(data: &[u8], offset: &mut usize) -> Result<Vec<u8>, E2eError> {
461    need(data, *offset, 1)?;
462    let first = data[*offset];
463    if first < 254 {
464        let len = first as usize;
465        *offset += 1;
466        need(data, *offset, len)?;
467        let out = data[*offset..*offset + len].to_vec();
468        *offset += len;
469        let pad = (4 - (1 + len) % 4) % 4;
470        *offset += pad;
471        Ok(out)
472    } else if first == 0xfe {
473        need(data, *offset, 4)?;
474        let len = (data[*offset + 1] as usize)
475            | ((data[*offset + 2] as usize) << 8)
476            | ((data[*offset + 3] as usize) << 16);
477        *offset += 4;
478        need(data, *offset, len)?;
479        let out = data[*offset..*offset + len].to_vec();
480        *offset += len;
481        let pad = (4 - (4 + len) % 4) % 4;
482        *offset += pad;
483        Ok(out)
484    } else {
485        Err(E2eError::TlDeserializationFailed)
486    }
487}
488
489fn read_string(data: &[u8], offset: &mut usize) -> Result<String, E2eError> {
490    String::from_utf8(read_bytes(data, offset)?).map_err(|_| E2eError::TlDeserializationFailed)
491}
492
493/// Read a `Vector<long>` (boxed: ctor + i32 count + i64 elements).
494fn read_vector_long(data: &[u8], offset: &mut usize) -> Result<Vec<i64>, E2eError> {
495    if read_u32(data, offset)? != TL_VECTOR {
496        return Err(E2eError::TlDeserializationFailed);
497    }
498    let count = read_i32(data, offset)?;
499    if !(0..=65536).contains(&count) {
500        return Err(E2eError::TlDeserializationFailed);
501    }
502    let mut out = Vec::with_capacity(count as usize);
503    for _ in 0..count {
504        out.push(read_i64(data, offset)?);
505    }
506    Ok(out)
507}
508
509fn serialize_doc_attr(buf: &mut Vec<u8>, attr: &DocumentAttribute) {
510    match attr {
511        DocumentAttribute::ImageSize { w, h } => {
512            write_u32(buf, ID_ATTR_IMAGE_SIZE);
513            write_i32(buf, *w);
514            write_i32(buf, *h);
515        }
516        DocumentAttribute::Animated => {
517            write_u32(buf, ID_ATTR_ANIMATED);
518        }
519        DocumentAttribute::Sticker { alt } => {
520            // #3a556302: alt:string stickerset:InputStickerSet, no flags field
521            write_u32(buf, ID_ATTR_STICKER);
522            write_string(buf, alt);
523            write_u32(buf, 0xffb62b95); // inputStickerSetEmpty
524        }
525        DocumentAttribute::Video { duration, w, h } => {
526            write_u32(buf, ID_ATTR_VIDEO);
527            write_u32(buf, 0u32); // flags: none
528            write_i32(buf, *duration);
529            write_i32(buf, *w);
530            write_i32(buf, *h);
531        }
532        DocumentAttribute::Audio {
533            duration,
534            title,
535            performer,
536        } => {
537            write_u32(buf, ID_ATTR_AUDIO);
538            let mut flags: u32 = 0;
539            if title.is_some() {
540                flags |= 1;
541            }
542            if performer.is_some() {
543                flags |= 2;
544            }
545            write_u32(buf, flags);
546            write_i32(buf, *duration);
547            if let Some(t) = title {
548                write_string(buf, t);
549            }
550            if let Some(p) = performer {
551                write_string(buf, p);
552            }
553        }
554        DocumentAttribute::FileName { file_name } => {
555            write_u32(buf, ID_ATTR_FILENAME);
556            write_string(buf, file_name);
557        }
558        DocumentAttribute::Unknown { .. } => {
559            // Never send an unknown attribute.
560        }
561    }
562}
563
564fn deserialize_doc_attr(data: &[u8], offset: &mut usize) -> Result<DocumentAttribute, E2eError> {
565    let ctor = read_u32(data, offset)?;
566    match ctor {
567        ID_ATTR_IMAGE_SIZE => Ok(DocumentAttribute::ImageSize {
568            w: read_i32(data, offset)?,
569            h: read_i32(data, offset)?,
570        }),
571        ID_ATTR_ANIMATED => Ok(DocumentAttribute::Animated),
572        // layer 8 sticker: no fields at all
573        0xfb0a5727 => Ok(DocumentAttribute::Sticker { alt: String::new() }),
574        ID_ATTR_STICKER => {
575            // #3a556302: alt:string stickerset:InputStickerSet, no flags field
576            let alt = read_string(data, offset)?;
577            // Skip the InputStickerSet field (boxed, variable size).
578            let set_ctor = read_u32(data, offset)?;
579            match set_ctor {
580                0xffb62b95 => {} // inputStickerSetEmpty: no fields
581                0x861cc8a0 => {
582                    let _ = read_string(data, offset);
583                } // inputStickerSetShortName: short_name:string
584                _ => {}
585            }
586            Ok(DocumentAttribute::Sticker { alt })
587        }
588        ID_ATTR_VIDEO => {
589            let _flags = read_u32(data, offset)?;
590            let duration = read_i32(data, offset)?;
591            let w = read_i32(data, offset)?;
592            let h = read_i32(data, offset)?;
593            Ok(DocumentAttribute::Video { duration, w, h })
594        }
595        ID_ATTR_AUDIO => {
596            let flags = read_u32(data, offset)?;
597            let duration = read_i32(data, offset)?;
598            let title = if flags & (1 << 0) != 0 {
599                Some(read_string(data, offset)?)
600            } else {
601                None
602            };
603            let performer = if flags & (1 << 1) != 0 {
604                Some(read_string(data, offset)?)
605            } else {
606                None
607            };
608            // waveform:flags.2?bytes must be consumed even though we don't expose it
609            if flags & (1 << 2) != 0 {
610                let _ = read_bytes(data, offset)?;
611            }
612            Ok(DocumentAttribute::Audio {
613                duration,
614                title,
615                performer,
616            })
617        }
618        ID_ATTR_FILENAME => Ok(DocumentAttribute::FileName {
619            file_name: read_string(data, offset)?,
620        }),
621        _ => Ok(DocumentAttribute::Unknown { ctor }),
622    }
623}
624
625/// Serialize `media` into `buf` (constructor ID followed by its fields).
626pub fn serialize_media(buf: &mut Vec<u8>, media: &DecryptedMedia) {
627    match media {
628        DecryptedMedia::Empty => {
629            write_u32(buf, ID_MEDIA_EMPTY);
630        }
631        DecryptedMedia::Photo {
632            thumb,
633            thumb_w,
634            thumb_h,
635            w,
636            h,
637            size,
638            key,
639            iv,
640            caption,
641        } => {
642            write_u32(buf, ID_MEDIA_PHOTO);
643            write_bytes(buf, thumb);
644            write_i32(buf, *thumb_w);
645            write_i32(buf, *thumb_h);
646            write_i32(buf, *w);
647            write_i32(buf, *h);
648            write_i32(buf, *size);
649            write_bytes(buf, key);
650            write_bytes(buf, iv);
651            write_string(buf, caption);
652        }
653        DecryptedMedia::Document {
654            thumb,
655            thumb_w,
656            thumb_h,
657            mime_type,
658            size,
659            key,
660            iv,
661            attributes,
662            caption,
663        } => {
664            write_u32(buf, ID_MEDIA_DOCUMENT);
665            write_bytes(buf, thumb);
666            write_i32(buf, *thumb_w);
667            write_i32(buf, *thumb_h);
668            write_string(buf, mime_type);
669            write_i64(buf, *size);
670            write_bytes(buf, key);
671            write_bytes(buf, iv);
672            write_u32(buf, TL_VECTOR);
673            write_i32(buf, attributes.len() as i32);
674            for attr in attributes {
675                serialize_doc_attr(buf, attr);
676            }
677            write_string(buf, caption);
678        }
679        DecryptedMedia::GeoPoint { lat, long } => {
680            write_u32(buf, ID_MEDIA_GEO);
681            buf.extend_from_slice(&lat.to_le_bytes());
682            buf.extend_from_slice(&long.to_le_bytes());
683        }
684        DecryptedMedia::Contact {
685            phone_number,
686            first_name,
687            last_name,
688            user_id,
689        } => {
690            write_u32(buf, ID_MEDIA_CONTACT);
691            write_string(buf, phone_number);
692            write_string(buf, first_name);
693            write_string(buf, last_name);
694            write_i32(buf, *user_id);
695        }
696        DecryptedMedia::Unknown { .. } => {
697            write_u32(buf, ID_MEDIA_EMPTY);
698        }
699    }
700}
701
702/// Parse a media object from `data` starting at `*offset`, advancing the offset.
703pub fn deserialize_media(data: &[u8], offset: &mut usize) -> Result<DecryptedMedia, E2eError> {
704    if *offset + 4 > data.len() {
705        return Ok(DecryptedMedia::Empty);
706    }
707    let ctor = read_u32(data, offset)?;
708    match ctor {
709        ID_MEDIA_EMPTY => Ok(DecryptedMedia::Empty),
710
711        ID_MEDIA_PHOTO => {
712            let thumb = read_bytes(data, offset)?;
713            let thumb_w = read_i32(data, offset)?;
714            let thumb_h = read_i32(data, offset)?;
715            let w = read_i32(data, offset)?;
716            let h = read_i32(data, offset)?;
717            let size = read_i32(data, offset)?;
718            let key = read_bytes(data, offset)?;
719            let iv = read_bytes(data, offset)?;
720            let caption = read_string(data, offset).unwrap_or_default();
721            Ok(DecryptedMedia::Photo {
722                thumb,
723                thumb_w,
724                thumb_h,
725                w,
726                h,
727                size,
728                key,
729                iv,
730                caption,
731            })
732        }
733
734        ID_MEDIA_PHOTO_OLD => {
735            // layer 8 photo: no caption field
736            let thumb = read_bytes(data, offset)?;
737            let thumb_w = read_i32(data, offset)?;
738            let thumb_h = read_i32(data, offset)?;
739            let w = read_i32(data, offset)?;
740            let h = read_i32(data, offset)?;
741            let size = read_i32(data, offset)?;
742            let key = read_bytes(data, offset)?;
743            let iv = read_bytes(data, offset)?;
744            Ok(DecryptedMedia::Photo {
745                thumb,
746                thumb_w,
747                thumb_h,
748                w,
749                h,
750                size,
751                key,
752                iv,
753                caption: String::new(),
754            })
755        }
756
757        ID_MEDIA_DOCUMENT => {
758            let thumb = read_bytes(data, offset)?;
759            let thumb_w = read_i32(data, offset)?;
760            let thumb_h = read_i32(data, offset)?;
761            let mime_type = read_string(data, offset)?;
762            let size = read_i64(data, offset)?;
763            let key = read_bytes(data, offset)?;
764            let iv = read_bytes(data, offset)?;
765            let attributes = if *offset + 4 <= data.len() {
766                let vec_ctor = read_u32(data, offset)?;
767                if vec_ctor == TL_VECTOR {
768                    let count = read_i32(data, offset)?.clamp(0, 64) as usize;
769                    let mut attrs = Vec::with_capacity(count);
770                    for _ in 0..count {
771                        match deserialize_doc_attr(data, offset) {
772                            Ok(a) => attrs.push(a),
773                            Err(_) => break,
774                        }
775                    }
776                    attrs
777                } else {
778                    Vec::new()
779                }
780            } else {
781                Vec::new()
782            };
783            let caption = read_string(data, offset).unwrap_or_default();
784            Ok(DecryptedMedia::Document {
785                thumb,
786                thumb_w,
787                thumb_h,
788                mime_type,
789                size,
790                key,
791                iv,
792                attributes,
793                caption,
794            })
795        }
796
797        ID_MEDIA_DOCUMENT_OLD => {
798            // layer 8 document: file_name + mime_type + size:int, no attributes, no caption
799            let thumb = read_bytes(data, offset)?;
800            let thumb_w = read_i32(data, offset)?;
801            let thumb_h = read_i32(data, offset)?;
802            let _file_name = read_string(data, offset)?; // separate field in layer 8
803            let mime_type = read_string(data, offset)?;
804            let size = read_i32(data, offset)? as i64;
805            let key = read_bytes(data, offset)?;
806            let iv = read_bytes(data, offset)?;
807            Ok(DecryptedMedia::Document {
808                thumb,
809                thumb_w,
810                thumb_h,
811                mime_type,
812                size,
813                key,
814                iv,
815                attributes: Vec::new(),
816                caption: String::new(),
817            })
818        }
819
820        // decryptedMessageMediaDocument#7afe8ae2, layer 45-142
821        // thumb:bytes thumb_w:int thumb_h:int mime_type:string size:int key:bytes iv:bytes attributes:Vector<DocumentAttribute> caption:string
822        0x7afe8ae2 => {
823            let thumb = read_bytes(data, offset)?;
824            let thumb_w = read_i32(data, offset)?;
825            let thumb_h = read_i32(data, offset)?;
826            let mime_type = read_string(data, offset)?;
827            let size = read_i32(data, offset)? as i64;
828            let key = read_bytes(data, offset)?;
829            let iv = read_bytes(data, offset)?;
830            let attributes = if *offset + 4 <= data.len() {
831                let vec_ctor = read_u32(data, offset)?;
832                if vec_ctor == TL_VECTOR {
833                    let count = read_i32(data, offset)?.clamp(0, 64) as usize;
834                    let mut attrs = Vec::with_capacity(count);
835                    for _ in 0..count {
836                        match deserialize_doc_attr(data, offset) {
837                            Ok(a) => attrs.push(a),
838                            Err(_) => break,
839                        }
840                    }
841                    attrs
842                } else {
843                    Vec::new()
844                }
845            } else {
846                Vec::new()
847            };
848            let caption = read_string(data, offset).unwrap_or_default();
849            Ok(DecryptedMedia::Document {
850                thumb,
851                thumb_w,
852                thumb_h,
853                mime_type,
854                size,
855                key,
856                iv,
857                attributes,
858                caption,
859            })
860        }
861
862        ID_MEDIA_GEO => {
863            let lat = read_f64(data, offset)?;
864            let long = read_f64(data, offset)?;
865            Ok(DecryptedMedia::GeoPoint { lat, long })
866        }
867
868        ID_MEDIA_CONTACT => {
869            let phone_number = read_string(data, offset)?;
870            let first_name = read_string(data, offset)?;
871            let last_name = read_string(data, offset)?;
872            let user_id = read_i32(data, offset)?;
873            Ok(DecryptedMedia::Contact {
874                phone_number,
875                first_name,
876                last_name,
877                user_id,
878            })
879        }
880
881        // Old audio/video types: just note the ctor, no fields we care about.
882        ID_MEDIA_AUDIO_L8 | ID_MEDIA_AUDIO_L17 | ID_MEDIA_VIDEO_L8 | ID_MEDIA_VIDEO_L17
883        | ID_MEDIA_VIDEO_L45 => Ok(DecryptedMedia::Unknown { ctor }),
884
885        // Venue: parsed but not exposed as a rich type yet.
886        ID_MEDIA_VENUE => Ok(DecryptedMedia::Unknown { ctor }),
887
888        _ => Ok(DecryptedMedia::Unknown { ctor }),
889    }
890}
891
892fn serialize_action(buf: &mut Vec<u8>, action: &DecryptedAction) {
893    match action {
894        DecryptedAction::NotifyLayer { layer } => {
895            write_u32(buf, ID_ACTION_NOTIFY_LAYER);
896            write_i32(buf, *layer);
897        }
898        DecryptedAction::RequestKey { exchange_id, g_a } => {
899            write_u32(buf, ID_ACTION_REQUEST_KEY);
900            write_i64(buf, *exchange_id);
901            write_bytes(buf, g_a);
902        }
903        DecryptedAction::AcceptKey {
904            exchange_id,
905            g_b,
906            key_fingerprint,
907        } => {
908            write_u32(buf, ID_ACTION_ACCEPT_KEY);
909            write_i64(buf, *exchange_id);
910            write_bytes(buf, g_b);
911            write_i64(buf, *key_fingerprint);
912        }
913        DecryptedAction::AbortKey { exchange_id } => {
914            write_u32(buf, ID_ACTION_ABORT_KEY);
915            write_i64(buf, *exchange_id);
916        }
917        DecryptedAction::CommitKey {
918            exchange_id,
919            key_fingerprint,
920        } => {
921            write_u32(buf, ID_ACTION_COMMIT_KEY);
922            write_i64(buf, *exchange_id);
923            write_i64(buf, *key_fingerprint);
924        }
925        DecryptedAction::Noop => {
926            write_u32(buf, ID_ACTION_NOOP);
927        }
928        DecryptedAction::SetTtl { ttl_seconds } => {
929            write_u32(buf, ID_ACTION_SET_TTL);
930            write_i32(buf, *ttl_seconds);
931        }
932        DecryptedAction::Resend {
933            start_seq_no,
934            end_seq_no,
935        } => {
936            write_u32(buf, ID_ACTION_RESEND);
937            write_i32(buf, *start_seq_no);
938            write_i32(buf, *end_seq_no);
939        }
940        // Peer-only actions: should never be serialized by us.
941        DecryptedAction::ReadMessages { .. }
942        | DecryptedAction::DeleteMessages { .. }
943        | DecryptedAction::ScreenshotMessages { .. }
944        | DecryptedAction::FlushHistory
945        | DecryptedAction::Typing { .. }
946        | DecryptedAction::Unknown { .. } => {}
947    }
948}
949
950fn deserialize_action(data: &[u8], offset: &mut usize) -> Result<DecryptedAction, E2eError> {
951    let ctor = read_u32(data, offset)?;
952    match ctor {
953        ID_ACTION_NOTIFY_LAYER => Ok(DecryptedAction::NotifyLayer {
954            layer: read_i32(data, offset)?,
955        }),
956        ID_ACTION_REQUEST_KEY => Ok(DecryptedAction::RequestKey {
957            exchange_id: read_i64(data, offset)?,
958            g_a: read_bytes(data, offset)?,
959        }),
960        ID_ACTION_ACCEPT_KEY => Ok(DecryptedAction::AcceptKey {
961            exchange_id: read_i64(data, offset)?,
962            g_b: read_bytes(data, offset)?,
963            key_fingerprint: read_i64(data, offset)?,
964        }),
965        ID_ACTION_ABORT_KEY => Ok(DecryptedAction::AbortKey {
966            exchange_id: read_i64(data, offset)?,
967        }),
968        ID_ACTION_COMMIT_KEY => Ok(DecryptedAction::CommitKey {
969            exchange_id: read_i64(data, offset)?,
970            key_fingerprint: read_i64(data, offset)?,
971        }),
972        ID_ACTION_NOOP => Ok(DecryptedAction::Noop),
973        ID_ACTION_SET_TTL => Ok(DecryptedAction::SetTtl {
974            ttl_seconds: read_i32(data, offset)?,
975        }),
976        ID_ACTION_RESEND => Ok(DecryptedAction::Resend {
977            start_seq_no: read_i32(data, offset)?,
978            end_seq_no: read_i32(data, offset)?,
979        }),
980        ID_ACTION_READ_MESSAGES => Ok(DecryptedAction::ReadMessages {
981            random_ids: read_vector_long(data, offset)?,
982        }),
983        ID_ACTION_DELETE_MESSAGES => Ok(DecryptedAction::DeleteMessages {
984            random_ids: read_vector_long(data, offset)?,
985        }),
986        ID_ACTION_SCREENSHOT_MESSAGES => Ok(DecryptedAction::ScreenshotMessages {
987            random_ids: read_vector_long(data, offset)?,
988        }),
989        ID_ACTION_FLUSH_HISTORY => Ok(DecryptedAction::FlushHistory),
990        ID_ACTION_TYPING => Ok(DecryptedAction::Typing {
991            action_ctor: read_u32(data, offset)?,
992        }),
993        _ => Ok(DecryptedAction::Unknown { ctor }),
994    }
995}
996
997fn serialize_message(buf: &mut Vec<u8>, msg: &DecryptedMessage) {
998    match msg {
999        DecryptedMessage::Text {
1000            random_id,
1001            ttl,
1002            message,
1003            media,
1004        } => {
1005            write_u32(buf, ID_DECRYPTED_MESSAGE);
1006            // flags bit 9 = media present. Must be set iff media is non-empty;
1007            // tdesktop (and any spec-compliant peer) reads media only when bit 9 is set.
1008            let has_media = !matches!(media, DecryptedMedia::Empty);
1009            let flags: u32 = if has_media { 1 << 9 } else { 0 };
1010            write_u32(buf, flags);
1011            write_i64(buf, *random_id);
1012            write_i32(buf, *ttl);
1013            write_string(buf, message);
1014            if has_media {
1015                serialize_media(buf, media);
1016            }
1017        }
1018        DecryptedMessage::Service { random_id, action } => {
1019            write_u32(buf, ID_DECRYPTED_MESSAGE_SERVICE);
1020            write_i64(buf, *random_id);
1021            serialize_action(buf, action);
1022        }
1023        DecryptedMessage::Unknown { .. } => {
1024            // Should not be serialized by us.
1025        }
1026    }
1027}
1028
1029fn deserialize_message(data: &[u8], offset: &mut usize) -> Result<DecryptedMessage, E2eError> {
1030    let ctor = read_u32(data, offset)?;
1031    match ctor {
1032        ID_DECRYPTED_MESSAGE => {
1033            let flags = read_u32(data, offset)?;
1034            let random_id = read_i64(data, offset)?;
1035            let ttl = read_i32(data, offset)?;
1036            let message = read_string(data, offset)?;
1037            // bit 9 = media present
1038            let media = if flags & (1 << 9) != 0 {
1039                deserialize_media(data, offset).unwrap_or(DecryptedMedia::Empty)
1040            } else {
1041                DecryptedMedia::Empty
1042            };
1043            Ok(DecryptedMessage::Text {
1044                random_id,
1045                ttl,
1046                message,
1047                media,
1048            })
1049        }
1050        ID_DECRYPTED_MESSAGE_OLD => {
1051            // layer 45: flags:# random_id:long ttl:int message:string media:flags.9?...
1052            let flags = read_u32(data, offset)?;
1053            let random_id = read_i64(data, offset)?;
1054            let ttl = read_i32(data, offset)?;
1055            let message = read_string(data, offset)?;
1056            let media = if flags & (1 << 9) != 0 {
1057                deserialize_media(data, offset).unwrap_or(DecryptedMedia::Empty)
1058            } else {
1059                DecryptedMedia::Empty
1060            };
1061            Ok(DecryptedMessage::Text {
1062                random_id,
1063                ttl,
1064                message,
1065                media,
1066            })
1067        }
1068        // layer 8 text: random_id:long random_bytes:bytes message:string media:DecryptedMessageMedia
1069        0x1f814f1f => {
1070            let random_id = read_i64(data, offset)?;
1071            let _random_bytes = read_bytes(data, offset)?;
1072            let message = read_string(data, offset)?;
1073            let media = deserialize_media(data, offset).unwrap_or(DecryptedMedia::Empty);
1074            Ok(DecryptedMessage::Text {
1075                random_id,
1076                ttl: 0,
1077                message,
1078                media,
1079            })
1080        }
1081        // layer 17 text: random_id:long ttl:int message:string media:DecryptedMessageMedia (no flags, unconditional media)
1082        0x204d3878 => {
1083            let random_id = read_i64(data, offset)?;
1084            let ttl = read_i32(data, offset)?;
1085            let message = read_string(data, offset)?;
1086            let media = deserialize_media(data, offset).unwrap_or(DecryptedMedia::Empty);
1087            Ok(DecryptedMessage::Text {
1088                random_id,
1089                ttl,
1090                message,
1091                media,
1092            })
1093        }
1094        ID_DECRYPTED_MESSAGE_SERVICE => {
1095            let random_id = read_i64(data, offset)?;
1096            let action = deserialize_action(data, offset)?;
1097            Ok(DecryptedMessage::Service { random_id, action })
1098        }
1099        // layer 8 service: random_id:long random_bytes:bytes action:DecryptedMessageAction
1100        ID_DECRYPTED_MESSAGE_SERVICE8 => {
1101            let random_id = read_i64(data, offset)?;
1102            let _random_bytes = read_bytes(data, offset)?;
1103            let action = deserialize_action(data, offset)?;
1104            Ok(DecryptedMessage::Service { random_id, action })
1105        }
1106        _ => {
1107            let raw = data[*offset..].to_vec();
1108            *offset = data.len();
1109            Ok(DecryptedMessage::Unknown { ctor, raw })
1110        }
1111    }
1112}
1113
1114/// Serialize a [`DecryptedMessageLayer`] to bytes, ready for `crypto::encrypt_message`.
1115pub fn serialize_message_layer(layer: &DecryptedMessageLayer) -> Result<Vec<u8>, E2eError> {
1116    let mut buf = Vec::new();
1117    write_u32(&mut buf, ID_DECRYPTED_MESSAGE_LAYER);
1118    write_bytes(&mut buf, &layer.random_bytes);
1119    write_i32(&mut buf, layer.layer);
1120    write_i32(&mut buf, layer.in_seq_no);
1121    write_i32(&mut buf, layer.out_seq_no);
1122    serialize_message(&mut buf, &layer.message);
1123    Ok(buf)
1124}
1125
1126/// Parse a [`DecryptedMessageLayer`] from decrypted bytes.
1127pub fn deserialize_message_layer(data: &[u8]) -> Result<DecryptedMessageLayer, E2eError> {
1128    let mut offset = 0usize;
1129    if read_u32(data, &mut offset)? != ID_DECRYPTED_MESSAGE_LAYER {
1130        return Err(E2eError::TlDeserializationFailed);
1131    }
1132    let random_bytes = read_bytes(data, &mut offset)?;
1133    let layer = read_i32(data, &mut offset)?;
1134    let in_seq_no = read_i32(data, &mut offset)?;
1135    let out_seq_no = read_i32(data, &mut offset)?;
1136    let message = deserialize_message(data, &mut offset)?;
1137    Ok(DecryptedMessageLayer {
1138        random_bytes,
1139        layer,
1140        in_seq_no,
1141        out_seq_no,
1142        message,
1143    })
1144}
1145
1146/// Serialize a layer-8 service message (no [`DecryptedMessageLayer`] wrapper).
1147///
1148/// Used for the initial `notify_layer` handshake.
1149pub fn serialize_layer8_service(
1150    random_id: i64,
1151    action: &DecryptedAction,
1152) -> Result<Vec<u8>, E2eError> {
1153    let mut buf = Vec::new();
1154    write_u32(&mut buf, ID_DECRYPTED_MESSAGE_SERVICE8);
1155    write_i64(&mut buf, random_id);
1156    let mut rb = [0u8; 15];
1157    rand::rng().fill_bytes(&mut rb);
1158    write_bytes(&mut buf, &rb);
1159    serialize_action(&mut buf, action);
1160    Ok(buf)
1161}
1162
1163/// Build the `random_bytes` field of a [`DecryptedMessageLayer`].
1164///
1165/// The length is 15, 19 or 23 bytes, so payload sizes vary slightly.
1166pub fn make_random_bytes() -> Vec<u8> {
1167    let extra = (rand::random::<u8>() % 3) as usize * 4;
1168    let mut rb = vec![0u8; 15 + extra];
1169    rand::rng().fill_bytes(&mut rb);
1170    rb
1171}