def test_channelcast(self): torrent_data = {'announce':"http://localhost", 'info':{'name':'Hello 123', 'files':[{'length':100, 'path':['license.txt']}]}} infohash = bin2str(sha(bencode(torrent_data['info'])).digest()) self.channelcastdb.addOwnTorrent(infohash,torrent_data) s = OLConnection(self.my_keypair,'localhost',self.hisport) chcast = ChannelCastCore(None, s, self.session, None, log = '', dnsindb = None) # Good message chdata = chcast.createChannelCastMessage() if chdata is None or len(chdata) ==0: print "test: no subscriptions for us.. hence do not send" else: msg = CHANNELCAST + bencode(chdata) print "test: channelcast msg created", repr(chdata) s.send(msg) time.sleep(3) # Bad message if chdata is None or len(chdata)==0: pass else: pub_id, pub_name, infohash, torrenthash, name, timestamp, signature = chdata[0] chdata = [(pub_id, pub_name, infohash, torrenthash, name, 12343, signature)] msg = CHANNELCAST + bencode(chdata) print "test: channelcast msg created", repr(chdata) s.send(msg) time.sleep(20) # the other side should have closed the connection, as it is invalid message s.close()
def create_bad_metadata_bad_torrent3(self): torrent = {'info':481} data = bencode(torrent) d = self.create_good_metadata_dict(data) d['metadata'] = data bd = bencode(d) return METADATA+bd
def create_bad_metadata_bad_torrent2(self): torrent = {} data = bencode(torrent) d = self.create_good_metadata_dict(data) d["metadata"] = data bd = bencode(d) return METADATA + bd
def create_good_simpleplustorrents_reply(self,id): d = self.create_good_simple_reply_dict(id) bmetainfo = bencode(self.tdef.get_metainfo()) d['a'][self.tdef.get_infohash()]['torrent_size'] = len(bmetainfo) d['a'][self.tdef.get_infohash()]['metatype'] = 'application/x-tribler-stream' d['a'][self.tdef.get_infohash()]['metadata'] = bmetainfo b = bencode(d) return QUERY_REPLY+b
def create_bad_metadata_bad_torrent3(self): torrent = {'info': 481} data = bencode(torrent) d = self.create_good_metadata_dict(data) d['metadata'] = data bd = bencode(d) return METADATA + bd
def create_good_simpleplustorrents_reply(self, id): d = self.create_good_simple_reply_dict(id) bmetainfo = bencode(self.tdef.get_metainfo()) d['a'][self.tdef.get_infohash()]['torrent_size'] = len(bmetainfo) d['a'][self.tdef.get_infohash( )]['metatype'] = 'application/x-tribler-stream' d['a'][self.tdef.get_infohash()]['metadata'] = bmetainfo b = bencode(d) return QUERY_REPLY + b
def test_channelcast(self): torrent_data = { 'announce': "http://localhost", 'info': { 'name': 'Hello 123', 'files': [{ 'length': 100, 'path': ['license.txt'] }] } } infohash = bin2str(sha(bencode(torrent_data['info'])).digest()) self.channelcastdb.addOwnTorrent(infohash, torrent_data) s = OLConnection(self.my_keypair, 'localhost', self.hisport) chcast = ChannelCastCore(None, s, self.session, None, log='', dnsindb=None) # Good message chdata = chcast.createChannelCastMessage() if chdata is None or len(chdata) == 0: print "test: no subscriptions for us.. hence do not send" else: msg = CHANNELCAST + bencode(chdata) print "test: channelcast msg created", repr(chdata) s.send(msg) time.sleep(3) # Bad message if chdata is None or len(chdata) == 0: pass else: pub_id, pub_name, infohash, torrenthash, name, timestamp, signature = chdata[ 0] chdata = [(pub_id, pub_name, infohash, torrenthash, name, 12343, signature)] msg = CHANNELCAST + bencode(chdata) print "test: channelcast msg created", repr(chdata) s.send(msg) time.sleep(20) # the other side should have closed the connection, as it is invalid message s.close()
def create_not_hashpiece(self,chunkid): index,begin,length = chunkid ohlist = [] bohlist = bencode(ohlist) chunk = self.read_chunk(index,begin,length) payload = tobinary(index)+tobinary(begin)+tobinary(len(bohlist))+bohlist+chunk return EXTEND+chr(231)+payload
def serialize(self): list = [self.torrent_id, self.torrent_pub_key, self.node_pub_key, self.expire_time, self.signature] return bencode(list)
def createAndSendBarterCastMessage(self, target_permid, selversion, active=False): # for older versions of Tribler (non-BarterCast): do nothing if selversion <= OLPROTO_VER_FIFTH: return if DEBUG: print >> sys.stderr, "===========bartercast: Sending BarterCast msg to ", self.bartercastdb.getName( target_permid) # create a new bartercast message bartercast_data = self.createBarterCastMessage(target_permid) if LOG: self.logMsg(bartercast_data, target_permid, 'out', logfile=self.logfile) try: bartercast_msg = bencode(bartercast_data) except: print_exc() print >> sys.stderr, "error bartercast_data:", bartercast_data return # send the message self.overlay_bridge.send(target_permid, BARTERCAST + bartercast_msg, self.bartercastSendCallback) self.blockPeer(target_permid, self.send_block_list, self.block_interval)
def subtest_good_friendship_stats(self): """ Send a valid message-id from a registered crawler peer """ print >> sys.stderr, "-" * 80, "\ntest: good friendship stats" s = OLConnection(self.my_keypair, "localhost", self.hisport) t = time.time() - 100.0 msg_dict = {'current time': int(t)} payload = bencode(msg_dict) self.send_crawler_request(s, CRAWLER_FRIENDSHIP_STATS, 0, 0, payload) error, payload = self.receive_crawler_reply(s, CRAWLER_FRIENDSHIP_STATS, 0) assert error == 0 d = bdecode(payload) if DEBUG: print >> sys.stderr, "test: Got FRIENDSHIPSTATISTICS", ` d ` stats = d['stats'] self.assert_(len(stats) == 1) record = d['stats'][0] self.assert_(record[0] == bin2str(self.his_permid)) # source_permid self.assert_(record[1] == bin2str(self.some_permid)) # target_permid self.assert_(record[2] == 0) # isForwarder time.sleep(1) s.close()
def create_good_nontribler_extend_hs(self): d = {} d['m'] = {'hallo': 12, 'dag': 255} d['p'] = self.mylistenport d['v'] = 'TestSweet 1.2.3.4' bd = bencode(d) return EXTEND + chr(0) + bd
def create_bad_chunk(self,chunkid): index,begin,length = chunkid ohlist = self.tree.get_hashes_for_piece(index) bohlist = bencode(ohlist) chunk = '*' * length payload = tobinary(index)+tobinary(begin)+tobinary(len(bohlist))+bohlist+chunk return EXTEND+HASHPIECE+payload
def create_good_tribler_extend_hs(self): d = {} d['m'] = {'Tr_OVERLAYSWARM': 253} d['p'] = self.mylistenport d['v'] = 'Tribler 3.5.1' bd = bencode(d) return EXTEND + chr(0) + bd
def create_ohlist_wrong_no_hashes(self,chunkid): index,begin,length = chunkid ohlist = [ (0,'#' * 20),(1,'$' * 20)] # should contain 3 for file2.wmv: own, sibling and root bohlist = bencode(ohlist) chunk = '*' * (2 ** 14) payload = tobinary(index)+tobinary(begin)+tobinary(len(bohlist))+bohlist+chunk return EXTEND+HASHPIECE+payload
def create_initiator_response(self, nonce_b): """ Create the response from the initiator after having the remote node perform the initial challenge. """ assert self.state == self.SEND_INITIATOR_RESPONSE self.state = self.COMPLETED assert nonce_b msg = [CS_INITIATOR_RESPONSE, nonce_b] # Provide the certificate if not self.poa: raise MissingCertificateException() msg.append(self.torrent_id) msg.append(self.poa.torrent_pub_key) msg.append(self.pub_permid) msg.append(self.poa.serialize()) # Sign it list = [nonce_b, self.torrent_id, self.poa.torrent_pub_key, self.pub_permid, self.poa.serialize()] b_list = bencode(list) digest = permid.sha(b_list).digest() sig = self.my_keypair.sign_dsa_asn1(digest) msg.append(sig) return msg
def olthread_cancel_piece_connect_callback(self, exc, dns, permid, piece, selversion): """ Sends the cancel piece message on the connection with the peer Called by the overlay thread. @param exc: Peer reachable/unreachable information. None = peer reachable @param dns: @param permid: the permid of the helper that is requested a piece @param peice: the canceled piece @param selversion: """ if exc is None: # Peer is reachable if DEBUG: print >> sys.stderr, "coordinator: olthread_cancel_piece_connect_callback sending a cancel request to", show_permid_short(permid), "for piece", piece # Create message according to protocol version message = CANCEL_PIECE + self.infohash + bencode(piece) # Connect using Tribler Ovrlay Swarm self.overlay_bridge.send(permid, message, self.olthread_cancel_piece_send_callback) else: # Peer is unreachable if DEBUG: print >> sys.stderr, "coordinator: olthread_cancel_piece_connect_callback: error connecting to",show_permid_short(permid),exc # Remove peer from the list of asked peers self.remove_unreachable_helper(permid)
def olthread_ask_for_help_connect_callback(self,exc,dns,permid,selversion): """ Sends the help request message on the connection with the peer Called by the overlay thread. @param exc: Peer reachable/unreachable information. None = peer reachable @param dns: @param permid: the permid of the peer that is contacted for helping @param selversion """ if exc is None: # Peer is reachable if DEBUG: print >> sys.stderr, "coordinator: olthread_ask_for_help_connect_callback sending help request to",show_permid_short(permid) # get the peer challenge challenge = self.sent_challenges_by_permid[permid] # Create message according to protocol version message = ASK_FOR_HELP + self.infohash + bencode(challenge) # Connect using Tribler Ovrlay Swarm self.overlay_bridge.send(permid, message, self.olthread_ask_for_help_send_callback) else: # Peer is unreachable if DEBUG: print >> sys.stderr, "coordinator: olthread_ask_for_help_connect_callback: error connecting to",show_permid_short(permid),exc # Remove peer from the list of asked peers self.remove_unreachable_helper(permid)
def udpConnect(self, permid, request_id, holePunchingAddr): if DEBUG: print >> sys.stderr, "NatCheckMsgHandler: request UDP connection" mh_data = request_id + ":" + holePunchingAddr[0] + ":" + str( holePunchingAddr[1]) if DEBUG: print >> sys.stderr, "NatCheckMsgHandler: udpConnect message is", mh_data try: mh_msg = bencode(mh_data) except: print_exc() if DEBUG: print >> sys.stderr, "NatCheckMsgHandler: error mh_data:", mh_data return False # send the message self.crawler.send_request(permid, CRAWLER_NATTRAVERSAL, mh_msg, frequency=0, callback=self.udpConnectCallback) if DEBUG: print >> sys.stderr, "NatCheckMsgHandler: request for", show_permid_short( permid), "sent to crawler"
def createAndSendChannelCastMessage(self, target_permid, selversion): """ Create and send a ChannelCast Message """ # ChannelCast feature starts from eleventh version; hence, do not send to lower version peers # Arno, 2010-02-05: v12 uses a different on-the-wire format, ignore those. # Andrea, 2010-04-08: sending the "old-style" channelcast message to older # peers, and enriched channelcast messages to new versions, for full backward # compatibility if selversion < OLPROTO_VER_THIRTEENTH: if DEBUG: print >> sys.stderr, "channelcast: Do not send to lower version peer:", selversion return # 3/5/2010 Andrea: adding the destination parameters to createChannelCastMessage for # logging reasons only. When logging will be disabled, that parameter will # become useless channelcast_data = self.createChannelCastMessage(selversion, target_permid) if channelcast_data is None or len(channelcast_data)==0: if DEBUG: print >>sys.stderr, "channelcast: No channels there.. hence we do not send" return channelcast_msg = bencode(channelcast_data) if self.log: dns = self.dnsindb(target_permid) if dns: ip,port = dns MSG_ID = "CHANNELCAST" msg = repr(channelcast_data) self.overlay_log('SEND_MSG', ip, port, show_permid(target_permid), selversion, MSG_ID, msg) data = CHANNELCAST + channelcast_msg self.overlay_bridge.send(target_permid, data, self.channelCastSendCallback)
def ValueToString(self, value, typex): if typex == "boolean": if value: text = "1" else: text = "0" elif typex == "color": red = str(value.Red()) while len(red) < 3: red = "0" + red green = str(value.Green()) while len(green) < 3: green = "0" + green blue = str(value.Blue()) while len(blue) < 3: blue = "0" + blue text = str(red) + str(green) + str(blue) elif typex.startswith("bencode"): text = bencode(value) else: if type(value) is unicode: text = value else: text = str(value) return text
def handle_crawler_request(self, permid, selversion, channel_id, message, reply_callback): """ Received a CRAWLER_FRIENDSHIP_QUERY request. @param permid The Crawler permid @param selversion The overlay protocol version @param channel_id Identifies a CRAWLER_REQUEST/CRAWLER_REPLY pair @param message The message payload @param reply_callback Call this function once to send the reply: reply_callback(payload [, error=123]) """ if DEBUG: print >> sys.stderr, "FriendshipCrawler: handle_friendship_crawler_database_query_request", message try: d = bdecode(message) stats = self.getStaticsFromFriendshipStatisticsTable( self.session.get_permid(), d['current time']) msg_dict = {'current time': d['current time'], 'stats': stats} msg = bencode(msg_dict) reply_callback(msg) except Exception, e: print_exc() reply_callback(str(e), 1)
def subtest_good_friendship_stats(self): """ Send a valid message-id from a registered crawler peer """ print >>sys.stderr, time.asctime(),'-', "-"*80, "\ntest: good friendship stats" s = OLConnection(self.my_keypair, "localhost", self.hisport) t = time.time() - 100.0 msg_dict = {'current time':int(t)} payload = bencode(msg_dict) self.send_crawler_request(s, CRAWLER_FRIENDSHIP_STATS, 0, 0, payload) error, payload = self.receive_crawler_reply(s, CRAWLER_FRIENDSHIP_STATS, 0) assert error == 0 d = bdecode(payload) if DEBUG: print >>sys.stderr, time.asctime(),'-', "test: Got FRIENDSHIPSTATISTICS",`d` stats = d['stats'] self.assert_(len(stats) == 1) record = d['stats'][0] self.assert_(record[0] == bin2str(self.his_permid)) # source_permid self.assert_(record[1] == bin2str(self.some_permid)) # target_permid self.assert_(record[2] == 0) # isForwarder time.sleep(1) s.close()
def setUpPostSession(self): """ override TestAsServer """ TestAsServer.setUpPostSession(self) self.mypermid = str(self.my_keypair.pub().get_der()) self.hispermid = str(self.his_keypair.pub().get_der()) # Calculating the infohash for proxyservice.test.torrent self.torrentfile = os.path.join('extend_hs_dir','proxyservice.test.torrent') # Read torrentfile to calculate the infohash torrentfile_content = open(self.torrentfile, "rb") # Decode all the file metainfo = bdecode(torrentfile_content.read()) # Re-encode only the info section self.infohash = hashlib.sha1(bencode(metainfo['info'])).digest() # Close the torrentfile torrentfile_content.close() # Add us as friend, so he will accept the ASK_FOR_HELP if False: # TEMP friendsdb = FriendDBHandler.getInstance() friendsdb.addFriend(self.mypermid) else: self.session.set_overlay_request_policy(AllowAllRequestPolicy()) self.session.set_download_states_callback(self.states_callback)
def create_good_tribler_extend_hs(self): d = {} d['m'] = {'Tr_OVERLAYSWARM':253} d['p'] = self.mylistenport d['v'] = 'Tribler 3.5.1' bd = bencode(d) return EXTEND+chr(0)+bd
def create_diff_ips(self, i): if self.NLISTENERS == 1: s = REPLY_IP else: s = '127.0.0.' + str(i) b = bencode(s) return DIALBACK_REPLY + b
def check_response1(self, resp1_data, rB, myid): resp1 = bdecode(resp1_data) self.assert_(type(resp1) == DictType) self.assert_(resp1.has_key('certA')) self.assert_(resp1.has_key('rA')) self.assert_(resp1.has_key('B')) self.assert_(resp1.has_key('SA')) # show throw exception when key no good pubA = EC.pub_key_from_der(resp1['certA']) rA = resp1['rA'] self.assert_(type(rA) == StringType) self.assert_(len(rA) == random_size) B = resp1['B'] self.assert_(type(B) == StringType) self.assert_(B, myid) SA = resp1['SA'] self.assert_(type(SA) == StringType) # verify signature sig_list = [rA, rB, myid] sig_data = bencode(sig_list) sig_hash = sha(sig_data).digest() self.assert_(pubA.verify_dsa_asn1(sig_hash, SA)) # Cannot resign the data with his keypair to double check. Signing # appears to yield different, supposedly valid sigs each time. return resp1
def create_good_nontribler_extend_hs(self): d = {} d['m'] = {'hallo':12, 'dag':255 } d['p'] = self.mylistenport d['v'] = 'TestSweet 1.2.3.4' bd = bencode(d) return EXTEND+chr(0)+bd
def createAndSendVoteCastMessage(self, target_permid, selversion): """ Creates and sends a VOTECAST message """ # Arno, 2010-02-05: v12 uses a different on-the-wire format, ignore those. if selversion < OLPROTO_VER_THIRTEENTH: if DEBUG: print >> sys.stderr, "votecast: Do not send to lower version peer:", selversion return votecast_data = self.createVoteCastMessage() if len(votecast_data) == 0: if DEBUG: print >>sys.stderr, "votecast: No votes there.. hence we do not send" return votecast_msg = bencode(votecast_data) if self.log: dns = self.dnsindb(target_permid) if dns: ip,port = dns MSG_ID = "VOTECAST" # msg = voteCastReplyMsgToString(votecast_data) self.overlay_log('SEND_MSG', ip, port, show_permid(target_permid), selversion, MSG_ID) if DEBUG: print >> sys.stderr, "votecast: Sending votecastmsg",voteCastMsgToString(votecast_data) # data = VOTECAST + votecast_msg # self.secure_overlay.send(target_permid, data, self.voteCastSendCallback) self.secure_overlay.send(target_permid, VOTECAST + votecast_msg, self.voteCastSendCallback)
def createAndSendChannelCastMessage(self, target_permid, selversion): """ Create and send a ChannelCast Message """ # ChannelCast feature starts from eleventh version; hence, do not send to lower version peers if selversion < OLPROTO_VER_ELEVENTH: if DEBUG: print >> sys.stderr, "Do not send to lower version peer:", selversion return channelcast_data = self.createChannelCastMessage() if channelcast_data is None or len(channelcast_data) == 0: if DEBUG: print >> sys.stderr, "No channels there.. hence we do not send" #self.session.chquery_connected_peers('k:MFIwEAYHKoZIzj0CAQYFK4EEABoDPgAEAf3BkHsZ6UdIpuIX441wjU5Ybe0HPjTDvS+iacFZABH20It9N9uwkwtpkS3uEvVvfcTX50jcFNXOSCwq') return channelcast_msg = bencode(channelcast_data) if self.log: dns = self.dnsindb(target_permid) if dns: ip, port = dns MSG_ID = "CHANNELCAST" msg = repr(channelcast_data) self.overlay_log('SEND_MSG', ip, port, show_permid(target_permid), selversion, MSG_ID, msg) data = CHANNELCAST + channelcast_msg self.secure_overlay.send(target_permid, data, self.channelCastSendCallback) if DEBUG: print >> sys.stderr, "Sent channelcastmsg", repr(channelcast_msg)
def create_remote_query_reply(self, id, hits, selversion): getsize = os.path.getsize join = os.path.join d = {} d['id'] = id d2 = {} for torrent in hits: r = {} # NEWDBSTANDARD. Do not rename r's fields: they are part of the # rquery protocol spec. r['content_name'] = torrent[ 'name'] # According to TorrentDBHandler.addExternalTorrentencoded this is the original encoded name, TODO: standardize on UTF-8 encoding. r['length'] = torrent['length'] r['leecher'] = torrent['num_leechers'] r['seeder'] = torrent['num_seeders'] # Arno: TODO: sending category doesn't make sense as that's user-defined # leaving it now because of time constraints r['category'] = torrent['category'] if selversion >= OLPROTO_VER_NINETH: r['torrent_size'] = getsize( join(self.torrent_dir, torrent['torrent_file_name'])) if selversion >= OLPROTO_VER_ELEVENTH: r['channel_permid'] = torrent['channel_permid'] r['channel_name'] = torrent['channel_name'] if selversion >= OLPROTO_VER_TWELFTH and 'metadata' in torrent: if DEBUG: print >> sys.stderr, "rqmh: create_query_reply: Adding torrent file" r['metatype'] = torrent['metatype'] r['metadata'] = torrent['metadata'] d2[torrent['infohash']] = r d['a'] = d2 return bencode(d)
def createAndSendChannelCastMessage(self, target_permid, selversion): """ Create and send a ChannelCast Message """ # ChannelCast feature starts from eleventh version; hence, do not send to lower version peers if selversion < OLPROTO_VER_ELEVENTH: if DEBUG: print >> sys.stderr, "Do not send to lower version peer:", selversion return channelcast_data = self.createChannelCastMessage() if channelcast_data is None or len(channelcast_data)==0: if DEBUG: print >>sys.stderr, "No channels there.. hence we do not send" #self.session.chquery_connected_peers('k:MFIwEAYHKoZIzj0CAQYFK4EEABoDPgAEAf3BkHsZ6UdIpuIX441wjU5Ybe0HPjTDvS+iacFZABH20It9N9uwkwtpkS3uEvVvfcTX50jcFNXOSCwq') return channelcast_msg = bencode(channelcast_data) if self.log: dns = self.dnsindb(target_permid) if dns: ip,port = dns MSG_ID = "CHANNELCAST" msg = repr(channelcast_data) self.overlay_log('SEND_MSG', ip, port, show_permid(target_permid), selversion, MSG_ID, msg) data = CHANNELCAST + channelcast_msg self.secure_overlay.send(target_permid, data, self.channelCastSendCallback) if DEBUG: print >> sys.stderr, "Sent channelcastmsg",repr(channelcast_msg)
def create_diff_ips(self,i): if self.NLISTENERS==1: s = REPLY_IP else: s = '127.0.0.'+str(i) b = bencode(s) return DIALBACK_REPLY+b
def createAndSendVoteCastMessage(self, target_permid, selversion): """ Creates and sends a VOTECAST message """ if selversion < OLPROTO_VER_ELEVENTH: if DEBUG: print >> sys.stderr, "Do not send to lower version peer:", selversion return votecast_data = self.createVoteCastMessage() if len(votecast_data) == 0: if DEBUG: print >>sys.stderr, "No votes there.. hence we do not send" return votecast_msg = bencode(votecast_data) if self.log: dns = self.dnsindb(target_permid) if dns: ip,port = dns MSG_ID = "VOTECAST" msg = voteCastReplyMsgToString(votecast_data) self.overlay_log('SEND_MSG', ip, port, show_permid(target_permid), selversion, MSG_ID, msg) if DEBUG: print >> sys.stderr, "Sending votecastmsg",voteCastMsgToString(votecast_data) data = VOTECAST+votecast_msg self.secure_overlay.send(target_permid, data, self.voteCastSendCallback)
def create_dropped_too_small(self): d = {} d['added'] = '' d['added.f'] = '' d['dropped'] = '\x82\x25\xc1\x40\x00' # should be 6 bytes bd = bencode(d) return EXTEND+chr(1)+bd
def create_dropped_not_str(self): d = {} d['added'] = '' d['added.f'] = '' d['dropped'] = 481 bd = bencode(d) return EXTEND+chr(1)+bd
def create_added_f_too_big(self): d = {} d['added'] = '' d['added.f'] = '\x00' d['dropped'] = '' bd = bencode(d) return EXTEND+chr(1)+bd
def get_default_torrent(self,filename,title,paths=None): metainfo = {} metainfo['announce'] = 'http://localhost:0/announce' metainfo['announce-list'] = [] metainfo['creation date'] = int(time.time()) metainfo['encoding'] = 'UTF-8' info = {} info['name'] = title.encode("UTF-8") info['piece length'] = 2 ** 16 info['pieces'] = '*' * 20 if paths is None: info['length'] = 481 else: d1 = {} d1['path'] = [paths[0].encode("UTF-8")] d1['length'] = 201 d2 = {} d2['path'] = [paths[1].encode("UTF-8")] d2['length'] = 280 info['files'] = [d1,d2] metainfo['info'] = info path = os.path.join(self.config.get_torrent_collecting_dir(),filename) tdef = TorrentDef.load_from_dict(metainfo) tdef.save(path) return tdef, bencode(metainfo)
def create_good_ut_pex(self,pex_id=1): d = {} d['added'] = '' d['added.f'] = '' d['dropped'] = '' bd = bencode(d) return EXTEND+chr(pex_id)+bd
def create_remote_query_reply(self,id,hits,selversion): getsize = os.path.getsize join = os.path.join d = {} d['id'] = id d2 = {} for torrent in hits: r = {} # NEWDBSTANDARD. Do not rename r's fields: they are part of the # rquery protocol spec. r['content_name'] = torrent['name'] # According to TorrentDBHandler.addExternalTorrentencoded this is the original encoded name, TODO: standardize on UTF-8 encoding. r['length'] = torrent['length'] r['leecher'] = torrent['num_leechers'] r['seeder'] = torrent['num_seeders'] # Arno: TODO: sending category doesn't make sense as that's user-defined # leaving it now because of time constraints r['category'] = torrent['category'] if selversion >= OLPROTO_VER_NINETH: r['torrent_size'] = getsize(join(self.torrent_dir, torrent['torrent_file_name'])) if selversion >= OLPROTO_VER_ELEVENTH: r['channel_permid'] = torrent['channel_permid'] r['channel_name'] = torrent['channel_name'] if selversion >= OLPROTO_VER_TWELFTH and 'metadata' in torrent: if DEBUG: print >>sys.stderr,"rqmh: create_query_reply: Adding torrent file" r['metatype'] = torrent['metatype'] r['metadata'] = torrent['metadata'] d2[torrent['infohash']] = r d['a'] = d2 return bencode(d)
def validChannelCastMsg(channelcast_data): """ Returns true if ChannelCastMsg is valid, format: {'signature':{'publisher_id':, 'publisher_name':, 'infohash':, 'torrenthash':, 'torrent_name':, 'timestamp':, 'signature':}} """ if not isinstance(channelcast_data,dict): return False for signature, ch in channelcast_data.items(): if not isinstance(ch,dict): if DEBUG: print >>sys.stderr,"rvalidChannelCastMsg: a: value not dict" return False if len(ch) !=6: if DEBUG: print >>sys.stderr,"rvalidChannelCastMsg: a: #keys!=6" return False if not ('publisher_id' in ch and 'publisher_name' in ch and 'infohash' in ch and 'torrenthash' in ch and 'torrentname' in ch and 'time_stamp' in ch): if DEBUG: print >>sys.stderr,"validChannelCastMsg: a: key missing, got",d.keys() return False if not (validPermid(ch['publisher_id']) and (isinstance(ch['publisher_name'],str) or isinstance(ch['publisher_name'], unicode)) and validInfohash(ch['infohash']) and validInfohash(ch['torrenthash']) and (isinstance(ch['torrentname'],str) or isinstance(ch['torrentname'],unicode)) and validTimestamp(ch['time_stamp'])): if DEBUG: print >>sys.stderr,"validChannelCastMsg: something not valid" return False # now, verify signature l = (ch['publisher_id'],ch['infohash'], ch['torrenthash'], ch['time_stamp']) if not verify_data(bencode(l),str2bin(ch['publisher_id']),str2bin(signature)): if DEBUG: print >>sys.stderr, "validChannelCastMsg: verification failed!" return False return True
def _create_poa_message(self, msg_id, nonce_a, nonce_b): """ Create the POA exchange message (messages 3 and 4). """ assert msg_id assert nonce_a assert nonce_b assert self.poa # Provide the certificate if not self.poa: raise MissingCertificateException("Missing certificate") msg = [msg_id] + self.poa.serialize_to_list() # Add signature lst = [nonce_a, nonce_b, self.poa.serialize()] b_list = bencode(lst) digest = permid.sha(b_list).digest() sig = self.my_keypair.sign_dsa_asn1(digest) msg.append(sig) return msg
def createAndSendBarterCastMessage(self, target_permid, selversion, active = False): # for older versions of Tribler (non-BarterCast): do nothing if selversion <= OLPROTO_VER_FIFTH: return if DEBUG: print >> sys.stderr, "===========bartercast: Sending BarterCast msg to ", self.bartercastdb.getName(target_permid) # create a new bartercast message bartercast_data = self.createBarterCastMessage(target_permid) if LOG: self.logMsg(bartercast_data, target_permid, 'out', logfile = self.logfile) try: bartercast_msg = bencode(bartercast_data) except: print_exc() print >> sys.stderr, "error bartercast_data:", bartercast_data return # send the message self.overlay_bridge.send(target_permid, BARTERCAST+bartercast_msg, self.bartercastSendCallback) self.blockPeer(target_permid, self.send_block_list, self.block_interval)
def create_not_bdecodable_torrentfile(self, id): d = self.create_good_simple_reply_dict(id) d['a'][self.tdef.get_infohash( )]['torrent_size'] = 3 # consistent with metadata. Should be named "metasize" d['a'][self.tdef.get_infohash()]['metadata'] = 'bla' b = bencode(d) return QUERY_REPLY + b
def check_response1(self, resp1_data, rB, myid): resp1 = bdecode(resp1_data) self.assert_(type(resp1) == DictType) self.assert_(resp1.has_key("certA")) self.assert_(resp1.has_key("rA")) self.assert_(resp1.has_key("B")) self.assert_(resp1.has_key("SA")) # show throw exception when key no good pubA = EC.pub_key_from_der(resp1["certA"]) rA = resp1["rA"] self.assert_(type(rA) == StringType) self.assert_(len(rA) == random_size) B = resp1["B"] self.assert_(type(B) == StringType) self.assert_(B, myid) SA = resp1["SA"] self.assert_(type(SA) == StringType) # verify signature sig_list = [rA, rB, myid] sig_data = bencode(sig_list) sig_hash = sha(sig_data).digest() self.assert_(pubA.verify_dsa_asn1(sig_hash, SA)) # Cannot resign the data with his keypair to double check. Signing # appears to yield different, supposedly valid sigs each time. return resp1
def create_good_tribler_extend_hs(self,pex_id=1): d = {} d['m'] = {'Tr_OVERLAYSWARM':253,'ut_pex':pex_id} d['p'] = self.mylistenport d['v'] = 'Tribler 3.5.1' d['e'] = 0 bd = bencode(d) return EXTEND+chr(0)+bd
def create_ohlist_wrong_bad_hash(self,chunkid): index,begin,length = chunkid ohlist = self.tree.get_hashes_for_piece(index) ohlist[1][1] = '$' * 20 bohlist = bencode(ohlist) chunk = self.read_chunk(index,begin,length) payload = tobinary(index)+tobinary(begin)+tobinary(len(bohlist))+bohlist+chunk return EXTEND+HASHPIECE+payload
def create_torrent_signature(metainfo,keypairfilename): keypair = EC.load_key(keypairfilename) bmetainfo = bencode(metainfo) digester = sha(bmetainfo[:]) digest = digester.digest() sigstr = keypair.sign_dsa_asn1(digest) metainfo['signature'] = sigstr metainfo['signer'] = str(keypair.pub().get_der())
def create_good_tribler_extend_hs_v2(self, g2g_id=G2G_ID): d = {} d['m'] = {'Tr_OVERLAYSWARM': 253, 'Tr_G2G_v2': g2g_id} d['p'] = self.mylistenport d['v'] = 'Tribler 4.2.0' d['e'] = 0 bd = bencode(d) return EXTEND + chr(0) + bd
def create_good_metadata(self): f = open(self.torrentfile, "rb") data = f.read() f.close() d = self.create_good_metadata_dict(data) bd = bencode(d) return METADATA + bd
def create_good_nontribler_extend_hs(self): """ Merkle BEP style """ d = {} d['m'] = {'Tr_hashpiece':250} d['p'] = self.mylistenport d['v'] = 'TestSweet 1.2.3.4' bd = bencode(d) return EXTEND+chr(0)+bd
def generate_response1(randomB,peeridB,keypairA): randomA = Rand.rand_bytes(num_random_bits/8) response1 = {} response1['certA'] = str(keypairA.pub().get_der()) response1['rA'] = randomA response1['B'] = peeridB response1['SA'] = sign_response(randomA,randomB,peeridB,keypairA) return [randomA,bencode(response1)]
def sign(self, torrent_key_pair): list = [self.torrent_id, self.torrent_pub_key, self.node_pub_key] b_list = bencode(list) digest = permid.sha(b_list).digest() self.signature = torrent_key_pair.sign_dsa_asn1(digest)
def create_good_tribler_extend_hs(self): d = {} d['m'] = {'Tr_OVERLAYSWARM': 253} d['p'] = self.mylistenport d['v'] = 'Tribler 4.5.0' d['yourip'] = compact_ip('127.0.0.1') d['ipv4'] = compact_ip('224.4.8.1') bd = bencode(d) return EXTEND + chr(0) + bd