Some refactor

now testing.py looks almost just like i want.
This commit is contained in:
Anton Grigoryev 2015-03-12 03:17:43 +03:00
parent 24a1b9b36b
commit 66a5577ab9
2 changed files with 81 additions and 127 deletions

View File

@ -49,8 +49,8 @@ class TlMethod:
class TL: class TL:
def __init__(self): def __init__(self, filename):
with open("TL_schema.JSON", 'r') as f: with open(filename, 'r') as f:
TL_dict = json.load(f) TL_dict = json.load(f)
# Read constructors # Read constructors
@ -71,15 +71,11 @@ class TL:
self.method_id[z.id] = z self.method_id[z.id] = z
self.method_name[z.method] = z self.method_name[z.method] = z
def method_call(self, method, **kwargs):
z = io.BytesIO()
tl_method = self.method_name[method]
z.write(struct.pack('<i', tl_method.id))
for param in tl_method.params:
self.serialize(bytes_io=z, value=kwargs[param['name']], type_=param['type'])
return z.getvalue()
def serialize(self, bytes_io, type_, value): ## Loading TL_schema
tl = TL("TL_schema.JSON")
def serialize(bytes_io, type_, value):
if type_ == "int": if type_ == "int":
assert isinstance(value, int) assert isinstance(value, int)
bytes_io.write(struct.pack('<i', value)) bytes_io.write(struct.pack('<i', value))
@ -87,7 +83,7 @@ class TL:
assert isinstance(value, bytes) assert isinstance(value, bytes)
bytes_io.write(struct.pack('<16s', value)) bytes_io.write(struct.pack('<16s', value))
def deserialize(self, bytes_io, type_=None, subtype=None): def deserialize(bytes_io, type_=None, subtype=None):
assert isinstance(bytes_io, io.BytesIO) assert isinstance(bytes_io, io.BytesIO)
# Built-in bare types # Built-in bare types
@ -125,25 +121,25 @@ class TL:
elif type_ == 'vector': elif type_ == 'vector':
assert subtype is not None assert subtype is not None
count = int.from_bytes(bytes_io.read(4), 'little') count = int.from_bytes(bytes_io.read(4), 'little')
x = [self.deserialize(bytes_io, type_=subtype) for i in range(count)] x = [deserialize(bytes_io, type_=subtype) for i in range(count)]
else: else:
# Boxed types # Boxed types
i = struct.unpack('<i', bytes_io.read(4))[0] # read type ID i = struct.unpack('<i', bytes_io.read(4))[0] # read type ID
try: try:
tl_elem = self.constructor_id[i] tl_elem = tl.constructor_id[i]
except: except:
raise Exception("Could not extract type: %s" % type_) raise Exception("Could not extract type: %s" % type_)
base_boxed_types = ["Vector t", "Int", "Long", "Double", "String", "Int128", "Int256"] base_boxed_types = ["Vector t", "Int", "Long", "Double", "String", "Int128", "Int256"]
if tl_elem.type in base_boxed_types: if tl_elem.type in base_boxed_types:
x = self.deserialize(bytes_io, type_=tl_elem.predicate, subtype=subtype) x = deserialize(bytes_io, type_=tl_elem.predicate, subtype=subtype)
else: # other types else: # other types
x = {} x = {}
for arg in tl_elem.params: for arg in tl_elem.params:
x[arg['name']] = self.deserialize(bytes_io, type_=arg['type'], subtype=arg['subtype']) x[arg['name']] = deserialize(bytes_io, type_=arg['type'], subtype=arg['subtype'])
return x return x
class Session: class Session:
""" Manages TCP Transport. encryption and message frames """
def __init__(self, ip, port): def __init__(self, ip, port):
# creating socket # creating socket
self.sock = socket.socket() self.sock = socket.socket()
@ -211,3 +207,19 @@ class Session:
print('<<') print('<<')
vis(data) # Received message visualisation to console vis(data) # Received message visualisation to console
return data return data
def method_call(self, method, **kwargs):
z = io.BytesIO()
tl_method = tl.method_name[method]
z.write(struct.pack('<i', tl_method.id))
for param in tl_method.params:
serialize(bytes_io=z, value=kwargs[param['name']], type_=param['type'])
self.send_message(z.getvalue())
server_answer = self.recv_message()
return deserialize(io.BytesIO(server_answer))
class Telegram:
global tl
def connect(self, ip, port):
self.session = Session(ip, port)

View File

@ -2,7 +2,6 @@
import mtproto import mtproto
import os import os
import prime import prime
import io
import configparser import configparser
config = configparser.ConfigParser() config = configparser.ConfigParser()
@ -10,67 +9,10 @@ config.read('credentials')
ip = config['App data']['ip_address'] ip = config['App data']['ip_address']
port = config['App data'].getint('port') port = config['App data'].getint('port')
TL=mtproto.TL()
Session = mtproto.Session(ip, port) Session = mtproto.Session(ip, port)
a = TL.method_call('req_pq', nonce=os.urandom(16)) x = Session.method_call('req_pq', nonce=os.urandom(16))
Session.send_message(a)
b = Session.recv_message()
x = TL.deserialize(io.BytesIO(b))
PQ = int.from_bytes(x['pq'], 'big') PQ = int.from_bytes(x['pq'], 'big')
[p, q] = prime.primefactors(PQ) [p, q] = prime.primefactors(PQ)
print("PQ = %d\np = %d, q = %d" % (PQ, p, q)) print("PQ = %d\np = %d, q = %d" % (PQ, p, q))
#sock = socket.socket()
# sock.connect(("149.154.167.40", 443))
# nonce = os.urandom(16)
# tosend = b'\x78\x97\x46\x60' + nonce
# good=(b'\x00\x00\x00\x00\x00\x00\x00\x00'
# #+b'\x00\x00\x00\x00\x0f\x35\xe8\x51
# +int(time.time()*2**32).to_bytes(8, 'little')
# +len(tosend).to_bytes(4, 'little')
# +tosend)
# #+b'\x14\x00\x00\x00'
# #+b'\x78\x97\x46\x60'
# #+b'\x15\x3e\xa9\xbe\xc5\x4f\xfc\x16'
# #+b'\x66\x23\x4a\xd0\x31\xc0\xf1\x3d')
# mtproto.sendpacket(sock, good, 0)
# (number, data) = mtproto.recvpacket(sock)
# auth_key_id = data[0:8]
# message_id = data[8:16]
# message_length = int.from_bytes(data[16:20], 'little')
# resPQ = data[20:24]
# nonce2 = data[24:40]
# server_nonce = data[40:56]
# pq = data[56:68]
# fingerprint_count = int.from_bytes(data[72:76], 'little')
# fingerprints = []
# for i in range(fingerprint_count):
# fingerprints.append(data[76+i*8:76+8*(i+1)])
# PQ = int.from_bytes(pq[1:9],'big')
# server_public_key = fingerprints[0]
# [p, q] = prime.primefactors(PQ)
# #(p, q)=factorize(PQ)
# def num_to_string(number, endianness):
# number_bytes = math.ceil(number.bit_length() / 8)
# return (number_bytes.to_bytes(3, endianness) +
# number.to_bytes(number_bytes, endianness) +
# b'\x00' * ((number_bytes + 3) %4) )
# new_nonce = os.urandom(32)
# data = (b'\x83\xc9\x5a\xec' + #(p_q_inner_data)
# num_to_string(PQ, 'big') +
# num_to_string(p, 'big') +
# num_to_string(q, 'big') +
# nonce +
# server_nonce +
# new_nonce )
# sock.close()
# #34 00 00 00 - len
# #00 00 00 00- num in the session
# #00 00 00 00 00 00 00 00
# #00 00 00 00 0f 35 e8 51 - message id (unixtime << 32)
# #14 00 00 00 - message len
# #78 97 46 60 - function
# #15 3e a9 be c5 4f fc 16 66 23 4a d0 31 c0 f1 3d - nonce (random number 16 bytes)
# #dd fe f0 07 - crc32