├── .gitignore
├── LICENSE
├── MANIFEST.in
├── README.md
├── ll_mtproto
├── __init__.py
├── client
│ ├── client.py
│ ├── connection_info.py
│ ├── error_description_resolver
│ │ ├── base_error_description_resolver.py
│ │ └── pwrtelegram_error_description_resolver.py
│ ├── pending_container_request.py
│ ├── pending_request.py
│ ├── rpc_error.py
│ └── update.py
├── constants.py
├── crypto
│ ├── aes_ige.py
│ ├── auth_key.py
│ ├── providers
│ │ ├── crypto_provider_base.py
│ │ └── crypto_provider_cryptg.py
│ └── public_rsa.py
├── math
│ └── primes.py
├── network
│ ├── auth_key_not_found_exception.py
│ ├── datacenter_info.py
│ ├── dh
│ │ ├── mtproto_key_binder_dispatcher.py
│ │ ├── mtproto_key_creator.py
│ │ └── mtproto_key_creator_dispatcher.py
│ ├── dispatcher.py
│ ├── mtproto.py
│ └── transport
│ │ ├── transport_address_resolver_base.py
│ │ ├── transport_address_resolver_cached.py
│ │ ├── transport_codec_abridged.py
│ │ ├── transport_codec_base.py
│ │ ├── transport_codec_factory.py
│ │ ├── transport_codec_intermediate.py
│ │ ├── transport_link_base.py
│ │ ├── transport_link_factory.py
│ │ └── transport_link_tcp.py
├── resources
│ ├── application.tl
│ ├── auth.tl
│ ├── service.tl
│ ├── telegram.rsa.pub
│ └── telegram.test.rsa.pub
├── tl
│ ├── byteutils.py
│ ├── structure.py
│ └── tl.py
└── typed.py
├── pyproject.toml
├── requirements.txt
├── setup.py
├── test_benchmark_tl.py
├── test_download.py
├── test_key_exchange.py
├── test_performance.py
├── test_rpc_call_container.py
└── test_upload.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # poetry
98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102 | #poetry.lock
103 |
104 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
105 | __pypackages__/
106 |
107 | # Celery stuff
108 | celerybeat-schedule
109 | celerybeat.pid
110 |
111 | # SageMath parsed files
112 | *.sage.py
113 |
114 | # Environments
115 | .env
116 | .venv
117 | env/
118 | venv/
119 | ENV/
120 | env.bak/
121 | venv.bak/
122 |
123 | # Spyder project settings
124 | .spyderproject
125 | .spyproject
126 |
127 | # Rope project settings
128 | .ropeproject
129 |
130 | # mkdocs documentation
131 | /site
132 |
133 | # mypy
134 | .mypy_cache/
135 | .dmypy.json
136 | dmypy.json
137 |
138 | # Pyre type checker
139 | .pyre/
140 |
141 | # pytype static type analyzer
142 | .pytype/
143 |
144 | # Cython debug symbols
145 | cython_debug/
146 |
147 | # PyCharm
148 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
149 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
150 | # and can be added to the global gitignore or merged into this file. For a more nuclear
151 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
152 | .idea/
153 |
154 | # ll-mtproto
155 | *.session
156 | *.session.config
157 | tests/
158 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | recursive-include ll_mtproto/resources *.tl *.pub
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # LL-MTPROTO
2 | > LL-mtproto is an abstraction-free mtproto client.
3 |
4 | # INSTALLATION
5 | pip3 install git+https://github.com/andrew-ld/LL-mtproto
6 |
7 | # ABOUT
8 | ll-mtproto was developed as an answer to the mtproto clients currently existing on the opensource market, they are too complicated due to excessive abstraction layers, unfortunately these abstractions are difficult to maintain and have a strong impact on performance.
9 |
10 | # FAST DYNAMIC TL DESERIALIZER
11 | ll-mtproto unlike many alternatives does not generate code to deserialize the received data, it parse at runtime the schema and use it to deserialize the data, deserializer has been heavily adapted to be able to be compiled to native machine code to achieve superior performance
12 |
13 | To compile the deserializer simply run mypyc by giving as input the file tl.py
14 |
15 | `python3 -m mypyc --strict ll_mtproto/tl/tl.py`
16 |
17 | # LICENSING
18 | it must be noted that ll-mtproto is a derivative work of mtproto2json developed by @nikat, the publication of ll-mtproto under agplv3 license is possible only thanks to the approval of nikat to change the license of mtproto2json with agplv3.
19 |
--------------------------------------------------------------------------------
/ll_mtproto/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | from ll_mtproto.client.client import Client
19 | from ll_mtproto.client.connection_info import ConnectionInfo
20 | from ll_mtproto.client.error_description_resolver.pwrtelegram_error_description_resolver import PwrTelegramErrorDescriptionResolver
21 | from ll_mtproto.client.rpc_error import RpcError
22 | from ll_mtproto.client.update import Update
23 | from ll_mtproto.constants import TelegramDatacenter, TelegramTestDatacenter
24 | from ll_mtproto.crypto.auth_key import AuthKey
25 | from ll_mtproto.crypto.providers.crypto_provider_cryptg import CryptoProviderCryptg
26 | from ll_mtproto.network.transport.transport_address_resolver_cached import CachedTransportAddressResolver
27 | from ll_mtproto.network.transport.transport_codec_intermediate import TransportCodecIntermediateFactory
28 | from ll_mtproto.network.transport.transport_codec_abridged import TransportCodecAbridgedFactory
29 | from ll_mtproto.network.transport.transport_link_tcp import TransportLinkTcpFactory
30 |
31 | __all__ = (
32 | "Client",
33 | "TelegramDatacenter",
34 | "TelegramTestDatacenter",
35 | "AuthKey",
36 | "RpcError",
37 | "ConnectionInfo",
38 | "Update",
39 | "CryptoProviderCryptg",
40 | "CachedTransportAddressResolver",
41 | "TransportCodecIntermediateFactory",
42 | "TransportCodecAbridgedFactory",
43 | "TransportLinkTcpFactory",
44 | "PwrTelegramErrorDescriptionResolver"
45 | )
46 |
--------------------------------------------------------------------------------
/ll_mtproto/client/connection_info.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 | import locale
18 | import logging
19 | import platform
20 | import functools
21 | import traceback
22 |
23 | from ll_mtproto.tl.tl import TlBodyData, TlBodyDataValue
24 |
25 | __all__ = ("ConnectionInfo",)
26 |
27 |
28 | class ConnectionInfo:
29 | __slots__ = (
30 | "api_id",
31 | "device_model",
32 | "system_version",
33 | "app_version",
34 | "lang_code",
35 | "system_lang_code",
36 | "lang_pack",
37 | "params"
38 | )
39 |
40 | api_id: int
41 | device_model: str
42 | system_version: str
43 | app_version: str
44 | lang_code: str
45 | system_lang_code: str
46 | lang_pack: str
47 | params: TlBodyData | None
48 |
49 | def __init__(
50 | self,
51 | *,
52 | api_id: int,
53 | device_model: str,
54 | system_version: str,
55 | app_version: str,
56 | lang_code: str,
57 | system_lang_code: str,
58 | lang_pack: str,
59 | params: TlBodyData | None = None
60 | ):
61 | self.api_id = api_id
62 | self.device_model = device_model
63 | self.system_version = system_version
64 | self.app_version = app_version
65 | self.lang_code = lang_code
66 | self.system_lang_code = system_lang_code
67 | self.lang_pack = lang_pack
68 | self.params = params
69 |
70 | @functools.cache
71 | def to_request_body(self) -> dict[str, TlBodyDataValue]:
72 | return {
73 | "api_id": self.api_id,
74 | "device_model": self.device_model,
75 | "system_version": self.system_version,
76 | "app_version": self.app_version,
77 | "lang_code": self.lang_code,
78 | "system_lang_code": self.system_lang_code,
79 | "lang_pack": self.lang_pack,
80 | "params": self.params
81 | }
82 |
83 | @staticmethod
84 | @functools.lru_cache()
85 | def generate_from_os_info(app_id: int, fallback_lang_code: str = "en") -> "ConnectionInfo":
86 | # noinspection PyBroadException
87 | try:
88 | current_locale = locale.getlocale()
89 | except:
90 | current_locale = None
91 | logging.warning("unable to get current locale: `%s`", traceback.format_exc())
92 |
93 | if current_locale:
94 | lang_code = current_locale[0]
95 |
96 | if not lang_code:
97 | lang_code = fallback_lang_code
98 | else:
99 | lang_code = fallback_lang_code
100 |
101 | system_version = platform.platform()
102 |
103 | return ConnectionInfo(
104 | api_id=app_id,
105 | device_model="ll-mtproto",
106 | system_version=system_version,
107 | app_version="1.0",
108 | lang_code=lang_code,
109 | system_lang_code=lang_code,
110 | lang_pack="",
111 | params=None
112 | )
113 |
--------------------------------------------------------------------------------
/ll_mtproto/client/error_description_resolver/base_error_description_resolver.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import abc
19 |
20 | __all__ = ("BaseErrorDescriptionResolver",)
21 |
22 |
23 | class BaseErrorDescriptionResolver(abc.ABC):
24 | @abc.abstractmethod
25 | def resolve(self, code: int, message: str) -> str | None:
26 | raise NotImplementedError
27 |
--------------------------------------------------------------------------------
/ll_mtproto/client/error_description_resolver/pwrtelegram_error_description_resolver.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 | import functools
18 | import json
19 | import re
20 | import typing
21 | import urllib.request
22 |
23 | from ll_mtproto.client.error_description_resolver.base_error_description_resolver import BaseErrorDescriptionResolver
24 |
25 | __all__ = ("PwrTelegramErrorDescriptionResolver",)
26 |
27 | _RE_replace_number = re.compile(r"_\d+$")
28 | _PWRTELEGRAM_database_url = "https://rpc.madelineproto.xyz/v4.json"
29 |
30 |
31 | class PwrTelegramErrorDescriptionResolver(BaseErrorDescriptionResolver):
32 | __slots__ = ("_database", "_database_url")
33 |
34 | _database: dict[str, str] | None
35 | _database_url: str
36 |
37 | def __init__(self, database_url: str = _PWRTELEGRAM_database_url, initial_database: dict[str, str] | None = None) -> None:
38 | self._database = initial_database
39 | self._database_url = database_url
40 |
41 | @staticmethod
42 | @functools.lru_cache()
43 | def _normalize_error_message(message: str) -> str:
44 | return _RE_replace_number.sub(r"_%d", message)
45 |
46 | @property
47 | def current_database(self) -> dict[str, str]:
48 | database = self._database
49 |
50 | if database is None:
51 | raise RuntimeError("database not initialized, must call synchronous_fetch_database")
52 |
53 | return database
54 |
55 | def synchronous_fetch_database(self) -> None:
56 | with urllib.request.urlopen(self._database_url) as response:
57 | self._database = typing.cast(dict[str, str], json.loads(response.read())["human_result"])
58 |
59 | def resolve(self, _code: int, message: str) -> str | None:
60 | return self.current_database.get(self._normalize_error_message(message), None)
61 |
--------------------------------------------------------------------------------
/ll_mtproto/client/pending_container_request.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 | from ll_mtproto.client.pending_request import PendingRequest
18 |
19 |
20 | class PendingContainerRequest:
21 | __slots__ = ("requests", "last_message_id")
22 |
23 | requests: list[PendingRequest]
24 | last_message_id: int | None
25 |
26 | @staticmethod
27 | def _validate_request(request: PendingRequest):
28 | if not request.allow_container:
29 | raise TypeError(f"Pending request `{request!r}` dont allow container.")
30 |
31 | if not request.expect_answer:
32 | raise TypeError(f"Pending request `{request!r}` dont expect an answer.")
33 |
34 | def __init__(self, requests: list[PendingRequest], last_message_id: int | None = None) -> None:
35 | for request in requests:
36 | self._validate_request(request)
37 | self.requests = requests
38 | self.last_message_id = last_message_id
39 |
40 | def finalize(self) -> None:
41 | for request in self.requests:
42 | request.finalize()
43 |
--------------------------------------------------------------------------------
/ll_mtproto/client/pending_request.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import asyncio
19 | import typing
20 |
21 | from ll_mtproto.tl.structure import StructureBody
22 | from ll_mtproto.tl.tl import TlBodyData, Value
23 |
24 | __all__ = ("PendingRequest",)
25 |
26 | SeqNoGenerator = typing.Callable[[], int]
27 |
28 |
29 | class PendingRequest:
30 | __slots__ = (
31 | "response",
32 | "request",
33 | "cleaner",
34 | "retries",
35 | "next_seq_no",
36 | "allow_container",
37 | "expect_answer",
38 | "force_init_connection",
39 | "serialized_payload",
40 | "init_connection_wrapped",
41 | "last_message_id",
42 | "container_message_id"
43 | )
44 |
45 | response: asyncio.Future[StructureBody]
46 | request: TlBodyData
47 | cleaner: asyncio.TimerHandle | None
48 | retries: int
49 | next_seq_no: SeqNoGenerator
50 | allow_container: bool
51 | expect_answer: bool
52 | force_init_connection: bool
53 | serialized_payload: Value | None
54 | init_connection_wrapped: bool
55 | last_message_id: int | None
56 | container_message_id: int | None
57 |
58 | def __init__(
59 | self,
60 | *,
61 | response: asyncio.Future[StructureBody],
62 | message: TlBodyData,
63 | seq_no_func: SeqNoGenerator,
64 | allow_container: bool,
65 | expect_answer: bool,
66 | force_init_connection: bool = False,
67 | serialized_payload: Value | None = None,
68 | previous_message_id: int | None = None,
69 | container_message_id: int | None = None
70 | ):
71 | self.response = response
72 | self.request = message
73 | self.cleaner = None
74 | self.retries = 0
75 | self.next_seq_no = seq_no_func
76 | self.allow_container = allow_container
77 | self.expect_answer = expect_answer
78 | self.force_init_connection = force_init_connection
79 | self.serialized_payload = serialized_payload
80 | self.init_connection_wrapped = False
81 | self.last_message_id = previous_message_id
82 | self.container_message_id = container_message_id
83 |
84 | def finalize(self) -> None:
85 | if not (response := self.response).done():
86 | response.set_exception(ConnectionResetError())
87 |
88 | if cleaner := self.cleaner:
89 | cleaner.cancel()
90 |
91 | self.cleaner = None
92 | self.response.exception()
93 |
94 | def get_value(self) -> BaseException | StructureBody:
95 | if not self.response.done():
96 | raise asyncio.InvalidStateError("Response is not already done")
97 |
98 | if exception := self.response.exception():
99 | return exception
100 |
101 | return self.response.result()
102 |
--------------------------------------------------------------------------------
/ll_mtproto/client/rpc_error.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | __all__ = ("RpcError",)
19 |
20 | from ll_mtproto.tl.structure import Structure
21 |
22 |
23 | class RpcError(BaseException):
24 | __slots__ = ("code", "message", "error_description")
25 |
26 | code: int
27 | message: str
28 | error_description: str | None
29 |
30 | def __init__(self, code: int, message: str, error_description: str | None):
31 | self.code = code
32 | self.message = message
33 | self.error_description = error_description
34 |
35 | @staticmethod
36 | def from_rpc_error(error: Structure) -> "RpcError":
37 | if error != "rpc_error":
38 | raise TypeError(f"Expected `rpc_error` Found `{error!r}`")
39 |
40 | return RpcError(error.error_code, error.error_message, None)
41 |
42 | def __str__(self) -> str:
43 | return f"RpcError {self.code} {repr(self.message)} {repr(self.error_description) if self.error_description is not None else ''}"
44 |
45 | def __repr__(self) -> str:
46 | return f"RpcError({self.code}, {repr(self.message)}, {repr(self.error_description)})"
47 |
--------------------------------------------------------------------------------
/ll_mtproto/client/update.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | from ll_mtproto.tl.structure import Structure
19 |
20 | __all__ = ("Update",)
21 |
22 |
23 | class Update:
24 | __slots__ = ("users", "chats", "update")
25 |
26 | users: list[Structure]
27 | chats: list[Structure]
28 | update: Structure
29 |
30 | def __init__(self, users: list[Structure], chats: list[Structure], update: Structure):
31 | self.users = users
32 | self.chats = chats
33 | self.update = update
34 |
--------------------------------------------------------------------------------
/ll_mtproto/constants.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import os.path
19 |
20 | from ll_mtproto.crypto.public_rsa import PublicRSA
21 | from ll_mtproto.network.datacenter_info import DatacenterInfo
22 | from ll_mtproto.tl.tl import Schema
23 |
24 | __all__ = ("TelegramDatacenter", "TelegramTestDatacenter")
25 |
26 |
27 | def _get_schema(resources_path: str) -> Schema:
28 | result = Schema()
29 | result.extend_from_raw_schema(open(os.path.join(resources_path, "auth.tl")).read())
30 | result.extend_from_raw_schema(open(os.path.join(resources_path, "application.tl")).read())
31 | result.extend_from_raw_schema(open(os.path.join(resources_path, "service.tl")).read())
32 |
33 | return result
34 |
35 |
36 | def _get_public_rsa(public_rsa_file_path: str) -> PublicRSA:
37 | telegram_rsa = open(public_rsa_file_path).read()
38 | return PublicRSA(telegram_rsa)
39 |
40 |
41 | _ll_mtproto_resources_path = os.path.join(os.path.dirname(__file__), "resources")
42 | _telegram_public_rsa = _get_public_rsa(os.path.join(_ll_mtproto_resources_path, "telegram.rsa.pub"))
43 | _telegram_test_public_rsa = _get_public_rsa(os.path.join(_ll_mtproto_resources_path, "telegram.test.rsa.pub"))
44 | _telegram_api_schema = _get_schema(_ll_mtproto_resources_path)
45 |
46 |
47 | class TelegramTestDatacenter:
48 | __slots__ = ()
49 |
50 | SCHEMA = _telegram_api_schema
51 | PUBLIC_RSA = _telegram_test_public_rsa
52 |
53 | PLUTO = DatacenterInfo("149.154.175.10", 443, _telegram_test_public_rsa, _telegram_api_schema, 1, False, True)
54 | VENUS = DatacenterInfo("149.154.167.40", 443, _telegram_test_public_rsa, _telegram_api_schema, 2, False, True)
55 | AURORA = DatacenterInfo("149.154.175.117", 443, _telegram_test_public_rsa, _telegram_api_schema, 3, False, True)
56 |
57 | ALL_MAIN_DATACENTERS: frozenset[DatacenterInfo] = frozenset((PLUTO, VENUS, AURORA))
58 | ALL_MEDIA_DATACENTERS: frozenset[DatacenterInfo] = frozenset()
59 | ALL_DATACENTERS: frozenset[DatacenterInfo] = ALL_MAIN_DATACENTERS
60 |
61 |
62 | class TelegramDatacenter:
63 | __slots__ = ()
64 |
65 | SCHEMA = _telegram_api_schema
66 | PUBLIC_RSA = _telegram_public_rsa
67 |
68 | PLUTO = DatacenterInfo("149.154.175.50", 443, _telegram_public_rsa, _telegram_api_schema, 1, False, False)
69 | VENUS = DatacenterInfo("149.154.167.51", 443, _telegram_public_rsa, _telegram_api_schema, 2, False, False)
70 | AURORA = DatacenterInfo("149.154.175.100", 443, _telegram_public_rsa, _telegram_api_schema, 3, False, False)
71 | VESTA = DatacenterInfo("149.154.167.91", 443, _telegram_public_rsa, _telegram_api_schema, 4, False, False)
72 | FLORA = DatacenterInfo("149.154.171.5", 443, _telegram_public_rsa, _telegram_api_schema, 5, False, False)
73 |
74 | VENUS_MEDIA = DatacenterInfo("149.154.167.151", 443, _telegram_public_rsa, _telegram_api_schema, 2, True, False)
75 | VESTA_MEDIA = DatacenterInfo("149.154.164.250", 443, _telegram_public_rsa, _telegram_api_schema, 4, True, False)
76 |
77 | ALL_MAIN_DATACENTERS: frozenset[DatacenterInfo] = frozenset((PLUTO, VENUS, AURORA, VESTA, FLORA))
78 | ALL_MEDIA_DATACENTERS: frozenset[DatacenterInfo] = frozenset((VENUS_MEDIA, VESTA_MEDIA))
79 | ALL_DATACENTERS: frozenset[DatacenterInfo] = frozenset((*ALL_MAIN_DATACENTERS, *ALL_MEDIA_DATACENTERS))
80 |
--------------------------------------------------------------------------------
/ll_mtproto/crypto/aes_ige.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | from ll_mtproto.crypto.providers.crypto_provider_base import CryptoProviderBase
19 | from ll_mtproto.tl.byteutils import short_hex, sha1
20 | from ll_mtproto.typed import InThread, PartialByteReader
21 |
22 | __all__ = ("AesIge", "AesIgeAsyncStream")
23 |
24 |
25 | class AesIge:
26 | __slots__ = ("_key", "_iv", "_crypto_provider")
27 |
28 | _key: bytes
29 | _iv: bytes
30 | _crypto_provider: CryptoProviderBase
31 |
32 | def __init__(self, key: bytes, iv: bytes, crypto_provider: CryptoProviderBase):
33 | if len(key) != 32:
34 | raise ValueError(f"AES key length must be 32 bytes, got {len(key):d} bytes: {short_hex(key)}")
35 |
36 | if len(iv) != 32:
37 | raise ValueError(f"AES init vector length must be 32 bytes, got {len(iv):d} bytes: {short_hex(key)}")
38 |
39 | self._key = key
40 | self._iv = iv
41 | self._crypto_provider = crypto_provider
42 |
43 | def decrypt(self, cipher: bytes) -> bytes:
44 | if len(cipher) % 16 != 0:
45 | raise ValueError(f"Encrypted length must be divisible by 16 bytes")
46 |
47 | return self._crypto_provider.decrypt_aes_ige(cipher, self._key, self._iv)
48 |
49 | def encrypt(self, plain: bytes) -> bytes:
50 | padded_plain = plain + self._crypto_provider.secure_random((-len(plain)) % 16)
51 | return self._crypto_provider.encrypt_aes_ige(padded_plain, self._key, self._iv)
52 |
53 | def encrypt_with_hash(self, plain: bytes) -> bytes:
54 | return self.encrypt(sha1(plain) + plain)
55 |
56 | def decrypt_with_hash(self, cipher: bytes) -> tuple[bytes, bytes]:
57 | plain_with_hash = self.decrypt(cipher)
58 | return plain_with_hash[:20], plain_with_hash[20:]
59 |
60 |
61 | class AesIgeAsyncStream:
62 | __slots__ = ("_plain_buffer", "_aes", "_in_thread", "_parent")
63 |
64 | _plain_buffer: bytearray
65 | _aes: AesIge
66 | _in_thread: InThread
67 | _parent: PartialByteReader
68 |
69 | def __init__(self, aes: AesIge, in_thread: InThread, parent: PartialByteReader):
70 | self._aes = aes
71 | self._in_thread = in_thread
72 | self._parent = parent
73 | self._plain_buffer = bytearray()
74 |
75 | async def __call__(self, nbytes: int) -> bytes:
76 | while len(self._plain_buffer) < nbytes:
77 | encrypted_buffer = await self._parent()
78 | self._plain_buffer += await self._in_thread(lambda: self._aes.decrypt(encrypted_buffer))
79 |
80 | plain = self._plain_buffer[:nbytes]
81 | del self._plain_buffer[:nbytes]
82 | return bytes(plain)
83 |
84 | def remaining_plain_buffer(self) -> bytes:
85 | return bytes(self._plain_buffer)
86 |
--------------------------------------------------------------------------------
/ll_mtproto/crypto/auth_key.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | # This program is distributed in the hope that it will be useful,
9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | # GNU Affero General Public License for more details.
12 | # You should have received a copy of the GNU Affero General Public License
13 | # along with this program. If not, see .
14 |
15 |
16 | import secrets
17 | import time
18 | import typing
19 |
20 | from ll_mtproto.tl.byteutils import sha1
21 |
22 | __all__ = ("AuthKey", "Key", "AuthKeyUpdatedCallback", "DhGenKey")
23 |
24 | AuthKeyUpdatedCallback = typing.Callable[[], typing.Any]
25 |
26 |
27 | class AuthKeyUpdatedCallbackHolder:
28 | __slots__ = ("on_content_change_callback",)
29 |
30 | on_content_change_callback: AuthKeyUpdatedCallback
31 |
32 | def __init__(self, callback: AuthKeyUpdatedCallback) -> None:
33 | self.on_content_change_callback = callback
34 |
35 | def set_content_change_callback(self, callback: AuthKeyUpdatedCallback) -> None:
36 | self.on_content_change_callback = callback
37 |
38 |
39 | class KeySession:
40 | __slots__ = ("id", "seqno", "ping_id", "stable_seqno", "seqno_increment")
41 |
42 | id: int
43 | seqno: int
44 | ping_id: int
45 | stable_seqno: bool
46 | seqno_increment: int
47 |
48 | def __init__(
49 | self,
50 | session_id: int | None = None,
51 | seqno: int | None = None,
52 | ping_id: int | None = None,
53 | stable_seqno: bool = True,
54 | seqno_increment: int = 1
55 | ):
56 | self.id = session_id or self.generate_new_session_id()
57 | self.seqno = seqno or 0
58 | self.ping_id = ping_id or 0
59 | self.stable_seqno = stable_seqno
60 | self.seqno_increment = seqno_increment
61 |
62 | def _get_and_increment_seqno(self) -> int:
63 | value = self.seqno
64 | self.seqno += 1
65 | return value
66 |
67 | def get_next_odd_seqno(self) -> int:
68 | return (self._get_and_increment_seqno()) * 2 + 1
69 |
70 | def get_next_even_seqno(self) -> int:
71 | return (self._get_and_increment_seqno()) * 2
72 |
73 | def __getstate__(self) -> dict[str, typing.Any]:
74 | return {
75 | "id": self.id,
76 | "seqno": self.seqno,
77 | "ping_id": self.ping_id,
78 | "stable_seqno": self.stable_seqno,
79 | "seqno_increment": self.seqno_increment
80 | }
81 |
82 | def __setstate__(self, state: dict[str, typing.Any]) -> None:
83 | self.id = state["id"]
84 | self.seqno = state.get("seqno", 0)
85 | self.ping_id = state.get("ping_id", 0)
86 | self.stable_seqno = state.get("stable_seqno", True)
87 | self.seqno_increment = state.get("seqno_increment", 1)
88 |
89 | @staticmethod
90 | def generate_new_session_id() -> int:
91 | return 0xabcd000000000000 | (secrets.randbits(64) & 0x0000ffffffffffff)
92 |
93 |
94 | class DhGenKey:
95 | __slots__ = ("auth_key", "auth_key_id", "server_salt", "session", "expire_at")
96 |
97 | auth_key: None | bytes
98 | auth_key_id: None | int
99 | server_salt: None | int
100 | session: KeySession
101 | expire_at: None | int
102 |
103 | def __init__(self) -> None:
104 | self.auth_key = None
105 | self.auth_key_id = None
106 | self.server_salt = None
107 | self.expire_at = None
108 | self.session = KeySession()
109 |
110 | def get_or_assert_empty(self) -> tuple[bytes, int, KeySession]:
111 | auth_key, auth_key_id, session = self.auth_key, self.auth_key_id, self.session
112 |
113 | if auth_key is None or auth_key_id is None:
114 | raise AssertionError("key is empty")
115 |
116 | return auth_key, auth_key_id, session
117 |
118 |
119 | class Key:
120 | __slots__ = (
121 | "auth_key",
122 | "auth_key_id",
123 | "server_salt",
124 | "session",
125 | "unused_sessions",
126 | "created_at",
127 | "expire_at",
128 | "_update_callback",
129 | )
130 |
131 | auth_key: None | bytes
132 | auth_key_id: None | int
133 | server_salt: None | int
134 | session: KeySession
135 | unused_sessions: set[int]
136 | created_at: None | float
137 | expire_at: None | int
138 | _update_callback: AuthKeyUpdatedCallbackHolder
139 |
140 | def __init__(
141 | self,
142 | update_callback: AuthKeyUpdatedCallbackHolder,
143 | auth_key: bytes | None = None,
144 | server_salt: int | None = None,
145 | created_at: int | None = None,
146 | expire_at: int | None = None
147 | ):
148 | self._update_callback = update_callback
149 | self.auth_key = auth_key
150 | self.server_salt = server_salt
151 | self.created_at = created_at
152 | self.expire_at = expire_at
153 |
154 | self.session = KeySession()
155 | self.unused_sessions = set()
156 |
157 | self.auth_key_id = self.generate_auth_key_id(auth_key)
158 |
159 | def __getstate__(self) -> dict[str, typing.Any]:
160 | return {
161 | "auth_key": self.auth_key,
162 | "auth_key_id": self.auth_key_id,
163 | "server_salt": self.server_salt,
164 | "session": self.session,
165 | "unused_sessions": self.unused_sessions,
166 | "created_at": self.created_at,
167 | "expire_at": self.expire_at
168 | }
169 |
170 | def __setstate__(self, state: dict[str, typing.Any]) -> None:
171 | self.auth_key = state["auth_key"]
172 | self.auth_key_id = state["auth_key_id"]
173 | self.server_salt = state["server_salt"]
174 | self.session = state["session"]
175 | self.unused_sessions = state["unused_sessions"]
176 | self.created_at = state.get("created_at", -1.)
177 | self.expire_at = state.get("expire_at", None)
178 |
179 | @staticmethod
180 | def generate_auth_key_id(auth_key: bytes | None) -> int | None:
181 | auth_key_id = sha1(auth_key)[-8:] if auth_key else None
182 | return int.from_bytes(auth_key_id, "little", signed=False) if auth_key_id else None
183 |
184 | def flush_changes(self) -> None:
185 | self._update_callback.on_content_change_callback()
186 |
187 | def is_empty(self) -> bool:
188 | return self.auth_key is None or self.auth_key_id is None
189 |
190 | def generate_new_unique_session_id(self) -> None:
191 | if (old_session := self.session).seqno > 0:
192 | self.unused_sessions.add(old_session.id)
193 |
194 | new_session_id = KeySession.generate_new_session_id()
195 |
196 | while new_session_id in self.unused_sessions:
197 | new_session_id = KeySession.generate_new_session_id()
198 |
199 | self.session = KeySession(session_id=new_session_id)
200 |
201 | def import_dh_gen_key(self, dh_gen_key: DhGenKey) -> None:
202 | self.created_at = time.time()
203 |
204 | self.auth_key = dh_gen_key.auth_key
205 | self.auth_key_id = dh_gen_key.auth_key_id
206 | self.server_salt = dh_gen_key.server_salt
207 | self.expire_at = dh_gen_key.expire_at
208 |
209 | if (old_session := self.session).seqno > 0:
210 | self.unused_sessions.add(old_session.id)
211 |
212 | self.session = dh_gen_key.session
213 |
214 | def get_or_assert_empty(self) -> tuple[bytes, int, KeySession]:
215 | auth_key, auth_key_id, session = self.auth_key, self.auth_key_id, self.session
216 |
217 | if auth_key is None or auth_key_id is None:
218 | raise AssertionError("key is empty")
219 |
220 | return auth_key, auth_key_id, session
221 |
222 | def is_fresh_key(self) -> bool:
223 | if (created_at := self.created_at) is not None:
224 | return (time.time() - created_at) < 60.
225 |
226 | return False
227 |
228 | def clear_key(self) -> None:
229 | self.auth_key = None
230 | self.auth_key_id = None
231 | self.server_salt = None
232 | self.session = KeySession()
233 | self.created_at = -1.
234 |
235 | def get_next_odd_seqno(self) -> int:
236 | return self.session.get_next_odd_seqno()
237 |
238 | def get_next_even_seqno(self) -> int:
239 | return self.session.get_next_even_seqno()
240 |
241 |
242 | class AuthKey:
243 | __slots__ = ("persistent_key", "temporary_key", "_update_callback")
244 |
245 | _update_callback: AuthKeyUpdatedCallbackHolder
246 | persistent_key: Key
247 | temporary_key: Key
248 |
249 | def __init__(self, persistent_key: Key | None = None, temporary_key: Key | None = None):
250 | self._update_callback = AuthKeyUpdatedCallbackHolder(self._stub_on_content_change)
251 | self.persistent_key = persistent_key or Key(self._update_callback)
252 | self.temporary_key = temporary_key or Key(self._update_callback)
253 |
254 | def _stub_on_content_change(self) -> None:
255 | pass
256 |
257 | def set_content_change_callback(self, callback: AuthKeyUpdatedCallback) -> None:
258 | self._update_callback.set_content_change_callback(callback)
259 |
260 | def __getstate__(self) -> dict[str, typing.Any]:
261 | return {
262 | "persistent_key": self.persistent_key,
263 | "temporary_key": self.temporary_key
264 | }
265 |
266 | def __setstate__(self, state: dict[str, typing.Any]) -> None:
267 | self.persistent_key = state["persistent_key"]
268 | self.temporary_key = state["temporary_key"]
269 |
270 | self._update_callback = AuthKeyUpdatedCallbackHolder(self._stub_on_content_change)
271 | self.persistent_key._update_callback = self._update_callback
272 | self.temporary_key._update_callback = self._update_callback
273 |
--------------------------------------------------------------------------------
/ll_mtproto/crypto/providers/crypto_provider_base.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 | import abc
18 |
19 | __all__ = ("CryptoProviderBase",)
20 |
21 |
22 | class CryptoProviderBase(abc.ABC):
23 | @abc.abstractmethod
24 | def factorize_pq(self, pq: int) -> tuple[int, int]:
25 | raise NotImplementedError()
26 |
27 | @abc.abstractmethod
28 | def secure_random(self, nbytes: int) -> bytes:
29 | raise NotImplementedError()
30 |
31 | @abc.abstractmethod
32 | def decrypt_aes_ige(self, data_in_out: bytes, key: bytes, iv: bytes) -> bytes:
33 | raise NotImplementedError()
34 |
35 | @abc.abstractmethod
36 | def encrypt_aes_ige(self, data_in_out: bytes, key: bytes, iv: bytes) -> bytes:
37 | raise NotImplementedError()
38 |
--------------------------------------------------------------------------------
/ll_mtproto/crypto/providers/crypto_provider_cryptg.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 | import typing
18 | import secrets
19 |
20 | import cryptg
21 |
22 | from ll_mtproto.crypto.providers.crypto_provider_base import CryptoProviderBase
23 |
24 | __all__ = ("CryptoProviderCryptg",)
25 |
26 |
27 | _TYPED_decrypt_ige = typing.cast(typing.Callable[[bytes, bytes, bytes], bytes], cryptg.decrypt_ige)
28 | _TYPED_encrypt_ige = typing.cast(typing.Callable[[bytes, bytes, bytes], bytes], cryptg.encrypt_ige)
29 | _TYPED_factorize_pq_pair = typing.cast(typing.Callable[[int], tuple[int, int]], cryptg.factorize_pq_pair)
30 |
31 |
32 | class CryptoProviderCryptg(CryptoProviderBase):
33 | def factorize_pq(self, pq: int) -> tuple[int, int]:
34 | return _TYPED_factorize_pq_pair(pq)
35 |
36 | def decrypt_aes_ige(self, data_in_out: bytes, key: bytes, iv: bytes) -> bytes:
37 | return _TYPED_decrypt_ige(data_in_out, key, iv)
38 |
39 | def encrypt_aes_ige(self, data_in_out: bytes, key: bytes, iv: bytes) -> bytes:
40 | return _TYPED_encrypt_ige(data_in_out, key, iv)
41 |
42 | def secure_random(self, nbytes: int) -> bytes:
43 | return secrets.token_bytes(nbytes)
44 |
--------------------------------------------------------------------------------
/ll_mtproto/crypto/public_rsa.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import base64
19 | import hashlib
20 | import re
21 | import typing
22 |
23 | from ll_mtproto.crypto.aes_ige import AesIge
24 | from ll_mtproto.crypto.providers.crypto_provider_base import CryptoProviderBase
25 | from ll_mtproto.tl.byteutils import to_bytes, xor, sha256
26 | from ll_mtproto.tl.tl import pack_binary_string, NativeByteReader
27 | from ll_mtproto.typed import SyncByteReader
28 |
29 | __all__ = ("PublicRSA",)
30 |
31 | _rsa_public_key_RE = re.compile(
32 | r"-----BEGIN RSA PUBLIC KEY-----(?P.*)-----END RSA PUBLIC KEY-----", re.S
33 | )
34 |
35 | _Asn1Field = typing.Union[bytes, typing.List['_Asn1Field']]
36 |
37 |
38 | class PublicRSA:
39 | __slots__ = ("fingerprint", "n", "e")
40 |
41 | fingerprint: int
42 | n: int
43 | e: int
44 |
45 | def __init__(self, pem_data: str):
46 | match = _rsa_public_key_RE.match(pem_data)
47 |
48 | if not match:
49 | raise SyntaxError("Error parsing public key data")
50 |
51 | asn1 = base64.standard_b64decode(match.groupdict()["key"])
52 | n, e = self._read_asn1(NativeByteReader(asn1))
53 |
54 | if not isinstance(n, bytes):
55 | raise SyntaxError(f"Error parsing public key data, the N field is not a buffer `{n!r}`")
56 |
57 | if not isinstance(e, bytes):
58 | raise SyntaxError(f"Error parsing public key data, the E field is not a buffer `{e!r}`")
59 |
60 | self.fingerprint = int.from_bytes(
61 | hashlib.sha1(pack_binary_string(n[1:]) + pack_binary_string(e)).digest()[-8:],
62 | "little",
63 | signed=True,
64 | )
65 |
66 | self.n = int.from_bytes(n, "big", signed=False)
67 | self.e = int.from_bytes(e, "big")
68 |
69 | @staticmethod
70 | def _read_asn1(reader: SyncByteReader) -> _Asn1Field:
71 | field_type, field_length = reader(2)
72 |
73 | if field_length & 0x80:
74 | field_length = int.from_bytes(reader(field_length ^ 0x80), "big")
75 |
76 | if field_type == 0x30:
77 | sequence = []
78 |
79 | while reader:
80 | sequence.append(PublicRSA._read_asn1(reader))
81 |
82 | return sequence
83 |
84 | elif field_type == 0x02:
85 | return reader(field_length)
86 |
87 | else:
88 | raise NotImplementedError("Unknown ASN.1 field `%02X` in record")
89 |
90 | def encrypt(self, data: bytes, crypto_provider: CryptoProviderBase) -> bytes:
91 | padding_length = max(0, 255 - len(data))
92 | m = int.from_bytes(data + crypto_provider.secure_random(padding_length), "big")
93 | x = pow(m, self.e, self.n)
94 | return to_bytes(x)
95 |
96 | def rsa_pad(self, data: bytes, crypto_provider: CryptoProviderBase) -> bytes:
97 | if len(data) > 144:
98 | raise TypeError("Plain data length is more that 144 bytes")
99 |
100 | data_with_padding = data + crypto_provider.secure_random(-len(data) % 192)
101 | data_pad_reversed = data_with_padding[::-1]
102 |
103 | while True:
104 | temp_key = crypto_provider.secure_random(32)
105 | temp_key_aes = AesIge(temp_key, b"\0" * 32, crypto_provider)
106 |
107 | data_with_hash = data_pad_reversed + sha256(temp_key + data_with_padding)
108 | encrypted_data_with_hash = temp_key_aes.encrypt(data_with_hash)
109 |
110 | temp_key_xor = xor(temp_key, sha256(encrypted_data_with_hash))
111 | key_aes_encrypted = temp_key_xor + encrypted_data_with_hash
112 |
113 | if self.n > int.from_bytes(key_aes_encrypted, "big", signed=False):
114 | break
115 |
116 | return key_aes_encrypted
117 |
--------------------------------------------------------------------------------
/ll_mtproto/math/primes.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import functools
19 | import random
20 |
21 | __all__ = ("is_safe_dh_prime", "miller_rabin")
22 |
23 |
24 | @functools.lru_cache()
25 | def miller_rabin(num: int, trials: int) -> bool:
26 | s = num - 1
27 | t = 0
28 |
29 | while s % 2 == 0:
30 | s = s // 2
31 | t += 1
32 |
33 | for _ in range(trials):
34 | a = random.randrange(2, num - 1)
35 | v = pow(a, s, num)
36 |
37 | if v != 1:
38 | i = 0
39 |
40 | while v != (num - 1):
41 | if i == t - 1:
42 | return False
43 | else:
44 | i = i + 1
45 | v = (v ** 2) % num
46 |
47 | return True
48 |
49 |
50 | @functools.lru_cache()
51 | def is_safe_dh_prime(g: int, n: int) -> bool:
52 | if n < 0:
53 | return False
54 |
55 | if n.bit_length() != 2048:
56 | return False
57 |
58 | if not miller_rabin(n, 30):
59 | return False
60 |
61 | if not miller_rabin((n - 1) // 2, 30):
62 | return False
63 |
64 | match g:
65 | case 2:
66 | if n % 8 != 7:
67 | return False
68 |
69 | case 3:
70 | if n % 3 != 2:
71 | return False
72 |
73 | case 4:
74 | pass
75 |
76 | case 5:
77 | if n % 5 not in (1, 4):
78 | return False
79 |
80 | case 6:
81 | if n % 24 not in (19, 23):
82 | return False
83 |
84 | case 7:
85 | if n % 7 not in (3, 5, 6):
86 | return False
87 |
88 | case _:
89 | return False
90 |
91 | return True
92 |
--------------------------------------------------------------------------------
/ll_mtproto/network/auth_key_not_found_exception.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | __all__ = ("AuthKeyNotFoundException",)
19 |
20 |
21 | class AuthKeyNotFoundException(BaseException):
22 | pass
23 |
--------------------------------------------------------------------------------
/ll_mtproto/network/datacenter_info.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import time
19 |
20 | from ll_mtproto.crypto.public_rsa import PublicRSA
21 | from ll_mtproto.tl.tl import Schema
22 |
23 | __all__ = ("DatacenterInfo",)
24 |
25 |
26 | class DatacenterInfo:
27 | __slots__ = (
28 | "default_direct_address",
29 | "default_direct_port",
30 | "public_rsa",
31 | "schema",
32 | "datacenter_id",
33 | "is_media",
34 | "_time_difference",
35 | "is_test"
36 | )
37 |
38 | default_direct_address: str
39 | default_direct_port: int
40 | public_rsa: PublicRSA
41 | schema: Schema
42 | datacenter_id: int
43 | is_media: bool
44 | is_test: bool
45 |
46 | _time_difference: int
47 |
48 | def __init__(self, address: str, port: int, public_rsa: PublicRSA, schema: Schema, datacenter_id: int, is_media: bool, is_test: bool):
49 | self.default_direct_address = address
50 | self.default_direct_port = port
51 | self.public_rsa = public_rsa
52 | self.schema = schema
53 | self.datacenter_id = datacenter_id
54 | self.is_media = is_media
55 | self._time_difference = 0
56 | self.is_test = is_test
57 |
58 | def set_synchronized_time(self, synchronized_now: int) -> None:
59 | self._time_difference = synchronized_now - int(time.time())
60 |
61 | def get_synchronized_time(self) -> int:
62 | return int(time.time()) + self._time_difference
63 |
64 | def __copy__(self) -> "DatacenterInfo":
65 | return DatacenterInfo(
66 | self.default_direct_address,
67 | self.default_direct_port,
68 | self.public_rsa,
69 | self.schema,
70 | self.datacenter_id,
71 | self.is_media,
72 | self.is_test
73 | )
74 |
75 | def __str__(self) -> str:
76 | return f"{'media' if self.is_media else 'main'} {'test' if self.is_test else 'prod'} datacenter {self.datacenter_id} with layer {self.schema.layer}"
77 |
--------------------------------------------------------------------------------
/ll_mtproto/network/dh/mtproto_key_binder_dispatcher.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 | import asyncio
18 |
19 | from ll_mtproto.client.rpc_error import RpcError
20 | from ll_mtproto.crypto.auth_key import Key
21 | from ll_mtproto.crypto.providers.crypto_provider_base import CryptoProviderBase
22 | from ll_mtproto.network.datacenter_info import DatacenterInfo
23 | from ll_mtproto.network.dispatcher import Dispatcher
24 | from ll_mtproto.network.mtproto import MTProto
25 | from ll_mtproto.tl.byteutils import sha1
26 | from ll_mtproto.tl.structure import Structure
27 | from ll_mtproto.typed import InThread
28 |
29 | __all__ = ("MTProtoKeyBinderDispatcher",)
30 |
31 |
32 | class MTProtoKeyBinderDispatcher(Dispatcher):
33 | __slots__ = ("_persistent_key", "_used_key", "_result", "_req_msg_id", "_parent_dispatcher", "_datacenter")
34 |
35 | _persistent_key: Key
36 | _used_key: Key
37 | _result: asyncio.Future[None]
38 | _req_msg_id: int
39 | _parent_dispatcher: Dispatcher
40 | _datacenter: DatacenterInfo
41 |
42 | @staticmethod
43 | async def initialize(
44 | persistent_key: Key,
45 | used_key: Key,
46 | in_thread: InThread,
47 | datacenter: DatacenterInfo,
48 | mtproto: MTProto,
49 | crypto_provider: CryptoProviderBase,
50 | parent_dispatcher: Dispatcher,
51 | expire_at: int
52 | ) -> tuple["MTProtoKeyBinderDispatcher", asyncio.Future[None]]:
53 | req_msg_id = mtproto.get_next_message_id()
54 |
55 | perm_auth_key_key, perm_auth_key_id, _ = persistent_key.get_or_assert_empty()
56 | used_auth_key_key, used_auth_key_id, used_key_session = used_key.get_or_assert_empty()
57 |
58 | bind_temp_auth_nonce = int.from_bytes(await in_thread(lambda: crypto_provider.secure_random(8)), "big", signed=True)
59 |
60 | bind_temp_auth_inner = datacenter.schema.boxed_kwargs(
61 | _cons="bind_auth_key_inner",
62 | nonce=bind_temp_auth_nonce,
63 | temp_auth_key_id=used_auth_key_id,
64 | perm_auth_key_id=perm_auth_key_id,
65 | temp_session_id=used_key_session.id,
66 | expires_at=expire_at
67 | )
68 |
69 | bind_temp_auth_inner_data = datacenter.schema.bare_kwargs(
70 | _cons="message_inner_data",
71 | salt=int.from_bytes(await in_thread(lambda: crypto_provider.secure_random(8)), "big", signed=True),
72 | session_id=int.from_bytes(await in_thread(lambda: crypto_provider.secure_random(8)), "big", signed=False),
73 | message=datacenter.schema.bare_kwargs(
74 | _cons="message_from_client",
75 | msg_id=req_msg_id,
76 | seqno=0,
77 | body=bind_temp_auth_inner
78 | ),
79 | ).get_flat_bytes()
80 |
81 | bind_temp_auth_inner_data_sha1 = await in_thread(lambda: sha1(bind_temp_auth_inner_data))
82 | bind_temp_auth_inner_data_msg_key = bind_temp_auth_inner_data_sha1[4:20]
83 |
84 | bind_temp_auth_inner_data_aes = await in_thread(lambda: MTProto.prepare_key_v1_write(
85 | perm_auth_key_key,
86 | bind_temp_auth_inner_data_msg_key,
87 | crypto_provider
88 | ))
89 |
90 | bind_temp_auth_inner_data_encrypted = await in_thread(lambda: bind_temp_auth_inner_data_aes.encrypt(bind_temp_auth_inner_data))
91 |
92 | bind_temp_auth_inner_data_encrypted_boxed = datacenter.schema.bare_kwargs(
93 | _cons="encrypted_message",
94 | auth_key_id=perm_auth_key_id,
95 | msg_key=bind_temp_auth_inner_data_msg_key,
96 | encrypted_data=bind_temp_auth_inner_data_encrypted,
97 | )
98 |
99 | bind_temp_auth_message = datacenter.schema.boxed_kwargs(
100 | _cons="auth.bindTempAuthKey",
101 | perm_auth_key_id=perm_auth_key_id,
102 | nonce=bind_temp_auth_nonce,
103 | expires_at=expire_at,
104 | encrypted_message=bind_temp_auth_inner_data_encrypted_boxed.get_flat_bytes()
105 | )
106 |
107 | bind_temp_auth_boxed_message = datacenter.schema.bare_kwargs(
108 | _cons="message_from_client",
109 | msg_id=req_msg_id,
110 | seqno=used_key_session.get_next_odd_seqno(),
111 | body=bind_temp_auth_message,
112 | )
113 |
114 | await mtproto.write_encrypted(bind_temp_auth_boxed_message, used_key)
115 |
116 | result = asyncio.get_running_loop().create_future()
117 | return MTProtoKeyBinderDispatcher(persistent_key, used_key, result, req_msg_id, parent_dispatcher, datacenter), result
118 |
119 | def __init__(
120 | self,
121 | persistent_key: Key,
122 | used_key: Key,
123 | result: asyncio.Future[None],
124 | req_msg_id: int,
125 | parent_dispatcher: Dispatcher,
126 | datacenter: DatacenterInfo,
127 | ) -> None:
128 | self._persistent_key = persistent_key
129 | self._used_key = used_key
130 | self._result = result
131 | self._req_msg_id = req_msg_id
132 | self._parent_dispatcher = parent_dispatcher
133 | self._datacenter = datacenter
134 |
135 | async def process_telegram_message_body(self, body: Structure, crypto_flag: bool) -> None:
136 | if not crypto_flag:
137 | raise TypeError(f"Expected an encrypted message, found `{body!r}`")
138 |
139 | if body == "new_session_created" or body == "msgs_ack":
140 | return await self._parent_dispatcher.process_telegram_message_body(body, True)
141 |
142 | if body != "rpc_result":
143 | raise RuntimeError("Diffie–Hellman exchange failed: `%r`, unexpected message", body)
144 |
145 | if body.req_msg_id != self._req_msg_id:
146 | raise RuntimeError("Diffie–Hellman exchange failed: `%r`, unexpected req_msg_id", body)
147 |
148 | bool_true_cons = self._datacenter.schema.constructors.get("boolTrue", None)
149 |
150 | if bool_true_cons is None:
151 | raise TypeError(f"Unable to find bool_true constructor")
152 |
153 | rpc_error_cons = self._datacenter.schema.constructors.get("rpc_error", None)
154 |
155 | if rpc_error_cons is None:
156 | raise TypeError(f"Unable to find rpc_error constructor")
157 |
158 | if bool_true_cons.boxed_buffer_match(body.result):
159 | return self._result.set_result(None)
160 |
161 | if rpc_error_cons.boxed_buffer_match(body.result):
162 | raise RpcError.from_rpc_error(Structure.from_dict(rpc_error_cons.deserialize_boxed_data(body.result)))
163 |
164 | raise RuntimeError("Diffie–Hellman exchange failed: `%r`, expected response", body)
165 |
166 | async def process_telegram_signaling_message(self, signaling: Structure, crypto_flag: bool) -> None:
167 | if not crypto_flag:
168 | raise TypeError(f"Expected an encrypted signaling, found `{signaling!r}`")
169 |
170 | await self._parent_dispatcher.process_telegram_signaling_message(signaling, crypto_flag)
171 |
--------------------------------------------------------------------------------
/ll_mtproto/network/dh/mtproto_key_creator.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import asyncio
19 | import hashlib
20 | import hmac
21 |
22 | from ll_mtproto.crypto.aes_ige import AesIge
23 | from ll_mtproto.crypto.auth_key import Key, DhGenKey
24 | from ll_mtproto.crypto.providers.crypto_provider_base import CryptoProviderBase
25 | from ll_mtproto.math import primes
26 | from ll_mtproto.network.datacenter_info import DatacenterInfo
27 | from ll_mtproto.network.mtproto import MTProto
28 | from ll_mtproto.tl.byteutils import to_bytes, sha1, xor, SyncByteReaderProxy
29 | from ll_mtproto.tl.structure import Structure
30 | from ll_mtproto.tl.tl import NativeByteReader
31 | from ll_mtproto.typed import InThread
32 |
33 | __all__ = ("MTProtoKeyCreator",)
34 |
35 |
36 | class _KeyExchangeStateWaitingResPq:
37 | def __init__(self) -> None:
38 | pass
39 |
40 |
41 | class _KeyExchangeStateWaitingDhParams:
42 | __slots__ = ("new_nonce", "server_nonce", "temp_key_expires_in")
43 |
44 | new_nonce: bytes
45 | server_nonce: bytes
46 | temp_key_expires_in: int
47 |
48 | def __init__(self, *, new_nonce: bytes, server_nonce: bytes, temp_key_expires_in: int):
49 | self.new_nonce = new_nonce
50 | self.server_nonce = server_nonce
51 | self.temp_key_expires_in = temp_key_expires_in
52 |
53 |
54 | class _KeyExchangeStateWaitingDhGenOk:
55 | __slots__ = ("key", "temp_key_expires_in", "server_nonce", "new_nonce")
56 |
57 | key: DhGenKey
58 | temp_key_expires_in: int
59 | server_nonce: bytes
60 | new_nonce: bytes
61 |
62 | def __init__(self, *, key: DhGenKey, temp_key_expires_in: int, server_nonce: bytes, new_nonce: bytes):
63 | self.key = key
64 | self.temp_key_expires_in = temp_key_expires_in
65 | self.server_nonce = server_nonce
66 | self.new_nonce = new_nonce
67 |
68 |
69 | class _KeyExchangeStateCompleted:
70 | __slots__ = ("key",)
71 |
72 | key: DhGenKey
73 |
74 | def __init__(self, *, key: DhGenKey):
75 | self.key = key
76 |
77 |
78 | class MTProtoKeyCreator:
79 | __slots__ = (
80 | "_mtproto",
81 | "_in_thread",
82 | "_datacenter",
83 | "_crypto_provider",
84 | "_exchange_state",
85 | "_temp_key",
86 | "_nonce",
87 | "_result"
88 | )
89 |
90 | TEMP_AUTH_KEY_EXPIRE_TIME = 24 * 60 * 60
91 |
92 | _in_thread: InThread
93 | _mtproto: MTProto
94 | _datacenter: DatacenterInfo
95 | _crypto_provider: CryptoProviderBase
96 | _temp_key: bool
97 | _exchange_state: _KeyExchangeStateWaitingResPq | _KeyExchangeStateWaitingDhParams | _KeyExchangeStateWaitingDhGenOk | _KeyExchangeStateCompleted
98 | _nonce: bytes
99 | _result: asyncio.Future[DhGenKey]
100 |
101 | @staticmethod
102 | async def initializate(
103 | mtproto: MTProto,
104 | in_thread: InThread,
105 | datacenter: DatacenterInfo,
106 | crypto_provider: CryptoProviderBase,
107 | temp_key: bool,
108 | result: asyncio.Future[DhGenKey]
109 | ) -> "MTProtoKeyCreator":
110 | nonce = await in_thread(lambda: crypto_provider.secure_random(16))
111 | await mtproto.write_unencrypted_message(_cons="req_pq_multi", nonce=nonce)
112 | return MTProtoKeyCreator(mtproto, in_thread, datacenter, crypto_provider, temp_key, nonce, result)
113 |
114 | def __init__(
115 | self,
116 | mtproto: MTProto,
117 | in_thread: InThread,
118 | datacenter: DatacenterInfo,
119 | crypto_provider: CryptoProviderBase,
120 | temp_key: bool,
121 | nonce: bytes,
122 | result: asyncio.Future[DhGenKey]
123 | ):
124 | self._mtproto = mtproto
125 | self._in_thread = in_thread
126 | self._datacenter = datacenter
127 | self._crypto_provider = crypto_provider
128 | self._temp_key = temp_key
129 | self._nonce = nonce
130 | self._exchange_state = _KeyExchangeStateWaitingResPq()
131 | self._result = result
132 |
133 | async def process_telegram_message_body(self, body: Structure) -> None:
134 | match (state := self._exchange_state):
135 | case _KeyExchangeStateWaitingResPq():
136 | await self._process_res_pq(body)
137 |
138 | case _KeyExchangeStateWaitingDhParams():
139 | await self._process_dh_params(body, state)
140 |
141 | case _KeyExchangeStateWaitingDhGenOk():
142 | await self._process_dh_gen_ok(body, state)
143 |
144 | case _KeyExchangeStateCompleted():
145 | pass
146 |
147 | case _:
148 | raise TypeError("Unknown exchange state `%r`", state)
149 |
150 | if isinstance(self._exchange_state, _KeyExchangeStateCompleted):
151 | self._result.set_result(self._exchange_state.key)
152 |
153 | async def _process_dh_gen_ok(self, params3: Structure, state: _KeyExchangeStateWaitingDhGenOk) -> None:
154 | if params3 != "dh_gen_ok":
155 | raise RuntimeError("Diffie–Hellman exchange failed: `%r`", params3)
156 |
157 | if not hmac.compare_digest(params3.nonce, self._nonce):
158 | raise RuntimeError("Diffie–Hellman exchange failed: nonce mismatch: `%r`", params3)
159 |
160 | if not hmac.compare_digest(params3.server_nonce, state.server_nonce):
161 | raise RuntimeError("Diffie–Hellman exchange failed: server nonce mismatch: `%r`", params3)
162 |
163 | new_nonce_hash1 = (await self._in_thread(lambda: sha1(state.new_nonce + b"\1" + sha1(state.key.auth_key)[0:8])))[4:20]
164 |
165 | if not hmac.compare_digest(params3.new_nonce_hash1, new_nonce_hash1):
166 | raise RuntimeError("Diffie–Hellman exchange failed: new nonce hash1 mismatch: `%r`", params3)
167 |
168 | self._exchange_state = _KeyExchangeStateCompleted(key=state.key)
169 |
170 | async def _process_dh_params(self, params: Structure, state: _KeyExchangeStateWaitingDhParams) -> None:
171 | if params != "server_DH_params_ok":
172 | raise RuntimeError("Diffie–Hellman exchange failed: `%r`", params)
173 |
174 | if not hmac.compare_digest(params.nonce, self._nonce):
175 | raise RuntimeError("Diffie–Hellman exchange failed: nonce mismatch: `%r`", params)
176 |
177 | if not hmac.compare_digest(params.server_nonce, state.server_nonce):
178 | raise RuntimeError("Diffie–Hellman exchange failed: params server nonce mismatch")
179 |
180 | tmp_aes_key_1, tmp_aes_key_2, tmp_aes_iv_1, tmp_aes_iv_2 = await asyncio.gather(
181 | self._in_thread(lambda: sha1(state.new_nonce + state.server_nonce)),
182 | self._in_thread(lambda: sha1(state.server_nonce + state.new_nonce)),
183 | self._in_thread(lambda: sha1(state.server_nonce + state.new_nonce)),
184 | self._in_thread(lambda: sha1(state.new_nonce + state.new_nonce))
185 | )
186 |
187 | tmp_aes_key = tmp_aes_key_1 + tmp_aes_key_2[:12]
188 | tmp_aes_iv = tmp_aes_iv_1[12:] + tmp_aes_iv_2 + state.new_nonce[:4]
189 | tmp_aes = AesIge(tmp_aes_key, tmp_aes_iv, self._crypto_provider)
190 |
191 | (answer_hash, answer), b = await asyncio.gather(
192 | self._in_thread(lambda: tmp_aes.decrypt_with_hash(params.encrypted_answer)),
193 | self._in_thread(lambda: int.from_bytes(self._crypto_provider.secure_random(256), signed=False)),
194 | )
195 |
196 | answer_reader = NativeByteReader(answer)
197 | answer_reader_sha1 = hashlib.sha1()
198 | answer_reader_with_hash = SyncByteReaderProxy(answer_reader, answer_reader_sha1.update)
199 |
200 | params2 = Structure.from_dict(await self._in_thread(lambda: self._datacenter.schema.read_by_boxed_data(answer_reader_with_hash)))
201 | answer_hash_computed = await self._in_thread(answer_reader_sha1.digest)
202 |
203 | if not hmac.compare_digest(answer_hash_computed, answer_hash):
204 | raise RuntimeError("Diffie–Hellman exchange failed: params2 hash mismatch")
205 |
206 | if params2 != "server_DH_inner_data":
207 | raise RuntimeError("Diffie–Hellman exchange failed: `%r`", params2)
208 |
209 | if not hmac.compare_digest(params2.nonce, self._nonce):
210 | raise RuntimeError("Diffie–Hellman exchange failed: params2 nonce mismatch")
211 |
212 | if not hmac.compare_digest(params2.server_nonce, state.server_nonce):
213 | raise RuntimeError("Diffie–Hellman exchange failed: params2 server nonce mismatch")
214 |
215 | self._datacenter.set_synchronized_time(params2.server_time)
216 |
217 | dh_prime = int.from_bytes(params2.dh_prime, "big")
218 | g = params2.g
219 | g_a = int.from_bytes(params2.g_a, "big")
220 |
221 | if not await self._in_thread(lambda: primes.is_safe_dh_prime(g, dh_prime)):
222 | raise RuntimeError("Diffie–Hellman exchange failed: unknown dh_prime")
223 |
224 | if g_a <= 1:
225 | raise RuntimeError("Diffie–Hellman exchange failed: g_a <= 1")
226 |
227 | if g_a >= (dh_prime - 1):
228 | raise RuntimeError("Diffie–Hellman exchange failed: g_a >= (dh_prime - 1)")
229 |
230 | if g_a < 2 ** (2048 - 64):
231 | raise RuntimeError("Diffie–Hellman exchange failed: g_a < 2 ** (2048 - 64)")
232 |
233 | if g_a > dh_prime - (2 ** (2048 - 64)):
234 | raise RuntimeError("Diffie–Hellman exchange failed: g_a > dh_prime - (2 ** (2048 - 64))")
235 |
236 | g_b, auth_key = await asyncio.gather(
237 | self._in_thread(lambda: pow(g, b, dh_prime)),
238 | self._in_thread(lambda: pow(g_a, b, dh_prime)),
239 | )
240 |
241 | if g_b <= 1:
242 | raise RuntimeError("Diffie–Hellman exchange failed: g_b <= 1")
243 |
244 | if g_b >= (dh_prime - 1):
245 | raise RuntimeError("Diffie–Hellman exchange failed: g_b >= (dh_prime - 1)")
246 |
247 | if g_b < 2 ** (2048 - 64):
248 | raise RuntimeError("Diffie–Hellman exchange failed: g_b < 2 ** (2048 - 64)")
249 |
250 | if g_b > dh_prime - (2 ** (2048 - 64)):
251 | raise RuntimeError("Diffie–Hellman exchange failed: g_b > dh_prime - (2 ** (2048 - 64))")
252 |
253 | server_salt = int.from_bytes(xor(state.new_nonce[:8], state.server_nonce[:8]), "little", signed=True)
254 |
255 | auth_key_bytes = to_bytes(auth_key)
256 |
257 | if len(auth_key_bytes) < 196:
258 | raise RuntimeError("Diffie–Hellman exchange failed: auth key is too small, this should never happen")
259 |
260 | auth_key_bytes = (b"\0" * (256 - len(auth_key_bytes))) + auth_key_bytes
261 |
262 | new_auth_key = DhGenKey()
263 | new_auth_key.auth_key = auth_key_bytes
264 | new_auth_key.auth_key_id = await self._in_thread(lambda: Key.generate_auth_key_id(auth_key_bytes))
265 | new_auth_key.server_salt = server_salt
266 |
267 | if self._temp_key:
268 | new_auth_key.expire_at = state.temp_key_expires_in
269 |
270 | client_dh_inner_data = self._datacenter.schema.boxed_kwargs(
271 | _cons="client_DH_inner_data",
272 | nonce=self._nonce,
273 | server_nonce=state.server_nonce,
274 | retry_id=0,
275 | g_b=to_bytes(g_b),
276 | ).get_flat_bytes()
277 |
278 | tmp_aes = AesIge(tmp_aes_key, tmp_aes_iv, self._crypto_provider)
279 |
280 | await self._mtproto.write_unencrypted_message(
281 | _cons="set_client_DH_params",
282 | nonce=self._nonce,
283 | server_nonce=state.server_nonce,
284 | encrypted_data=await self._in_thread(lambda: tmp_aes.encrypt_with_hash(client_dh_inner_data)),
285 | )
286 |
287 | self._exchange_state = _KeyExchangeStateWaitingDhGenOk(
288 | key=new_auth_key,
289 | temp_key_expires_in=state.temp_key_expires_in,
290 | server_nonce=state.server_nonce,
291 | new_nonce=state.new_nonce
292 | )
293 |
294 | async def _process_res_pq(self, res_pq: Structure) -> None:
295 | if res_pq != "resPQ":
296 | raise RuntimeError("Diffie–Hellman exchange failed: `%r`", res_pq)
297 |
298 | if not hmac.compare_digest(res_pq.nonce, self._nonce):
299 | raise RuntimeError("Diffie–Hellman exchange failed: nonce mismatch: `%r`", res_pq)
300 |
301 | if self._datacenter.public_rsa.fingerprint not in res_pq.server_public_key_fingerprints:
302 | raise ValueError(f"Our certificate is not supported by the server: `%r`", res_pq)
303 |
304 | server_nonce = res_pq.server_nonce
305 | pq = int.from_bytes(res_pq.pq, "big", signed=False)
306 |
307 | new_nonce, (p, q) = await asyncio.gather(
308 | self._in_thread(lambda: self._crypto_provider.secure_random(32)),
309 | self._in_thread(lambda: self._crypto_provider.factorize_pq(pq)),
310 | )
311 |
312 | p_string = to_bytes(p)
313 | q_string = to_bytes(q)
314 |
315 | if len(p_string) + len(q_string) != 8:
316 | raise RuntimeError("Diffie–Hellman exchange failed: p q length is invalid, `%r`", pq)
317 |
318 | temp_key_expires_in = self.TEMP_AUTH_KEY_EXPIRE_TIME + self._datacenter.get_synchronized_time()
319 |
320 | dc_id = self._datacenter.datacenter_id
321 |
322 | if self._datacenter.is_test:
323 | dc_id += 10000
324 |
325 | if self._datacenter.is_media:
326 | dc_id = -dc_id
327 |
328 | p_q_inner_data = self._datacenter.schema.boxed_kwargs(
329 | _cons="p_q_inner_data_temp_dc" if self._temp_key else "p_q_inner_data_dc",
330 | pq=res_pq.pq,
331 | p=p_string,
332 | q=q_string,
333 | nonce=self._nonce,
334 | server_nonce=server_nonce,
335 | new_nonce=new_nonce,
336 | expires_in=temp_key_expires_in,
337 | dc=dc_id
338 | )
339 |
340 | p_q_inner_data_rsa_pad = await self._in_thread(lambda: self._datacenter.public_rsa.rsa_pad(p_q_inner_data.get_flat_bytes(), self._crypto_provider))
341 | p_q_inner_data_encrypted = await self._in_thread(lambda: self._datacenter.public_rsa.encrypt(p_q_inner_data_rsa_pad, self._crypto_provider))
342 |
343 | await self._mtproto.write_unencrypted_message(
344 | _cons="req_DH_params",
345 | server_nonce=server_nonce,
346 | p=p_string,
347 | q=q_string,
348 | nonce=self._nonce,
349 | public_key_fingerprint=self._datacenter.public_rsa.fingerprint,
350 | encrypted_data=p_q_inner_data_encrypted,
351 | )
352 |
353 | self._exchange_state = _KeyExchangeStateWaitingDhParams(
354 | new_nonce=new_nonce,
355 | server_nonce=server_nonce,
356 | temp_key_expires_in=temp_key_expires_in
357 | )
358 |
--------------------------------------------------------------------------------
/ll_mtproto/network/dh/mtproto_key_creator_dispatcher.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | # This program is distributed in the hope that it will be useful,
9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | # GNU Affero General Public License for more details.
12 | # You should have received a copy of the GNU Affero General Public License
13 | # along with this program. If not, see .
14 |
15 | import asyncio
16 |
17 | from ll_mtproto.crypto.auth_key import DhGenKey
18 | from ll_mtproto.crypto.providers.crypto_provider_base import CryptoProviderBase
19 | from ll_mtproto.network.datacenter_info import DatacenterInfo
20 | from ll_mtproto.network.dh.mtproto_key_creator import MTProtoKeyCreator
21 | from ll_mtproto.network.dispatcher import Dispatcher
22 | from ll_mtproto.network.mtproto import MTProto
23 | from ll_mtproto.tl.structure import Structure
24 | from ll_mtproto.typed import InThread
25 |
26 | __all__ = ("initialize_key_creator_dispatcher", "KeyCreatorDispatcher")
27 |
28 |
29 | class KeyCreatorDispatcher(Dispatcher):
30 | __slots__ = ("_creator", "_mtproto")
31 |
32 | _creator: MTProtoKeyCreator
33 | _mtproto: MTProto
34 |
35 | def __init__(self, creator: MTProtoKeyCreator, mtproto: MTProto):
36 | self._creator = creator
37 | self._mtproto = mtproto
38 |
39 | async def process_telegram_message_body(self, body: Structure, crypto_flag: bool) -> None:
40 | if crypto_flag:
41 | raise TypeError(f"Expected an plaintext message, found `{body!r}`")
42 |
43 | await self._creator.process_telegram_message_body(body)
44 |
45 | async def process_telegram_signaling_message(self, signaling: Structure, crypto_flag: bool) -> None:
46 | if crypto_flag:
47 | raise TypeError(f"Expected an plaintext signaling, found `{signaling!r}`")
48 |
49 | await self._mtproto.write_unencrypted_message(_cons="msgs_ack", msg_ids=[signaling.msg_id])
50 |
51 |
52 | async def initialize_key_creator_dispatcher(
53 | temp_key: bool,
54 | mtproto: MTProto,
55 | in_thread: InThread,
56 | datacenter: DatacenterInfo,
57 | crypto_provider: CryptoProviderBase
58 | ) -> tuple[Dispatcher, asyncio.Future[DhGenKey]]:
59 | result = asyncio.get_running_loop().create_future()
60 | creator = await MTProtoKeyCreator.initializate(mtproto, in_thread, datacenter, crypto_provider, temp_key, result)
61 | return KeyCreatorDispatcher(creator, mtproto), result
62 |
--------------------------------------------------------------------------------
/ll_mtproto/network/dispatcher.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | __all__ = ("Dispatcher", "dispatch_event")
19 |
20 | import abc
21 | import logging
22 |
23 | from ll_mtproto.crypto.auth_key import DhGenKey, Key
24 | from ll_mtproto.network.mtproto import MTProto
25 | from ll_mtproto.tl.structure import Structure
26 |
27 |
28 | class Dispatcher(abc.ABC):
29 | @abc.abstractmethod
30 | async def process_telegram_message_body(self, body: Structure, crypto_flag: bool) -> None:
31 | raise NotImplementedError
32 |
33 | @abc.abstractmethod
34 | async def process_telegram_signaling_message(self, signaling: Structure, crypto_flag: bool) -> None:
35 | raise NotImplementedError
36 |
37 |
38 | async def _process_telegram_message(dispatcher: Dispatcher, signaling: Structure, body: Structure, crypto_flag: bool) -> None:
39 | await dispatcher.process_telegram_signaling_message(signaling, crypto_flag)
40 |
41 | if body == "msg_container":
42 | for m in body.messages:
43 | await _process_telegram_message(dispatcher, m, m.body, crypto_flag)
44 |
45 | else:
46 | await dispatcher.process_telegram_message_body(body, crypto_flag)
47 |
48 |
49 | async def _process_inbound_message(dispatcher: Dispatcher, signaling: Structure, body: Structure, crypto_flag: bool) -> None:
50 | logging.debug("received message (%s) %d from mtproto", body.constructor_name, signaling.msg_id)
51 | await _process_telegram_message(dispatcher, signaling, body, crypto_flag)
52 |
53 |
54 | async def dispatch_event(dispatcher: Dispatcher, mtproto: MTProto, encryption_key: Key | DhGenKey | None) -> None:
55 | if encryption_key is not None:
56 | signaling, body = await mtproto.read_encrypted(encryption_key)
57 | else:
58 | signaling, body = await mtproto.read_unencrypted_message()
59 |
60 | await _process_inbound_message(dispatcher, signaling, body, encryption_key is not None)
61 |
--------------------------------------------------------------------------------
/ll_mtproto/network/mtproto.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import asyncio
19 | import hashlib
20 | import hmac
21 | import logging
22 |
23 | from ll_mtproto.crypto.aes_ige import AesIge, AesIgeAsyncStream
24 | from ll_mtproto.crypto.auth_key import Key, DhGenKey
25 | from ll_mtproto.crypto.providers.crypto_provider_base import CryptoProviderBase
26 | from ll_mtproto.network.auth_key_not_found_exception import AuthKeyNotFoundException
27 | from ll_mtproto.network.datacenter_info import DatacenterInfo
28 | from ll_mtproto.network.transport.transport_link_base import TransportLinkBase
29 | from ll_mtproto.network.transport.transport_link_factory import TransportLinkFactory
30 | from ll_mtproto.tl.byteutils import sha256, ByteReaderApply, sha1
31 | from ll_mtproto.tl.structure import Structure
32 | from ll_mtproto.tl.tl import Constructor, TlBodyDataValue, Value, TlBodyData, NativeByteReader
33 | from ll_mtproto.typed import InThread
34 |
35 | __all__ = ("MTProto",)
36 |
37 |
38 | class MTProto:
39 | __slots__ = (
40 | "_loop",
41 | "_link",
42 | "_read_message_lock",
43 | "_last_message_id",
44 | "_datacenter",
45 | "_in_thread",
46 | "_crypto_provider",
47 | "_unencrypted_message_constructor",
48 | "_message_inner_data_from_server_constructor"
49 | )
50 |
51 | @staticmethod
52 | def prepare_key_v2(auth_key: bytes, msg_key: bytes, read: bool, crypto_provider: CryptoProviderBase) -> AesIge:
53 | x = 0 if read else 8
54 |
55 | sha256a = sha256(msg_key + auth_key[x: x + 36])
56 | sha256b = sha256(auth_key[x + 40:x + 76] + msg_key)
57 |
58 | aes_key = sha256a[:8] + sha256b[8:24] + sha256a[24:32]
59 | aes_iv = sha256b[:8] + sha256a[8:24] + sha256b[24:32]
60 |
61 | return AesIge(aes_key, aes_iv, crypto_provider)
62 |
63 | @staticmethod
64 | def prepare_key_v1_write(auth_key: bytes, msg_key: bytes, crypto_provider: CryptoProviderBase) -> AesIge:
65 | sha1_a = sha1(msg_key + auth_key[:32])
66 | sha1_b = sha1(auth_key[32:48] + msg_key + auth_key[48:64])
67 | sha1_c = sha1(auth_key[64:96] + msg_key)
68 | sha1_d = sha1(msg_key + auth_key[96:128])
69 |
70 | aes_key = sha1_a[:8] + sha1_b[8:20] + sha1_c[4:16]
71 | aes_iv = sha1_a[8:20] + sha1_b[:8] + sha1_c[16:20] + sha1_d[:8]
72 |
73 | return AesIge(aes_key, aes_iv, crypto_provider)
74 |
75 | _loop: asyncio.AbstractEventLoop
76 | _link: TransportLinkBase
77 | _read_message_lock: asyncio.Lock
78 | _auth_key_lock: asyncio.Lock
79 | _last_message_id: int
80 | _datacenter: DatacenterInfo
81 | _in_thread: InThread
82 | _crypto_provider: CryptoProviderBase
83 |
84 | _unencrypted_message_constructor: Constructor
85 | _message_inner_data_from_server_constructor: Constructor
86 |
87 | def __init__(
88 | self,
89 | datacenter: DatacenterInfo,
90 | transport_link_factory: TransportLinkFactory,
91 | in_thread: InThread,
92 | crypto_provider: CryptoProviderBase
93 | ):
94 | self._loop = asyncio.get_running_loop()
95 | self._link = transport_link_factory.new_transport_link(datacenter)
96 | self._read_message_lock = asyncio.Lock()
97 | self._last_message_id = 0
98 | self._datacenter = datacenter
99 | self._in_thread = in_thread
100 | self._crypto_provider = crypto_provider
101 |
102 | unencrypted_message_constructor = datacenter.schema.constructors.get("unencrypted_message", None)
103 |
104 | if unencrypted_message_constructor is None:
105 | raise TypeError(f"Unable to find unencrypted_message constructor")
106 |
107 | message_inner_data_from_server_constructor = datacenter.schema.constructors.get("message_inner_data_from_server", None)
108 |
109 | if message_inner_data_from_server_constructor is None:
110 | raise TypeError(f"Unable to find message_inner_data_from_server constructor")
111 |
112 | self._unencrypted_message_constructor = unencrypted_message_constructor
113 | self._message_inner_data_from_server_constructor = message_inner_data_from_server_constructor
114 |
115 | def get_next_message_id(self) -> int:
116 | message_id = self._datacenter.get_synchronized_time() << 32
117 |
118 | if message_id <= self._last_message_id:
119 | message_id = self._last_message_id + 1
120 |
121 | while message_id % 4 != 0:
122 | message_id += 1
123 |
124 | self._last_message_id = message_id
125 |
126 | return message_id
127 |
128 | async def read_unencrypted_message(self) -> tuple[Structure, Structure]:
129 | async with self._read_message_lock:
130 | server_auth_key_id = await self._link.readn(8)
131 |
132 | if server_auth_key_id != b"\0\0\0\0\0\0\0\0":
133 | raise ValueError("Received a message with unknown auth key id!", server_auth_key_id)
134 |
135 | message_id = await self._link.readn(8)
136 |
137 | body_len_envelope = await self._link.readn(4)
138 | body_len = int.from_bytes(body_len_envelope, signed=False, byteorder="little")
139 | body_envelope = await self._link.readn(body_len)
140 |
141 | full_message_reader = NativeByteReader(b"".join((server_auth_key_id, message_id, body_len_envelope, body_envelope)))
142 |
143 | try:
144 | message = Structure.from_dict(await self._in_thread(lambda: self._unencrypted_message_constructor.deserialize_bare_data(full_message_reader)))
145 | finally:
146 | del full_message_reader
147 |
148 | self._link.discard_packet()
149 |
150 | return message, message.body
151 |
152 | async def write_unencrypted_message(self, **body: TlBodyDataValue) -> None:
153 | message_id = self.get_next_message_id()
154 |
155 | logging.debug(f"writing plain message {message_id} ({body["_cons"]})")
156 |
157 | message = self._datacenter.schema.bare_kwargs(
158 | _cons="unencrypted_message",
159 | auth_key_id=0,
160 | msg_id=message_id,
161 | body=self._datacenter.schema.boxed(body),
162 | )
163 |
164 | await self._link.write(message.get_flat_bytes())
165 |
166 | async def write_encrypted(self, message: Value, key: Key | DhGenKey) -> None:
167 | auth_key_key, auth_key_id, session = key.get_or_assert_empty()
168 |
169 | message_inner_data = self._datacenter.schema.bare_kwargs(
170 | _cons="message_inner_data",
171 | salt=key.server_salt,
172 | session_id=session.id,
173 | message=message,
174 | )
175 |
176 | message_inner_data_envelope = await self._in_thread(message_inner_data.get_flat_bytes)
177 |
178 | padding = await self._in_thread(lambda: self._crypto_provider.secure_random((-(len(message_inner_data_envelope) + 12) % 16 + 12)))
179 | msg_key = (await self._in_thread(lambda: sha256(auth_key_key[88:88 + 32] + message_inner_data_envelope + padding)))[8:24]
180 | aes = await self._in_thread(lambda: self.prepare_key_v2(auth_key_key, msg_key, True, self._crypto_provider))
181 | encrypted_message = await self._in_thread(lambda: aes.encrypt(message_inner_data_envelope + padding))
182 |
183 | full_message = self._datacenter.schema.bare_kwargs(
184 | _cons="encrypted_message",
185 | auth_key_id=auth_key_id,
186 | msg_key=msg_key,
187 | encrypted_data=encrypted_message,
188 | )
189 |
190 | await self._link.write(full_message.get_flat_bytes())
191 |
192 | async def read_encrypted(self, key: Key | DhGenKey) -> tuple[Structure, Structure]:
193 | auth_key_key, auth_key_id, session = key.get_or_assert_empty()
194 |
195 | auth_key_part = auth_key_key[88 + 8:88 + 8 + 32]
196 |
197 | async with self._read_message_lock:
198 | server_auth_key_id_bytes = await self._link.readn(8)
199 |
200 | if server_auth_key_id_bytes == b"l\xfe\xff\xffl\xfe\xff\xff":
201 | raise AuthKeyNotFoundException()
202 |
203 | if server_auth_key_id_bytes == b'S\xfe\xff\xffS\xfe\xff\xff':
204 | raise ValueError("Too many requests!")
205 |
206 | server_auth_key_id = int.from_bytes(server_auth_key_id_bytes, "little", signed=False)
207 |
208 | if server_auth_key_id != auth_key_id:
209 | raise ValueError("Received a message with unknown auth key id!", server_auth_key_id)
210 |
211 | msg_key = await self._link.readn(16)
212 | msg_aes = await self._in_thread(lambda: self.prepare_key_v2(auth_key_key, msg_key, False, self._crypto_provider))
213 | msg_aes_stream = AesIgeAsyncStream(msg_aes, self._in_thread, self._link.read)
214 |
215 | plain_sha256 = hashlib.sha256()
216 | await self._in_thread(lambda: plain_sha256.update(auth_key_part))
217 | msg_aes_stream_with_hash = ByteReaderApply(msg_aes_stream, plain_sha256.update, self._in_thread)
218 |
219 | message_inner_data_reader = NativeByteReader(await msg_aes_stream_with_hash(8 + 8 + 8 + 4))
220 |
221 | try:
222 | message = Structure.from_dict(self._message_inner_data_from_server_constructor.deserialize_bare_data(message_inner_data_reader))
223 | finally:
224 | del message_inner_data_reader
225 |
226 | message_body_len = int.from_bytes(await msg_aes_stream_with_hash(4), signed=False, byteorder="little")
227 | message_body_envelope = await msg_aes_stream_with_hash(message_body_len)
228 |
229 | remaining_plain_buffer = msg_aes_stream.remaining_plain_buffer()
230 |
231 | if len(remaining_plain_buffer) not in range(12, 1024):
232 | raise ValueError("Received a message with wrong padding length!")
233 |
234 | await self._in_thread(lambda: plain_sha256.update(remaining_plain_buffer))
235 | msg_key_computed = (await self._in_thread(plain_sha256.digest))[8:24]
236 |
237 | if not hmac.compare_digest(msg_key, msg_key_computed):
238 | raise ValueError("Received a message with unknown msg key!", msg_key, msg_key_computed)
239 |
240 | if (msg_session_id := message.session_id) != session.id:
241 | raise ValueError("Received a message with unknown session id!", msg_session_id)
242 |
243 | if (msg_msg_id := message.message.msg_id) % 2 != 1:
244 | raise ValueError("Received message from server to client need odd parity!", msg_msg_id)
245 |
246 | if ((message.message.msg_id >> 32) - self._datacenter.get_synchronized_time()) not in range(-300, 30):
247 | raise RuntimeError("Time is not synchronised with telegram time!")
248 |
249 | message_body_reader = NativeByteReader(message_body_envelope)
250 |
251 | try:
252 | message_body = Structure.from_dict(await self._in_thread(lambda: self._datacenter.schema.read_by_boxed_data(message_body_reader)))
253 | finally:
254 | del message_body_reader
255 |
256 | return message.message, message_body
257 |
258 | def prepare_message_for_write(self, seq_no: int, body: TlBodyData | Value) -> tuple[Value, int]:
259 | if not isinstance(body, Value):
260 | body = self._datacenter.schema.boxed(body)
261 |
262 | boxed_message_id = self.get_next_message_id()
263 |
264 | boxed_message = self._datacenter.schema.bare_kwargs(
265 | _cons="message_from_client",
266 | msg_id=boxed_message_id,
267 | seqno=seq_no,
268 | body=body,
269 | )
270 |
271 | return boxed_message, boxed_message_id
272 |
273 | def stop(self) -> None:
274 | self._link.stop()
275 | self._last_message_id = 0
276 | logging.debug("disconnected from Telegram")
277 |
--------------------------------------------------------------------------------
/ll_mtproto/network/transport/transport_address_resolver_base.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import abc
19 |
20 | from ll_mtproto.network.datacenter_info import DatacenterInfo
21 |
22 | __all__ = ("TransportAddressResolverBase",)
23 |
24 |
25 | class TransportAddressResolverBase(abc.ABC):
26 | @abc.abstractmethod
27 | async def get_address(self, datacenter_info: DatacenterInfo) -> tuple[str, int]:
28 | raise NotImplementedError()
29 |
--------------------------------------------------------------------------------
/ll_mtproto/network/transport/transport_address_resolver_cached.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import copy
19 | import random
20 |
21 | from ll_mtproto.network.datacenter_info import DatacenterInfo
22 | from ll_mtproto.network.transport.transport_address_resolver_base import TransportAddressResolverBase
23 | from ll_mtproto.tl.structure import Structure
24 |
25 | __all__ = ("CachedTransportAddressResolver",)
26 |
27 |
28 | class CachedTransportAddressResolver(TransportAddressResolverBase):
29 | __slots__ = ("_cached_resolved",)
30 |
31 | _cached_resolved: dict[DatacenterInfo, list[tuple[str, int]]]
32 |
33 | def __init__(self) -> None:
34 | self._cached_resolved = dict()
35 |
36 | def on_new_address(self, datacenter_info: DatacenterInfo, direct_address: str, direct_port: int) -> None:
37 | self._cached_resolved.setdefault(datacenter_info, []).append((direct_address, direct_port))
38 |
39 | def get_cache_copy(self) -> dict[DatacenterInfo, list[tuple[str, int]]]:
40 | return copy.deepcopy(self._cached_resolved)
41 |
42 | def apply_telegram_config(
43 | self,
44 | datacenters: frozenset[DatacenterInfo],
45 | config: Structure,
46 | allow_ipv6: bool = False
47 | ) -> None:
48 | if config.constructor_name != "config":
49 | raise TypeError(f"Expected: config, Found: {config!r}")
50 |
51 | supported_dc_options = config.dc_options
52 |
53 | if not allow_ipv6:
54 | supported_dc_options = filter(lambda option: not option.ipv6, supported_dc_options)
55 |
56 | for datacenter in datacenters:
57 | self._cached_resolved.pop(datacenter, None)
58 |
59 | for dc_option in supported_dc_options:
60 | found_datacenter = next(
61 | datacenter
62 | for datacenter in datacenters
63 | if datacenter.datacenter_id == dc_option.id and datacenter.is_media == bool(dc_option.media_only)
64 | )
65 |
66 | self.on_new_address(found_datacenter, dc_option.ip_address, dc_option.port)
67 |
68 | async def get_address(self, datacenter_info: DatacenterInfo) -> tuple[str, int]:
69 | if cached_address := self._cached_resolved.get(datacenter_info, None):
70 | return random.choice(cached_address)
71 | else:
72 | return datacenter_info.default_direct_address, datacenter_info.default_direct_port
73 |
--------------------------------------------------------------------------------
/ll_mtproto/network/transport/transport_codec_abridged.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import asyncio
19 |
20 | from ll_mtproto.network.transport.transport_codec_base import TransportCodecBase
21 | from ll_mtproto.network.transport.transport_codec_factory import TransportCodecFactory
22 |
23 | __all__ = ("TransportCodecAbridgedFactory", "TransportCodecAbridged")
24 |
25 |
26 | class TransportCodecAbridged(TransportCodecBase):
27 | __slots__ = ("_must_write_transport_type",)
28 |
29 | _must_write_transport_type: bool
30 |
31 | def __init__(self) -> None:
32 | self._must_write_transport_type = True
33 |
34 | async def read_packet(self, reader: asyncio.StreamReader) -> bytes:
35 | packet_data_length = ord(await reader.readexactly(1))
36 |
37 | if packet_data_length > 0x7F:
38 | raise NotImplementedError(f"Wrong packet data length {packet_data_length:d}")
39 |
40 | if packet_data_length == 0x7F:
41 | packet_data_length = int.from_bytes(await reader.readexactly(3), "little", signed=False)
42 |
43 | return await reader.readexactly(packet_data_length * 4)
44 |
45 | async def write_packet(self, writer: asyncio.StreamWriter, data: bytes) -> None:
46 | packet_header = bytearray()
47 |
48 | if self._must_write_transport_type:
49 | packet_header += b"\xef"
50 | self._must_write_transport_type = False
51 |
52 | packet_data_length = len(data) >> 2
53 |
54 | if packet_data_length < 0x7F:
55 | packet_header += packet_data_length.to_bytes(1, "little")
56 |
57 | elif packet_data_length <= 0x7FFFFF:
58 | packet_header += b"\x7f"
59 | packet_header += packet_data_length.to_bytes(3, "little")
60 |
61 | else:
62 | raise OverflowError("Packet data is too long")
63 |
64 | writer.write(packet_header + data)
65 |
66 |
67 | class TransportCodecAbridgedFactory(TransportCodecFactory):
68 | def new_codec(self) -> TransportCodecBase:
69 | return TransportCodecAbridged()
70 |
--------------------------------------------------------------------------------
/ll_mtproto/network/transport/transport_codec_base.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import abc
19 | import asyncio
20 |
21 | __all__ = ("TransportCodecBase",)
22 |
23 |
24 | class TransportCodecBase(abc.ABC):
25 | @abc.abstractmethod
26 | async def read_packet(self, reader: asyncio.StreamReader) -> bytes:
27 | raise NotImplementedError()
28 |
29 | @abc.abstractmethod
30 | async def write_packet(self, writer: asyncio.StreamWriter, data: bytes) -> None:
31 | raise NotImplementedError()
32 |
--------------------------------------------------------------------------------
/ll_mtproto/network/transport/transport_codec_factory.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import abc
19 |
20 | from ll_mtproto.network.transport.transport_codec_base import TransportCodecBase
21 |
22 | __all__ = ("TransportCodecFactory",)
23 |
24 |
25 | class TransportCodecFactory(abc.ABC):
26 | @abc.abstractmethod
27 | def new_codec(self) -> TransportCodecBase:
28 | raise NotImplementedError()
29 |
--------------------------------------------------------------------------------
/ll_mtproto/network/transport/transport_codec_intermediate.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import asyncio
19 | import struct
20 |
21 | from ll_mtproto.network.transport.transport_codec_base import TransportCodecBase
22 | from ll_mtproto.network.transport.transport_codec_factory import TransportCodecFactory
23 |
24 | __all__ = ("TransportCodecIntermediate", "TransportCodecIntermediateFactory")
25 |
26 |
27 | class TransportCodecIntermediate(TransportCodecBase):
28 | __slots__ = ("_must_write_transport_type",)
29 |
30 | _must_write_transport_type: bool
31 |
32 | def __init__(self) -> None:
33 | self._must_write_transport_type = True
34 |
35 | async def read_packet(self, reader: asyncio.StreamReader) -> bytes:
36 | packet_data_length = struct.unpack(" None:
40 | packet_header = bytearray()
41 |
42 | if self._must_write_transport_type:
43 | packet_header += b"\xee" * 4
44 | self._must_write_transport_type = False
45 |
46 | packet_header += struct.pack(" TransportCodecBase:
53 | return TransportCodecIntermediate()
54 |
--------------------------------------------------------------------------------
/ll_mtproto/network/transport/transport_link_base.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import abc
19 |
20 | __all__ = ("TransportLinkBase",)
21 |
22 |
23 | class TransportLinkBase(abc.ABC):
24 | @abc.abstractmethod
25 | async def read(self) -> bytes:
26 | raise NotImplementedError
27 |
28 | @abc.abstractmethod
29 | async def readn(self, n: int) -> bytes:
30 | raise NotImplementedError
31 |
32 | @abc.abstractmethod
33 | def discard_packet(self) -> None:
34 | raise NotImplementedError
35 |
36 | @abc.abstractmethod
37 | async def write(self, data: bytes) -> None:
38 | raise NotImplementedError
39 |
40 | @abc.abstractmethod
41 | def stop(self) -> None:
42 | raise NotImplementedError
43 |
--------------------------------------------------------------------------------
/ll_mtproto/network/transport/transport_link_factory.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import abc
19 |
20 | from ll_mtproto.network.datacenter_info import DatacenterInfo
21 | from ll_mtproto.network.transport.transport_link_base import TransportLinkBase
22 |
23 | __all__ = ("TransportLinkFactory",)
24 |
25 |
26 | class TransportLinkFactory(abc.ABC):
27 | @abc.abstractmethod
28 | def new_transport_link(self, datacenter: DatacenterInfo) -> TransportLinkBase:
29 | raise NotImplementedError
30 |
--------------------------------------------------------------------------------
/ll_mtproto/network/transport/transport_link_tcp.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import _socket
19 | import asyncio
20 | import ipaddress
21 | import logging
22 | import socket
23 | import traceback
24 |
25 | from ll_mtproto.network.datacenter_info import DatacenterInfo
26 | from ll_mtproto.network.transport.transport_address_resolver_base import TransportAddressResolverBase
27 | from ll_mtproto.network.transport.transport_codec_base import TransportCodecBase
28 | from ll_mtproto.network.transport.transport_codec_factory import TransportCodecFactory
29 | from ll_mtproto.network.transport.transport_link_base import TransportLinkBase
30 | from ll_mtproto.network.transport.transport_link_factory import TransportLinkFactory
31 |
32 | __all__ = ("TransportLinkTcp", "TransportLinkTcpFactory")
33 |
34 |
35 | class TransportLinkTcp(TransportLinkBase):
36 | __slots__ = (
37 | "_loop",
38 | "_datacenter",
39 | "_connect_lock",
40 | "_reader",
41 | "_writer",
42 | "_write_lock",
43 | "_read_buffer",
44 | "_transport_codec_factory",
45 | "_transport_codec",
46 | "_resolver"
47 | )
48 |
49 | _loop: asyncio.AbstractEventLoop
50 | _datacenter: DatacenterInfo
51 | _connect_lock: asyncio.Lock
52 | _reader: asyncio.StreamReader | None
53 | _writer: asyncio.StreamWriter | None
54 | _write_lock: asyncio.Lock
55 | _read_buffer: bytearray
56 | _transport_codec: TransportCodecBase | None
57 | _transport_codec_factory: TransportCodecFactory
58 | _resolver: TransportAddressResolverBase
59 |
60 | def __init__(
61 | self,
62 | datacenter: DatacenterInfo,
63 | transport_codec_factory: TransportCodecFactory,
64 | resolver: TransportAddressResolverBase
65 | ):
66 | self._loop = asyncio.get_running_loop()
67 |
68 | self._datacenter = datacenter
69 | self._transport_codec_factory = transport_codec_factory
70 | self._resolver = resolver
71 |
72 | self._connect_lock = asyncio.Lock()
73 | self._write_lock = asyncio.Lock()
74 |
75 | self._read_buffer = bytearray()
76 |
77 | self._reader = None
78 | self._writer = None
79 | self._transport_codec = None
80 |
81 | async def _reconnect_if_needed(self) -> tuple[asyncio.StreamReader, asyncio.StreamWriter, TransportCodecBase, bytearray]:
82 | async with self._connect_lock:
83 | reader, writer, transport_codec, read_buffer = self._reader, self._writer, self._transport_codec, self._read_buffer
84 |
85 | if reader is None or writer is None or transport_codec is None:
86 | if writer is not None:
87 | try:
88 | writer.close()
89 | except:
90 | logging.warning("usable to close leaked writer: %s", traceback.format_exc())
91 |
92 | transport_codec = self._transport_codec_factory.new_codec()
93 | address, port = await self._resolver.get_address(self._datacenter)
94 |
95 | match address_version := ipaddress.ip_address(address):
96 | case ipaddress.IPv4Address():
97 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
98 |
99 | case ipaddress.IPv6Address():
100 | sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
101 |
102 | case _:
103 | raise TypeError(f"Invalid IP address: `{address_version!r}` `{address!r}`")
104 |
105 | if hasattr(_socket, "SO_REUSEADDR"):
106 | sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
107 |
108 | if hasattr(_socket, "SO_KEEPALIVE"):
109 | sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_KEEPALIVE, 1)
110 |
111 | if hasattr(_socket, "SO_NOSIGPIPE"):
112 | sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_NOSIGPIPE, 1)
113 |
114 | if hasattr(_socket, "TCP_NODELAY"):
115 | sock.setsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, 1)
116 |
117 | sock.setblocking(False)
118 |
119 | await asyncio.get_running_loop().sock_connect(sock, (address, port))
120 |
121 | reader, writer = await asyncio.open_connection(sock=sock)
122 | read_buffer = bytearray()
123 |
124 | self._reader, self._writer, self._transport_codec, self._read_buffer = reader, writer, transport_codec, read_buffer
125 |
126 | return reader, writer, transport_codec, read_buffer
127 |
128 | async def read(self) -> bytes:
129 | reader, _, codec, read_buffer = await self._reconnect_if_needed()
130 |
131 | if read_buffer:
132 | result = bytes(read_buffer)
133 | read_buffer.clear()
134 | else:
135 | result = await codec.read_packet(reader)
136 |
137 | return result
138 |
139 | def discard_packet(self) -> None:
140 | self._read_buffer.clear()
141 |
142 | async def readn(self, n: int) -> bytes:
143 | reader, _, codec, read_buffer = await self._reconnect_if_needed()
144 |
145 | while len(read_buffer) < n:
146 | read_buffer += bytearray(await codec.read_packet(reader))
147 |
148 | result = read_buffer[:n]
149 | del read_buffer[:n]
150 | return bytes(result)
151 |
152 | async def write(self, data: bytes) -> None:
153 | data = bytearray(data)
154 |
155 | _, writer, codec, _ = await self._reconnect_if_needed()
156 |
157 | async with self._write_lock:
158 | while (writable_len := min(len(data), 0x7FFFFF)) > 0:
159 | await codec.write_packet(writer, data[:writable_len])
160 | del data[:writable_len]
161 |
162 | def stop(self) -> None:
163 | if writer := self._writer:
164 | writer.close()
165 |
166 | self._writer = None
167 | self._reader = None
168 | self._transport_codec = None
169 | self._read_buffer.clear()
170 |
171 |
172 | class TransportLinkTcpFactory(TransportLinkFactory):
173 | __slots__ = ("_transport_codec_factory", "_resolver")
174 |
175 | _transport_codec_factory: TransportCodecFactory
176 | _resolver: TransportAddressResolverBase
177 |
178 | def __init__(self, transport_codec_factory: TransportCodecFactory, resolver: TransportAddressResolverBase):
179 | self._transport_codec_factory = transport_codec_factory
180 | self._resolver = resolver
181 |
182 | def new_transport_link(self, datacenter: DatacenterInfo) -> TransportLinkBase:
183 | return TransportLinkTcp(datacenter, self._transport_codec_factory, self._resolver)
184 |
--------------------------------------------------------------------------------
/ll_mtproto/resources/auth.tl:
--------------------------------------------------------------------------------
1 | // Core types (no need to gen)
2 |
3 | //vector#1cb5c415 {t:Type} # [ t ] = Vector t;
4 |
5 | ///////////////////////////////
6 | /////////////////// Layer cons
7 | ///////////////////////////////
8 |
9 | //invokeAfterMsg#cb9f372d msg_id:long query:!X = X;
10 | //invokeAfterMsgs#3dc4b4f0 msg_ids:Vector query:!X = X;
11 | //invokeWithLayer1#53835315 query:!X = X;
12 | //invokeWithLayer2#289dd1f6 query:!X = X;
13 | //invokeWithLayer3#b7475268 query:!X = X;
14 | //invokeWithLayer4#dea0d430 query:!X = X;
15 | //invokeWithLayer5#417a57ae query:!X = X;
16 | //invokeWithLayer6#3a64d54d query:!X = X;
17 | //invokeWithLayer7#a5be56d3 query:!X = X;
18 | //invokeWithLayer8#e9abd9fd query:!X = X;
19 | //invokeWithLayer9#76715a63 query:!X = X;
20 | //invokeWithLayer10#39620c41 query:!X = X;
21 | //invokeWithLayer11#a6b88fdf query:!X = X;
22 | //invokeWithLayer12#dda60d3c query:!X = X;
23 | //invokeWithLayer13#427c8ea2 query:!X = X;
24 | //invokeWithLayer14#2b9b08fa query:!X = X;
25 | //invokeWithLayer15#b4418b64 query:!X = X;
26 | //invokeWithLayer16#cf5f0987 query:!X = X;
27 | //invokeWithLayer17#50858a19 query:!X = X;
28 | //invokeWithLayer18#1c900537 query:!X = X;
29 | //invokeWithLayer#da9b0d0d layer:int query:!X = X; // after 18 layer
30 |
31 | ///////////////////////////////
32 | /// Authorization key creation
33 | ///////////////////////////////
34 |
35 | resPQ#05162463 nonce:int128 server_nonce:int128 pq:bytes server_public_key_fingerprints:Vector = ResPQ;
36 |
37 | p_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;
38 | p_q_inner_data_temp#3c6a84d4 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 expires_in:int = P_Q_inner_data;
39 | bind_auth_key_inner#75a3f765 nonce:long temp_auth_key_id:ulong perm_auth_key_id:ulong temp_session_id:ulong expires_at:int = BindAuthKeyInner;
40 |
41 | p_q_inner_data_dc#a9f55f95 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 dc:int = P_Q_inner_data;
42 | p_q_inner_data_temp_dc#56fddf88 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 dc:int expires_in:int = P_Q_inner_data;
43 |
44 | server_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;
45 | server_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:bytes = Server_DH_Params;
46 |
47 | server_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:bytes g_a:bytes server_time:int = Server_DH_inner_data;
48 |
49 | client_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:bytes = Client_DH_Inner_Data;
50 |
51 | dh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;
52 | dh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;
53 | dh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;
54 |
55 | destroy_auth_key_ok#f660e1d4 = DestroyAuthKeyRes;
56 | destroy_auth_key_none#0a9f2259 = DestroyAuthKeyRes;
57 | destroy_auth_key_fail#ea109b13 = DestroyAuthKeyRes;
58 |
59 | ---functions---
60 |
61 | req_pq#60469778 nonce:int128 = ResPQ;
62 | req_pq_multi#be7e8ef1 nonce:int128 = ResPQ;
63 |
64 | req_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;
65 |
66 | set_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;
67 |
68 | destroy_auth_key#d1435160 = DestroyAuthKeyRes;
69 |
70 | ///////////////////////////////
71 | ////////////// System messages
72 | ///////////////////////////////
73 |
74 | ---types---
75 |
76 | msgs_ack#62d6b459 msg_ids:Vector = MsgsAck;
77 |
78 | bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;
79 | bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;
80 |
81 | msgs_state_req#da69fb52 msg_ids:Vector = MsgsStateReq;
82 | msgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;
83 | msgs_all_info#8cc0d131 msg_ids:Vector info:string = MsgsAllInfo;
84 |
85 | msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;
86 | msg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;
87 |
88 | msg_resend_req#7d861a08 msg_ids:Vector = MsgResendReq;
89 |
90 | //rpc_result#f35c6d01 req_msg_id:long result:Object = RpcResult; // parsed manually
91 |
92 | rpc_error#2144ca19 error_code:int error_message:string = RpcError;
93 |
94 | rpc_answer_unknown#5e2ad36e = RpcDropAnswer;
95 | rpc_answer_dropped_running#cd78e586 = RpcDropAnswer;
96 | rpc_answer_dropped#a43ad8b7 msg_id:long seq_no:int bytes:int = RpcDropAnswer;
97 |
98 | future_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;
99 | future_salts#ae500895 req_msg_id:long now:int salts:vector = FutureSalts;
100 |
101 | pong#347773c5 msg_id:long ping_id:long = Pong;
102 |
103 | destroy_session_ok#e22045fc session_id:ulong = DestroySessionRes;
104 | destroy_session_none#62d350c9 session_id:ulong = DestroySessionRes;
105 |
106 | new_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;
107 |
108 | //message msg_id:long seqno:int bytes:int body:Object = Message; // parsed manually
109 | //msg_container#73f1f8dc messages:vector = MessageContainer; // parsed manually
110 | //msg_copy#e06046b2 orig_message:Message = MessageCopy; // parsed manually, not used - use msg_container
111 | //gzip_packed#3072cfa1 packed_data:string = Object; // parsed manually
112 |
113 | http_wait#9299359f max_delay:int wait_after:int max_wait:int = HttpWait;
114 |
115 | ---functions---
116 |
117 | rpc_drop_answer#58e4a740 req_msg_id:long = RpcDropAnswer;
118 |
119 | get_future_salts#b921bd04 num:int = FutureSalts;
120 |
121 | ping#7abe77ec ping_id:long = Pong;
122 | ping_delay_disconnect#f3427b8c ping_id:long disconnect_delay:int = Pong;
123 |
124 | destroy_session#e7512126 session_id:ulong = DestroySessionRes;
125 |
126 | contest.saveDeveloperInfo#9a5f6e95 vk_id:int name:string phone_number:string age:int city:string = Bool;
127 |
--------------------------------------------------------------------------------
/ll_mtproto/resources/service.tl:
--------------------------------------------------------------------------------
1 | msg_container#73f1f8dc messages:vector = MessageContainer;
2 |
3 | message_from_client msg_id:ulong seqno:uint body:object = Message;
4 | message_from_server msg_id:ulong seqno:uint = Message;
5 |
6 | unencrypted_message auth_key_id:ulong msg_id:ulong body:padded_object = DataToSend;
7 | encrypted_message auth_key_id:ulong msg_key:int128 encrypted_data:encrypted = DataToSend;
8 |
9 | message_inner_data salt:long session_id:ulong message:message_from_client = DataToEncrypt;
10 | message_inner_data_from_server salt:long session_id:ulong message:message_from_server = DataToDecrypt;
11 |
12 | authorization_inner_data data_hash:sha1 data:string = DataToEncrypt;
13 |
14 | rpc_result#f35c6d01 req_msg_id:long result:rawobject = RpcResult;
15 | gzip_packed#3072cfa1 data:gzip = Object;
16 |
--------------------------------------------------------------------------------
/ll_mtproto/resources/telegram.rsa.pub:
--------------------------------------------------------------------------------
1 | -----BEGIN RSA PUBLIC KEY-----
2 | MIIBCgKCAQEA6LszBcC1LGzyr992NzE0ieY+BSaOW622Aa9Bd4ZHLl+TuFQ4lo4g
3 | 5nKaMBwK/BIb9xUfg0Q29/2mgIR6Zr9krM7HjuIcCzFvDtr+L0GQjae9H0pRB2OO
4 | 62cECs5HKhT5DZ98K33vmWiLowc621dQuwKWSQKjWf50XYFw42h21P2KXUGyp2y/
5 | +aEyZ+uVgLLQbRA1dEjSDZ2iGRy12Mk5gpYc397aYp438fsJoHIgJ2lgMv5h7WY9
6 | t6N/byY9Nw9p21Og3AoXSL2q/2IJ1WRUhebgAdGVMlV1fkuOQoEzR7EdpqtQD9Cs
7 | 5+bfo3Nhmcyvk5ftB0WkJ9z6bNZ7yxrP8wIDAQAB
8 | -----END RSA PUBLIC KEY-----
--------------------------------------------------------------------------------
/ll_mtproto/resources/telegram.test.rsa.pub:
--------------------------------------------------------------------------------
1 | -----BEGIN RSA PUBLIC KEY-----
2 | MIIBCgKCAQEAyMEdY1aR+sCR3ZSJrtztKTKqigvO/vBfqACJLZtS7QMgCGXJ6XIR
3 | yy7mx66W0/sOFa7/1mAZtEoIokDP3ShoqF4fVNb6XeqgQfaUHd8wJpDWHcR2OFwv
4 | plUUI1PLTktZ9uW2WE23b+ixNwJjJGwBDJPQEQFBE+vfmH0JP503wr5INS1poWg/
5 | j25sIWeYPHYeOrFp/eXaqhISP6G+q2IeTaWTXpwZj4LzXq5YOpk4bYEQ6mvRq7D1
6 | aHWfYmlEGepfaYR8Q0YqvvhYtMte3ITnuSJs171+GDqpdKcSwHnd6FudwGO4pcCO
7 | j4WcDuXc2CTHgH8gFTNhp/Y8/SpDOhvn9QIDAQAB
8 | -----END RSA PUBLIC KEY-----
9 |
--------------------------------------------------------------------------------
/ll_mtproto/tl/byteutils.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import functools
19 | import hashlib
20 | import typing
21 | import zlib
22 |
23 | from ll_mtproto.typed import ByteReader, InThread, ByteConsumer, SyncByteReader
24 |
25 | __all__ = (
26 | "xor",
27 | "sha1",
28 | "sha256",
29 | "to_bytes",
30 | "ByteReaderApply",
31 | "short_hex",
32 | "GzipStreamReader",
33 | "SyncByteReaderProxy",
34 | "BinaryStreamReader"
35 | )
36 |
37 |
38 | def xor(a: bytes, b: bytes) -> bytes:
39 | return bytes(ca ^ cb for ca, cb in zip(a, b))
40 |
41 |
42 | @functools.lru_cache()
43 | def sha1(b: bytes) -> bytes:
44 | return bytes(hashlib.sha1(b).digest())
45 |
46 |
47 | @functools.lru_cache()
48 | def sha256(b: bytes) -> bytes:
49 | return bytes(hashlib.sha256(b).digest())
50 |
51 |
52 | @functools.lru_cache()
53 | def to_bytes(x: int, byte_order: typing.Literal["big", "little"] = "big", signed: bool = False) -> bytes:
54 | return x.to_bytes(((x.bit_length() - 1) // 8) + 1, byte_order, signed=signed)
55 |
56 |
57 | class GzipStreamReader(SyncByteReader):
58 | __slots__ = ("_parent", "_buffer", "_decompressor")
59 |
60 | _parent: SyncByteReader
61 | _buffer: bytearray
62 |
63 | # _decompressor: zlib.Decompress
64 |
65 | def __init__(self, parent: SyncByteReader):
66 | self._parent = parent
67 | self._buffer = bytearray()
68 | self._decompressor = zlib.decompressobj(16 + zlib.MAX_WBITS)
69 |
70 | def __bool__(self) -> bool:
71 | return bool(self._buffer) or bool(self._parent)
72 |
73 | def __call__(self, nbytes: int) -> bytes:
74 | if nbytes == -1:
75 | buffer = self._buffer[:]
76 | del self._buffer[:]
77 | return bytes(buffer + bytearray(self._decompressor.decompress(self._parent(-1))))
78 |
79 | while len(self._buffer) < nbytes:
80 | self._buffer += bytearray(self._decompressor.decompress(self._parent(4096)))
81 |
82 | result = self._buffer[:nbytes]
83 | del self._buffer[:nbytes]
84 | return bytes(result)
85 |
86 |
87 | class ByteReaderApply:
88 | __slots__ = ("_parent", "_apply_function", "_in_thread")
89 |
90 | _parent: ByteReader
91 | _apply_function: ByteConsumer
92 | _in_thread: InThread
93 |
94 | def __init__(self, parent: ByteReader, apply_function: ByteConsumer, in_thread: InThread):
95 | self._parent = parent
96 | self._apply_function = apply_function
97 | self._in_thread = in_thread
98 |
99 | async def __call__(self, nbytes: int) -> bytes:
100 | result = await self._parent(nbytes)
101 | await self._in_thread(lambda: self._apply_function(result))
102 | return result
103 |
104 |
105 | class SyncByteReaderProxy(SyncByteReader):
106 | __slots__ = ("_parent", "_apply_function")
107 |
108 | _parent: SyncByteReader
109 | _apply_function: ByteConsumer
110 |
111 | def __init__(self, parent: SyncByteReader, proxy_function: ByteConsumer):
112 | self._parent = parent
113 | self._apply_function = proxy_function
114 |
115 | def __bool__(self) -> bool:
116 | return bool(self._parent)
117 |
118 | def __call__(self, nbytes: int) -> bytes:
119 | result = self._parent(nbytes)
120 | self._apply_function(result)
121 | return result
122 |
123 |
124 | class BinaryStreamReader(SyncByteReader):
125 | __slots__ = ("_parent", "_remaining", "_padding")
126 |
127 | _parent: SyncByteReader
128 | _remaining: int
129 | _padding: int
130 |
131 | def __init__(self, parent: SyncByteReader, remaining: int, padding: int):
132 | self._parent = parent
133 | self._remaining = remaining
134 | self._padding = padding
135 |
136 | def __bool__(self) -> bool:
137 | return self._remaining != 0
138 |
139 | def __call__(self, nbytes: int) -> bytes:
140 | if nbytes == -1:
141 | nbytes = self._remaining
142 |
143 | if nbytes >= (remaining := self._remaining):
144 | result = self._parent(remaining)
145 |
146 | if remaining > 0:
147 | self._parent(self._padding)
148 | self._remaining = 0
149 |
150 | return result
151 | else:
152 | self._remaining -= nbytes
153 | return self._parent(nbytes)
154 |
155 |
156 | @functools.lru_cache()
157 | def short_hex(data: bytes) -> str:
158 | return ":".join("%02X" % b for b in data)
159 |
--------------------------------------------------------------------------------
/ll_mtproto/tl/structure.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import typing
19 |
20 | __all__ = ("Structure", "StructureBody")
21 |
22 |
23 | class Structure:
24 | __slots__ = ("constructor_name", "_fields")
25 |
26 | constructor_name: typing.Final[str]
27 | _fields: typing.Final[dict[str, typing.Any]]
28 |
29 | def __init__(self, constructor_name: str, fields: dict[str, typing.Any]):
30 | self.constructor_name = constructor_name
31 | self._fields = fields
32 |
33 | def __eq__(self, other: typing.Any) -> bool:
34 | if isinstance(other, str):
35 | return self.constructor_name == other
36 |
37 | raise NotImplementedError()
38 |
39 | def __repr__(self) -> str:
40 | return repr(self.get_dict())
41 |
42 | def __getattr__(self, name: str) -> typing.Any:
43 | try:
44 | return self._fields[name]
45 | except KeyError as parent_key_error:
46 | raise KeyError(f"key `{name}` not found in `{self!r}`") from parent_key_error
47 |
48 | def get_dict(self) -> dict[str, typing.Any]:
49 | # _get_dict_inner from Structure always return dict
50 | return typing.cast(dict[str, typing.Any], Structure._get_dict_inner(self))
51 |
52 | @staticmethod
53 | def from_dict(obj: dict[str, typing.Any]) -> "Structure":
54 | # _from_obj_inner from dict always return Structure
55 | return typing.cast(Structure, Structure.from_obj(obj))
56 |
57 | @staticmethod
58 | def from_obj(obj: typing.Any) -> typing.Any:
59 | if isinstance(obj, dict):
60 | fields = dict(
61 | (k, Structure.from_obj(v))
62 | for k, v in obj.items()
63 | if k != "_cons"
64 | )
65 |
66 | return Structure(obj["_cons"], fields)
67 |
68 | elif isinstance(obj, (list, tuple)):
69 | return [Structure.from_obj(x) for x in obj]
70 |
71 | else:
72 | return obj
73 |
74 | @staticmethod
75 | def _get_dict_inner(obj: typing.Any) -> typing.Any:
76 | if isinstance(obj, Structure):
77 | return {
78 | "_cons": obj.constructor_name,
79 | **{
80 | key: Structure._get_dict_inner(value)
81 | for key, value in obj._fields.items()
82 | }
83 | }
84 |
85 | elif isinstance(obj, (list, tuple)):
86 | return [Structure._get_dict_inner(value) for value in obj]
87 |
88 | else:
89 | return obj
90 |
91 |
92 | StructureBody = typing.Union[Structure, typing.List['StructureBody']]
93 |
--------------------------------------------------------------------------------
/ll_mtproto/typed.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 (nikat) https://github.com/nikat/mtproto2json
2 | # Copyright (C) 2020-2025 (andrew) https://github.com/andrew-ld/LL-mtproto
3 |
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU Affero General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 |
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU Affero General Public License for more details.
13 |
14 | # You should have received a copy of the GNU Affero General Public License
15 | # along with this program. If not, see .
16 |
17 |
18 | import asyncio
19 | import typing
20 | import abc
21 |
22 | __all__ = (
23 | "InThread",
24 | "ByteReader",
25 | "PartialByteReader",
26 | "Loop",
27 | "ByteConsumer",
28 | "SyncByteReader",
29 | )
30 |
31 |
32 | class InThread(metaclass=abc.ABCMeta):
33 | InThreadRetType = typing.TypeVar("InThreadRetType")
34 |
35 | @abc.abstractmethod
36 | def __call__(self, target: typing.Callable[[], InThreadRetType]) -> asyncio.Future[InThreadRetType]:
37 | raise NotImplementedError()
38 |
39 |
40 | class SyncByteReader(metaclass=abc.ABCMeta):
41 | @abc.abstractmethod
42 | def __call__(self, nbytes: int) -> bytes:
43 | raise NotImplementedError()
44 |
45 | @abc.abstractmethod
46 | def __bool__(self) -> bool:
47 | raise NotImplementedError()
48 |
49 |
50 | ByteReader = typing.Callable[[int], typing.Awaitable[bytes]]
51 |
52 | PartialByteReader = typing.Callable[[], typing.Awaitable[bytes]]
53 |
54 | Loop = asyncio.AbstractEventLoop
55 |
56 | ByteConsumer = typing.Callable[[bytes], None]
57 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = [
3 | "setuptools >= 75.3.0",
4 | "mypy[mypyc,faster-cache]==1.13.0"
5 | ]
6 | build-backend = "setuptools.build_meta"
7 |
8 | [project]
9 | name = "ll_mtproto"
10 | version = "0.0.1"
11 | authors = [
12 | {name = "andrew-ld"}
13 | ]
14 | readme = "README.md"
15 | license = { file = "LICENSE" }
16 | requires-python = ">=3.13.0"
17 | dynamic = ["dependencies"]
18 |
19 | [tool.setuptools.dynamic]
20 | dependencies = {file = ["requirements.txt"]}
21 |
22 | [tool.setuptools]
23 | include-package-data = true
24 |
25 | [tool.mypy]
26 | python_version = "3.13"
27 | files = [ "ll_mtproto/tl/tl.py" ]
28 | warn_return_any = true
29 | warn_unused_configs = true
30 | strict = true
31 |
32 | [[tool.mypy.overrides]]
33 | module = ["cryptg.*"]
34 | ignore_missing_imports = true
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | cryptg==0.5.0.post0
2 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 | from mypyc.build import mypycify
3 |
4 | setup(ext_modules=mypycify([]))
5 |
--------------------------------------------------------------------------------
/test_benchmark_tl.py:
--------------------------------------------------------------------------------
1 | import pickle
2 | import sys
3 | import timeit
4 | import typing
5 |
6 | from ll_mtproto import TelegramDatacenter
7 | from ll_mtproto.tl.structure import Structure
8 | from ll_mtproto.tl.tl import NativeByteReader
9 |
10 | tlobjpath = sys.argv[-1]
11 |
12 |
13 | with open(tlobjpath, "rb") as cf:
14 | tlobj = typing.cast(Structure, Structure.from_obj(pickle.load(cf)))
15 |
16 |
17 | tlobjdict = tlobj.get_dict()
18 | tlobjcons = tlobj.constructor_name
19 | tlschema = TelegramDatacenter.SCHEMA
20 | serialized = tlschema.serialize(True, tlobjcons, tlobjdict).get_flat_bytes()
21 |
22 |
23 | def test_read():
24 | tlschema.read_by_boxed_data(NativeByteReader(serialized))
25 |
26 |
27 | def test_write():
28 | tlschema.serialize(True, tlobjcons, tlobjdict).get_flat_bytes()
29 |
30 |
31 | print("read", timeit.timeit(test_read, number=1_000_000))
32 | print("write", timeit.timeit(test_write, number=1_000_000))
33 |
--------------------------------------------------------------------------------
/test_download.py:
--------------------------------------------------------------------------------
1 | import traceback
2 | import argparse
3 | import asyncio
4 | import concurrent.futures
5 | import logging
6 |
7 | from ll_mtproto import *
8 |
9 |
10 | async def get_updates(client: Client):
11 | while True:
12 | update = await client.get_update()
13 |
14 | if update:
15 | print("received", update.update.get_dict())
16 |
17 |
18 | async def test(api_id: int, api_hash: str, bot_token: str):
19 | logging.getLogger().setLevel(level=logging.DEBUG)
20 |
21 | connection_info = ConnectionInfo.generate_from_os_info(api_id)
22 |
23 | auth_key = AuthKey()
24 |
25 | def on_auth_key_updated():
26 | print("auth key updated:", auth_key)
27 |
28 | auth_key.set_content_change_callback(on_auth_key_updated)
29 |
30 | datacenter_info = TelegramDatacenter.VESTA
31 |
32 | address_resolver = CachedTransportAddressResolver()
33 |
34 | transport_link_factory = TransportLinkTcpFactory(TransportCodecIntermediateFactory(), address_resolver)
35 |
36 | blocking_executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)
37 |
38 | crypto_provider = CryptoProviderCryptg()
39 |
40 | error_description_resolver = PwrTelegramErrorDescriptionResolver()
41 |
42 | try:
43 | error_description_resolver.synchronous_fetch_database()
44 | except:
45 | traceback.print_exc()
46 | error_description_resolver = None
47 |
48 | session = Client(
49 | datacenter_info,
50 | auth_key,
51 | connection_info,
52 | transport_link_factory,
53 | blocking_executor,
54 | crypto_provider,
55 | use_perfect_forward_secrecy=True,
56 | no_updates=False,
57 | error_description_resolver=error_description_resolver
58 | )
59 |
60 | get_updates_task = asyncio.get_event_loop().create_task(get_updates(session))
61 |
62 | configuration = await session.rpc_call({"_cons": "help.getConfig"})
63 |
64 | address_resolver.apply_telegram_config(TelegramDatacenter.ALL_DATACENTERS, configuration)
65 |
66 | session.disconnect()
67 |
68 | await session.rpc_call({
69 | "_cons": "auth.importBotAuthorization",
70 | "api_id": api_id,
71 | "api_hash": api_hash,
72 | "flags": 0,
73 | "bot_auth_token": bot_token
74 | })
75 |
76 | peer = await session.rpc_call({
77 | "_cons": "contacts.resolveUsername",
78 | "username": "eqf3wefwe"
79 | })
80 |
81 | # I deliberately break the auth_key status to see if the client can restore it
82 | session._used_session_key.session.seqno = 0
83 | session._used_session_key.server_salt = 0
84 | await session.rpc_call({"_cons": "help.getConfig"})
85 |
86 | # I deliberately break the auth_key status to see if the client can restore it
87 | session._used_session_key.session.seqno = 6969
88 | session._used_session_key.server_salt = -1
89 | await session.rpc_call({"_cons": "help.getConfig"})
90 |
91 | # I deliberately write a non-serializable message to check if the error is propagated correctly
92 | try:
93 | await session.rpc_call({"_cons": "lol"})
94 | except:
95 | print("ok serialization error received")
96 | else:
97 | raise asyncio.InvalidStateError("error not received")
98 |
99 | messages = await session.rpc_call({
100 | "_cons": "channels.getMessages",
101 | "channel": {
102 | "_cons": "inputChannel",
103 | "channel_id": peer.peer.channel_id,
104 | "access_hash": peer.chats[0].access_hash
105 | },
106 | "id": [{"_cons": "inputMessageID", "id": 5}]
107 | })
108 |
109 | media = messages.messages[0].media.document
110 | media_auth_key = AuthKey(persistent_key=auth_key.persistent_key)
111 |
112 | def on_media_auth_key_updated():
113 | print("media auth key updated:", media_auth_key)
114 |
115 | media_auth_key.set_content_change_callback(on_media_auth_key_updated)
116 |
117 | media_session = Client(
118 | TelegramDatacenter.VESTA_MEDIA,
119 | media_auth_key,
120 | connection_info,
121 | transport_link_factory,
122 | blocking_executor,
123 | crypto_provider,
124 | use_perfect_forward_secrecy=True,
125 | no_updates=True
126 | )
127 |
128 | get_file_request = {
129 | "_cons": "upload.getFile",
130 | "offset": 0,
131 | "limit": 1024 * 1024,
132 | "location": {
133 | "_cons": "inputDocumentFileLocation",
134 | "id": media.id,
135 | "access_hash": media.access_hash,
136 | "file_reference": media.file_reference,
137 | "thumb_size": ""
138 | }
139 | }
140 |
141 | while get_file_request["offset"] < media.size:
142 | await media_session.rpc_call(get_file_request)
143 | get_file_request["offset"] += get_file_request["limit"]
144 |
145 | media_session.disconnect()
146 | get_updates_task.cancel()
147 | session.disconnect()
148 |
149 |
150 | if __name__ == "__main__" or __name__ == "uwsgi_file_test":
151 | _parser = argparse.ArgumentParser()
152 | _parser.add_argument("--api-id", type=int, required=True)
153 | _parser.add_argument("--api-hash", type=str, required=True)
154 | _parser.add_argument("--bot-token", type=str, required=True)
155 |
156 | _parsed_arguments = _parser.parse_args()
157 |
158 | asyncio.run(test(_parsed_arguments.api_id, _parsed_arguments.api_hash, _parsed_arguments.bot_token))
159 |
--------------------------------------------------------------------------------
/test_key_exchange.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import concurrent.futures
3 | import logging
4 | import typing
5 |
6 | from ll_mtproto import TelegramDatacenter
7 | from ll_mtproto.client.client import Client
8 | from ll_mtproto.client.connection_info import ConnectionInfo
9 | from ll_mtproto.crypto.auth_key import AuthKey
10 | from ll_mtproto.crypto.providers.crypto_provider_cryptg import CryptoProviderCryptg
11 | from ll_mtproto.network.datacenter_info import DatacenterInfo
12 | from ll_mtproto.network.dh.mtproto_key_creator_dispatcher import initialize_key_creator_dispatcher
13 | from ll_mtproto.network.dispatcher import dispatch_event
14 | from ll_mtproto.network.mtproto import MTProto
15 | from ll_mtproto.network.transport.transport_address_resolver_cached import CachedTransportAddressResolver
16 | from ll_mtproto.network.transport.transport_codec_abridged import TransportCodecAbridgedFactory
17 | from ll_mtproto.network.transport.transport_link_tcp import TransportLinkTcpFactory
18 |
19 | blocking_executor = concurrent.futures.ThreadPoolExecutor(max_workers=8)
20 | crypto_provider = CryptoProviderCryptg()
21 | resolver = CachedTransportAddressResolver()
22 | link = TransportLinkTcpFactory(TransportCodecAbridgedFactory(), resolver)
23 |
24 |
25 | async def in_thread(*args: typing.Any, **kwargs: typing.Any) -> typing.Any:
26 | return await asyncio.get_running_loop().run_in_executor(blocking_executor, *args, **kwargs)
27 |
28 |
29 | async def main():
30 | tasks = []
31 |
32 | async def configure_resolver():
33 | tmp_connection_info = ConnectionInfo.generate_from_os_info(6)
34 | tmp_datacenter_info = TelegramDatacenter.VENUS
35 |
36 | tmp_auth_key = AuthKey()
37 | tmp_auth_key.set_content_change_callback(lambda: None)
38 |
39 | tmp_client = Client(tmp_datacenter_info, tmp_auth_key, tmp_connection_info, link, blocking_executor, crypto_provider)
40 |
41 | try:
42 | resolver.apply_telegram_config(TelegramDatacenter.ALL_DATACENTERS, await tmp_client.rpc_call({"_cons": "help.getConfig"}))
43 | finally:
44 | tmp_client.disconnect()
45 |
46 | await configure_resolver()
47 |
48 | for dc in TelegramDatacenter.ALL_DATACENTERS:
49 | for _ in range(2):
50 | tasks.append(test_exchange(dc, True))
51 |
52 | for _ in range(2):
53 | tasks.append(test_exchange(dc, False))
54 |
55 | await asyncio.gather(*tasks)
56 |
57 |
58 | async def test_exchange(datacenter: DatacenterInfo, temp_key: bool) -> None:
59 | mtproto = MTProto(
60 | datacenter,
61 | link,
62 | in_thread,
63 | crypto_provider,
64 | )
65 |
66 | while True:
67 | dispatcher, result = await initialize_key_creator_dispatcher(
68 | temp_key,
69 | mtproto,
70 | in_thread,
71 | datacenter,
72 | crypto_provider
73 | )
74 |
75 | while not result.done():
76 | await dispatch_event(dispatcher, mtproto, None)
77 |
78 | print("key generated", result.result().auth_key_id)
79 |
80 |
81 | if __name__ == "__main__":
82 | logging.getLogger().setLevel(level=logging.DEBUG)
83 | asyncio.run(main())
84 |
--------------------------------------------------------------------------------
/test_performance.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import concurrent.futures
3 | import logging
4 | import time
5 | import traceback
6 |
7 | from ll_mtproto import *
8 | from ll_mtproto.network.transport.transport_codec_abridged import TransportCodecAbridgedFactory
9 | from ll_mtproto.network.transport.transport_codec_base import TransportCodecBase
10 | from ll_mtproto.network.transport.transport_codec_factory import TransportCodecFactory
11 |
12 |
13 | class TransportCodecPerformanceTrack(TransportCodecBase):
14 | _parent_codec: TransportCodecBase
15 | _first_write_time: float | None
16 | _first_read: bool
17 |
18 | def __init__(self, parent_codec: TransportCodecBase):
19 | self._parent_codec = parent_codec
20 | self._first_write_time = None
21 | self._first_read = True
22 |
23 | async def write_packet(self, writer: asyncio.StreamWriter, data: bytes) -> None:
24 | try:
25 | return await self._parent_codec.write_packet(writer, data)
26 | finally:
27 | if self._first_write_time is None:
28 | self._first_write_time = time.time()
29 |
30 | async def read_packet(self, reader: asyncio.StreamReader) -> bytes:
31 | try:
32 | return await self._parent_codec.read_packet(reader)
33 | finally:
34 | if self._first_read:
35 | self._first_read = False
36 | print("difference: ", time.time() - self._first_write_time)
37 |
38 |
39 | class TransportCodecPerformanceTrackFactory(TransportCodecFactory):
40 | _parent_factory: TransportCodecFactory
41 |
42 | def __init__(self, parent_factory: TransportCodecFactory):
43 | self._parent_factory = parent_factory
44 |
45 | def new_codec(self) -> TransportCodecBase:
46 | return TransportCodecPerformanceTrack(self._parent_factory.new_codec())
47 |
48 |
49 | async def test():
50 | connection_info = ConnectionInfo.generate_from_os_info(6)
51 |
52 | auth_key = AuthKey()
53 | auth_key.set_content_change_callback(lambda: None)
54 |
55 | datacenter_info = TelegramDatacenter.VESTA
56 | address_resolver = CachedTransportAddressResolver()
57 | transport_link_factory = TransportLinkTcpFactory(TransportCodecPerformanceTrackFactory(TransportCodecAbridgedFactory()), address_resolver)
58 | blocking_executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)
59 | crypto_provider = CryptoProviderCryptg()
60 |
61 | session = Client(
62 | datacenter_info,
63 | auth_key,
64 | connection_info,
65 | transport_link_factory,
66 | blocking_executor,
67 | crypto_provider,
68 | use_perfect_forward_secrecy=True,
69 | no_updates=False,
70 | error_description_resolver=None
71 | )
72 |
73 | configuration = await session.rpc_call({"_cons": "help.getConfig"})
74 | address_resolver.apply_telegram_config(TelegramDatacenter.ALL_DATACENTERS, configuration)
75 | session.disconnect()
76 |
77 | while True:
78 | # noinspection PyBroadException
79 | try:
80 | _ = await session.rpc_call({"_cons": "help.getConfig"})
81 | except:
82 | traceback.print_exc()
83 | finally:
84 | session.disconnect()
85 |
86 |
87 | if __name__ == "__main__" or __name__ == "uwsgi_file_test":
88 | logging.getLogger().setLevel(level=logging.ERROR)
89 | asyncio.run(test())
90 |
--------------------------------------------------------------------------------
/test_rpc_call_container.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import concurrent.futures
3 | import logging
4 |
5 | from ll_mtproto import TelegramDatacenter
6 | from ll_mtproto.client.client import Client
7 | from ll_mtproto.client.connection_info import ConnectionInfo
8 | from ll_mtproto.crypto.auth_key import AuthKey
9 | from ll_mtproto.crypto.providers.crypto_provider_cryptg import CryptoProviderCryptg
10 | from ll_mtproto.network.transport.transport_address_resolver_cached import CachedTransportAddressResolver
11 | from ll_mtproto.network.transport.transport_codec_intermediate import TransportCodecIntermediateFactory
12 | from ll_mtproto.network.transport.transport_link_tcp import TransportLinkTcpFactory
13 |
14 |
15 | # noinspection PyProtectedMember
16 | async def main():
17 | logging.getLogger().setLevel(level=logging.DEBUG)
18 |
19 | connection_info = ConnectionInfo.generate_from_os_info(6)
20 | auth_key = AuthKey()
21 | datacenter_info = TelegramDatacenter.VESTA
22 | address_resolver = CachedTransportAddressResolver()
23 | transport_link_factory = TransportLinkTcpFactory(TransportCodecIntermediateFactory(), address_resolver)
24 | blocking_executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)
25 | crypto_provider = CryptoProviderCryptg()
26 |
27 | session = Client(
28 | datacenter_info,
29 | auth_key,
30 | connection_info,
31 | transport_link_factory,
32 | blocking_executor,
33 | crypto_provider,
34 | use_perfect_forward_secrecy=True,
35 | no_updates=True,
36 | )
37 |
38 | print(await session.rpc_call_container([{"_cons": "help.getConfig"}, {"_cons": "help.getConfig"}]))
39 |
40 | # I deliberately break the auth_key status to see if the client can restore it
41 | session._used_session_key.session.seqno = 0
42 | session._used_session_key.server_salt = 0
43 | print(await session.rpc_call_container([{"_cons": "help.getConfig"}, {"_cons": "help.getConfig"}]))
44 |
45 | # I deliberately break the auth_key status to see if the client can restore it
46 | session._used_session_key.session.seqno = 6969
47 | session._used_session_key.server_salt = -1
48 | print(await session.rpc_call_container([{"_cons": "help.getConfig"}, {"_cons": "help.getConfig"}]))
49 |
50 | session.disconnect()
51 |
52 |
53 | if __name__ == "__main__":
54 | asyncio.run(main())
55 |
--------------------------------------------------------------------------------
/test_upload.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import asyncio
3 | import concurrent.futures
4 | import logging
5 | import multiprocessing
6 | import os
7 | import secrets
8 | import time
9 |
10 | from ll_mtproto import *
11 |
12 |
13 | async def test(api_id: int, api_hash: str, bot_token: str):
14 | logging.getLogger().setLevel(level=logging.ERROR)
15 |
16 | connection_info = ConnectionInfo.generate_from_os_info(api_id)
17 | auth_key = AuthKey()
18 | auth_key.set_content_change_callback(lambda: None)
19 | datacenter_info = TelegramDatacenter.VESTA
20 | address_resolver = CachedTransportAddressResolver()
21 | transport_link_factory = TransportLinkTcpFactory(TransportCodecAbridgedFactory(), address_resolver)
22 | blocking_executor = concurrent.futures.ThreadPoolExecutor(max_workers=multiprocessing.cpu_count())
23 | crypto_provider = CryptoProviderCryptg()
24 |
25 | session = Client(
26 | datacenter_info,
27 | auth_key,
28 | connection_info,
29 | transport_link_factory,
30 | blocking_executor,
31 | crypto_provider,
32 | use_perfect_forward_secrecy=True,
33 | no_updates=True,
34 | error_description_resolver=None
35 | )
36 |
37 | configuration = await session.rpc_call({"_cons": "help.getConfig"})
38 | address_resolver.apply_telegram_config(TelegramDatacenter.ALL_DATACENTERS, configuration)
39 | session.disconnect()
40 |
41 | await session.rpc_call({
42 | "_cons": "auth.importBotAuthorization",
43 | "api_id": api_id,
44 | "api_hash": api_hash,
45 | "flags": 0,
46 | "bot_auth_token": bot_token
47 | })
48 |
49 | media_sessions = []
50 |
51 | for _ in range(10):
52 | new_media_auth_key = AuthKey(persistent_key=auth_key.persistent_key)
53 | new_media_auth_key.set_content_change_callback(lambda: None)
54 |
55 | new_media_session = Client(
56 | TelegramDatacenter.VESTA_MEDIA,
57 | new_media_auth_key,
58 | connection_info,
59 | transport_link_factory,
60 | blocking_executor,
61 | crypto_provider,
62 | use_perfect_forward_secrecy=True,
63 | no_updates=True
64 | )
65 |
66 | media_sessions.append(new_media_session)
67 |
68 | media_sessions_tasks = []
69 |
70 | file_block_size = 524288
71 | file_part = os.urandom(file_block_size)
72 | assert len(file_part) == file_block_size
73 | file_id = secrets.randbits(63)
74 | file_size = 1048576000
75 | file_parts = file_size // file_block_size
76 |
77 | requests_queue = asyncio.Queue()
78 |
79 | for file_part_number in range(file_parts):
80 | request = {
81 | "_cons": "upload.saveBigFilePart",
82 | "file_id": file_id,
83 | "bytes": file_part,
84 | "file_total_parts": file_parts,
85 | "file_part": file_part_number
86 | }
87 | requests_queue.put_nowait((request, file_part_number))
88 |
89 | print("starting upload")
90 | current_time = time.time()
91 |
92 | for media_session in media_sessions:
93 | async def upload_task():
94 | while requests_queue.qsize():
95 | (pending_request, pending_request_part_number) = requests_queue.get_nowait()
96 | if pending_request_part_number % 100 == 0:
97 | print("uploading part", pending_request_part_number, "elapsed time", time.time() - current_time)
98 | while True:
99 | try:
100 | await media_session.rpc_call(pending_request)
101 | break
102 | except RpcError as rpc_error:
103 | if rpc_error.code == 420:
104 | continue
105 | raise rpc_error from rpc_error
106 |
107 | media_sessions_tasks.append(upload_task())
108 |
109 | await asyncio.gather(*media_sessions_tasks)
110 |
111 | for media_session in media_sessions:
112 | media_session.disconnect()
113 |
114 | session.disconnect()
115 |
116 | print("upload done in", time.time() - current_time, "seconds")
117 |
118 |
119 | if __name__ == "__main__" or __name__ == "uwsgi_file_test":
120 | _parser = argparse.ArgumentParser()
121 | _parser.add_argument("--api-id", type=int, required=True)
122 | _parser.add_argument("--api-hash", type=str, required=True)
123 | _parser.add_argument("--bot-token", type=str, required=True)
124 |
125 | _parsed_arguments = _parser.parse_args()
126 |
127 | asyncio.run(test(_parsed_arguments.api_id, _parsed_arguments.api_hash, _parsed_arguments.bot_token))
128 |
--------------------------------------------------------------------------------