From 4dea6d5ced8e30bc05a4f10ec130529c3be8b43f Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Mon, 23 Dec 2019 19:47:23 +0530 Subject: [PATCH 1/8] mpybit py3 fixes --- src/bitmessagekivy/identiconGeneration.py | 10 ------ src/bitmessagekivy/kivy_helper_search.py | 23 +++++++----- src/bitmessagekivy/mpybit.py | 43 +++++++++-------------- src/bitmessagekivy/uikivysignaler.py | 12 ++++--- 4 files changed, 38 insertions(+), 50 deletions(-) diff --git a/src/bitmessagekivy/identiconGeneration.py b/src/bitmessagekivy/identiconGeneration.py index 42b5816a..25bd2254 100644 --- a/src/bitmessagekivy/identiconGeneration.py +++ b/src/bitmessagekivy/identiconGeneration.py @@ -2,7 +2,6 @@ Core classes for loading images and converting them to a Texture. The raw image data can be keep in memory for further access """ - import hashlib from io import BytesIO @@ -26,7 +25,6 @@ def generate(Generate_string=None): image = Image.new(MODE, V_RESOLUTION, BACKGROUND_COLOR) image = generate_image(image, color, hash_string) image = image.resize(RESOLUTION, 0) - data = BytesIO() image.save(data, format='png') data.seek(0) @@ -46,10 +44,8 @@ def generate_hash(string): string = str.lower(string) hash_object = hashlib.md5(str.encode(string)) print(hash_object.hexdigest()) - # returned object is a hex string return hash_object.hexdigest() - except IndexError: print("Error: Please enter a string as an argument.") @@ -59,29 +55,24 @@ def random_color(hash_string): # remove first three digits from hex string split = 6 rgb = hash_string[:split] - split = 2 r = rgb[:split] g = rgb[split:2 * split] b = rgb[2 * split:3 * split] - color = (int(r, 16), int(g, 16), int(b, 16), 0xFF) - return color def generate_image(image, color, hash_string): """Generating images""" hash_string = hash_string[6:] - lower_x = 1 lower_y = 1 upper_x = int(V_RESOLUTION[0] / 2) + 1 upper_y = V_RESOLUTION[1] - 1 limit_x = V_RESOLUTION[0] - 1 index = 0 - for x in range(lower_x, upper_x): for y in range(lower_y, upper_y): if int(hash_string[index], 16) % 2 == 0: @@ -89,5 +80,4 @@ def generate_image(image, color, hash_string): image.putpixel((limit_x - x, y), color) index = index + 1 - return image diff --git a/src/bitmessagekivy/kivy_helper_search.py b/src/bitmessagekivy/kivy_helper_search.py index 48e77cb2..83683d15 100644 --- a/src/bitmessagekivy/kivy_helper_search.py +++ b/src/bitmessagekivy/kivy_helper_search.py @@ -4,25 +4,25 @@ Sql queries for bitmessagekivy from helper_sql import sqlQuery -def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, what=None, unreadOnly=False, start_indx=0, end_indx=20): +def search_sql( + xAddress="toaddress", account=None, folder="inbox", where=None, + what=None, unreadOnly=False, start_indx=0, end_indx=20): """Method helping for searching mails""" # pylint: disable=too-many-arguments, too-many-branches if what is not None and what != "": what = "%" + what + "%" else: what = None - if folder == "sent" or folder == "draft": sqlStatementBase = ( - '''SELECT toaddress, fromaddress, subject, message, status, ackdata,''' - ''' lastactiontime FROM sent ''') + '''SELECT toaddress, fromaddress, subject, message, status,''' + ''' ackdata, lastactiontime FROM sent ''') elif folder == "addressbook": sqlStatementBase = '''SELECT label, address From addressbook ''' else: sqlStatementBase = ( - '''SELECT folder, msgid, toaddress, message, fromaddress, subject,''' - ''' received, read FROM inbox ''') - + '''SELECT folder, msgid, toaddress, message, fromaddress,''' + ''' subject, received, read FROM inbox ''') sqlStatementParts = [] sqlArguments = [] if account is not None: @@ -58,10 +58,15 @@ def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, w sqlStatementParts.append("read = 0") if sqlStatementParts: sqlStatementBase += "WHERE " + " AND ".join(sqlStatementParts) + # if folder in ("sent", "draft"): if folder == "sent" or folder == "draft": - sqlStatementBase += " ORDER BY lastactiontime DESC limit {0}, {1}".format(start_indx, end_indx) + sqlStatementBase += \ + "ORDER BY lastactiontime DESC limit {0}, {1}".format( + start_indx, end_indx) elif folder == "inbox": - sqlStatementBase += " ORDER BY received DESC limit {0}, {1}".format(start_indx, end_indx) + sqlStatementBase += \ + "ORDER BY received DESC limit {0}, {1}".format( + start_indx, end_indx) # elif folder == "addressbook": # sqlStatementBase += " limit {0}, {1}".format(start_indx, end_indx) return sqlQuery(sqlStatementBase, sqlArguments) diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 64bbfc67..790cdb97 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -1,8 +1,8 @@ """ Bitmessage android(mobile) interface """ -# pylint: disable=relative-import, import-error, no-name-in-module -# pylint: disable=too-few-public-methods, too-many-lines, unused-argument +# pylint: disable=import-error, no-name-in-module, too-many-lines +# pylint: disable=too-few-public-methods, unused-argument, too-many-ancestors import os import time from bmconfigparser import BMConfigParser @@ -36,9 +36,7 @@ from kivy.uix.screenmanager import Screen from kivy.uix.spinner import Spinner from kivy.uix.textinput import TextInput from kivy.utils import platform - - -from bitmessagekivy import kivy_helper_search +from bitmessagekivy import kivy_helper_search from kivymd.uix.button import MDIconButton from kivymd.uix.dialog import MDDialog from kivymd.uix.label import MDLabel @@ -48,7 +46,6 @@ from kivymd.uix.list import ( IRightBodyTouch, TwoLineAvatarIconListItem, TwoLineListItem, - OneLineIconListItem ) from kivymd.uix.navigationdrawer import ( MDNavigationDrawer, @@ -525,7 +522,7 @@ class AddressBook(Screen): class SelectableRecycleBoxLayout( FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout): """Adds selection and focus behaviour to the view""" - # pylint: disable = too-many-ancestors, duplicate-bases + # pylint: disable = duplicate-bases pass @@ -541,7 +538,6 @@ class SelectableLabel(RecycleDataViewBehavior, Label): return super(SelectableLabel, self).refresh_view_attrs( rv, index, data) - # pylint: disable=inconsistent-return-statements def on_touch_down(self, touch): """Add selection on touch down""" if super(SelectableLabel, self).on_touch_down(touch): @@ -568,7 +564,6 @@ class RV(RecycleView): class DropDownWidget(BoxLayout): """Adding Dropdown Widget""" # pylint: disable=too-many-statements, too-many-locals - # pylint: disable=inconsistent-return-statements txt_input = ObjectProperty() rv = ObjectProperty() @@ -579,7 +574,7 @@ class DropDownWidget(BoxLayout): subject = self.ids.subject.text.strip() message = self.ids.subject.text.strip() encoding = 3 - print ("message: ", self.ids.body.text) + print("message: ", self.ids.body.text) sendMessageToPeople = True if sendMessageToPeople: if toAddress != '' and subject and message: @@ -606,12 +601,11 @@ class DropDownWidget(BoxLayout): statusIconColor = 'red' if (addressVersionNumber > 4) or ( addressVersionNumber <= 1): - print ("addressVersionNumber > 4"\ - " or addressVersionNumber <= 1") + print("addressVersionNumber > 4 or addressVersionNumber <= 1") if streamNumber > 1 or streamNumber == 0: - print ("streamNumber > 1 or streamNumber == 0") + print("streamNumber > 1 or streamNumber == 0") if statusIconColor == 'red': - print ("shared.statusIconColor == 'red'") + print("shared.statusIconColor == 'red'") stealthLevel = BMConfigParser().safeGetInt( 'bitmessagesettings', 'ackstealthlevel') from helper_ackPayload import genAckPayload @@ -652,7 +646,7 @@ class DropDownWidget(BoxLayout): # self.parent.parent.screens[16].add_widget(Allmails()) Clock.schedule_once(self.callback_for_msgsend, 3) queues.workerQueue.put(('sendmessage', toAddress)) - print ("sqlExecute successfully #######################") + print("sqlExecute successfully #######################") state.in_composer = True return else: @@ -708,7 +702,7 @@ class MyTextInput(TextInput): starting_no = NumericProperty(3) suggestion_text = '' - def __init__(self, **kwargs): # pylint: disable=useless-super-delegation + def __init__(self, **kwargs): # pylint: disable=useless-super-delegation """Getting Text Input.""" super(MyTextInput, self).__init__(**kwargs) @@ -802,6 +796,7 @@ class NetworkStat(Screen): class ContentNavigationDrawer(Navigatorss): """Navigate Content Drawer""" + # pylint: disable=too-many-arguments pass @@ -1283,8 +1278,6 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods def build(self): """Method builds the widget""" - print("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSss") - print(os.path.join(os.path.dirname(__file__), 'main.kv')) main_widget = Builder.load_file( os.path.join(os.path.dirname(__file__), 'main.kv')) self.nav_drawer = Navigatorss() @@ -1385,7 +1378,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods if not os.path.exists(directory): os.makedirs(directory) except OSError: - print ('Error: Creating directory. ' + directory) + print('Error: Creating directory. ' + directory) @staticmethod def get_default_image(): @@ -1586,7 +1579,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods @staticmethod def on_stop(): """On stop methos is used for stoping the runing script""" - print ("*******************EXITING FROM APPLICATION*******************") + print("*******************EXITING FROM APPLICATION*******************") import shutdown shutdown.doCleanShutdown() @@ -1699,7 +1692,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods self.root.ids.scr_mngr.current = 'allmails' try: self.root.ids.sc17.children[1].active = True - except Exception as e: + except Exception: self.root.ids.sc17.children[0].children[1].active = True Clock.schedule_once(partial(self.load_screen_callback, instance), 1) @@ -1714,7 +1707,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods self.root.ids.sc17.add_widget(Allmails()) try: self.root.ids.sc17.children[1].active = False - except Exception as e: + except Exception: self.root.ids.sc17.children[0].children[1].active = False @@ -2328,9 +2321,7 @@ class Draft(Screen): 0, 'draft', encoding, - int(BMConfigParser().safeGet( - 'bitmessagesettings', 'ttl'))) - + int(BMConfigParser().safeGet('bitmessagesettings', 'ttl'))) state.msg_counter_objs = src_object.children[2].children[0].ids state.draft_count = str(int(state.draft_count) + 1) src_object.ids.sc16.clear_widgets() @@ -2366,7 +2357,7 @@ class Allmails(Screen): def init_ui(self, dt=0): """Clock Schdule for method all mails""" self.loadMessagelist() - print (dt) + print(dt) def loadMessagelist(self): """Load Inbox, Sent anf Draft list of messages.""" diff --git a/src/bitmessagekivy/uikivysignaler.py b/src/bitmessagekivy/uikivysignaler.py index cb9473e2..aac45fd5 100644 --- a/src/bitmessagekivy/uikivysignaler.py +++ b/src/bitmessagekivy/uikivysignaler.py @@ -1,12 +1,15 @@ - +""" +Ui Singnaler for kivy interface +""" from threading import Thread -import state + import queues +import state from semaphores import kivyuisignaler -from helper_sql import SqlBulkExecute, sqlExecute, sqlQuery, sqlStoredProcedure class UIkivySignaler(Thread): + """Kivy ui signaler""" def run(self): kivyuisignaler.acquire() @@ -14,13 +17,12 @@ class UIkivySignaler(Thread): try: command, data = queues.UISignalQueue.get() if command == 'writeNewAddressToTable': - label, address, streamNumber = data + address = data[1] state.kivyapp.variable_1.append(address) # elif command == 'rerenderAddressBook': # state.kivyapp.obj_1.refreshs() # Need to discuss this elif command == 'updateSentItemStatusByAckdata': state.kivyapp.status_dispatching(data) - except Exception as e: print(e) From 0de9e3841523368ecf100320fb811b610938c253 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Tue, 24 Dec 2019 19:32:37 +0530 Subject: [PATCH 2/8] python3 fixes --- src/addresses.py | 14 ++++--- src/api.py | 65 +++++++++++++++++--------------- src/bitmessagecurses/__init__.py | 8 ++-- src/bitmessagemain.py | 42 ++++++++++++--------- src/bmconfigparser.py | 26 ++++++++----- src/build_osx.py | 10 ++++- 6 files changed, 95 insertions(+), 70 deletions(-) diff --git a/src/addresses.py b/src/addresses.py index 50602c5a..e58d06de 100644 --- a/src/addresses.py +++ b/src/addresses.py @@ -2,7 +2,6 @@ Operations with addresses """ # pylint: disable=redefined-outer-name,inconsistent-return-statements - import hashlib from binascii import hexlify, unhexlify from struct import pack, unpack @@ -46,7 +45,8 @@ def decodeBase58(string, alphabet=ALPHABET): for char in string: num *= base num += alphabet.index(char) - except: # ValueError + # ValueError + except: # character not found (like a space character or a 0) return 0 return num @@ -85,13 +85,13 @@ def decodeVarint(data): the minimum amount of data possible or else it is malformed. Returns a tuple: (theEncodedValue, theSizeOfTheVarintInBytes) """ - if not data: return (0, 0) firstByte, = unpack('>B', data[0:1]) if firstByte < 253: # encodes 0 to 252 - return (firstByte, 1) # the 1 is the length of the varint + # the 1 is the length of the varint + return (firstByte, 1) if firstByte == 253: # encodes 253 to 65535 if len(data) < 3: @@ -180,7 +180,8 @@ def decodeAddress(address): returns (status, address version number, stream number, data (almost certainly a ripe hash)) """ - # pylint: disable=too-many-return-statements,too-many-statements,too-many-return-statements,too-many-branches + # pylint: disable=too-many-return-statements,too-many-statements + # pylint: disable=too-many-branches address = str(address).strip() if address[:3] == 'BM-': @@ -237,7 +238,8 @@ def decodeAddress(address): status = 'success' if addressVersionNumber == 1: return status, addressVersionNumber, streamNumber, data[-24:-4] - elif addressVersionNumber == 2 or addressVersionNumber == 3: + # elif addressVersionNumber == 2 or addressVersionNumber == 3: + elif addressVersionNumber in (2, 3): embeddedRipeData = \ data[bytesUsedByVersionNumber + bytesUsedByStreamNumber:-4] if len(embeddedRipeData) == 19: diff --git a/src/api.py b/src/api.py index f9d0a518..cceff623 100644 --- a/src/api.py +++ b/src/api.py @@ -1,15 +1,12 @@ -# pylint: disable=too-many-locals,too-many-lines,no-self-use,too-many-public-methods,too-many-branches -# pylint: disable=too-many-statements - -# Copyright (c) 2012-2016 Jonathan Warren -# Copyright (c) 2012-2019 The Bitmessage developers - """ This is not what you run to run the Bitmessage API. Instead, enable the API ( https://bitmessage.org/wiki/API ) and optionally enable daemon mode ( https://bitmessage.org/wiki/Daemon ) then run bitmessagemain.py. """ - +# pylint: disable=too-many-locals,too-many-lines,no-self-use,unused-argument +# pylint: disable=too-many-statements,too-many-public-methods,too-many-branches +# Copyright (c) 2012-2016 Jonathan Warren +# Copyright (c) 2012-2019 The Bitmessage developers import base64 import errno import hashlib @@ -58,6 +55,7 @@ class APIError(Exception): class StoppableXMLRPCServer(SimpleXMLRPCServer): """A SimpleXMLRPCServer that honours state.shutdown""" + # pylint:disable=too-few-public-methods allow_reuse_address = True def serve_forever(self): @@ -150,7 +148,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): Note: this method is the same as in SimpleXMLRPCRequestHandler, just hacked to handle cookies """ - # Check that the path is legal if not self.is_rpc_path_valid(): self.report_404() @@ -175,10 +172,12 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): # SimpleXMLRPCDispatcher. To maintain backwards compatibility, # check to see if a subclass implements _dispatch and dispatch # using that method if present. - response = self.server._marshaled_dispatch( # pylint: disable=protected-access + # pylint: disable=protected-access + response = self.server._marshaled_dispatch( data, getattr(self, '_dispatch', None) ) - except BaseException: # This should only happen if the module is buggy + # This should only happen if the module is buggy + except BaseException: # internal error, report as HTTP server error self.send_response(500) self.end_headers() @@ -251,7 +250,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): if status == 'invalidcharacters': raise APIError(9, 'Invalid characters in address: ' + address) if status == 'versiontoohigh': - raise APIError(10, 'Address version number too high (or zero) in address: ' + address) + raise APIError( + 10, 'Address version number too high (or zero) in address: ' + address) if status == 'varintmalformed': raise APIError(26, 'Malformed varint in address: ' + address) raise APIError(7, 'Could not decode address: %s : %s' % (address, status)) @@ -275,7 +275,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): data = '{"addresses":[' for addressInKeysFile in BMConfigParser().addresses(): - status, addressVersionNumber, streamNumber, hash01 = decodeAddress( # pylint: disable=unused-variable + # pylint: disable=unused-variable + status, addressVersionNumber, streamNumber, hash01 = decodeAddress( addressInKeysFile) if len(data) > 20: data += ',' @@ -485,7 +486,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): # 0 means "just use the proper addressVersionNumber" if addressVersionNumber == 0: addressVersionNumber = 4 - if addressVersionNumber != 3 and addressVersionNumber != 4: + # if addressVersionNumber != 3 and addressVersionNumber != 4: + if addressVersionNumber not in (3, 4): raise APIError( 2, 'The address version number currently must be 3, 4, or 0' ' (which means auto-select). %i isn\'t supported.' % @@ -536,7 +538,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): if not passphrase: raise APIError(1, 'The specified passphrase is blank.') passphrase = self._decode(passphrase, "base64") - if addressVersionNumber != 3 and addressVersionNumber != 4: + # if addressVersionNumber != 3 and addressVersionNumber != 4: + if addressVersionNumber not in (3, 4): raise APIError( 2, 'The address version number currently must be 3 or 4. %i' ' isn\'t supported.' % addressVersionNumber) @@ -606,8 +609,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): label = str_chan + ' ' + passphrase except BaseException: label = str_chan + ' ' + repr(passphrase) - - status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress( # pylint: disable=unused-variable + # pylint: disable=unused-variable + status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress( suppliedAddress) suppliedAddress = addBMIfNotPresent(suppliedAddress) queues.apiAddressGeneratorReturnQueue.queue.clear() @@ -632,7 +635,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): elif len(params) == 1: address, = params # pylint: disable=unused-variable - status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(address) + status, addressVersionNumber, streamNumber, toRipe = \ + self._verifyAddress(address) address = addBMIfNotPresent(address) if not BMConfigParser().has_section(address): raise APIError( @@ -654,7 +658,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): elif len(params) == 1: address, = params # pylint: disable=unused-variable - status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(address) + status, addressVersionNumber, streamNumber, toRipe = \ + self._verifyAddress(address) address = addBMIfNotPresent(address) if not BMConfigParser().has_section(address): raise APIError( @@ -666,7 +671,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): shared.reloadMyAddressHashes() return 'success' - def HandleGetAllInboxMessages(self, params): # pylint: disable=unused-argument + def HandleGetAllInboxMessages(self, params): """Handle a request to get all inbox messages""" queryreturn = sqlQuery( @@ -694,7 +699,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): data += ']}' return data - def HandleGetAllInboxMessageIds(self, params): # pylint: disable=unused-argument + def HandleGetAllInboxMessageIds(self, params): """Handle a request to get all inbox message IDs""" queryreturn = sqlQuery( @@ -753,7 +758,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): data += ']}' return data - def HandleGetAllSentMessages(self, params): # pylint: disable=unused-argument + def HandleGetAllSentMessages(self, params): """Handle a request to get all sent messages""" queryreturn = sqlQuery( @@ -782,7 +787,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): data += ']}' return data - def HandleGetAllSentMessageIds(self, params): # pylint: disable=unused-argument + def HandleGetAllSentMessageIds(self, params): """Handle a request to get all sent message IDs""" queryreturn = sqlQuery( @@ -1157,7 +1162,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): queues.UISignalQueue.put(('rerenderSubscriptions', '')) return 'Deleted subscription if it existed.' - def ListSubscriptions(self, params): # pylint: disable=unused-argument + def ListSubscriptions(self, params): """Handle a request to list susbcriptions""" # pylint: disable=unused-variable @@ -1206,7 +1211,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): initialHash = hashlib.sha512(encryptedPayload).digest() trialValue, nonce = proofofwork.run(target, initialHash) with shared.printLock: - print '(For msg message via API) Found proof of work', trialValue, 'Nonce:', nonce + print('(For msg message via API) Found proof of work', trialValue, 'Nonce:', nonce) try: print( 'POW took', int(time.time() - powStartTime), 'seconds.', @@ -1224,7 +1229,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): int(time.time()) + TTL, '' ) with shared.printLock: - print 'Broadcasting inv for msg(API disseminatePreEncryptedMsg command):', hexlify(inventoryHash) + print('Broadcasting inv for msg(API disseminatePreEncryptedMsg command):', hexlify(inventoryHash)) queues.invQueue.put((toStreamNumber, inventoryHash)) def HandleTrashSentMessageByAckDAta(self, params): @@ -1237,7 +1242,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): sqlExecute("UPDATE sent SET folder='trash' WHERE ackdata=?", ackdata) return 'Trashed sent message (assuming message existed).' - def HandleDissimatePubKey(self, params): # pylint: disable=unused-argument + def HandleDissimatePubKey(self, params): """Handle a request to disseminate a public key""" # The device issuing this command to PyBitmessage supplies a pubkey @@ -1254,10 +1259,10 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): target = 2 ** 64 / (( len(payload) + defaults.networkDefaultPayloadLengthExtraBytes + 8 ) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte) - print '(For pubkey message via API) Doing proof of work...' + print('(For pubkey message via API) Doing proof of work...') initialHash = hashlib.sha512(payload).digest() trialValue, nonce = proofofwork.run(target, initialHash) - print '(For pubkey message via API) Found proof of work', trialValue, 'Nonce:', nonce + print('(For pubkey message via API) Found proof of work', trialValue, 'Nonce:', nonce) payload = pack('>Q', nonce) + payload pubkeyReadPosition = 8 # bypass the nonce @@ -1279,7 +1284,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): objectType, pubkeyStreamNumber, payload, int(time.time()) + TTL, '' ) with shared.printLock: - print 'broadcasting inv within API command disseminatePubkey with hash:', hexlify(inventoryHash) + print('broadcasting inv within API command disseminatePubkey with hash:', hexlify(inventoryHash)) queues.invQueue.put((pubkeyStreamNumber, inventoryHash)) def HandleGetMessageDataByDestinationHash(self, params): @@ -1325,7 +1330,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): data += ']}' return data - def HandleClientStatus(self, params): # pylint: disable=unused-argument + def HandleClientStatus(self, params): """Handle a request to get the status of the client""" connections_num = len(network.stats.connectedHostsList()) diff --git a/src/bitmessagecurses/__init__.py b/src/bitmessagecurses/__init__.py index 80dc3f14..4b893852 100644 --- a/src/bitmessagecurses/__init__.py +++ b/src/bitmessagecurses/__init__.py @@ -1010,7 +1010,7 @@ def sendMessage(sender="", recv="", broadcast=None, subject="", body="", reply=F def loadInbox(): """Load the list of messages""" sys.stdout = sys.__stdout__ - print "Loading inbox messages..." + print("Loading inbox messages...") sys.stdout = printlog where = "toaddress || fromaddress || subject || message" @@ -1062,7 +1062,7 @@ def loadInbox(): def loadSent(): """Load the messages that sent""" sys.stdout = sys.__stdout__ - print "Loading sent messages..." + print("Loading sent messages...") sys.stdout = printlog where = "toaddress || fromaddress || subject || message" @@ -1148,7 +1148,7 @@ def loadSent(): def loadAddrBook(): """Load address book""" sys.stdout = sys.__stdout__ - print "Loading address book..." + print("Loading address book...") sys.stdout = printlog ret = sqlQuery("SELECT label, address FROM addressbook") @@ -1254,7 +1254,7 @@ def run(stdscr): def doShutdown(): """Shutting the app down""" sys.stdout = sys.__stdout__ - print "Shutting down..." + print("Shutting down...") sys.stdout = printlog shutdown.doCleanShutdown() sys.stdout = sys.__stdout__ diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index bbed1741..bc78b96f 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -9,7 +9,6 @@ The PyBitmessage startup script # Right now, PyBitmessage only support connecting to stream 1. It doesn't # yet contain logic to expand into further streams. - import os import sys import ctypes @@ -30,7 +29,8 @@ import state import shutdown from bmconfigparser import BMConfigParser -from debug import logger # this should go before any threads +# this should go before any threads +from debug import logger from helper_startup import ( isOurOperatingSystemLimitedToHavingVeryFewHalfOpenConnections ) @@ -156,11 +156,11 @@ def signal_handler(signum, frame): if shared.thisapp.daemon or not state.enableGUI: shutdown.doCleanShutdown() else: - print ('# Thread: {}({})'.format(thread.name, thread.ident)) + print('# Thread: {}({})'.format(thread.name, thread.ident)) for filename, lineno, name, line in traceback.extract_stack(frame): - print ("File: '{}', line {}, in {}" .format(filename, lineno, name)) + print("File: '{}', line {}, in {}" .format(filename, lineno, name)) if line: - print (' {}'.format(line.strip())) + print(' {}'.format(line.strip())) print('Unfortunately you cannot use Ctrl+C when running the UI \ because the UI captures the signal.') @@ -189,8 +189,9 @@ class Main(object): 'Started proxy config plugin %s in %s sec', proxy_type, time.time() - proxyconfig_start) - def start(self): # pylint: disable=too-many-statements, too-many-branches, too-many-locals + def start(self): """Start main application""" + # pylint: disable=too-many-statements, too-many-branches, too-many-locals _fixSocket() config = BMConfigParser() @@ -218,7 +219,8 @@ class Main(object): if os.path.isfile(os.path.join( state.appdata, 'unittest.lock')): daemon = True - state.enableGUI = False # run without a UI + # run without a UI + state.enableGUI = False # Fallback: in case when no api command was issued state.last_api_response = time.time() # Apply special settings @@ -234,7 +236,8 @@ class Main(object): ) if daemon: - state.enableGUI = False # run without a UI + # run without a UI + state.enableGUI = False # is the application already running? If yes then exit. if state.enableGUI and not state.curses and not state.kivy and not depends.check_pyqt(): @@ -281,7 +284,6 @@ class Main(object): readKnownNodes() - # Not needed if objproc is disabled if state.enableObjProc: @@ -340,7 +342,8 @@ class Main(object): shared.reloadBroadcastSendersForWhichImWatching() # API is also objproc dependent if config.safeGetBoolean('bitmessagesettings', 'apienabled'): - import api # pylint: disable=relative-import + # pylint: disable=relative-import + import api singleAPIThread = api.singleAPI() # close the main program even if there are threads left singleAPIThread.daemon = True @@ -405,7 +408,8 @@ class Main(object): if (state.testmode and time.time() - state.last_api_response >= 30): self.stop() elif not state.enableGUI: - from tests import core as test_core # pylint: disable=relative-import + # pylint: disable=relative-import + from tests import core as test_core test_core_result = test_core.run(self) state.enableGUI = True self.stop() @@ -429,13 +433,14 @@ class Main(object): while True: time.sleep(1) - os._exit(0) # pylint: disable=protected-access + os._exit(0) # pylint: disable=protected-access except AttributeError: # fork not implemented pass else: parentPid = os.getpid() - shared.thisapp.lock() # relock + # relock + shared.thisapp.lock() os.umask(0) try: @@ -450,14 +455,16 @@ class Main(object): # wait until child ready while True: time.sleep(1) - - os._exit(0) # pylint: disable=protected-access + # pylint: disable=protected-access + os._exit(0) except AttributeError: # fork not implemented pass else: - shared.thisapp.lock() # relock - shared.thisapp.lockPid = None # indicate we're the final child + # relock + shared.thisapp.lock() + # indicate we're the final child + shared.thisapp.lockPid = None sys.stdout.flush() sys.stderr.flush() if not sys.platform.startswith('win'): @@ -480,7 +487,6 @@ class Main(object): # signal.signal(signal.SIGINT, signal.SIG_DFL) @staticmethod - def usage(): """Displaying the usages""" print('Usage: ' + sys.argv[0] + ' [OPTIONS]') diff --git a/src/bmconfigparser.py b/src/bmconfigparser.py index 150333ec..3293c5b3 100644 --- a/src/bmconfigparser.py +++ b/src/bmconfigparser.py @@ -1,7 +1,7 @@ """ BMConfigParser class definition and default configuration settings """ - +# pylint: disable=no-self-use, arguments-differ import configparser import shutil import os @@ -45,7 +45,7 @@ BMConfigDefaults = { class BMConfigParser(configparser.ConfigParser): """Singleton class inherited from ConfigParsedadfeConfigParser with additional methods specific to bitmessage config.""" - + # pylint: disable=too-many-ancestors _temp = {} def set(self, section, option, value=None): @@ -56,7 +56,8 @@ class BMConfigParser(configparser.ConfigParser): raise ValueError("Invalid value %s" % value) return configparser.ConfigParser.set(self, section, option, value) - def get(self, section, option, raw=False, variables=None): # pylint: disable=arguments-differ + def get(self, section, option, raw=False, variables=None): + # pylint: disable=unused-argument try: if section == "bitmessagesettings" and option == "timeformat": return configparser.ConfigParser.get( @@ -84,24 +85,26 @@ class BMConfigParser(configparser.ConfigParser): self._temp[section] = {option: value} def safeGetBoolean(self, section, field): + """Return value as boolean, False on exceptions""" config = configparser.ConfigParser() - try: - #Used in the python2.7 + # Used in the python2.7 # return self.getboolean(section, field) - #Used in the python3.5.2 + # Used in the python3.5.2 return config.getboolean(section, field) except (configparser.NoSectionError, configparser.NoOptionError, ValueError, AttributeError): return False def safeGetInt(self, section, field, default=0): + """Return value as integer, default on exceptions, + 0 if default missing""" config = configparser.ConfigParser() try: - #Used in the python2.7 + # Used in the python2.7 # return self.getint(section, field) - #Used in the python3.5.2 + # Used in the python3.5.2 return config.getint(section, field) except (configparser.NoSectionError, configparser.NoOptionError, ValueError, AttributeError): @@ -116,12 +119,14 @@ class BMConfigParser(configparser.ConfigParser): return default def items(self, section, raw=False, variables=None): + """Return section variables as parent, + but override the "raw" argument to always True""" return configparser.ConfigParser.items(self, section, True, variables) def addresses(self): + """Return a list of local bitmessage addresses (from section labels)""" return [x for x in BMConfigParser().sections() if x.startswith('BM-')] - def read(self, filenames): configparser.ConfigParser.read(self, filenames) for section in self.sections(): @@ -167,7 +172,8 @@ class BMConfigParser(configparser.ConfigParser): def validate(self, section, option, value): """Input validator interface (using factory pattern)""" try: - return getattr(self, 'validate_{}_{}'.format(section, option))(value) + return getattr(self, 'validate_{}_{}'.format( + section, option))(value) except AttributeError: return True diff --git a/src/build_osx.py b/src/build_osx.py index 7ab74dc2..6618d5da 100644 --- a/src/build_osx.py +++ b/src/build_osx.py @@ -13,8 +13,14 @@ DATA_FILES = [ ('bitmsghash', ['bitmsghash/bitmsghash.cl', 'bitmsghash/bitmsghash.so']), ('translations', glob('translations/*.qm')), ('ui', glob('bitmessageqt/*.ui')), - ('translations', glob(str(QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath)) + '/qt_??.qm')), - ('translations', glob(str(QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath)) + '/qt_??_??.qm')), + ('translations', glob( + str( + QtCore.QLibraryInfo.location( + QtCore.QLibraryInfo.TranslationsPath)) + '/qt_??.qm')), + ('translations', glob( + str( + QtCore.QLibraryInfo.location( + QtCore.QLibraryInfo.TranslationsPath)) + '/qt_??_??.qm')), ] setup( From ca6a56fcb9af1a3d9cc9e832ee7d54d0d371be75 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Wed, 25 Dec 2019 20:21:08 +0530 Subject: [PATCH 3/8] python3 formatting and indentation fixes --- src/class_addressGenerator.py | 29 +++++++++++++++++++---------- src/class_objectProcessor.py | 5 ++--- src/class_objectProcessorQueue.py | 24 ------------------------ src/class_singleCleaner.py | 9 +++++++-- src/class_singleWorker.py | 3 ++- src/class_smtpDeliver.py | 19 ++++++++++++------- src/class_sqlThread.py | 11 ++++++++--- src/debug.py | 2 +- 8 files changed, 51 insertions(+), 51 deletions(-) delete mode 100644 src/class_objectProcessorQueue.py diff --git a/src/class_addressGenerator.py b/src/class_addressGenerator.py index 8cd63099..1f60e051 100644 --- a/src/class_addressGenerator.py +++ b/src/class_addressGenerator.py @@ -20,7 +20,6 @@ from network.threads import StoppableThread class addressGenerator(StoppableThread): """A thread for creating addresses""" - name = "addressGenerator" def stopThread(self): @@ -35,7 +34,8 @@ class addressGenerator(StoppableThread): Process the requests for addresses generation from `.queues.addressGeneratorQueue` """ - # pylint: disable=too-many-locals, too-many-branches, protected-access, too-many-statements + # pylint: disable=too-many-locals, too-many-branches + # pylint: disable=protected-access, too-many-statements while state.shutdown == 0: queueValue = queues.addressGeneratorQueue.get() nonceTrialsPerByte = 0 @@ -140,7 +140,7 @@ class addressGenerator(StoppableThread): ripe = RIPEMD160Hash(sha.digest()).digest() if ( ripe[:numberOfNullBytesDemandedOnFrontOfRipeHash] == - '\x00'.encode('utf-8') * numberOfNullBytesDemandedOnFrontOfRipeHash + '\x00'.encode('utf-8') * numberOfNullBytesDemandedOnFrontOfRipeHash ): break self.logger.info( @@ -206,9 +206,14 @@ class addressGenerator(StoppableThread): queues.workerQueue.put(( 'sendOutOrStoreMyV4Pubkey', address)) - elif command == 'createDeterministicAddresses' \ - or command == 'getDeterministicAddress' \ - or command == 'createChan' or command == 'joinChan': + # elif command == 'createDeterministicAddresses' \ + # or command == 'getDeterministicAddress' \ + # or command == 'createChan' or command == 'joinChan': + elif command in ( + 'createDeterministicAddresses', + 'getDeterministicAddress', + 'createChan', + 'joinChan'): if not deterministicPassphrase: self.logger.warning( 'You are creating deterministic' @@ -333,8 +338,8 @@ class addressGenerator(StoppableThread): BMConfigParser().set(address, 'label', label) BMConfigParser().set(address, 'enabled', 'true') BMConfigParser().set(address, 'decoy', 'false') - if command == 'joinChan' \ - or command == 'createChan': + # if command == 'joinChan' or command == 'createChan': + if command in ('joinChan', 'createChan'): BMConfigParser().set(address, 'chan', 'true') BMConfigParser().set( address, 'noncetrialsperbyte', @@ -385,8 +390,12 @@ class addressGenerator(StoppableThread): address) # Done generating addresses. - if command == 'createDeterministicAddresses' \ - or command == 'joinChan' or command == 'createChan': + # if command == 'createDeterministicAddresses' \ + # or command == 'joinChan' or command == 'createChan': + if command in ( + 'createDeterministicAddresses', + 'joinChan', + 'createChan'): queues.apiAddressGeneratorReturnQueue.put( listOfNewAddressesToSendOutThroughTheAPI) elif command == 'getDeterministicAddress': diff --git a/src/class_objectProcessor.py b/src/class_objectProcessor.py index 2c741661..298b12bf 100644 --- a/src/class_objectProcessor.py +++ b/src/class_objectProcessor.py @@ -152,9 +152,8 @@ class objectProcessor(threading.Thread): (data[readPosition:], tr._translate( "MainWindow", - "Acknowledgement of the message received %1" - ).arg(l10n.formatTimestamp())) - )) + "Acknowledgement of the message received %1").arg( + l10n.formatTimestamp())))) else: logger.debug('This object is not an acknowledgement bound for me.') diff --git a/src/class_objectProcessorQueue.py b/src/class_objectProcessorQueue.py deleted file mode 100644 index 24c24023..00000000 --- a/src/class_objectProcessorQueue.py +++ /dev/null @@ -1,24 +0,0 @@ -import queue as Queue -import threading -import time - -class ObjectProcessorQueue(Queue.Queue): - maxSize = 32000000 - - def __init__(self): - Queue.Queue.__init__(self) - self.sizeLock = threading.Lock() - self.curSize = 0 # in Bytes. We maintain this to prevent nodes from flooing us with objects which take up too much memory. If this gets too big we'll sleep before asking for further objects. - - def put(self, item, block = True, timeout = None): - while self.curSize >= self.maxSize: - time.sleep(1) - with self.sizeLock: - self.curSize += len(item[1]) - Queue.Queue.put(self, item, block, timeout) - - def get(self, block = True, timeout = None): - item = Queue.Queue.get(self, block, timeout) - with self.sizeLock: - self.curSize -= len(item[1]) - return item diff --git a/src/class_singleCleaner.py b/src/class_singleCleaner.py index f5442837..3c905b22 100644 --- a/src/class_singleCleaner.py +++ b/src/class_singleCleaner.py @@ -35,6 +35,7 @@ from inventory import Inventory from network.connectionpool import BMConnectionPool from network.threads import StoppableThread + class singleCleaner(StoppableThread): """The singleCleaner thread class""" name = "singleCleaner" @@ -200,6 +201,10 @@ def deleteTrashMsgPermonantly(): """This method is used to delete old messages""" ndays_before_time = datetime.now() - timedelta(days=30) old_messages = time.mktime(ndays_before_time.timetuple()) - sqlExecute("delete from sent where folder = 'trash' and lastactiontime <= ?;", int(old_messages)) - sqlExecute("delete from inbox where folder = 'trash' and received <= ?;", int(old_messages)) + sqlExecute( + "delete from sent where folder = 'trash' and lastactiontime <= ?;", + int(old_messages)) + sqlExecute( + "delete from inbox where folder = 'trash' and received <= ?;", + int(old_messages)) return diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index 9f1d39bd..b5bf2e43 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -23,7 +23,8 @@ import queues import shared import state import tr -from addresses import calculateInventoryHash, decodeAddress, decodeVarint, encodeVarint +from addresses import ( + calculateInventoryHash, decodeAddress, decodeVarint, encodeVarint) from bmconfigparser import BMConfigParser from helper_sql import sqlExecute, sqlQuery from inventory import Inventory diff --git a/src/class_smtpDeliver.py b/src/class_smtpDeliver.py index 58cd4631..6186f3ac 100644 --- a/src/class_smtpDeliver.py +++ b/src/class_smtpDeliver.py @@ -3,7 +3,6 @@ src/class_smtpDeliver.py ======================== """ # pylint: disable=unused-variable - import smtplib import urlparse from email.header import Header @@ -24,7 +23,8 @@ class smtpDeliver(StoppableThread): def stopThread(self): try: - queues.UISignallerQueue.put(("stopThread", "data")) # pylint: disable=no-member + # pylint: disable=no-member + queues.UISignallerQueue.put(("stopThread", "data")) except: pass super(smtpDeliver, self).stopThread() @@ -50,23 +50,27 @@ class smtpDeliver(StoppableThread): ackData, message = data elif command == 'displayNewInboxMessage': inventoryHash, toAddress, fromAddress, subject, body = data - dest = BMConfigParser().safeGet("bitmessagesettings", "smtpdeliver", '') + dest = BMConfigParser().safeGet( + "bitmessagesettings", "smtpdeliver", '') if dest == '': continue try: + # pylint: disable=deprecated-lambda u = urlparse.urlparse(dest) to = urlparse.parse_qs(u.query)['to'] client = smtplib.SMTP(u.hostname, u.port) msg = MIMEText(body, 'plain', 'utf-8') msg['Subject'] = Header(subject, 'utf-8') msg['From'] = fromAddress + '@' + SMTPDOMAIN - toLabel = map( # pylint: disable=deprecated-lambda + toLabel = map( lambda y: BMConfigParser().safeGet(y, "label"), - filter( # pylint: disable=deprecated-lambda + filter( lambda x: x == toAddress, BMConfigParser().addresses()) ) if toLabel: - msg['To'] = "\"%s\" <%s>" % (Header(toLabel[0], 'utf-8'), toAddress + '@' + SMTPDOMAIN) + msg['To'] = "\"%s\" <%s>" % ( + Header(toLabel[0], 'utf-8'), + toAddress + '@' + SMTPDOMAIN) else: msg['To'] = toAddress + '@' + SMTPDOMAIN client.ehlo() @@ -80,7 +84,8 @@ class smtpDeliver(StoppableThread): except: self.logger.error('smtp delivery error', exc_info=True) elif command == 'displayNewSentMessage': - toAddress, fromLabel, fromAddress, subject, message, ackdata = data + toAddress, fromLabel, fromAddress, subject, message, ackdata = \ + data elif command == 'updateNetworkStatusTab': pass elif command == 'updateNumberOfMessagesProcessed': diff --git a/src/class_sqlThread.py b/src/class_sqlThread.py index d0d8a001..5de53b27 100644 --- a/src/class_sqlThread.py +++ b/src/class_sqlThread.py @@ -214,7 +214,8 @@ class sqlThread(threading.Thread): parameters = '' self.cur.execute(item, parameters) currentVersion = int(self.cur.fetchall()[0][0]) - if currentVersion == 1 or currentVersion == 3: + # if currentVersion == 1 or currentVersion == 3: + if currentVersion in (1, 3): logger.debug( 'In messages.dat database, adding tag field to' ' the inventory table.') @@ -578,9 +579,13 @@ class sqlThread(threading.Thread): # print ('+++++++++++++++++++++++++++++') try: if 'sent' == parameters[1] and 'B' in parameters[0]: - item = '''SELECT toaddress, fromaddress, subject, message, status, ackdata, lastactiontime FROM sent WHERE fromaddress = ? ORDER BY lastactiontime DESC ''' + item = ( + '''SELECT toaddress, fromaddress, subject,''' + ''' message, status, ackdata, lastactiontime''' + ''' FROM sent WHERE fromaddress = ?''' + ''' ORDER BY lastactiontime DESC''') parameters = (parameters[0],) - except (IndexError,TypeError) as e: + except(IndexError, TypeError): pass try: self.cur.execute(item, parameters) diff --git a/src/debug.py b/src/debug.py index 685844ab..99994d22 100644 --- a/src/debug.py +++ b/src/debug.py @@ -151,7 +151,7 @@ def resetLogging(): try: preconfigured, msg = configureLogging() if msg: - logger.log(logging.WARNING if preconfigured else logging.INFO, msg) + logger.log(logging.WARNING if preconfigured else logging.INFO, msg) except: pass From 4ada9f68b3b95b0e4f801d3830bf39564dd098ab Mon Sep 17 00:00:00 2001 From: navjot Date: Thu, 26 Dec 2019 21:26:04 +0530 Subject: [PATCH 4/8] Kivy fixes part 4 --- src/bitmessagekivy/kivy_helper_search.py | 2 +- src/bitmessagekivy/main.kv | 42 ++++---- src/bitmessagekivy/mpybit.py | 117 +++++++++++++---------- src/class_sqlThread.py | 17 ---- src/state.py | 45 +++------ 5 files changed, 103 insertions(+), 120 deletions(-) diff --git a/src/bitmessagekivy/kivy_helper_search.py b/src/bitmessagekivy/kivy_helper_search.py index 83683d15..c05e69d4 100644 --- a/src/bitmessagekivy/kivy_helper_search.py +++ b/src/bitmessagekivy/kivy_helper_search.py @@ -69,4 +69,4 @@ def search_sql( start_indx, end_indx) # elif folder == "addressbook": # sqlStatementBase += " limit {0}, {1}".format(start_indx, end_indx) - return sqlQuery(sqlStatementBase, sqlArguments) + return sqlQuery(sqlStatementBase, sqlArguments) \ No newline at end of file diff --git a/src/bitmessagekivy/main.kv b/src/bitmessagekivy/main.kv index b360a534..83183084 100644 --- a/src/bitmessagekivy/main.kv +++ b/src/bitmessagekivy/main.kv @@ -25,7 +25,8 @@ #:set color_font (0.957, 0.890, 0.843, 1) # off white : - icon: 'checkbox-blank-circle' + font_style: 'Body1' + theme_text_color: 'Secondary' : font_size: '12.5sp' @@ -39,7 +40,7 @@ height: dp(7) NavigationDrawerSubheader: text: "Accounts" - NavigationDrawerIconButton: + AddressDropdown: CustomSpinner: id: btn pos_hint:{"x":0,"y":.25} @@ -57,47 +58,48 @@ y: self.parent.y + self.parent.height/4 size: self.parent.height/2, self.parent.height/2 ArrowImg: - NavigationDrawerIconButton: + MyNavigationDrawerIconButton: id: inbox_cnt icon: 'email-open' text: "Inbox" on_release: app.root.ids.scr_mngr.current = 'inbox' badge_text: "0" on_press: app.load_screen(self) - NavigationDrawerIconButton: + MyNavigationDrawerIconButton: id: send_cnt icon: 'send' text: "Sent" + #use_active: False on_release: app.root.ids.scr_mngr.current = 'sent' badge_text: "0" - NavigationDrawerIconButton: + MyNavigationDrawerIconButton: id: draft_cnt icon: 'message-draw' text: "Draft" on_release: app.root.ids.scr_mngr.current = 'draft' badge_text: "0" - #NavigationDrawerIconButton: + #MyNavigationDrawerIconButton: #text: "Starred" #icon:'star' #on_release: app.root.ids.scr_mngr.current = 'starred' #badge_text: "0" - #NavigationDrawerIconButton: + #MyNavigationDrawerIconButton: #icon: 'archive' #text: "Archieve" #on_release: app.root.ids.scr_mngr.current = 'archieve' #badge_text: "0" - #NavigationDrawerIconButton: + #MyNavigationDrawerIconButton: #icon: 'email-open-outline' #text: "Spam" #on_release: app.root.ids.scr_mngr.current = 'spam' #badge_text: "0" - NavigationDrawerIconButton: + MyNavigationDrawerIconButton: id: trash_cnt icon: 'delete' text: "Trash" on_release: app.root.ids.scr_mngr.current = 'trash' badge_text: "0" - NavigationDrawerIconButton: + MyNavigationDrawerIconButton: id: allmail_cnt text: "All Mails" icon:'contact-mail' @@ -107,31 +109,31 @@ NavigationDrawerDivider: NavigationDrawerSubheader: text: "All labels" - NavigationDrawerIconButton: + MyNavigationDrawerIconButton: text: "Address Book" icon:'book-multiple' on_release: app.root.ids.scr_mngr.current = 'addressbook' - NavigationDrawerIconButton: + MyNavigationDrawerIconButton: text: "Settings" icon:'settings' on_release: app.root.ids.scr_mngr.current = 'set' - NavigationDrawerIconButton: + MyNavigationDrawerIconButton: text: "Subscriptions/Payment" icon:'bell' on_release: app.root.ids.scr_mngr.current = 'payment' - NavigationDrawerIconButton: + MyNavigationDrawerIconButton: text: "Credits" icon:'wallet' on_release: app.root.ids.scr_mngr.current = 'credits' - NavigationDrawerIconButton: + MyNavigationDrawerIconButton: text: "new address" icon:'account-plus' on_release: app.root.ids.scr_mngr.current = 'login' - NavigationDrawerIconButton: + MyNavigationDrawerIconButton: text: "Network Status" icon:'server-network' on_release: app.root.ids.scr_mngr.current = 'networkstat' - NavigationDrawerIconButton: + MyNavigationDrawerIconButton: text: "My Addresses" icon:'account-multiple' on_release: app.root.ids.scr_mngr.current = 'myaddress' @@ -545,12 +547,6 @@ NavigationLayout: color: (1,1,1,1) halign: 'center' -: - name: 'add_sucess' - Label: - text: 'Successfully created a new bit address' - color: 0,0,0,1 - : name: 'set' ScrollView: diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 790cdb97..5b03ffd8 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -1,5 +1,6 @@ """ -Bitmessage android(mobile) interface +src/bitmessagekivy/mpybit.py +================================= """ # pylint: disable=import-error, no-name-in-module, too-many-lines # pylint: disable=too-few-public-methods, unused-argument, too-many-ancestors @@ -46,6 +47,7 @@ from kivymd.uix.list import ( IRightBodyTouch, TwoLineAvatarIconListItem, TwoLineListItem, + OneLineIconListItem, ) from kivymd.uix.navigationdrawer import ( MDNavigationDrawer, @@ -57,35 +59,36 @@ import queues from semaphores import kivyuisignaler import state -from bitmessagekivy.uikivysignaler import UIkivySignaler +from bitmessagekivy.uikivysignaler import UIkivySignaler from bitmessagekivy import identiconGeneration -from addresses import addBMIfNotPresent, decodeAddress +from addresses import addBMIfNotPresent, decodeAddress, encodeVarint +# pylint: disable=unused-argument, too-few-public-methods def toast(text): - """Function displays toast message""" - # pylint: disable=redefined-outer-name - from kivymd.toast.kivytoast import toast + """Method will display the toast message""" + from kivymd.toast.kivytoast import toast # pylint: disable=redefined-outer-name toast(text) return class Navigatorss(MDNavigationDrawer): - """Navigator class (image, title and logo)""" + """Navigators class contains image, title and logo""" + image_source = StringProperty('images/qidenticon_two.png') title = StringProperty('Navigation') drawer_logo = StringProperty() class Inbox(Screen): - """Inbox Screen uses screen to show widgets of screens.""" + """Inbox Screen uses screen to show widgets of screens""" queryreturn = ListProperty() has_refreshed = True account = StringProperty() def __init__(self, *args, **kwargs): - """Method Parsing the address.""" + """Method Parsing the address""" super(Inbox, self).__init__(*args, **kwargs) Clock.schedule_once(self.init_ui, 0) @@ -97,11 +100,11 @@ class Inbox(Screen): state.association = BMConfigParser().addresses()[0] def init_ui(self, dt=0): - """Clock schdule for method inbox accounts.""" + """Clock schdule for method inbox accounts""" self.loadMessagelist() def loadMessagelist(self, where="", what=""): - """Load Inbox list for Inbox messages.""" + """Load Inbox list for Inbox messages""" # pylint: disable=too-many-locals self.set_defaultAddress() self.account = state.association @@ -300,13 +303,13 @@ class Inbox(Screen): class MyAddress(Screen): - """MyAddress screen uses screen to show widgets of screens.""" + """MyAddress screen uses screen to show widgets of screens""" addresses_list = ListProperty() has_refreshed = True is_add_created = False def __init__(self, *args, **kwargs): - """Clock schdule for method Myaddress accounts.""" + """Clock schdule for method Myaddress accounts""" super(MyAddress, self).__init__(*args, **kwargs) Clock.schedule_once(self.init_ui, 0) @@ -316,9 +319,7 @@ class MyAddress(Screen): self.addresses_list = state.kivyapp.variable_1 if state.searcing_text: self.ids.refresh_layout.scroll_y = 1.0 - filtered_list = filter( - lambda addr: self.filter_address( - addr), BMConfigParser().addresses()) + filtered_list = [x for x in BMConfigParser().addresses() if self.filter_address(x)] self.addresses_list = filtered_list self.addresses_list = [obj for obj in reversed(self.addresses_list)] if self.addresses_list: @@ -403,9 +404,7 @@ class MyAddress(Screen): @staticmethod def filter_address(address): """Method will filter the my address list data""" - if filter(lambda x: (state.searcing_text).lower() in x, [ - BMConfigParser().get( - address, 'label').lower(), address.lower()]): + if [x for x in [BMConfigParser().get(address, 'label').lower(), address.lower()] if (state.searcing_text).lower() in x]: return True return False @@ -519,8 +518,8 @@ class AddressBook(Screen): "DELETE FROM addressbook WHERE address = '{}';".format(address)) -class SelectableRecycleBoxLayout( - FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout): +class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior, + RecycleBoxLayout): """Adds selection and focus behaviour to the view""" # pylint: disable = duplicate-bases pass @@ -528,6 +527,7 @@ class SelectableRecycleBoxLayout( class SelectableLabel(RecycleDataViewBehavior, Label): """Add selection support to the Label""" + index = None selected = BooleanProperty(False) selectable = BooleanProperty(True) @@ -556,7 +556,8 @@ class SelectableLabel(RecycleDataViewBehavior, Label): class RV(RecycleView): """Recycling View""" - def __init__(self, **kwargs): # pylint: disable=useless-super-delegation + + def __init__(self, **kwargs): # pylint: disable=useless-super-delegation """Recycling Method""" super(RV, self).__init__(**kwargs) @@ -578,6 +579,7 @@ class DropDownWidget(BoxLayout): sendMessageToPeople = True if sendMessageToPeople: if toAddress != '' and subject and message: + from addresses import decodeAddress status, addressVersionNumber, streamNumber, ripe = ( decodeAddress(toAddress)) if status == 'success': @@ -596,7 +598,10 @@ class DropDownWidget(BoxLayout): state.send_draft_mail) self.parent.parent.screens[15].clear_widgets() self.parent.parent.screens[15].add_widget(Draft()) + # state.detailPageType = '' + # state.send_draft_mail = None else: + from addresses import addBMIfNotPresent toAddress = addBMIfNotPresent(toAddress) statusIconColor = 'red' if (addressVersionNumber > 4) or ( @@ -696,6 +701,7 @@ class DropDownWidget(BoxLayout): class MyTextInput(TextInput): """Takes the text input in the field""" + txt_input = ObjectProperty() flt_list = ObjectProperty() word_list = ListProperty() @@ -751,12 +757,14 @@ class Payment(Screen): class Credits(Screen): - """Credits Module""" - available_credits = StringProperty('{0}'.format('0')) + """Credits Method""" + available_credits = StringProperty( + '{0}'.format('0')) class Login(Screen): """Login Screeen""" + pass @@ -867,7 +875,7 @@ class Sent(Screen): account = StringProperty() def __init__(self, *args, **kwargs): - """Association with the screen.""" + """Association with the screen""" super(Sent, self).__init__(*args, **kwargs) if state.association == '': if BMConfigParser().addresses(): @@ -880,7 +888,7 @@ class Sent(Screen): print(dt) def loadSent(self, where="", what=""): - """Load Sent list for Sent messages.""" + """Load Sent list for Sent messages""" self.account = state.association if state.searcing_text: self.ids.scroll_y.scroll_y = 1.0 @@ -918,7 +926,7 @@ class Sent(Screen): self.queryreturn = kivy_helper_search.search_sql( xAddress, self.account, - "sent", + 'sent', where, what, False, @@ -1084,7 +1092,7 @@ class Trash(Screen): """Trash Screen uses screen to show widgets of screens""" trash_messages = ListProperty() has_refreshed = True - delete_index = StringProperty() + # delete_index = StringProperty() table_name = StringProperty() def __init__(self, *args, **kwargs): @@ -1093,7 +1101,7 @@ class Trash(Screen): Clock.schedule_once(self.init_ui, 0) def init_ui(self, dt=0): - """Clock Schdule for method trash screen.""" + """Clock Schdule for method trash screen""" if state.association == '': if BMConfigParser().addresses(): state.association = BMConfigParser().addresses()[0] @@ -1199,7 +1207,7 @@ class Trash(Screen): events_callback=self.callback_for_delete_msg) delete_msg_dialog.open() - def callback_for_delete_msg(self, text_item): + def callback_for_delete_msg(self, text_item, *arg): """Getting the callback of alert box""" if text_item == 'Yes': self.delete_message_from_trash() @@ -1210,11 +1218,9 @@ class Trash(Screen): """Deleting message from trash""" self.children[1].active = True if self.table_name == 'inbox': - sqlExecute("DELETE FROM inbox WHERE msgid = ?;", str( - self.delete_index)) + sqlExecute("DELETE FROM inbox WHERE msgid = ?;", self.delete_index) elif self.table_name == 'sent': - sqlExecute("DELETE FROM sent WHERE ackdata = ?;", str( - self.delete_index)) + sqlExecute("DELETE FROM sent WHERE ackdata = ?;", self.delete_index) msg_count_objs = state.kivyapp.root.children[2].children[0].ids if int(state.trash_count) > 0: msg_count_objs.trash_cnt.badge_text = str( @@ -1225,6 +1231,7 @@ class Trash(Screen): class Page(Screen): """Page Screen show widgets of page""" + pass @@ -1244,6 +1251,7 @@ class Create(Screen): class Setting(Screen): """Setting the Screen components""" + pass @@ -1320,7 +1328,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods Clock.schedule_once(self.setCurrentAccountData, 0.5) def setCurrentAccountData(self, dt=0): - """This method set the current accout data on all the screens.""" + """This method set the current accout data on all the screens""" self.root.ids.sc1.ids.ml.clear_widgets() self.root.ids.sc1.loadMessagelist(state.association) @@ -1827,8 +1835,7 @@ class GrashofPopup(Popup): elif status == 'checksumfailed': text = "The address is not typed or copied correctly(the checksum failed)." elif status == 'versiontoohigh': - text = "The version number of this address is higher"\ - " than this software can support. Please upgrade Bitmessage." + text = "The version number of this address is higher than this software can support. Please upgrade Bitmessage." elif status == 'invalidcharacters': text = "The address contains invalid characters." elif status == 'ripetooshort': @@ -1842,22 +1849,26 @@ class GrashofPopup(Popup): class AvatarSampleWidget(ILeftBody, Image): """Avatar Sample Widget""" + pass class IconLeftSampleWidget(ILeftBodyTouch, MDIconButton): """Left icon sample widget""" + pass class IconRightSampleWidget(IRightBodyTouch, MDCheckbox): """Right icon sample widget""" + pass class NavigationDrawerTwoLineListItem( TwoLineListItem, NavigationDrawerHeaderBase): """Navigation Drawer in Listitems""" + address_property = StringProperty() def __init__(self, **kwargs): @@ -1948,7 +1959,7 @@ class MailDetail(Screen): 1].ids.search_field.text = '' sqlExecute( "UPDATE inbox SET folder = 'trash' WHERE" - " msgid = ?;", str(state.mail_id)) + " msgid = ?;", state.mail_id) msg_count_objs.inbox_cnt.badge_text = str( int(state.inbox_count) - 1) state.inbox_count = str(int(state.inbox_count) - 1) @@ -1956,8 +1967,7 @@ class MailDetail(Screen): self.parent.screens[0].loadMessagelist(state.association) elif state.detailPageType == 'draft': - sqlExecute("DELETE FROM sent WHERE ackdata = ?;", str( - state.mail_id)) + sqlExecute("DELETE FROM sent WHERE ackdata = ?;", state.mail_id) msg_count_objs.draft_cnt.badge_text = str( int(state.draft_count) - 1) state.draft_count = str(int(state.draft_count) - 1) @@ -1992,7 +2002,7 @@ class MailDetail(Screen): """Reply inbox messages""" data = sqlQuery( "select toaddress, fromaddress, subject, message from inbox where" - " msgid = ?;", str(state.mail_id)) + " msgid = ?;", state.mail_id) composer_obj = self.parent.screens[2].children[1].ids composer_obj.ti.text = data[0][0] composer_obj.btn.text = data[0][0] @@ -2131,7 +2141,7 @@ class ShowQRCode(Screen): """ShowQRCode Screen uses to show the detail of mails""" def qrdisplay(self): - """Showing QR Code""" + """Method used for showing QR Code""" # self.manager.parent.parent.parent.ids.search_bar.clear_widgets() self.ids.qr.clear_widgets() from kivy.garden.qrcode import QRCodeWidget @@ -2161,12 +2171,12 @@ class Draft(Screen): print(dt) def sentaccounts(self): - """Load draft accounts.""" + """Load draft accounts""" self.account = state.association self.loadDraft() def loadDraft(self, where="", what=""): - """Load draft list for Draft messages.""" + """Load draft list for Draft messages""" xAddress = 'fromaddress' self.draftDataQuery(xAddress, where, what) if state.msg_counter_objs: @@ -2273,8 +2283,7 @@ class Draft(Screen): data_index)) try: msg_count_objs = ( - self.parent.parent.parent.parent.parent.parent.children[ - 2].children[0].ids) + self.parent.parent.parent.parent.parent.children[2].children[0].ids) except Exception: msg_count_objs = self.parent.parent.parent.parent.parent.parent.children[ 2].children[0].ids @@ -2298,7 +2307,9 @@ class Draft(Screen): encoding = 3 sendMessageToPeople = True if sendMessageToPeople: + from addresses import decodeAddress streamNumber, ripe = decodeAddress(toAddress)[2:] + from addresses import addBMIfNotPresent toAddress = addBMIfNotPresent(toAddress) stealthLevel = BMConfigParser().safeGetInt( 'bitmessagesettings', 'ackstealthlevel') @@ -2334,7 +2345,7 @@ class CustomSpinner(Spinner): """This class is used for setting spinner size""" def __init__(self, *args, **kwargs): - """Setting size of spinner""" + """Method used for setting size of spinner""" super(CustomSpinner, self).__init__(*args, **kwargs) self.dropdown_cls.max_height = Window.size[1] / 3 @@ -2347,7 +2358,7 @@ class Allmails(Screen): account = StringProperty() def __init__(self, *args, **kwargs): - """Method Parsing the address.""" + """Method Parsing the address""" super(Allmails, self).__init__(*args, **kwargs) if state.association == '': if BMConfigParser().addresses(): @@ -2360,7 +2371,7 @@ class Allmails(Screen): print(dt) def loadMessagelist(self): - """Load Inbox, Sent anf Draft list of messages.""" + """Load Inbox, Sent anf Draft list of messages""" self.account = state.association self.allMessageQuery(0, 20) if self.all_mails: @@ -2538,16 +2549,19 @@ def avatarImageFirstLetter(letter_string): class Starred(Screen): """Starred Screen show widgets of page""" + pass class Archieve(Screen): """Archieve Screen show widgets of page""" + pass class Spam(Screen): """Spam Screen show widgets of page""" + pass @@ -2562,3 +2576,8 @@ class LoadingPopup(Popup): def dismiss_popup(self, dt): """Dismiss popups""" self.dismiss() + + +class AddressDropdown(OneLineIconListItem): + """AddressDropdown showns all the addresses""" + pass \ No newline at end of file diff --git a/src/class_sqlThread.py b/src/class_sqlThread.py index 5de53b27..d7bb158f 100644 --- a/src/class_sqlThread.py +++ b/src/class_sqlThread.py @@ -573,27 +573,10 @@ class sqlThread(threading.Thread): rowcount = 0 # print 'item', item # print 'parameters', parameters - # print('++++454++++++++++++++++++++++++') - # print ('parameters') - # print (parameters) - # print ('+++++++++++++++++++++++++++++') - try: - if 'sent' == parameters[1] and 'B' in parameters[0]: - item = ( - '''SELECT toaddress, fromaddress, subject,''' - ''' message, status, ackdata, lastactiontime''' - ''' FROM sent WHERE fromaddress = ?''' - ''' ORDER BY lastactiontime DESC''') - parameters = (parameters[0],) - except(IndexError, TypeError): - pass try: self.cur.execute(item, parameters) rowcount = self.cur.rowcount except Exception as err: - print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@') - print('inside the expectation') - print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@') if str(err) == 'database or disk is full': logger.fatal( '(while cur.execute) Alert: Your disk or data storage volume is full.' diff --git a/src/state.py b/src/state.py index 038e0e0a..54251270 100644 --- a/src/state.py +++ b/src/state.py @@ -1,43 +1,30 @@ """ -Global runtime variables. +src/state.py +================================= """ import collections neededPubkeys = {} streamsInWhichIAmParticipating = [] - +# For UPnP extPort = None -"""For UPnP""" - +# for Tor hidden service socksIP = None -"""for Tor hidden service""" - -appdata = '' -"""holds the location of the application data storage directory""" - +# Network protocols availability, initialised below +networkProtocolAvailability = None +appdata = '' # holds the location of the application data storage directory +# Set to 1 by the doCleanShutdown function. +# Used to tell the proof of work worker threads to exit. shutdown = 0 -""" -Set to 1 by the `.shutdown.doCleanShutdown` function. -Used to tell the threads to exit. -""" - # Component control flags - set on startup, do not change during runtime # The defaults are for standalone GUI (default operating mode) -enableNetwork = True -"""enable network threads""" -enableObjProc = True -"""enable object processing thread""" -enableAPI = True -"""enable API (if configured)""" -enableGUI = True -"""enable GUI (QT or ncurses)""" -enableSTDIO = False -"""enable STDIO threads""" +enableNetwork = True # enable network threads +enableObjProc = True # enable object processing threads +enableAPI = True # enable API (if configured) +enableGUI = True # enable GUI (QT or ncurses) +enableSTDIO = False # enable STDIO threads curses = False - -sqlReady = False -"""set to true by `.threads.sqlThread` when ready for processing""" - +sqlReady = False # set to true by sqlTread when ready for processing maximumNumberOfHalfOpenConnections = 0 invThread = None addrThread = None @@ -68,8 +55,6 @@ def resetNetworkProtocolAvailability(): resetNetworkProtocolAvailability() -discoveredPeers = {} - dandelion = 0 testmode = False From 5a1b5e177fd3b4920c488539847bddc50271cb2d Mon Sep 17 00:00:00 2001 From: navjot Date: Mon, 30 Dec 2019 13:35:07 +0530 Subject: [PATCH 5/8] kivy fixes part 5 --- src/bitmessagekivy/main.kv | 121 +++++++++++++++++++++++++++++------ src/bitmessagekivy/mpybit.py | 86 ++++++++++++++----------- 2 files changed, 148 insertions(+), 59 deletions(-) diff --git a/src/bitmessagekivy/main.kv b/src/bitmessagekivy/main.kv index 83183084..67f24e01 100644 --- a/src/bitmessagekivy/main.kv +++ b/src/bitmessagekivy/main.kv @@ -208,8 +208,17 @@ NavigationLayout: transition: NoTransition() BoxLayout: orientation: 'vertical' - spacing: dp(10) + spacing: dp(5) SearchBar: + GridLayout: + id: identi_tag + padding: [20, 0, 0, 5] + cols: 1 + size_hint_y: None + height: self.minimum_height + MDLabel: + text: '' + font_style: 'Subtitle2' #FloatLayout: # MDScrollViewRefreshLayout: # id: refresh_layout @@ -231,7 +240,17 @@ NavigationLayout: name: 'sent' BoxLayout: orientation: 'vertical' + spacing: dp(5) SearchBar: + GridLayout: + id: identi_tag + padding: [20, 0, 0, 5] + cols: 1 + size_hint_y: None + height: self.minimum_height + MDLabel: + text: '' + font_style: 'Subtitle2' BoxLayout: orientation:'vertical' ScrollView: @@ -244,21 +263,50 @@ NavigationLayout: : name: 'trash' - ScrollView: - id: scroll_y - do_scroll_x: False - MDList: - id: ml + BoxLayout: + orientation: 'vertical' + spacing: dp(5) + GridLayout: + id: identi_tag + padding: [20, 20, 0, 5] + spacing: dp(5) + cols: 1 + size_hint_y: None + height: self.minimum_height + MDLabel: + text: '' + font_style: 'Subtitle2' + BoxLayout: + orientation:'vertical' + ScrollView: + id: scroll_y + do_scroll_x: False + MDList: + id: ml Loader: ComposerButton: : name: 'draft' - ScrollView: - id: scroll_y - do_scroll_x: False - MDList: - id: ml + BoxLayout: + orientation: 'vertical' + spacing: dp(5) + GridLayout: + id: identi_tag + padding: [20, 20, 0, 5] + cols: 1 + size_hint_y: None + height: self.minimum_height + MDLabel: + text: '' + font_style: 'Subtitle2' + BoxLayout: + orientation:'vertical' + ScrollView: + id: scroll_y + do_scroll_x: False + MDList: + id: ml ComposerButton: : @@ -295,12 +343,25 @@ NavigationLayout: # MDList: # id: ml BoxLayout: - orientation:'vertical' - ScrollView: - id: scroll_y - do_scroll_x: False - MDList: - id: ml + orientation: 'vertical' + spacing: dp(5) + GridLayout: + id: identi_tag + padding: [20, 20, 0, 5] + spacing: dp(5) + cols: 1 + size_hint_y: None + height: self.minimum_height + MDLabel: + text: '' + font_style: 'Subtitle2' + BoxLayout: + orientation:'vertical' + ScrollView: + id: scroll_y + do_scroll_x: False + MDList: + id: ml Loader: ComposerButton: @@ -620,7 +681,17 @@ NavigationLayout: name: 'myaddress' BoxLayout: orientation: 'vertical' + spacing: dp(5) SearchBar: + GridLayout: + id: identi_tag + padding: [20, 0, 0, 5] + cols: 1 + size_hint_y: None + height: self.minimum_height + MDLabel: + text: 'My Addresses' + font_style: 'Subtitle2' FloatLayout: MDScrollViewRefreshLayout: id: refresh_layout @@ -635,7 +706,17 @@ NavigationLayout: name: 'addressbook' BoxLayout: orientation: 'vertical' + spacing: dp(5) SearchBar: + GridLayout: + id: identi_tag + padding: [20, 0, 0, 5] + cols: 1 + size_hint_y: None + height: self.minimum_height + MDLabel: + text: '' + font_style: 'Subtitle2' BoxLayout: orientation:'vertical' ScrollView: @@ -796,7 +877,7 @@ NavigationLayout: id: popup size_hint : (None,None) height: 2*(label.height + address.height) + 10 - width :app.window_size[0] - app.window_size[0]/10 + width :app.window_size[0] - (app.window_size[0]/10 if app.app_platform == 'android' else app.window_size[0]/4) title: 'add contact\'s' background: './images/popup.jpeg' title_size: sp(20) @@ -1027,7 +1108,7 @@ NavigationLayout: id: myadd_popup size_hint : (None,None) height: 4.5*(myaddr_label.height+ my_add_btn.children[0].height) - width :app.window_size[0] - app.window_size[0]/10 + width :app.window_size[0] - (app.window_size[0]/10 if app.app_platform == 'android' else app.window_size[0]/4) background: './images/popup.jpeg' auto_dismiss: False separator_height: 0 @@ -1107,7 +1188,7 @@ NavigationLayout: id: addbook_popup size_hint : (None,None) height: 4*(add_label.height) - width :app.window_size[0] - app.window_size[0]/10 + width :app.window_size[0] - (app.window_size[0]/10 if app.app_platform == 'android' else app.window_size[0]/4) background: './images/popup.jpeg' separator_height: 0 auto_dismiss: False diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 5b03ffd8..df0e1c26 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -260,6 +260,8 @@ class Inbox(Screen): int(state.trash_count) + 1) state.all_count = str( int(state.all_count) - 1) + if int(state.inbox_count) <= 0: + self.ids.identi_tag.children[0].text = '' self.ids.ml.remove_widget( instance.parent.parent) toast('Deleted') @@ -322,7 +324,9 @@ class MyAddress(Screen): filtered_list = [x for x in BMConfigParser().addresses() if self.filter_address(x)] self.addresses_list = filtered_list self.addresses_list = [obj for obj in reversed(self.addresses_list)] + self.ids.identi_tag.children[0].text = '' if self.addresses_list: + self.ids.identi_tag.children[0].text = 'My Addresses' self.has_refreshed = True self.set_mdList(0, 15) self.ids.refresh_layout.bind(scroll_y=self.check_scroll_y) @@ -393,7 +397,7 @@ class MyAddress(Screen): """Method used for loading the myaddress screen data""" state.searcing_text = '' state.kivyapp.root.ids.sc10.children[2].active = False - self.children[2].children[1].ids.search_field.text = '' + self.children[2].children[2].ids.search_field.text = '' self.has_refreshed = True self.ids.ml.clear_widgets() self.init_ui() @@ -435,10 +439,12 @@ class AddressBook(Screen): where = ['label', 'address'] what = state.searcing_text xAddress = '' + self.ids.identi_tag.children[0].text = '' self.queryreturn = kivy_helper_search.search_sql( xAddress, account, "addressbook", where, what, False) self.queryreturn = [obj for obj in reversed(self.queryreturn)] if self.queryreturn: + self.ids.identi_tag.children[0].text = 'Address Book' self.has_refreshed = True self.set_mdList(0, 20) self.ids.scroll_y.bind(scroll_y=self.check_scroll_y) @@ -514,6 +520,8 @@ class AddressBook(Screen): def delete_address(self, address, instance, *args): """Delete inbox mail from inbox listing""" self.ids.ml.remove_widget(instance.parent.parent) + if len(self.ids.ml.children) == 0: + self.ids.identi_tag.children[0].text = '' sqlExecute( "DELETE FROM addressbook WHERE address = '{}';".format(address)) @@ -673,9 +681,10 @@ class DropDownWidget(BoxLayout): # pylint: disable=attribute-defined-outside-init def address_error_message(self, msg): """Generates error message""" + width = .8 if platform == 'android' else .55 msg_dialog = MDDialog( text=msg, - title='', size_hint=(.8, .25), text_button_ok='Ok', + title='', size_hint=(width, .25), text_button_ok='Ok', events_callback=self.callback_for_menu_items) msg_dialog.open() @@ -896,8 +905,10 @@ class Sent(Screen): what = state.searcing_text xAddress = 'fromaddress' data = [] + self.ids.identi_tag.children[0].text = '' self.sentDataQuery(xAddress, where, what) if self.queryreturn: + self.ids.identi_tag.children[0].text = 'Sent' self.set_sentCount(state.sent_count) for mail in self.queryreturn: data.append({ @@ -1059,6 +1070,8 @@ class Sent(Screen): state.sent_count = str(int(state.sent_count) - 1) state.trash_count = str(int(state.trash_count) + 1) state.all_count = str(int(state.all_count) - 1) + if int(state.sent_count) <= 0: + self.ids.identi_tag.children[0].text = '' sqlExecute( "UPDATE sent SET folder = 'trash'" " WHERE ackdata = ?;", data_index) @@ -1105,8 +1118,10 @@ class Trash(Screen): if state.association == '': if BMConfigParser().addresses(): state.association = BMConfigParser().addresses()[0] + self.ids.identi_tag.children[0].text = '' self.trashDataQuery(0, 20) if self.trash_messages: + self.ids.identi_tag.children[0].text = 'Trash' src_mng_obj = state.kivyapp.root.children[2].children[0].ids src_mng_obj.trash_cnt.badge_text = state.trash_count self.set_mdList() @@ -1197,11 +1212,12 @@ class Trash(Screen): def delete_confirmation(self): """Show confirmation delete popup""" + width = .8 if platform == 'android' else .55 delete_msg_dialog = MDDialog( text='Are you sure you want to delete this' ' message permanently from trash?', title='', - size_hint=(.8, .25), + size_hint=(width, .25), text_button_ok='Yes', text_button_cancel='No', events_callback=self.callback_for_delete_msg) @@ -1264,6 +1280,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods nav_drawer = ObjectProperty() state.screen_density = Window.size window_size = state.screen_density + app_platform = platform title = "PyBitmessage" imgstatus = False count = 0 @@ -1333,7 +1350,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods self.root.ids.sc1.loadMessagelist(state.association) self.root.ids.sc4.ids.ml.clear_widgets() - self.root.ids.sc4.children[2].children[1].ids.search_field.text = '' + self.root.ids.sc4.children[2].children[2].ids.search_field.text = '' self.root.ids.sc4.loadSent(state.association) self.root.ids.sc16.clear_widgets() @@ -1637,30 +1654,30 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods if state.search_screen == 'inbox': try: self.root.ids.sc1.children[ - 3].children[1].ids.search_field.text = '' + 3].children[2].ids.search_field.text = '' except Exception: self.root.ids.sc1.children[ - 2].children[1].ids.search_field.text = '' + 2].children[2].ids.search_field.text = '' self.root.ids.sc1.children[1].active = True Clock.schedule_once(self.search_callback, 0.5) elif state.search_screen == 'addressbook': self.root.ids.sc11.children[ - 2].children[1].ids.search_field.text = '' + 2].children[2].ids.search_field.text = '' self.root.ids.sc11.children[ 1].active = True Clock.schedule_once(self.search_callback, 0.5) elif state.search_screen == 'myaddress': try: self.root.ids.sc10.children[ - 3].children[1].ids.search_field.text = '' + 3].children[2].ids.search_field.text = '' except Exception: self.root.ids.sc10.children[ - 2].children[1].ids.search_field.text = '' + 2].children[2].ids.search_field.text = '' self.root.ids.sc10.children[1].active = True Clock.schedule_once(self.search_callback, 0.5) else: self.root.ids.sc4.children[ - 2].children[1].ids.search_field.text = '' + 2].children[2].ids.search_field.text = '' self.root.ids.sc4.children[1].active = True Clock.schedule_once(self.search_callback, 0.5) return @@ -1711,8 +1728,12 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods self.root.ids.sc1.loadMessagelist(state.association) self.root.ids.sc1.children[1].active = False elif instance.text == 'All Mails': - self.root.ids.sc17.clear_widgets() - self.root.ids.sc17.add_widget(Allmails()) + if len(self.root.ids.sc17.ids.ml.children) <= 2: + self.root.ids.sc17.clear_widgets() + self.root.ids.sc17.add_widget(Allmails()) + else: + self.root.ids.sc17.ids.ml.clear_widgets() + self.root.ids.sc17.loadMessagelist() try: self.root.ids.sc17.children[1].active = False except Exception: @@ -1754,26 +1775,6 @@ class GrashofPopup(Popup): self.parent.children[1].ids.scr_mngr.current = 'addressbook' toast('Saved') - # pylint: disable=attribute-defined-outside-init - def show_error_message(self): - """Showing error message""" - content = MDLabel( - font_style='Body1', - theme_text_color='Secondary', - text="Hey you are not allowed to save blank address contact. " - "That's wrong!", - size_hint_y=None, - valign='top') - content.bind(texture_size=content.setter('size')) - self.dialog = MDDialog(content=content, - size_hint=(.8, None), - height=dp(200), - auto_dismiss=False) - - self.dialog.add_action_button("ok", - action=lambda *x: self.dialog.dismiss()) - self.dialog.open() - @staticmethod def close_pop(): """Pop is Canceled""" @@ -1944,7 +1945,7 @@ class MailDetail(Screen): self.children[0].children[0].active = True if state.detailPageType == 'sent': state.kivyapp.root.ids.sc4.children[ - 2].children[1].ids.search_field.text = '' + 2].children[2].ids.search_field.text = '' sqlExecute( "UPDATE sent SET folder = 'trash' WHERE" " ackdata = ?;", state.mail_id) @@ -1954,9 +1955,9 @@ class MailDetail(Screen): self.parent.screens[3].loadSent(state.association) elif state.detailPageType == 'inbox': state.kivyapp.root.ids.sc1.children[ - 2].children[1].ids.search_field.text = '' + 2].children[2].ids.search_field.text = '' self.parent.screens[0].children[2].children[ - 1].ids.search_field.text = '' + 2].ids.search_field.text = '' sqlExecute( "UPDATE inbox SET folder = 'trash' WHERE" " msgid = ?;", state.mail_id) @@ -1985,8 +1986,8 @@ class MailDetail(Screen): state.all_count = str(int(state.all_count) - 1) self.parent.screens[4].clear_widgets() self.parent.screens[4].add_widget(Trash()) - self.parent.screens[16].ids.ml.clear_widgets() - self.parent.screens[16].init_ui(dt=0) + self.parent.screens[16].clear_widgets() + self.parent.screens[16].add_widget(Allmails()) Clock.schedule_once(self.callback_for_delete, 4) def callback_for_delete(self, dt=0): @@ -2178,11 +2179,13 @@ class Draft(Screen): def loadDraft(self, where="", what=""): """Load draft list for Draft messages""" xAddress = 'fromaddress' + self.ids.identi_tag.children[0].text = '' self.draftDataQuery(xAddress, where, what) if state.msg_counter_objs: state.msg_counter_objs.draft_cnt.badge_text = str( len(self.queryreturn)) if self.queryreturn: + self.ids.identi_tag.children[0].text = 'Draft' src_mng_obj = state.kivyapp.root.children[2].children[0].ids src_mng_obj.draft_cnt.badge_text = state.draft_count self.set_mdList() @@ -2279,8 +2282,7 @@ class Draft(Screen): def delete_draft(self, data_index, instance, *args): """Delete draft message permanently""" - sqlExecute("DELETE FROM sent WHERE ackdata = ?;", str( - data_index)) + sqlExecute("DELETE FROM sent WHERE ackdata = ?;", data_index) try: msg_count_objs = ( self.parent.parent.parent.parent.parent.children[2].children[0].ids) @@ -2293,6 +2295,8 @@ class Draft(Screen): msg_count_objs.draft_cnt.badge_text = str( int(state.draft_count) - 1) state.draft_count = str(int(state.draft_count) - 1) + if int(state.draft_count) <= 0: + self.ids.identi_tag.children[0].text = '' self.ids.ml.remove_widget(instance.parent.parent) toast('Deleted') @@ -2373,8 +2377,10 @@ class Allmails(Screen): def loadMessagelist(self): """Load Inbox, Sent anf Draft list of messages""" self.account = state.association + self.ids.identi_tag.children[0].text = '' self.allMessageQuery(0, 20) if self.all_mails: + self.ids.identi_tag.children[0].text = 'All Mails' state.kivyapp.get_inbox_count() state.kivyapp.get_sent_count() state.all_count = str( @@ -2504,6 +2510,8 @@ class Allmails(Screen): int(state.all_count) - 1) state.trash_count = str(int(state.trash_count) + 1) state.all_count = str(int(state.all_count) - 1) + if int(state.all_count) <= 0: + self.ids.identi_tag.children[0].text = '' nav_lay_obj.sc5.clear_widgets() nav_lay_obj.sc5.add_widget(Trash()) nav_lay_obj.sc17.remove_widget(instance.parent.parent) From 256ca151abb6ad5c3b203978e87cccb0637ed1b8 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Mon, 30 Dec 2019 17:40:02 +0530 Subject: [PATCH 6/8] py3 fixes --- src/api.py | 10 +- src/bitmessagecli.py | 614 +++++++++++++++++------------------ src/class_objectProcessor.py | 6 +- src/class_smtpServer.py | 3 +- src/depends.py | 4 +- src/helper_ackPayload.py | 6 +- src/helper_bitcoin.py | 1 + src/helper_search.py | 4 +- src/helper_sent.py | 2 +- src/helper_sql.py | 2 +- src/helper_startup.py | 3 +- src/inventory.py | 2 +- src/l10n.py | 12 +- src/openclpow.py | 2 +- src/proofofwork.py | 4 +- src/protocol.py | 16 +- src/queues.py | 3 +- src/semaphores.py | 2 +- src/shared.py | 3 +- src/singleinstance.py | 6 +- src/state.py | 2 +- src/tr.py | 14 +- src/upnp.py | 36 +- 23 files changed, 371 insertions(+), 386 deletions(-) diff --git a/src/api.py b/src/api.py index cceff623..6c1191a4 100644 --- a/src/api.py +++ b/src/api.py @@ -37,6 +37,7 @@ from helper_ackPayload import genAckPayload from helper_sql import SqlBulkExecute, sqlExecute, sqlQuery, sqlStoredProcedure from inventory import Inventory from network.threads import StoppableThread +# pylint: disable=unused-variable str_chan = '[chan]' @@ -275,7 +276,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): data = '{"addresses":[' for addressInKeysFile in BMConfigParser().addresses(): - # pylint: disable=unused-variable status, addressVersionNumber, streamNumber, hash01 = decodeAddress( addressInKeysFile) if len(data) > 20: @@ -609,7 +609,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): label = str_chan + ' ' + passphrase except BaseException: label = str_chan + ' ' + repr(passphrase) - # pylint: disable=unused-variable status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress( suppliedAddress) suppliedAddress = addBMIfNotPresent(suppliedAddress) @@ -634,7 +633,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): raise APIError(0, 'I need parameters.') elif len(params) == 1: address, = params - # pylint: disable=unused-variable status, addressVersionNumber, streamNumber, toRipe = \ self._verifyAddress(address) address = addBMIfNotPresent(address) @@ -657,7 +655,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): raise APIError(0, 'I need parameters.') elif len(params) == 1: address, = params - # pylint: disable=unused-variable status, addressVersionNumber, streamNumber, toRipe = \ self._verifyAddress(address) address = addBMIfNotPresent(address) @@ -878,7 +875,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): data = '{"sentMessages":[' for row in queryreturn: msgid, toAddress, fromAddress, subject, lastactiontime, message, \ - encodingtype, status, ackdata = row # pylint: disable=unused-variable + encodingtype, status, ackdata = row subject = shared.fixPotentiallyInvalidUTF8Data(subject) message = shared.fixPotentiallyInvalidUTF8Data(message) if len(data) > 25: @@ -988,7 +985,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): TTL = 28 * 24 * 60 * 60 toAddress = addBMIfNotPresent(toAddress) fromAddress = addBMIfNotPresent(fromAddress) - # pylint: disable=unused-variable status, addressVersionNumber, streamNumber, toRipe = \ self._verifyAddress(toAddress) self._verifyAddress(fromAddress) @@ -1165,7 +1161,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): def ListSubscriptions(self, params): """Handle a request to list susbcriptions""" - # pylint: disable=unused-variable queryreturn = sqlQuery( "SELECT label, address, enabled FROM subscriptions") data = {'subscriptions': []} @@ -1271,7 +1266,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): pubkeyReadPosition += 8 else: pubkeyReadPosition += 4 - # pylint: disable=unused-variable addressVersion, addressVersionLength = decodeVarint( payload[pubkeyReadPosition:pubkeyReadPosition + 10]) pubkeyReadPosition += addressVersionLength diff --git a/src/bitmessagecli.py b/src/bitmessagecli.py index 02fed7e9..ff8fb290 100644 --- a/src/bitmessagecli.py +++ b/src/bitmessagecli.py @@ -29,7 +29,8 @@ from bmconfigparser import BMConfigParser api = '' keysName = 'keys.dat' keysPath = 'keys.dat' -usrPrompt = 0 # 0 = First Start, 1 = prompt, 2 = no prompt if the program is starting up +# 0 = First Start, 1 = prompt, 2 = no prompt if the program is starting up +usrPrompt = 0 knownAddresses = dict() @@ -38,7 +39,7 @@ def userInput(message): global usrPrompt - print '\n' + message + print('\n' + message) uInput = raw_input('> ') if uInput.lower() == 'exit': # Returns the user to the main menu @@ -46,7 +47,7 @@ def userInput(message): main() elif uInput.lower() == 'quit': # Quits the program - print '\n Bye\n' + print('\n Bye\n') sys.exit(0) else: @@ -55,9 +56,9 @@ def userInput(message): def restartBmNotify(): """Prompt the user to restart Bitmessage""" - print '\n *******************************************************************' - print ' WARNING: If Bitmessage is running locally, you must restart it now.' - print ' *******************************************************************\n' + print('\n *******************************************************************') + print(' WARNING: If Bitmessage is running locally, you must restart it now.') + print(' *******************************************************************\n') # Begin keys.dat interactions @@ -96,8 +97,8 @@ def configInit(): with open(keysName, 'wb') as configfile: BMConfigParser().write(configfile) - print '\n ' + str(keysName) + ' Initalized in the same directory as daemon.py' - print ' You will now need to configure the ' + str(keysName) + ' file.\n' + print('\n ' + str(keysName) + ' Initalized in the same directory as daemon.py') + print(' You will now need to configure the ' + str(keysName) + ' file.\n') def apiInit(apiEnabled): @@ -114,20 +115,20 @@ def apiInit(apiEnabled): with open(keysPath, 'wb') as configfile: BMConfigParser().write(configfile) - print 'Done' + print('Done') restartBmNotify() return True elif uInput == "n": - print ' \n************************************************************' - print ' Daemon will not work when the API is disabled. ' - print ' Please refer to the Bitmessage Wiki on how to setup the API.' - print ' ************************************************************\n' + print(' \n************************************************************') + print(' Daemon will not work when the API is disabled. ') + print(' Please refer to the Bitmessage Wiki on how to setup the API.') + print(' ************************************************************\n') usrPrompt = 1 main() else: - print '\n Invalid Entry\n' + print('\n Invalid Entry\n') usrPrompt = 1 main() @@ -136,11 +137,11 @@ def apiInit(apiEnabled): return True else: # API information was not present. - print '\n ' + str(keysPath) + ' not properly configured!\n' + print('\n ' + str(keysPath) + ' not properly configured!\n') uInput = userInput("Would you like to do this now, (Y)es or (N)o?").lower() if uInput == "y": # User said yes, initalize the api by writing these values to the keys.dat file - print ' ' + print(' ') apiUsr = userInput("API Username") apiPwd = userInput("API Password") @@ -149,11 +150,11 @@ def apiInit(apiEnabled): daemon = userInput("Daemon mode Enabled? (True) or (False)").lower() if (daemon != 'true' and daemon != 'false'): - print '\n Invalid Entry for Daemon.\n' + print('\n Invalid Entry for Daemon.\n') uInput = 1 main() - print ' -----------------------------------\n' + print(' -----------------------------------\n') # sets the bitmessage port to stop the warning about the api not properly # being setup. This is in the event that the keys.dat is in a different @@ -168,18 +169,18 @@ def apiInit(apiEnabled): with open(keysPath, 'wb') as configfile: BMConfigParser().write(configfile) - print '\n Finished configuring the keys.dat file with API information.\n' + print('\n Finished configuring the keys.dat file with API information.\n') restartBmNotify() return True elif uInput == "n": - print '\n ***********************************************************' - print ' Please refer to the Bitmessage Wiki on how to setup the API.' - print ' ***********************************************************\n' + print('\n ***********************************************************') + print(' Please refer to the Bitmessage Wiki on how to setup the API.') + print(' ***********************************************************\n') usrPrompt = 1 main() else: - print ' \nInvalid entry\n' + print(' \nInvalid entry\n') usrPrompt = 1 main() @@ -206,11 +207,11 @@ def apiData(): BMConfigParser().get('bitmessagesettings', 'port') except: # keys.dat was not there either, something is wrong. - print '\n ******************************************************************' - print ' There was a problem trying to access the Bitmessage keys.dat file' - print ' or keys.dat is not set up correctly' - print ' Make sure that daemon is in the same directory as Bitmessage. ' - print ' ******************************************************************\n' + print('\n ******************************************************************') + print(' There was a problem trying to access the Bitmessage keys.dat file') + print(' or keys.dat is not set up correctly') + print(' Make sure that daemon is in the same directory as Bitmessage. ') + print(' ******************************************************************\n') uInput = userInput("Would you like to create a keys.dat in the local directory, (Y)es or (N)o?").lower() @@ -220,11 +221,11 @@ def apiData(): usrPrompt = 0 main() elif (uInput == "n" or uInput == "no"): - print '\n Trying Again.\n' + print('\n Trying Again.\n') usrPrompt = 0 main() else: - print '\n Invalid Input.\n' + print('\n Invalid Input.\n') usrPrompt = 1 main() @@ -249,7 +250,7 @@ def apiData(): apiUsername = BMConfigParser().get('bitmessagesettings', 'apiusername') apiPassword = BMConfigParser().get('bitmessagesettings', 'apipassword') - print '\n API data successfully imported.\n' + print('\n API data successfully imported.\n') # Build the api credentials return "http://" + apiUsername + ":" + apiPassword + "@" + apiInterface + ":" + str(apiPort) + "/" @@ -281,7 +282,7 @@ def bmSettings(): try: port = BMConfigParser().get('bitmessagesettings', 'port') except: - print '\n File not found.\n' + print('\n File not found.\n') usrPrompt = 0 main() @@ -300,27 +301,27 @@ def bmSettings(): socksusername = BMConfigParser().get('bitmessagesettings', 'socksusername') sockspassword = BMConfigParser().get('bitmessagesettings', 'sockspassword') - print '\n -----------------------------------' - print ' | Current Bitmessage Settings |' - print ' -----------------------------------' - print ' port = ' + port - print ' startonlogon = ' + str(startonlogon) - print ' minimizetotray = ' + str(minimizetotray) - print ' showtraynotifications = ' + str(showtraynotifications) - print ' startintray = ' + str(startintray) - print ' defaultnoncetrialsperbyte = ' + defaultnoncetrialsperbyte - print ' defaultpayloadlengthextrabytes = ' + defaultpayloadlengthextrabytes - print ' daemon = ' + str(daemon) - print '\n ------------------------------------' - print ' | Current Connection Settings |' - print ' -----------------------------------' - print ' socksproxytype = ' + socksproxytype - print ' sockshostname = ' + sockshostname - print ' socksport = ' + socksport - print ' socksauthentication = ' + str(socksauthentication) - print ' socksusername = ' + socksusername - print ' sockspassword = ' + sockspassword - print ' ' + print('\n -----------------------------------') + print(' | Current Bitmessage Settings |') + print(' -----------------------------------') + print(' port = ' + port) + print(' startonlogon = ' + str(startonlogon)) + print(' minimizetotray = ' + str(minimizetotray)) + print(' showtraynotifications = ' + str(showtraynotifications)) + print(' startintray = ' + str(startintray)) + print(' defaultnoncetrialsperbyte = ' + defaultnoncetrialsperbyte) + print(' defaultpayloadlengthextrabytes = ' + defaultpayloadlengthextrabytes) + print(' daemon = ' + str(daemon)) + print('\n ------------------------------------') + print(' | Current Connection Settings |') + print(' -----------------------------------') + print(' socksproxytype = ' + socksproxytype) + print(' sockshostname = ' + sockshostname) + print(' socksport = ' + socksport) + print(' socksauthentication = ' + str(socksauthentication)) + print(' socksusername = ' + socksusername) + print(' sockspassword = ' + sockspassword) + print(' ') uInput = userInput("Would you like to modify any of these settings, (Y)es or (N)o?").lower() @@ -328,74 +329,74 @@ def bmSettings(): while True: # loops if they mistype the setting name, they can exit the loop with 'exit' invalidInput = False uInput = userInput("What setting would you like to modify?").lower() - print ' ' + print(' ') if uInput == "port": - print ' Current port number: ' + port + print(' Current port number: ' + port) uInput = userInput("Enter the new port number.") BMConfigParser().set('bitmessagesettings', 'port', str(uInput)) elif uInput == "startonlogon": - print ' Current status: ' + str(startonlogon) + print(' Current status: ' + str(startonlogon)) uInput = userInput("Enter the new status.") BMConfigParser().set('bitmessagesettings', 'startonlogon', str(uInput)) elif uInput == "minimizetotray": - print ' Current status: ' + str(minimizetotray) + print(' Current status: ' + str(minimizetotray)) uInput = userInput("Enter the new status.") BMConfigParser().set('bitmessagesettings', 'minimizetotray', str(uInput)) elif uInput == "showtraynotifications": - print ' Current status: ' + str(showtraynotifications) + print(' Current status: ' + str(showtraynotifications)) uInput = userInput("Enter the new status.") BMConfigParser().set('bitmessagesettings', 'showtraynotifications', str(uInput)) elif uInput == "startintray": - print ' Current status: ' + str(startintray) + print(' Current status: ' + str(startintray)) uInput = userInput("Enter the new status.") BMConfigParser().set('bitmessagesettings', 'startintray', str(uInput)) elif uInput == "defaultnoncetrialsperbyte": - print ' Current default nonce trials per byte: ' + defaultnoncetrialsperbyte + print(' Current default nonce trials per byte: ' + defaultnoncetrialsperbyte) uInput = userInput("Enter the new defaultnoncetrialsperbyte.") BMConfigParser().set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(uInput)) elif uInput == "defaultpayloadlengthextrabytes": - print ' Current default payload length extra bytes: ' + defaultpayloadlengthextrabytes + print(' Current default payload length extra bytes: ' + defaultpayloadlengthextrabytes) uInput = userInput("Enter the new defaultpayloadlengthextrabytes.") BMConfigParser().set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(uInput)) elif uInput == "daemon": - print ' Current status: ' + str(daemon) + print(' Current status: ' + str(daemon)) uInput = userInput("Enter the new status.").lower() BMConfigParser().set('bitmessagesettings', 'daemon', str(uInput)) elif uInput == "socksproxytype": - print ' Current socks proxy type: ' + socksproxytype - print "Possibilities: 'none', 'SOCKS4a', 'SOCKS5'." + print(' Current socks proxy type: ' + socksproxytype) + print("Possibilities: 'none', 'SOCKS4a', 'SOCKS5'.") uInput = userInput("Enter the new socksproxytype.") BMConfigParser().set('bitmessagesettings', 'socksproxytype', str(uInput)) elif uInput == "sockshostname": - print ' Current socks host name: ' + sockshostname + print(' Current socks host name: ' + sockshostname) uInput = userInput("Enter the new sockshostname.") BMConfigParser().set('bitmessagesettings', 'sockshostname', str(uInput)) elif uInput == "socksport": - print ' Current socks port number: ' + socksport + print(' Current socks port number: ' + socksport) uInput = userInput("Enter the new socksport.") BMConfigParser().set('bitmessagesettings', 'socksport', str(uInput)) elif uInput == "socksauthentication": - print ' Current status: ' + str(socksauthentication) + print(' Current status: ' + str(socksauthentication)) uInput = userInput("Enter the new status.") BMConfigParser().set('bitmessagesettings', 'socksauthentication', str(uInput)) elif uInput == "socksusername": - print ' Current socks username: ' + socksusername + print(' Current socks username: ' + socksusername) uInput = userInput("Enter the new socksusername.") BMConfigParser().set('bitmessagesettings', 'socksusername', str(uInput)) elif uInput == "sockspassword": - print ' Current socks password: ' + sockspassword + print(' Current socks password: ' + sockspassword) uInput = userInput("Enter the new password.") BMConfigParser().set('bitmessagesettings', 'sockspassword', str(uInput)) else: - print "\n Invalid input. Please try again.\n" + print("\n Invalid input. Please try again.\n") invalidInput = True if invalidInput is not True: # don't prompt if they made a mistake. uInput = userInput("Would you like to change another setting, (Y)es or (N)o?").lower() if uInput != "y": - print '\n Changes Made.\n' + print('\n Changes Made.\n') with open(keysPath, 'wb') as configfile: BMConfigParser().write(configfile) restartBmNotify() @@ -405,7 +406,7 @@ def bmSettings(): usrPrompt = 1 main() else: - print "Invalid input." + print("Invalid input.") usrPrompt = 1 main() @@ -433,10 +434,10 @@ def subscribe(): if address == "c": usrPrompt = 1 - print ' ' + print(' ') main() elif validAddress(address) is False: - print '\n Invalid. "c" to cancel. Please try again.\n' + print('\n Invalid. "c" to cancel. Please try again.\n') else: break @@ -444,7 +445,7 @@ def subscribe(): label = label.encode('base64') api.addSubscription(address, label) - print '\n You are now subscribed to: ' + address + '\n' + print('\n You are now subscribed to: ' + address + '\n') def unsubscribe(): @@ -456,31 +457,31 @@ def unsubscribe(): if address == "c": usrPrompt = 1 - print ' ' + print(' ') main() elif validAddress(address) is False: - print '\n Invalid. "c" to cancel. Please try again.\n' + print('\n Invalid. "c" to cancel. Please try again.\n') else: break userInput("Are you sure, (Y)es or (N)o?").lower() # uInput = api.deleteSubscription(address) - print '\n You are now unsubscribed from: ' + address + '\n' + print('\n You are now unsubscribed from: ' + address + '\n') def listSubscriptions(): """List subscriptions""" global usrPrompt - print '\nLabel, Address, Enabled\n' + print('\nLabel, Address, Enabled\n') try: - print api.listSubscriptions() + print(api.listSubscriptions()) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() - print ' ' + print(' ') def createChan(): @@ -490,9 +491,9 @@ def createChan(): password = userInput("Enter channel name") password = password.encode('base64') try: - print api.createChan(password) + print(api.createChan(password)) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() @@ -506,19 +507,19 @@ def joinChan(): if address == "c": usrPrompt = 1 - print ' ' + print(' ') main() elif validAddress(address) is False: - print '\n Invalid. "c" to cancel. Please try again.\n' + print('\n Invalid. "c" to cancel. Please try again.\n') else: break password = userInput("Enter channel name") password = password.encode('base64') try: - print api.joinChan(password, address) + print(api.joinChan(password, address)) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() @@ -532,17 +533,17 @@ def leaveChan(): if address == "c": usrPrompt = 1 - print ' ' + print(' ') main() elif validAddress(address) is False: - print '\n Invalid. "c" to cancel. Please try again.\n' + print('\n Invalid. "c" to cancel. Please try again.\n') else: break try: - print api.leaveChan(address) + print(api.leaveChan(address)) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() @@ -554,14 +555,14 @@ def listAdd(): jsonAddresses = json.loads(api.listAddresses()) numAddresses = len(jsonAddresses['addresses']) # Number of addresses except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() - # print '\nAddress Number,Label,Address,Stream,Enabled\n' - print '\n --------------------------------------------------------------------------' - print ' | # | Label | Address |S#|Enabled|' - print ' |---|-------------------|-------------------------------------|--|-------|' + # print('\nAddress Number,Label,Address,Stream,Enabled\n') + print('\n --------------------------------------------------------------------------') + print(' | # | Label | Address |S#|Enabled|') + print(' |---|-------------------|-------------------------------------|--|-------|') for addNum in range(0, numAddresses): # processes all of the addresses and lists them out label = (jsonAddresses['addresses'][addNum]['label']).encode( 'utf') # may still misdiplay in some consoles @@ -572,7 +573,7 @@ def listAdd(): if len(label) > 19: label = label[:16] + '...' - print ''.join([ + print(''.join([ ' |', str(addNum).ljust(3), '|', @@ -584,13 +585,13 @@ def listAdd(): '|', enabled.ljust(7), '|', - ]) + ])) - print ''.join([ + print(''.join([ ' ', 74 * '-', '\n', - ]) + ])) def genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe): @@ -603,7 +604,7 @@ def genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe): try: generatedAddress = api.createRandomAddress(addressLabel) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() @@ -614,7 +615,7 @@ def genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe): try: generatedAddress = api.createDeterministicAddresses(passphrase, numOfAdd, addVNum, streamNum, ripe) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() return generatedAddress @@ -646,7 +647,7 @@ def saveFile(fileName, fileData): with open(filePath, 'wb+') as path_to_file: path_to_file.write(fileData.decode("base64")) - print '\n Successfully saved ' + filePath + '\n' + print('\n Successfully saved ' + filePath + '\n') def attachment(): @@ -667,26 +668,26 @@ def attachment(): with open(filePath): break except IOError: - print '\n %s was not found on your filesystem or can not be opened.\n' % filePath + print('\n %s was not found on your filesystem or can not be opened.\n' % filePath) - # print filesize, and encoding estimate with confirmation if file is over X size (1mb?) + # print(filesize, and encoding estimate with confirmation if file is over X size (1mb?)) invSize = os.path.getsize(filePath) invSize = (invSize / 1024) # Converts to kilobytes round(invSize, 2) # Rounds to two decimal places if invSize > 500.0: # If over 500KB - print ''.join([ + print(''.join([ '\n WARNING:The file that you are trying to attach is ', invSize, 'KB and will take considerable time to send.\n' - ]) + ])) uInput = userInput('Are you sure you still want to attach it, (Y)es or (N)o?').lower() if uInput != "y": - print '\n Attachment discarded.\n' + print('\n Attachment discarded.\n') return '' elif invSize > 184320.0: # If larger than 180MB, discard. - print '\n Attachment too big, maximum allowed size:180MB\n' + print('\n Attachment too big, maximum allowed size:180MB\n') main() pathLen = len(str(ntpath.basename(filePath))) # Gets the length of the filepath excluding the filename @@ -694,17 +695,17 @@ def attachment(): filetype = imghdr.what(filePath) # Tests if it is an image file if filetype is not None: - print '\n ---------------------------------------------------' - print ' Attachment detected as an Image.' - print ' tags will automatically be included,' - print ' allowing the recipient to view the image' - print ' using the "View HTML code..." option in Bitmessage.' - print ' ---------------------------------------------------\n' + print('\n ---------------------------------------------------') + print(' Attachment detected as an Image.') + print(' tags will automatically be included,') + print(' allowing the recipient to view the image') + print(' using the "View HTML code..." option in Bitmessage.') + print(' ---------------------------------------------------\n') isImage = True time.sleep(2) # Alert the user that the encoding process may take some time. - print '\n Encoding Attachment, Please Wait ...\n' + print('\n Encoding Attachment, Please Wait ...\n') with open(filePath, 'rb') as f: # Begin the actual encoding data = f.read(188743680) # Reads files up to 180MB, the maximum size for Bitmessage. @@ -759,10 +760,10 @@ def sendMsg(toAddress, fromAddress, subject, message): if toAddress == "c": usrPrompt = 1 - print ' ' + print(' ') main() elif validAddress(toAddress) is False: - print '\n Invalid Address. "c" to cancel. Please try again.\n' + print('\n Invalid Address. "c" to cancel. Please try again.\n') else: break @@ -771,14 +772,14 @@ def sendMsg(toAddress, fromAddress, subject, message): jsonAddresses = json.loads(api.listAddresses()) numAddresses = len(jsonAddresses['addresses']) # Number of addresses except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() if numAddresses > 1: # Ask what address to send from if multiple addresses found = False while True: - print ' ' + print(' ') fromAddress = userInput("Enter an Address or Address Label to send from.") if fromAddress == "exit": @@ -795,7 +796,7 @@ def sendMsg(toAddress, fromAddress, subject, message): if found is False: if validAddress(fromAddress) is False: - print '\n Invalid Address. Please try again.\n' + print('\n Invalid Address. Please try again.\n') else: for addNum in range(0, numAddresses): # processes all of the addresses @@ -805,13 +806,13 @@ def sendMsg(toAddress, fromAddress, subject, message): break if found is False: - print '\n The address entered is not one of yours. Please try again.\n' + print('\n The address entered is not one of yours. Please try again.\n') if found: break # Address was found else: # Only one address in address book - print '\n Using the only address in the addressbook to send from.\n' + print('\n Using the only address in the addressbook to send from.\n') fromAddress = jsonAddresses['addresses'][0]['address'] if subject == '': @@ -828,9 +829,9 @@ def sendMsg(toAddress, fromAddress, subject, message): try: ackData = api.sendMessage(toAddress, fromAddress, subject, message) - print '\n Message Status:', api.getStatus(ackData), '\n' + print('\n Message Status:', api.getStatus(ackData), '\n') except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() @@ -845,7 +846,7 @@ def sendBrd(fromAddress, subject, message): jsonAddresses = json.loads(api.listAddresses()) numAddresses = len(jsonAddresses['addresses']) # Number of addresses except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() @@ -868,7 +869,7 @@ def sendBrd(fromAddress, subject, message): if found is False: if validAddress(fromAddress) is False: - print '\n Invalid Address. Please try again.\n' + print('\n Invalid Address. Please try again.\n') else: for addNum in range(0, numAddresses): # processes all of the addresses @@ -878,13 +879,13 @@ def sendBrd(fromAddress, subject, message): break if found is False: - print '\n The address entered is not one of yours. Please try again.\n' + print('\n The address entered is not one of yours. Please try again.\n') if found: break # Address was found else: # Only one address in address book - print '\n Using the only address in the addressbook to send from.\n' + print('\n Using the only address in the addressbook to send from.\n') fromAddress = jsonAddresses['addresses'][0]['address'] if subject == '': @@ -901,9 +902,9 @@ def sendBrd(fromAddress, subject, message): try: ackData = api.sendBroadcast(fromAddress, subject, message) - print '\n Message Status:', api.getStatus(ackData), '\n' + print('\n Message Status:', api.getStatus(ackData), '\n') except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() @@ -916,7 +917,7 @@ def inbox(unreadOnly=False): inboxMessages = json.loads(api.getAllInboxMessages()) numMessages = len(inboxMessages['inboxMessages']) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() @@ -926,16 +927,16 @@ def inbox(unreadOnly=False): message = inboxMessages['inboxMessages'][msgNum] # if we are displaying all messages or if this message is unread then display it if not unreadOnly or not message['read']: - print ' -----------------------------------\n' - print ' Message Number:', msgNum # Message Number - print ' To:', getLabelForAddress(message['toAddress']) # Get the to address - print ' From:', getLabelForAddress(message['fromAddress']) # Get the from address - print ' Subject:', message['subject'].decode('base64') # Get the subject - print ''.join([ + print(' -----------------------------------\n') + print(' Message Number:', msgNum) # Message Number + print(' To:', getLabelForAddress(message['toAddress'])) # Get the to address + print(' From:', getLabelForAddress(message['fromAddress'])) # Get the from address + print(' Subject:', message['subject'].decode('base64')) # Get the subject + print(''.join([ ' Received:', datetime.datetime.fromtimestamp( float(message['receivedTime'])).strftime('%Y-%m-%d %H:%M:%S'), - ]) + ])) messagesPrinted += 1 if not message['read']: messagesUnread += 1 @@ -943,9 +944,9 @@ def inbox(unreadOnly=False): if messagesPrinted % 20 == 0 and messagesPrinted != 0: userInput('(Press Enter to continue or type (Exit) to return to the main menu.)').lower() # uInput = - print '\n -----------------------------------' - print ' There are %d unread messages of %d messages in the inbox.' % (messagesUnread, numMessages) - print ' -----------------------------------\n' + print('\n -----------------------------------') + print(' There are %d unread messages of %d messages in the inbox.' % (messagesUnread, numMessages)) + print(' -----------------------------------\n') def outbox(): @@ -956,32 +957,32 @@ def outbox(): outboxMessages = json.loads(api.getAllSentMessages()) numMessages = len(outboxMessages['sentMessages']) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() for msgNum in range(0, numMessages): # processes all of the messages in the outbox - print '\n -----------------------------------\n' - print ' Message Number:', msgNum # Message Number - # print ' Message ID:', outboxMessages['sentMessages'][msgNum]['msgid'] - print ' To:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['toAddress']) # Get the to address + print('\n -----------------------------------\n') + print(' Message Number:', msgNum) # Message Number + # print(' Message ID:', outboxMessages['sentMessages'][msgNum]['msgid']) + # Get the to address + print(' To:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['toAddress'])) # Get the from address - print ' From:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['fromAddress']) - print ' Subject:', outboxMessages['sentMessages'][msgNum]['subject'].decode('base64') # Get the subject - print ' Status:', outboxMessages['sentMessages'][msgNum]['status'] # Get the subject - - print ''.join([ + print(' From:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['fromAddress'])) + print(' Subject:', outboxMessages['sentMessages'][msgNum]['subject'].decode('base64')) # Get the subject + print(' Status:', outboxMessages['sentMessages'][msgNum]['status']) # Get the subject + print(''.join([ ' Last Action Time:', datetime.datetime.fromtimestamp( float(outboxMessages['sentMessages'][msgNum]['lastActionTime'])).strftime('%Y-%m-%d %H:%M:%S'), - ]) + ])) if msgNum % 20 == 0 and msgNum != 0: userInput('(Press Enter to continue or type (Exit) to return to the main menu.)').lower() # uInput = - print '\n -----------------------------------' - print ' There are ', numMessages, ' messages in the outbox.' - print ' -----------------------------------\n' + print('\n -----------------------------------') + print(' There are ', numMessages, ' messages in the outbox.') + print(' -----------------------------------\n') def readSentMsg(msgNum): @@ -992,14 +993,14 @@ def readSentMsg(msgNum): outboxMessages = json.loads(api.getAllSentMessages()) numMessages = len(outboxMessages['sentMessages']) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() - print ' ' + print(' ') if msgNum >= numMessages: - print '\n Invalid Message Number.\n' + print('\n Invalid Message Number.\n') main() # Begin attachment detection @@ -1035,19 +1036,19 @@ def readSentMsg(msgNum): # End attachment Detection - print '\n To:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['toAddress']) # Get the to address + print('\n To:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['toAddress'])) # Get the to address # Get the from address - print ' From:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['fromAddress']) - print ' Subject:', outboxMessages['sentMessages'][msgNum]['subject'].decode('base64') # Get the subject - print ' Status:', outboxMessages['sentMessages'][msgNum]['status'] # Get the subject - print ''.join([ + print(' From:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['fromAddress'])) + print(' Subject:', outboxMessages['sentMessages'][msgNum]['subject'].decode('base64')) # Get the subject + print(' Status:', outboxMessages['sentMessages'][msgNum]['status']) # Get the subject + print(''.join([ ' Last Action Time:', datetime.datetime.fromtimestamp( float(outboxMessages['sentMessages'][msgNum]['lastActionTime'])).strftime('%Y-%m-%d %H:%M:%S'), - ]) - print ' Message:\n' - print message # inboxMessages['inboxMessages'][msgNum]['message'].decode('base64') - print ' ' + ])) + print(' Message:\n') + print(message) # inboxMessages['inboxMessages'][msgNum]['message'].decode('base64') + print(' ') def readMsg(msgNum): @@ -1057,12 +1058,12 @@ def readMsg(msgNum): inboxMessages = json.loads(api.getAllInboxMessages()) numMessages = len(inboxMessages['inboxMessages']) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() if msgNum >= numMessages: - print '\n Invalid Message Number.\n' + print('\n Invalid Message Number.\n') main() # Begin attachment detection @@ -1097,17 +1098,17 @@ def readMsg(msgNum): break # End attachment Detection - print '\n To:', getLabelForAddress(inboxMessages['inboxMessages'][msgNum]['toAddress']) # Get the to address + print('\n To:', getLabelForAddress(inboxMessages['inboxMessages'][msgNum]['toAddress'])) # Get the to address # Get the from address - print ' From:', getLabelForAddress(inboxMessages['inboxMessages'][msgNum]['fromAddress']) - print ' Subject:', inboxMessages['inboxMessages'][msgNum]['subject'].decode('base64') # Get the subject - print ''.join([ + print(' From:', getLabelForAddress(inboxMessages['inboxMessages'][msgNum]['fromAddress'])) + print(' Subject:', inboxMessages['inboxMessages'][msgNum]['subject'].decode('base64')) # Get the subject + print(''.join([ ' Received:', datetime.datetime.fromtimestamp( float(inboxMessages['inboxMessages'][msgNum]['receivedTime'])).strftime('%Y-%m-%d %H:%M:%S'), - ]) - print ' Message:\n' - print message # inboxMessages['inboxMessages'][msgNum]['message'].decode('base64') - print ' ' + ])) + print(' Message:\n') + print(message) # inboxMessages['inboxMessages'][msgNum]['message'].decode('base64') + print(' ') return inboxMessages['inboxMessages'][msgNum]['msgid'] @@ -1119,7 +1120,7 @@ def replyMsg(msgNum, forwardORreply): try: inboxMessages = json.loads(api.getAllInboxMessages()) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() @@ -1141,14 +1142,14 @@ def replyMsg(msgNum, forwardORreply): if toAdd == "c": usrPrompt = 1 - print ' ' + print(' ') main() elif validAddress(toAdd) is False: - print '\n Invalid Address. "c" to cancel. Please try again.\n' + print('\n Invalid Address. "c" to cancel. Please try again.\n') else: break else: - print '\n Invalid Selection. Reply or Forward only' + print('\n Invalid Selection. Reply or Forward only') usrPrompt = 0 main() @@ -1180,7 +1181,7 @@ def delMsg(msgNum): msgAck = api.trashMessage(msgId) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() @@ -1197,7 +1198,7 @@ def delSentMsg(msgNum): msgId = outboxMessages['sentMessages'][int(msgNum)]['msgid'] msgAck = api.trashSentMessage(msgId) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() @@ -1233,7 +1234,7 @@ def buildKnownAddresses(): if entry['address'] not in knownAddresses: knownAddresses[entry['address']] = "%s (%s)" % (entry['label'].decode('base64'), entry['address']) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() @@ -1248,7 +1249,7 @@ def buildKnownAddresses(): if entry['address'] not in knownAddresses: knownAddresses[entry['address']] = "%s (%s)" % (entry['label'].decode('base64'), entry['address']) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() @@ -1263,21 +1264,20 @@ def listAddressBookEntries(): if "API Error" in response: return getAPIErrorCode(response) addressBook = json.loads(response) - print - print ' --------------------------------------------------------------' - print ' | Label | Address |' - print ' |--------------------|---------------------------------------|' + print() + print(' --------------------------------------------------------------') + print(' | Label | Address |') + print(' |--------------------|---------------------------------------|') for entry in addressBook['addresses']: label = entry['label'].decode('base64') address = entry['address'] if len(label) > 19: label = label[:16] + '...' - print ' | ' + label.ljust(19) + '| ' + address.ljust(37) + ' |' - print ' --------------------------------------------------------------' - print - + print(' | ' + label.ljust(19) + '| ' + address.ljust(37) + ' |') + print(' --------------------------------------------------------------') + print() except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() @@ -1292,7 +1292,7 @@ def addAddressToAddressBook(address, label): if "API Error" in response: return getAPIErrorCode(response) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() @@ -1307,7 +1307,7 @@ def deleteAddressFromAddressBook(address): if "API Error" in response: return getAPIErrorCode(response) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() @@ -1331,7 +1331,7 @@ def markMessageRead(messageID): if "API Error" in response: return getAPIErrorCode(response) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() @@ -1346,7 +1346,7 @@ def markMessageUnread(messageID): if "API Error" in response: return getAPIErrorCode(response) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() @@ -1359,7 +1359,7 @@ def markAllMessagesRead(): try: inboxMessages = json.loads(api.getAllInboxMessages())['inboxMessages'] except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() for message in inboxMessages: @@ -1375,7 +1375,7 @@ def markAllMessagesUnread(): try: inboxMessages = json.loads(api.getAllInboxMessages())['inboxMessages'] except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() for message in inboxMessages: @@ -1391,15 +1391,15 @@ def clientStatus(): try: client_status = json.loads(api.clientStatus()) except: - print '\n Connection Error\n' + print('\n Connection Error\n') usrPrompt = 0 main() - print "\nnetworkStatus: " + client_status['networkStatus'] + "\n" - print "\nnetworkConnections: " + str(client_status['networkConnections']) + "\n" - print "\nnumberOfPubkeysProcessed: " + str(client_status['numberOfPubkeysProcessed']) + "\n" - print "\nnumberOfMessagesProcessed: " + str(client_status['numberOfMessagesProcessed']) + "\n" - print "\nnumberOfBroadcastsProcessed: " + str(client_status['numberOfBroadcastsProcessed']) + "\n" + print("\nnetworkStatus: " + client_status['networkStatus'] + "\n") + print("\nnetworkConnections: " + str(client_status['networkConnections']) + "\n") + print("\nnumberOfPubkeysProcessed: " + str(client_status['numberOfPubkeysProcessed']) + "\n") + print("\nnumberOfMessagesProcessed: " + str(client_status['numberOfMessagesProcessed']) + "\n") + print("\nnumberOfBroadcastsProcessed: " + str(client_status['numberOfBroadcastsProcessed']) + "\n") def shutdown(): @@ -1409,7 +1409,7 @@ def shutdown(): api.shutdown() except socket.error: pass - print "\nShutdown command relayed\n" + print("\nShutdown command relayed\n") def UI(usrInput): @@ -1418,75 +1418,75 @@ def UI(usrInput): global usrPrompt if usrInput == "help" or usrInput == "h" or usrInput == "?": - print ' ' - print ' -------------------------------------------------------------------------' - print ' | https://github.com/Dokument/PyBitmessage-Daemon |' - print ' |-----------------------------------------------------------------------|' - print ' | Command | Description |' - print ' |------------------------|----------------------------------------------|' - print ' | help | This help file. |' - print ' | apiTest | Tests the API |' - print ' | addInfo | Returns address information (If valid) |' - print ' | bmSettings | BitMessage settings |' - print ' | exit | Use anytime to return to main menu |' - print ' | quit | Quits the program |' - print ' |------------------------|----------------------------------------------|' - print ' | listAddresses | Lists all of the users addresses |' - print ' | generateAddress | Generates a new address |' - print ' | getAddress | Get determinist address from passphrase |' - print ' |------------------------|----------------------------------------------|' - print ' | listAddressBookEntries | Lists entries from the Address Book |' - print ' | addAddressBookEntry | Add address to the Address Book |' - print ' | deleteAddressBookEntry | Deletes address from the Address Book |' - print ' |------------------------|----------------------------------------------|' - print ' | subscribe | Subscribes to an address |' - print ' | unsubscribe | Unsubscribes from an address |' - print ' |------------------------|----------------------------------------------|' - print ' | create | Creates a channel |' - print ' | join | Joins a channel |' - print ' | leave | Leaves a channel |' - print ' |------------------------|----------------------------------------------|' - print ' | inbox | Lists the message information for the inbox |' - print ' | outbox | Lists the message information for the outbox |' - print ' | send | Send a new message or broadcast |' - print ' | unread | Lists all unread inbox messages |' - print ' | read | Reads a message from the inbox or outbox |' - print ' | save | Saves message to text file |' - print ' | delete | Deletes a message or all messages |' - print ' -------------------------------------------------------------------------' - print ' ' + print(' ') + print(' -------------------------------------------------------------------------') + print(' | https://github.com/Dokument/PyBitmessage-Daemon |') + print(' |-----------------------------------------------------------------------|') + print(' | Command | Description |') + print(' |------------------------|----------------------------------------------|') + print(' | help | This help file. |') + print(' | apiTest | Tests the API |') + print(' | addInfo | Returns address information (If valid) |') + print(' | bmSettings | BitMessage settings |') + print(' | exit | Use anytime to return to main menu |') + print(' | quit | Quits the program |') + print(' |------------------------|----------------------------------------------|') + print(' | listAddresses | Lists all of the users addresses |') + print(' | generateAddress | Generates a new address |') + print(' | getAddress | Get determinist address from passphrase |') + print(' |------------------------|----------------------------------------------|') + print(' | listAddressBookEntries | Lists entries from the Address Book |') + print(' | addAddressBookEntry | Add address to the Address Book |') + print(' | deleteAddressBookEntry | Deletes address from the Address Book |') + print(' |------------------------|----------------------------------------------|') + print(' | subscribe | Subscribes to an address |') + print(' | unsubscribe | Unsubscribes from an address |') + print(' |------------------------|----------------------------------------------|') + print(' | create | Creates a channel |') + print(' | join | Joins a channel |') + print(' | leave | Leaves a channel |') + print(' |------------------------|----------------------------------------------|') + print(' | inbox | Lists the message information for the inbox |') + print(' | outbox | Lists the message information for the outbox |') + print(' | send | Send a new message or broadcast |') + print(' | unread | Lists all unread inbox messages |') + print(' | read | Reads a message from the inbox or outbox |') + print(' | save | Saves message to text file |') + print(' | delete | Deletes a message or all messages |') + print(' -------------------------------------------------------------------------') + print(' ') main() elif usrInput == "apitest": # tests the API Connection. if apiTest(): - print '\n API connection test has: PASSED\n' + print('\n API connection test has: PASSED\n') else: - print '\n API connection test has: FAILED\n' + print('\n API connection test has: FAILED\n') main() elif usrInput == "addinfo": tmp_address = userInput('\nEnter the Bitmessage Address.') address_information = json.loads(api.decodeAddress(tmp_address)) - print '\n------------------------------' + print('\n------------------------------') if 'success' in str(address_information['status']).lower(): - print ' Valid Address' - print ' Address Version: %s' % str(address_information['addressVersion']) - print ' Stream Number: %s' % str(address_information['streamNumber']) + print(' Valid Address') + print(' Address Version: %s' % str(address_information['addressVersion'])) + print(' Stream Number: %s' % str(address_information['streamNumber'])) else: - print ' Invalid Address !' + print(' Invalid Address !') - print '------------------------------\n' + print('------------------------------\n') main() elif usrInput == "bmsettings": # tests the API Connection. bmSettings() - print ' ' + print(' ') main() elif usrInput == "quit": # Quits the application - print '\n Bye\n' + print('\n Bye\n') sys.exit(0) elif usrInput == "listaddresses": # Lists all of the identities in the addressbook @@ -1508,17 +1508,17 @@ def UI(usrInput): if isRipe == "y": ripe = True - print genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe) + print(genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe)) main() elif isRipe == "n": ripe = False - print genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe) + print(genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe)) main() elif isRipe == "exit": usrPrompt = 1 main() else: - print '\n Invalid input\n' + print('\n Invalid input\n') main() elif uInput == "r" or uInput == "random": # Creates a random address with user-defined label @@ -1526,18 +1526,18 @@ def UI(usrInput): null = '' lbl = userInput('Enter the label for the new address.') - print genAdd(lbl, deterministic, null, null, null, null, null) + print(genAdd(lbl, deterministic, null, null, null, null, null)) main() else: - print '\n Invalid input\n' + print('\n Invalid input\n') main() elif usrInput == "getaddress": # Gets the address for/from a passphrase phrase = userInput("Enter the address passphrase.") - print '\n Working...\n' + print('\n Working...\n') address = getAddress(phrase, 4, 1) # ,vNumber,sNumber) - print '\n Address: ' + address + '\n' + print('\n Address: ' + address + '\n') usrPrompt = 1 main() @@ -1572,17 +1572,17 @@ def UI(usrInput): main() elif usrInput == "inbox": - print '\n Loading...\n' + print('\n Loading...\n') inbox() main() elif usrInput == "unread": - print '\n Loading...\n' + print('\n Loading...\n') inbox(True) main() elif usrInput == "outbox": - print '\n Loading...\n' + print('\n Loading...\n') outbox() main() @@ -1603,14 +1603,14 @@ def UI(usrInput): uInput = userInput("Would you like to read a message from the (I)nbox or (O)utbox?").lower() if (uInput != 'i' and uInput != 'inbox' and uInput != 'o' and uInput != 'outbox'): - print '\n Invalid Input.\n' + print('\n Invalid Input.\n') usrPrompt = 1 main() msgNum = int(userInput("What is the number of the message you wish to open?")) if (uInput == 'i' or uInput == 'inbox'): - print '\n Loading...\n' + print('\n Loading...\n') messageID = readMsg(msgNum) uInput = userInput("\nWould you like to keep this message unread, (Y)es or (N)o?").lower() @@ -1622,14 +1622,14 @@ def UI(usrInput): uInput = userInput("\nWould you like to (D)elete, (F)orward, (R)eply to, or (Exit) this message?").lower() if uInput in ['r', 'reply']: - print '\n Loading...\n' - print ' ' + print('\n Loading...\n') + print(' ') replyMsg(msgNum, 'reply') usrPrompt = 1 elif uInput == 'f' or uInput == 'forward': - print '\n Loading...\n' - print ' ' + print('\n Loading...\n') + print(' ') replyMsg(msgNum, 'forward') usrPrompt = 1 @@ -1638,12 +1638,12 @@ def UI(usrInput): if uInput == "y": delMsg(msgNum) - print '\n Message Deleted.\n' + print('\n Message Deleted.\n') usrPrompt = 1 else: usrPrompt = 1 else: - print '\n Invalid entry\n' + print('\n Invalid entry\n') usrPrompt = 1 elif (uInput == 'o' or uInput == 'outbox'): @@ -1657,12 +1657,12 @@ def UI(usrInput): if uInput == "y": delSentMsg(msgNum) - print '\n Message Deleted.\n' + print('\n Message Deleted.\n') usrPrompt = 1 else: usrPrompt = 1 else: - print '\n Invalid Entry\n' + print('\n Invalid Entry\n') usrPrompt = 1 main() @@ -1672,7 +1672,7 @@ def UI(usrInput): uInput = userInput("Would you like to save a message from the (I)nbox or (O)utbox?").lower() if uInput not in ['i', 'inbox', 'o', 'outbox']: - print '\n Invalid Input.\n' + print('\n Invalid Input.\n') usrPrompt = 1 main() @@ -1684,7 +1684,7 @@ def UI(usrInput): msgNum = int(userInput("What is the number of the message you wish to save?")) if msgNum >= numMessages: - print '\n Invalid Message Number.\n' + print('\n Invalid Message Number.\n') else: break @@ -1700,7 +1700,7 @@ def UI(usrInput): msgNum = int(userInput("What is the number of the message you wish to save?")) if msgNum >= numMessages: - print '\n Invalid Message Number.\n' + print('\n Invalid Message Number.\n') else: break @@ -1729,7 +1729,7 @@ def UI(usrInput): if msgNum == 'a' or msgNum == 'all': break elif int(msgNum) >= numMessages: - print '\n Invalid Message Number.\n' + print('\n Invalid Message Number.\n') else: break @@ -1737,17 +1737,17 @@ def UI(usrInput): if uInput == "y": if msgNum in ['a', 'all']: - print ' ' + print(' ') for msgNum in range(0, numMessages): # processes all of the messages in the inbox - print ' Deleting message ', msgNum + 1, ' of ', numMessages + print(' Deleting message ', msgNum + 1, ' of ', numMessages) delMsg(0) - print '\n Inbox is empty.' + print('\n Inbox is empty.') usrPrompt = 1 else: delMsg(int(msgNum)) - print '\n Notice: Message numbers may have changed.\n' + print('\n Notice: Message numbers may have changed.\n') main() else: usrPrompt = 1 @@ -1763,7 +1763,7 @@ def UI(usrInput): if msgNum in ['a', 'all']: break elif int(msgNum) >= numMessages: - print '\n Invalid Message Number.\n' + print('\n Invalid Message Number.\n') else: break @@ -1771,33 +1771,33 @@ def UI(usrInput): if uInput == "y": if msgNum in ['a', 'all']: - print ' ' + print(' ') for msgNum in range(0, numMessages): # processes all of the messages in the outbox - print ' Deleting message ', msgNum + 1, ' of ', numMessages + print(' Deleting message ', msgNum + 1, ' of ', numMessages) delSentMsg(0) - print '\n Outbox is empty.' + print('\n Outbox is empty.') usrPrompt = 1 else: delSentMsg(int(msgNum)) - print '\n Notice: Message numbers may have changed.\n' + print('\n Notice: Message numbers may have changed.\n') main() else: usrPrompt = 1 else: - print '\n Invalid Entry.\n' + print('\n Invalid Entry.\n') usrPrompt = 1 main() elif usrInput == "exit": - print '\n You are already at the main menu. Use "quit" to quit.\n' + print('\n You are already at the main menu. Use "quit" to quit.\n') usrPrompt = 1 main() elif usrInput == "listaddressbookentries": res = listAddressBookEntries() if res == 20: - print '\n Error: API function not supported.\n' + print('\n Error: API function not supported.\n') usrPrompt = 1 main() @@ -1806,9 +1806,9 @@ def UI(usrInput): label = userInput('Enter label') res = addAddressToAddressBook(address, label) if res == 16: - print '\n Error: Address already exists in Address Book.\n' + print('\n Error: Address already exists in Address Book.\n') if res == 20: - print '\n Error: API function not supported.\n' + print('\n Error: API function not supported.\n') usrPrompt = 1 main() @@ -1816,7 +1816,7 @@ def UI(usrInput): address = userInput('Enter address') res = deleteAddressFromAddressBook(address) if res == 20: - print '\n Error: API function not supported.\n' + print('\n Error: API function not supported.\n') usrPrompt = 1 main() @@ -1841,7 +1841,7 @@ def UI(usrInput): main() else: - print '\n "', usrInput, '" is not a command.\n' + print('\n "', usrInput, '" is not a command.\n') usrPrompt = 1 main() @@ -1853,24 +1853,24 @@ def main(): global usrPrompt if usrPrompt == 0: - print '\n ------------------------------' - print ' | Bitmessage Daemon by .dok |' - print ' | Version 0.3.1 for BM 0.6.2 |' - print ' ------------------------------' + print('\n ------------------------------') + print(' | Bitmessage Daemon by .dok |') + print(' | Version 0.3.1 for BM 0.6.2 |') + print(' ------------------------------') api = xmlrpclib.ServerProxy(apiData()) # Connect to BitMessage using these api credentials if apiTest() is False: - print '\n ****************************************************************' - print ' WARNING: You are not connected to the Bitmessage client.' - print ' Either Bitmessage is not running or your settings are incorrect.' - print ' Use the command "apiTest" or "bmSettings" to resolve this issue.' - print ' ****************************************************************\n' + print('\n ****************************************************************') + print(' WARNING: You are not connected to the Bitmessage client.') + print(' Either Bitmessage is not running or your settings are incorrect.') + print(' Use the command "apiTest" or "bmSettings" to resolve this issue.') + print(' ****************************************************************\n') - print 'Type (H)elp for a list of commands.' # Startup message + print('Type (H)elp for a list of commands.') # Startup message usrPrompt = 2 elif usrPrompt == 1: - print '\nType (H)elp for a list of commands.' # Startup message + print('\nType (H)elp for a list of commands.') # Startup message usrPrompt = 2 try: diff --git a/src/class_objectProcessor.py b/src/class_objectProcessor.py index 298b12bf..19f4861c 100644 --- a/src/class_objectProcessor.py +++ b/src/class_objectProcessor.py @@ -34,7 +34,8 @@ import tr from fallback import RIPEMD160Hash import l10n -# pylint: disable=too-many-locals, too-many-return-statements, too-many-branches, too-many-statements +# pylint: disable=too-many-locals, too-many-return-statements +# pylint: disable=too-many-branches, too-many-statements logger = logging.getLogger('default') @@ -644,7 +645,8 @@ class objectProcessor(threading.Thread): if decodeAddress(toAddress)[1] >= 3 \ and not BMConfigParser().safeGetBoolean(toAddress, 'chan'): # If I'm not friendly with this person: - if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(fromAddress): + if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist( + fromAddress): requiredNonceTrialsPerByte = BMConfigParser().getint( toAddress, 'noncetrialsperbyte') requiredPayloadLengthExtraBytes = BMConfigParser().getint( diff --git a/src/class_smtpServer.py b/src/class_smtpServer.py index cdf867a9..013420cd 100644 --- a/src/class_smtpServer.py +++ b/src/class_smtpServer.py @@ -114,8 +114,9 @@ class smtpServerPyBitmessage(smtpd.SMTPServer): return ret - def process_message(self, peer, mailfrom, rcpttos, data): # pylint: disable=too-many-locals, too-many-branches + def process_message(self, peer, mailfrom, rcpttos, data): """Process an email""" + # pylint: disable=too-many-locals, too-many-branches # print 'Receiving message from:', peer p = re.compile(".*<([^>]+)>") if not hasattr(self.channel, "auth") or not self.channel.auth: diff --git a/src/depends.py b/src/depends.py index 8182fca3..ead33cae 100755 --- a/src/depends.py +++ b/src/depends.py @@ -231,12 +231,13 @@ def check_sqlite(): conn.close() -def check_openssl(): # pylint: disable=too-many-branches, too-many-return-statements +def check_openssl(): """Do openssl dependency check. Here we are checking for openssl with its all dependent libraries and version checking. """ + # pylint: disable=too-many-branches, too-many-return-statements # pylint: disable=protected-access, redefined-outer-name ctypes = try_import('ctypes') if not ctypes: @@ -365,6 +366,7 @@ def check_pyqt(): Here we are checking for PyQt4 with its version, as for it require PyQt 4.8 or later. """ + QtCore = try_import( 'PyQt4.QtCore', 'PyBitmessage requires PyQt 4.8 or later and Qt 4.7 or later.') diff --git a/src/helper_ackPayload.py b/src/helper_ackPayload.py index dcce3153..2f89d540 100644 --- a/src/helper_ackPayload.py +++ b/src/helper_ackPayload.py @@ -22,7 +22,7 @@ def genAckPayload(streamNumber=1, stealthLevel=0): - level 1: a getpubkey request for a (random) dummy key hash - level 2: a standard message, encrypted to a random pubkey """ - if stealthLevel == 2: # Generate privacy-enhanced payload + if stealthLevel == 2: # Generate privacy-enhanced payload # Generate a dummy privkey and derive the pubkey dummyPubKeyHex = highlevelcrypto.privToPub( hexlify(helper_random.randomBytes(32))) @@ -35,12 +35,12 @@ def genAckPayload(streamNumber=1, stealthLevel=0): acktype = 2 # message version = 1 - elif stealthLevel == 1: # Basic privacy payload (random getpubkey) + elif stealthLevel == 1: # Basic privacy payload (random getpubkey) ackdata = helper_random.randomBytes(32) acktype = 0 # getpubkey version = 4 - else: # Minimum viable payload (non stealth) + else: # Minimum viable payload (non stealth) ackdata = helper_random.randomBytes(32) acktype = 2 # message version = 1 diff --git a/src/helper_bitcoin.py b/src/helper_bitcoin.py index 695bdbcf..d4f1d105 100644 --- a/src/helper_bitcoin.py +++ b/src/helper_bitcoin.py @@ -53,3 +53,4 @@ def calculateTestnetAddressFromPubkey(pubkey): numberOfZeroBytesOnBinaryBitcoinAddress += 1 binaryBitcoinAddress = binaryBitcoinAddress[1:] base58encoded = arithmetic.changebase(binaryBitcoinAddress, 256, 58) + return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded diff --git a/src/helper_search.py b/src/helper_search.py index 69acec43..2384ff01 100644 --- a/src/helper_search.py +++ b/src/helper_search.py @@ -7,6 +7,7 @@ try: haveQt = True except ImportError: haveQt = False +# pylint: disable=too-many-arguments def search_translate(context, text): @@ -18,7 +19,7 @@ def search_translate(context, text): def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, what=None, unreadOnly=False): """Perform a search in mailbox tables""" - # pylint: disable=too-many-arguments, too-many-branches + # pylint: disable=too-many-branches if what is not None and what != "": what = "%" + what + "%" if where == search_translate("MainWindow", "To"): @@ -75,7 +76,6 @@ def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, w def check_match(toAddress, fromAddress, subject, message, where=None, what=None): """Check if a single message matches a filter (used when new messages are added to messagelists)""" - # pylint: disable=too-many-arguments if what is not None and what != "": if where in (search_translate("MainWindow", "To"), search_translate("MainWindow", "All")): if what.lower() not in toAddress.lower(): diff --git a/src/helper_sent.py b/src/helper_sent.py index 5a345fe7..47fc5bb4 100644 --- a/src/helper_sent.py +++ b/src/helper_sent.py @@ -1,8 +1,8 @@ """ Insert values into sent table """ +from helper_sql import sqlExecute -from helper_sql import * def insert(t): """Perform an insert into the `sent` table""" diff --git a/src/helper_sql.py b/src/helper_sql.py index a13747e2..f848ee24 100644 --- a/src/helper_sql.py +++ b/src/helper_sql.py @@ -101,7 +101,7 @@ def sqlStoredProcedure(procName): sqlLock.release() -class SqlBulkExecute(object): +class SqlBulkExecute(object): # pylint: disable=no-init """This is used when you have to execute the same statement in a cycle.""" def __enter__(self): diff --git a/src/helper_startup.py b/src/helper_startup.py index 8434f8ff..bc0ede92 100644 --- a/src/helper_startup.py +++ b/src/helper_startup.py @@ -4,7 +4,6 @@ Startup operations. # pylint: disable=too-many-branches,too-many-statements from __future__ import print_function -import configparser import os import platform import sys @@ -21,6 +20,7 @@ from bmconfigparser import BMConfigParser # the config files to stay in the application data folder. StoreConfigFilesInSameDirectoryAsProgramByDefault = False + def loadConfig(): """Load the config""" config = BMConfigParser() @@ -116,7 +116,6 @@ def loadConfig(): updateConfig() - def updateConfig(): """Save the config""" config = BMConfigParser() diff --git a/src/inventory.py b/src/inventory.py index 4b9ad226..fc06e455 100644 --- a/src/inventory.py +++ b/src/inventory.py @@ -1,8 +1,8 @@ """The Inventory singleton""" # TODO make this dynamic, and watch out for frozen, like with messagetypes -import storage.sqlite import storage.filesystem +import storage.sqlite from bmconfigparser import BMConfigParser from singleton import Singleton diff --git a/src/l10n.py b/src/l10n.py index a3237cb0..bf727244 100644 --- a/src/l10n.py +++ b/src/l10n.py @@ -64,25 +64,25 @@ else: # comprehensive decoding tests if time_format != DEFAULT_TIME_FORMAT: try: - #Check day names + # Check day names new_time_format = time_format import sys if sys.version_info >= (3, 0, 0) and time_format == '%%c': time_format = '%c' for i in range(7): - #this work for python2.7 + # this work for python2.7 # unicode(time.strftime(time_format, (0, 0, 0, 0, 0, 0, i, 0, 0)), encoding) - #this code for the python3 + # this code for the python3 (time.strftime(time_format, (0, 0, 0, 0, 0, 0, i, 0, 0))).encode() - #Check month names + # Check month names for i in range(1, 13): # unicode(time.strftime(time_format, (0, i, 0, 0, 0, 0, 0, 0, 0)), encoding) (time.strftime(time_format, (0, i, 0, 0, 0, 0, 0, 0, 0))).encode() - #Check AM/PM + # Check AM/PM (time.strftime(time_format, (0, 0, 0, 11, 0, 0, 0, 0, 0))).encode() (time.strftime(time_format, (0, 0, 0, 13, 0, 0, 0, 0, 0))).encode() - #Check DST + # Check DST (time.strftime(time_format, (0, 0, 0, 0, 0, 0, 0, 0, 1))).encode() except: diff --git a/src/openclpow.py b/src/openclpow.py index 717acc93..d90e55d1 100644 --- a/src/openclpow.py +++ b/src/openclpow.py @@ -119,4 +119,4 @@ if __name__ == "__main__": nonce = do_opencl_pow(initialHash.encode("hex"), target_) trialValue, = unpack( '>Q', hashlib.sha512(hashlib.sha512(pack('>Q', nonce) + initialHash).digest()).digest()[0:8]) - print ("{} - value {} < {}".format(nonce, trialValue, target_)) + print("{} - value {} < {}".format(nonce, trialValue, target_)) diff --git a/src/proofofwork.py b/src/proofofwork.py index 6fefb196..e79efc3b 100644 --- a/src/proofofwork.py +++ b/src/proofofwork.py @@ -294,7 +294,7 @@ def init(): global bitmsglib, bmpow openclpow.initCL() - if "win32" == sys.platform: + if sys.platform == "win32": if ctypes.sizeof(ctypes.c_voidp) == 4: bitmsglib = 'bitmsghash32.dll' else: @@ -323,7 +323,7 @@ def init(): elif platform == "android": try: bso = ctypes.CDLL('libbitmsghash.so') - except Exception as e: + except Exception: bso = None else: diff --git a/src/protocol.py b/src/protocol.py index 246ee8ad..fba68fe3 100644 --- a/src/protocol.py +++ b/src/protocol.py @@ -185,7 +185,8 @@ def checkIPv4Address(host, hostStandardFormat, private=False): logger.debug( 'Ignoring IP address in private range: %s', hostStandardFormat) return hostStandardFormat if private else False - if host[0:2] >= '\xAC\x10'.encode('raw_unicode_escape') and host[0:2] < '\xAC\x20'.encode('raw_unicode_escape'): # 172.16/12 + # 172.16/12 + if host[0:2] >= '\xAC\x10'.encode('raw_unicode_escape') and host[0:2] < '\xAC\x20'.encode('raw_unicode_escape'): if not private: logger.debug( 'Ignoring IP address in private range: %s', hostStandardFormat) @@ -198,15 +199,15 @@ def checkIPv6Address(host, hostStandardFormat, private=False): if host == ('\x00'.encode() * 15) + '\x01'.encode(): if not private: - logger.debug('Ignoring loopback address: {}'.format( hostStandardFormat)) + logger.debug('Ignoring loopback address: {}'.format(hostStandardFormat)) return False if host[0] == '\xFE' and (ord(host[1]) & 0xc0) == 0x80: if not private: - logger.debug('Ignoring local address: {}'.format( hostStandardFormat)) + logger.debug('Ignoring local address: {}'.format(hostStandardFormat)) return hostStandardFormat if private else False if (ord(host[0:1]) & 0xfe) == 0xfc: if not private: - logger.debug('Ignoring unique local address: {}'.format( hostStandardFormat)) + logger.debug('Ignoring unique local address: {}'.format(hostStandardFormat)) return hostStandardFormat if private else False return False if private else hostStandardFormat @@ -325,7 +326,7 @@ def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server= ) # = 127.0.0.1. This will be ignored by the remote host. The actual remote connected IP will be used. - #python3 need to check + # python3 need to check payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode() + pack('>L', 2130706433) # we have a separate extPort and incoming over clearnet @@ -338,11 +339,10 @@ def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server= ): payload += pack('>H', extport) elif checkSocksIP(remoteHost) and server: # incoming connection over Tor - payload += pack('>H', int(BMConfigParser().safeGet('bitmessagesettings', 'onionport'))) + payload += pack('>H', int(BMConfigParser().safeGet('bitmessagesettings', 'onionport'))) else: # no extport and not incoming over Tor payload += pack('>H', int(BMConfigParser().safeGet('bitmessagesettings', 'port'))) - if nodeid is not None: payload += nodeid[0:8] else: @@ -374,7 +374,7 @@ def assembleErrorMessage(fatal=0, banTime=0, inventoryVector='', errorText=''): payload += encodeVarint(len(inventoryVector)) payload += inventoryVector.encode() if type(payload) == bytes else inventoryVector payload += encodeVarint(len(errorText)) - payload += errorText.encode() if type(payload)== bytes else errorText + payload += errorText.encode() if type(payload) == bytes else errorText return CreatePacket('error', payload) diff --git a/src/queues.py b/src/queues.py index bce5eb32..6a76adb6 100644 --- a/src/queues.py +++ b/src/queues.py @@ -1,6 +1,5 @@ - -import queue as Queue """Most of the queues used by bitmessage threads are defined here.""" +import queue as Queue import threading import time diff --git a/src/semaphores.py b/src/semaphores.py index 04120fe7..960d86a9 100644 --- a/src/semaphores.py +++ b/src/semaphores.py @@ -1,3 +1,3 @@ from threading import Semaphore -kivyuisignaler = Semaphore(0) \ No newline at end of file +kivyuisignaler = Semaphore(0) diff --git a/src/shared.py b/src/shared.py index d02578ce..98f47d19 100644 --- a/src/shared.py +++ b/src/shared.py @@ -101,6 +101,7 @@ def isAddressInMyAddressBookSubscriptionsListOrWhitelist(address): return True return False + def decodeWalletImportFormat(WIFstring): # pylint: disable=inconsistent-return-statements """ @@ -116,7 +117,7 @@ def decodeWalletImportFormat(WIFstring): ' 6 characters of the PRIVATE key: {}'.format(str(WIFstring)[:6]) ) - os._exit(0) + os._exit(0) # pylint: disable=protected-access if privkey[0:1] == '\x80'.encode()[1:]: # checksum passed return privkey[1:] diff --git a/src/singleinstance.py b/src/singleinstance.py index 169613a3..2936e49b 100644 --- a/src/singleinstance.py +++ b/src/singleinstance.py @@ -75,7 +75,7 @@ class singleinstance(object): fcntl.lockf(self.fp, fcntl.LOCK_EX | fcntl.LOCK_NB) self.lockPid = os.getpid() except IOError: - print ('Another instance of this application is already running') + print('Another instance of this application is already running') sys.exit(-1) else: pidLine = "%i\n" % self.lockPid @@ -95,10 +95,10 @@ class singleinstance(object): os.close(self.fd) else: fcntl.lockf(self.fp, fcntl.LOCK_UN) - except Exception as e: + except Exception: pass return - print ("Cleaning up lockfile") + print("Cleaning up lockfile") try: if sys.platform == 'win32': if hasattr(self, 'fd'): diff --git a/src/state.py b/src/state.py index 54251270..5207099f 100644 --- a/src/state.py +++ b/src/state.py @@ -109,4 +109,4 @@ availabe_credit = 0 in_sent_method = False -in_search_mode = False \ No newline at end of file +in_search_mode = False diff --git a/src/tr.py b/src/tr.py index ce8edc8e..f3498037 100644 --- a/src/tr.py +++ b/src/tr.py @@ -6,17 +6,17 @@ import os import state -class translateClass: +class translateClass(object): """ This is used so that the translateText function can be used when we are in daemon mode and not using any QT functions. """ - # pylint: disable=old-style-class,too-few-public-methods + # pylint: disable=too-few-public-methods def __init__(self, context, text): self.context = context self.text = text - def arg(self, argument): # pylint: disable=unused-argument + def arg(self, _): """Replace argument placeholders""" if '%' in self.text: return translateClass(self.context, self.text.replace('%', '', 1)) @@ -25,7 +25,7 @@ class translateClass: return self.text -def _translate(context, text, disambiguation=None, encoding=None, n=None): # pylint: disable=unused-argument +def _translate(context, text, disambiguation=None, encoding=None, n=None): # pylint: disable=unused-argument return translateText(context, text, n) @@ -39,12 +39,12 @@ def translateText(context, text, n=None): try: from PyQt4 import QtCore, QtGui except Exception as err: - print ('PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API\ + print('PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API\ .You can download PyQt from http://www.riverbankcomputing.com/software/pyqt/download\ or by searching Google for \'PyQt Download\'.\ If you want to run in daemon mode, see https://bitmessage.org/wiki/Daemon') - print ('Error message:', err) - os._exit(0) # pylint: disable=protected-access + print('Error message:', err) + os._exit(0) # pylint: disable=protected-access if n is None: return QtGui.QApplication.translate(context, text) diff --git a/src/upnp.py b/src/upnp.py index 9ef4c4e8..93753de3 100644 --- a/src/upnp.py +++ b/src/upnp.py @@ -1,8 +1,8 @@ -# pylint: disable=too-many-statements,too-many-branches,protected-access,no-self-use -""" +""" Complete UPnP port forwarding implementation in separate thread. Reference: http://mattscodecave.com/posts/using-python-and-upnp-to-forward-a-port """ +# pylint: disable=too-many-statements,too-many-branches,protected-access,no-self-use import httplib import socket @@ -19,8 +19,8 @@ import tr from bmconfigparser import BMConfigParser from debug import logger from network.connectionpool import BMConnectionPool -from network.threads import StoppableThread from network.node import Peer +from network.threads import StoppableThread def createRequestXML(service, action, arguments=None): @@ -83,6 +83,7 @@ class UPnPError(Exception): class Router: # pylint: disable=old-style-class """Encapulate routing""" + name = "" path = "" address = None @@ -152,7 +153,6 @@ class Router: # pylint: disable=old-style-class def DeletePortMapping(self, externalPort, protocol): """Delete UPnP port mapping""" - resp = self.soapRequest(self.upnp_schema + ':1', 'DeletePortMapping', [ ('NewRemoteHost', ''), ('NewExternalPort', str(externalPort)), @@ -163,16 +163,12 @@ class Router: # pylint: disable=old-style-class def GetExternalIPAddress(self): """Get the external address""" - - resp = self.soapRequest( - self.upnp_schema + ':1', 'GetExternalIPAddress') + resp = self.soapRequest(self.upnp_schema + ':1', 'GetExternalIPAddress') dom = parseString(resp.read()) - return dom.getElementsByTagName( - 'NewExternalIPAddress')[0].childNodes[0].data + return dom.getElementsByTagName('NewExternalIPAddress')[0].childNodes[0].data def soapRequest(self, service, action, arguments=None): """Make a request to a router""" - conn = httplib.HTTPConnection(self.routerPath.hostname, self.routerPath.port) conn.request( 'POST', @@ -223,7 +219,6 @@ class uPnPThread(StoppableThread): def run(self): """Start the thread to manage UPnP activity""" - logger.debug("Starting UPnP thread") logger.debug("Local IP: %s", self.localIP) lastSent = 0 @@ -261,16 +256,12 @@ class uPnPThread(StoppableThread): self.routers.append(newRouter) self.createPortMapping(newRouter) try: - self_peer = Peer( - newRouter.GetExternalIPAddress(), - self.extPort - ) + self_peer = Peer(newRouter.GetExternalIPAddress(), self.extPort) except: logger.debug('Failed to get external IP') else: with knownnodes.knownNodesLock: - knownnodes.addKnownNode( - 1, self_peer, is_self=True) + knownnodes.addKnownNode(1, self_peer, is_self=True) queues.UISignalQueue.put(('updateStatusBar', tr._translate( "MainWindow", 'UPnP port mapping established on port %1' ).arg(str(self.extPort)))) @@ -296,12 +287,12 @@ class uPnPThread(StoppableThread): deleted = True self.deletePortMapping(router) if deleted: - queues.UISignalQueue.put(('updateStatusBar', tr._translate("MainWindow", 'UPnP port mapping removed'))) + queues.UISignalQueue.put( + ('updateStatusBar', tr._translate("MainWindow", 'UPnP port mapping removed'))) logger.debug("UPnP thread done") def getLocalIP(self): """Get the local IP of the node""" - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.connect((uPnPThread.GOOGLE_DNS, 1)) @@ -309,7 +300,6 @@ class uPnPThread(StoppableThread): def sendSearchRouter(self): """Querying for UPnP services""" - ssdpRequest = "M-SEARCH * HTTP/1.1\r\n" + \ "HOST: %s:%d\r\n" % (uPnPThread.SSDP_ADDR, uPnPThread.SSDP_PORT) + \ "MAN: \"ssdp:discover\"\r\n" + \ @@ -324,7 +314,6 @@ class uPnPThread(StoppableThread): def createPortMapping(self, router): """Add a port mapping""" - for i in range(50): try: localIP = self.localIP @@ -336,10 +325,7 @@ class uPnPThread(StoppableThread): extPort = randint(32767, 65535) logger.debug( "Attempt %i, requesting UPnP mapping for %s:%i on external port %i", - i, - localIP, - self.localPort, - extPort) + i, localIP, self.localPort, extPort) router.AddPortMapping(extPort, self.localPort, localIP, 'TCP', 'BitMessage') self.extPort = extPort BMConfigParser().set('bitmessagesettings', 'extport', str(extPort)) From 69eedf7bc2910dcba65b18893cc483f077082bd9 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Tue, 31 Dec 2019 18:22:56 +0530 Subject: [PATCH 7/8] network files fixes python3 --- src/network/__init__.py | 20 ++++++------- src/network/addrthread.py | 1 - src/network/advanceddispatcher.py | 3 +- src/network/announcethread.py | 12 ++++---- src/network/assemble.py | 2 +- src/network/asyncore_pollchoose.py | 10 ++++--- src/network/bmproto.py | 47 ++++++++++++++++-------------- src/network/connectionchooser.py | 2 +- src/network/connectionpool.py | 27 +++++++++-------- src/network/dandelion.py | 10 +++---- src/network/downloadthread.py | 3 +- src/network/http.py | 7 +++-- src/network/http_old.py | 3 ++ src/network/httpd.py | 6 ++-- src/network/https.py | 7 +++-- src/network/networkthread.py | 4 +-- src/network/randomtrackingdict.py | 8 ++--- src/network/tcp.py | 6 ++-- src/network/tls.py | 3 +- 19 files changed, 93 insertions(+), 88 deletions(-) diff --git a/src/network/__init__.py b/src/network/__init__.py index 77b80b5c..72865e87 100644 --- a/src/network/__init__.py +++ b/src/network/__init__.py @@ -1,13 +1,13 @@ -from .addrthread import AddrThread -from .announcethread import AnnounceThread -from .connectionpool import BMConnectionPool -from .dandelion import Dandelion -from .downloadthread import DownloadThread -from .invthread import InvThread -from .networkthread import BMNetworkThread -from .receivequeuethread import ReceiveQueueThread -from .threads import StoppableThread -from .uploadthread import UploadThread +from network.addrthread import AddrThread +from network.announcethread import AnnounceThread +from network.connectionpool import BMConnectionPool +from network.dandelion import Dandelion +from network.downloadthread import DownloadThread +from network.invthread import InvThread +from network.networkthread import BMNetworkThread +from network.receivequeuethread import ReceiveQueueThread +from network.threads import StoppableThread +from network.uploadthread import UploadThread __all__ = [ diff --git a/src/network/addrthread.py b/src/network/addrthread.py index 861da3ef..c041695f 100644 --- a/src/network/addrthread.py +++ b/src/network/addrthread.py @@ -1,4 +1,3 @@ -# import queue as Queue """ Announce addresses as they are received from other hosts """ diff --git a/src/network/advanceddispatcher.py b/src/network/advanceddispatcher.py index a21b946f..2eb0e46d 100644 --- a/src/network/advanceddispatcher.py +++ b/src/network/advanceddispatcher.py @@ -3,7 +3,6 @@ src/network/advanceddispatcher.py ================================= """ # pylint: disable=attribute-defined-outside-init -# import pdb;pdb.set_trace() import socket import threading import time @@ -32,7 +31,7 @@ class AdvancedDispatcher(asyncore.dispatcher): # python 2 below condition is used # if not hasattr(self, '_map'): # python 3 below condition is used - if not '_map' in dir(self): + if '_map' not in dir(self): asyncore.dispatcher.__init__(self, sock) self.read_buf = bytearray() self.write_buf = bytearray() diff --git a/src/network/announcethread.py b/src/network/announcethread.py index 938599d5..7929417e 100644 --- a/src/network/announcethread.py +++ b/src/network/announcethread.py @@ -11,7 +11,7 @@ from bmconfigparser import BMConfigParser from network.assemble import assemble_addr from network.connectionpool import BMConnectionPool from network.udp import UDPSocket -from .node import Peer +from network.node import Peer from network.threads import StoppableThread @@ -32,17 +32,15 @@ class AnnounceThread(StoppableThread): @staticmethod def announceSelf(): """Announce our presence""" - for connection in [ udpSockets for udpSockets in BMConnectionPool().udpSockets.values()]: + for connection in [udpSockets for udpSockets in BMConnectionPool().udpSockets.values()]: if not connection.announcing: continue for stream in state.streamsInWhichIAmParticipating: addr = ( stream, - - # state.Peer('127.0.0.1',int( BMConfigParser().safeGet("bitmessagesettings", "port"))), - # int(time.time())) - # connection.append_write_buf(BMProto.assembleAddr([addr])) - + # state.Peer('127.0.0.1',int( BMConfigParser().safeGet("bitmessagesettings", "port"))), + # int(time.time())) + # connection.append_write_buf(BMProto.assembleAddr([addr])) Peer( '127.0.0.1', BMConfigParser().safeGetInt('bitmessagesettings', 'port')), diff --git a/src/network/assemble.py b/src/network/assemble.py index 2d31914c..9ae853f7 100644 --- a/src/network/assemble.py +++ b/src/network/assemble.py @@ -13,7 +13,7 @@ from protocol import CreatePacket, encodeHost def assemble_addr(peerList): """Create address command""" if isinstance(peerList, Peer): - peerList = (peerList) + peerList = [peerList] if not peerList: return b'' retval = b'' diff --git a/src/network/asyncore_pollchoose.py b/src/network/asyncore_pollchoose.py index 3f6e8ad0..43bebdcf 100644 --- a/src/network/asyncore_pollchoose.py +++ b/src/network/asyncore_pollchoose.py @@ -102,7 +102,9 @@ def _strerror(err): return os.strerror(err) except (ValueError, OverflowError, NameError): if err in errorcode: - ret18 ("Unknown error {}".format(err)) + return errorcode[err] + return "Unknown error %s" % err + # ret18 ("Unknown error {}".format(err)) class ExitNow(Exception): @@ -477,7 +479,7 @@ def kqueue_poller(timeout=0.0, map=None): current_thread().stop.wait(timeout) -def loop(timeout=30.0, use_poll=False, map=None, count=None, poller=None): +def loop(timeout=30.0, _=False, map=None, count=None, poller=None): """Poll in a loop, until count or timeout is reached""" # pylint: disable=redefined-builtin @@ -518,7 +520,7 @@ def loop(timeout=30.0, use_poll=False, map=None, count=None, poller=None): count = count - 1 -class dispatcher: +class dispatcher(object): """Dispatcher for socket objects""" # pylint: disable=too-many-public-methods,too-many-instance-attributes,old-style-class @@ -786,7 +788,7 @@ class dispatcher: def log_info(self, message, log_type='info'): """Conditionally print a message""" if log_type not in self.ignore_log_types: - print ('{}: {}'.format(log_type, message)) + print('{}: {}'.format(log_type, message)) def handle_read_event(self): """Handle a read event""" diff --git a/src/network/bmproto.py b/src/network/bmproto.py index 12e26972..ad2260fa 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -32,7 +32,7 @@ from network.bmobject import ( BMObjectInvalidError, BMObjectAlreadyHaveError) from network.proxy import ProxyError from network.objectracker import missingObjects, ObjectTracker -from .node import Node, Peer +from network.node import Node, Peer from queues import objectProcessorQueue, portCheckerQueue, invQueue, addrQueue from network.randomtrackingdict import RandomTrackingDict @@ -52,6 +52,7 @@ count = 0 logger = logging.getLogger('default') + class BMProtoError(ProxyError): """A Bitmessage Protocol Base Error""" errorCodes = ("Protocol error") @@ -94,30 +95,30 @@ class BMProto(AdvancedDispatcher, ObjectTracker): self.object = None def state_bm_header(self): - """Process incoming header""" self.magic, self.command, self.payloadLength, self.checksum = \ protocol.Header.unpack(self.read_buf[:protocol.Header.size]) - #its shoule be in string + # its shoule be in string self.command = self.command.rstrip('\x00'.encode('utf-8')) - global count,addr_version,addr_count,addr_verack - count+=1 + # pylint: disable=global-statement + global count, addr_version, addr_count, addr_verack + count += 1 if self.command == 'verack'.encode(): - addr_verack+=1 + addr_verack += 1 # print('the addr_verack count are -{}'.format(addr_verack)) if self.command == 'version'.encode(): - addr_version+=1 + addr_version += 1 # print('the addr_version count are -{}'.format(addr_version)) if self.command == 'addr'.encode(): - addr_count+=1 + addr_count += 1 # print('the addr_count count are -{}'.format(addr_count)) if self.magic != 0xE9BEB4D9: # skip 1 byte in order to sync - #in the advancedispatched and length commend's - #escape the 1 length + # in the advancedispatched and length commend's + # escape the 1 length self.set_state("bm_header", length=1) self.bm_proto_reset() logger.debug('Bad magic') @@ -132,7 +133,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): length=protocol.Header.size, expectBytes=self.payloadLength) return True - def state_bm_command(self): # pylint: disable=too-many-branches + def state_bm_command(self): # pylint: disable=too-many-branches, too-many-statements """Process incoming command""" self.payload = self.read_buf[:self.payloadLength] if self.checksum != hashlib.sha512(self.payload).digest()[0:4]: @@ -143,14 +144,14 @@ class BMProto(AdvancedDispatcher, ObjectTracker): "error".encode(), "version".encode(), "verack".encode()): logger.error( 'Received command {} before connection was fully' - ' established, ignoring'.format (self.command)) + ' established, ignoring'.format(self.command)) self.invalid = True if not self.invalid: try: command = self.command.decode() if self.command else self.command retval = getattr( - self, "bm_command_" +command)() + self, "bm_command_" + command)() except AttributeError: # unimplemented command logger.debug('unimplemented command %s', self.command) @@ -346,8 +347,11 @@ class BMProto(AdvancedDispatcher, ObjectTracker): def bm_command_error(self): """Decode an error message and log it""" - fatalStatus, banTime, inventoryVector, errorText = \ - self.decode_payload_content("vvlsls") + err_values = self.decode_payload_content("vvlsls") + fatalStatus = err_values[0] + # banTime = err_values[1] + # inventoryVector = err_values[2] + errorText = err_values[3] logger.error( '%s:%i error: %i, %s', self.destination.host, self.destination.port, fatalStatus, errorText) @@ -359,7 +363,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): If we have them and some other conditions are fulfilled, append them to the write queue. """ - #32 an array bit long strings + # 32 an array bit long strings items = self.decode_payload_content("l32s") # skip? now = time.time() @@ -463,11 +467,11 @@ class BMProto(AdvancedDispatcher, ObjectTracker): def bm_command_addr(self): # print('+++++++++++++++++++++++++++\ - # bm_command_addr bm_command_addr bm_command_addr ++++++++++++++++') + # bm_command_addr bm_command_addr bm_command_addr ++++++++++++++++') """Incoming addresses, process them""" addresses = self._decode_addr() # pylint: disable=redefined-outer-name for i in addresses: - seenTime, stream, services, ip, port = i + seenTime, stream, _, ip, port = i decodedIP = protocol.checkIPAddress(ip) if stream not in state.streamsInWhichIAmParticipating: continue @@ -533,6 +537,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): "tls_init" if self.isSSL else "connection_fully_established", length=self.payloadLength, expectBytes=0) return False + def bm_command_version(self): # print('inside the bmproto ') """ @@ -566,7 +571,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): logger.debug( '%(host)s:%(port)i sending version', self.destination._asdict()) - if ((self.services & protocol.NODE_SSL == protocol.NODE_SSL)): + if self.services & protocol.NODE_SSL == protocol.NODE_SSL: # self.isSSL = True pass if not self.verackReceived: @@ -625,7 +630,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): if not protocol.checkSocksIP(self.destination.host): self.append_write_buf(protocol.assembleErrorMessage( errorText="Too many connections from your IP." - " Closing connection.", fatal=2)) + " Closing connection.", fatal=2)) logger.debug( 'Closed connection to {} because we are already connected' ' to that IP.'.format(self.destination)) @@ -660,10 +665,8 @@ class BMProto(AdvancedDispatcher, ObjectTracker): "Closed connection to %s because I'm connected to myself.", self.destination) return False - return True - @staticmethod def stopDownloadingObject(hashId, forwardAnyway=False): """Stop downloading an object""" diff --git a/src/network/connectionchooser.py b/src/network/connectionchooser.py index 0e090b62..bd5b3d7d 100644 --- a/src/network/connectionchooser.py +++ b/src/network/connectionchooser.py @@ -39,7 +39,7 @@ def chooseConnection(stream): # discovered peers are already filtered by allowed streams return getDiscoveredPeer() for _ in range(50): - peer = random.choice([key for key in knownnodes.knownNodes[stream].keys()]) + peer = random.choice([key for key in knownnodes.knownNodes[stream].keys()]) try: peer_info = knownnodes.knownNodes[stream][peer] if peer_info.get('self'): diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index a9bbe2e7..4b9ab62b 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -17,11 +17,11 @@ from bmconfigparser import BMConfigParser from network.connectionchooser import chooseConnection from network.proxy import Proxy -from .node import Peer -from singleton import Singleton from network.tcp import ( - TCPServer, Socks5BMConnection, Socks4aBMConnection, TCPConnection,bootstrap) + TCPServer, Socks5BMConnection, Socks4aBMConnection, TCPConnection, bootstrap) from network.udp import UDPSocket +from singleton import Singleton +from .node import Peer logger = logging.getLogger('default') @@ -78,8 +78,8 @@ class BMConnectionPool(object): `inboundConnections` and `outboundConnections` dicts """ inboundConnections = [inboundConnections for inboundConnections in self.inboundConnections.values()] - outboundConnections = [outboundConnections for outboundConnections in self.outboundConnections.values()] - return [ connections for connections in inboundConnections +outboundConnections] + outboundConnections = [outboundConnections for outboundConnections in self.outboundConnections.values()] + return [connections for connections in inboundConnections + outboundConnections] def establishedConnections(self): """Shortcut for list of connections having fullyEstablished == True""" @@ -292,7 +292,7 @@ class BMConnectionPool(object): except ValueError: Proxy.onion_proxy = None established = sum( - 1 for c in [outboundConnections for outboundConnections in self.outboundConnections.values()] + 1 for c in [outboundConnections for outboundConnections in self.outboundConnections.values()] if (c.connected and c.fullyEstablished)) pending = len(self.outboundConnections) - established if established < int(BMConfigParser().safeGet( @@ -430,14 +430,13 @@ class BMConnectionPool(object): # list(self.udpSockets.values()) # ): for i in ( - - # [inboundConnections for inboundConnections in self.inboundConnections.values()] + - # [outboundConnections for outboundConnections in self.outboundConnections.values()] + - # [listeningSockets for listeningSockets in self.listeningSockets.values()] + - # [udpSockets for udpSockets in self.udpSockets.values()] - - self.connections() - + [listeningSockets for listeningSockets in self.listeningSockets.values()] + [udpSockets for udpSockets in self.udpSockets.values()] + # [inboundConnections for inboundConnections in self.inboundConnections.values()] + + # [outboundConnections for outboundConnections in self.outboundConnections.values()] + + # [listeningSockets for listeningSockets in self.listeningSockets.values()] + + # [udpSockets for udpSockets in self.udpSockets.values()] + self.connections() + + [listeningSockets for listeningSockets in self.listeningSockets.values()] + + [udpSockets for udpSockets in self.udpSockets.values()] ): if not (i.accepting or i.connecting or i.connected): reaper.append(i) diff --git a/src/network/dandelion.py b/src/network/dandelion.py index 7e059f7f..ec9384e5 100644 --- a/src/network/dandelion.py +++ b/src/network/dandelion.py @@ -28,7 +28,7 @@ logger = logging.getLogger('default') @Singleton -class Dandelion(): # pylint: disable=old-style-class +class Dandelion(object): """Dandelion class for tracking stem/fluff stages.""" def __init__(self): # currently assignable child stems @@ -104,12 +104,12 @@ class Dandelion(): # pylint: disable=old-style-class self.stem.append(connection) for k in (k for k, v in iter(self.nodeMap.items()) if v is None): self.nodeMap[k] = connection - #The Purpose of adding this condition that if self - #hashMap is has any value + # The Purpose of adding this condition that if self + # hashMap is has any value # if not [hasmap for hasmap in self.hashMap.items()] ==[]: try: for k, v in { - k: v for k, v in iter([hasmap for hasmap in self.hashMap.items()]) + k: v for k, v in iter([hasmap for hasmap in self.hashMap.items()]) if v.child is None }.items(): self.hashMap[k] = Stem( @@ -142,7 +142,7 @@ class Dandelion(): # pylint: disable=old-style-class ): self.nodeMap[k] = None for k, v in { - k: v for k, v in iter(iter([hasmap for hasmap in self.hashMap.items()])) + k: v for k, v in iter(iter([hasmap for hasmap in self.hashMap.items()])) if v.child == connection }.items(): self.hashMap[k] = Stem( diff --git a/src/network/downloadthread.py b/src/network/downloadthread.py index c4519bb4..6e1f9ca8 100644 --- a/src/network/downloadthread.py +++ b/src/network/downloadthread.py @@ -44,7 +44,8 @@ class DownloadThread(StoppableThread): # Choose downloading peers randomly # connections = [ # x for x in - # list(BMConnectionPool().inboundConnections.values()) + list(BMConnectionPool().outboundConnections.values()) + # list(BMConnectionPool().inboundConnections.values()) + + # list(BMConnectionPool().outboundConnections.values()) # if x.fullyEstablished] connections = BMConnectionPool().establishedConnections() diff --git a/src/network/http.py b/src/network/http.py index fdfe8370..4a21b63e 100644 --- a/src/network/http.py +++ b/src/network/http.py @@ -1,3 +1,4 @@ +# pylint: disable=redefined-outer-name, too-many-ancestors, missing-docstring import socket from advanceddispatcher import AdvancedDispatcher @@ -12,7 +13,7 @@ class HttpError(ProxyError): class HttpConnection(AdvancedDispatcher): - def __init__(self, host, path="/"): # pylint: disable=redefined-outer-name + def __init__(self, host, path="/"): AdvancedDispatcher.__init__(self) self.path = path self.destination = (host, 80) @@ -38,7 +39,7 @@ class HttpConnection(AdvancedDispatcher): class Socks5HttpConnection(Socks5Connection, HttpConnection): - def __init__(self, host, path="/"): # pylint: disable=super-init-not-called, redefined-outer-name + def __init__(self, host, path="/"): # pylint: disable=super-init-not-called self.path = path Socks5Connection.__init__(self, address=(host, 80)) @@ -48,7 +49,7 @@ class Socks5HttpConnection(Socks5Connection, HttpConnection): class Socks4aHttpConnection(Socks4aConnection, HttpConnection): - def __init__(self, host, path="/"): # pylint: disable=super-init-not-called, redefined-outer-name + def __init__(self, host, path="/"): # pylint: disable=super-init-not-called Socks4aConnection.__init__(self, address=(host, 80)) self.path = path diff --git a/src/network/http_old.py b/src/network/http_old.py index 64d09983..c46a5d09 100644 --- a/src/network/http_old.py +++ b/src/network/http_old.py @@ -1,3 +1,6 @@ +""" +src/network/http_old.py +""" import asyncore import socket import time diff --git a/src/network/httpd.py b/src/network/httpd.py index b69ffa99..1679f864 100644 --- a/src/network/httpd.py +++ b/src/network/httpd.py @@ -5,7 +5,7 @@ src/network/httpd.py import asyncore import socket -from tls import TLSHandshake +from .tls import TLSHandshake class HTTPRequestHandler(asyncore.dispatcher): @@ -129,7 +129,7 @@ class HTTPServer(asyncore.dispatcher): def handle_accept(self): pair = self.accept() if pair is not None: - sock, addr = pair + sock, _ = pair # print 'Incoming connection from %s' % repr(addr) self.connections += 1 # if self.connections % 1000 == 0: @@ -148,7 +148,7 @@ class HTTPSServer(HTTPServer): def handle_accept(self): pair = self.accept() if pair is not None: - sock, addr = pair + sock, _ = pair # print 'Incoming connection from %s' % repr(addr) self.connections += 1 # if self.connections % 1000 == 0: diff --git a/src/network/https.py b/src/network/https.py index a7b8b57c..fc944d97 100644 --- a/src/network/https.py +++ b/src/network/https.py @@ -1,8 +1,8 @@ +# pylint: disable=missing-docstring import asyncore -from http import HTTPClient -from tls import TLSHandshake - +from .http import HTTPClient +from .tls import TLSHandshake """ self.sslSock = ssl.wrap_socket( self.sock, @@ -17,6 +17,7 @@ self.sslSock = ssl.wrap_socket( class HTTPSClient(HTTPClient, TLSHandshake): def __init__(self, host, path): + # pylint: disable=non-parent-init-called if not hasattr(self, '_map'): asyncore.dispatcher.__init__(self) self.tlsDone = False diff --git a/src/network/networkthread.py b/src/network/networkthread.py index 34c94bf2..9b4ba1e5 100644 --- a/src/network/networkthread.py +++ b/src/network/networkthread.py @@ -19,12 +19,12 @@ class BMNetworkThread(StoppableThread): def stopThread(self): super(BMNetworkThread, self).stopThread() - for i in [listeningSockets for listeningSockets in BMConnectionPool().listeningSockets.values()]: + for i in [listeningSockets for listeningSockets in BMConnectionPool().listeningSockets.values()]: try: i.close() except: pass - for i in [ outboundConnections for outboundConnections in BMConnectionPool().outboundConnections.values()]: + for i in [outboundConnections for outboundConnections in BMConnectionPool().outboundConnections.values()]: try: i.close() except: diff --git a/src/network/randomtrackingdict.py b/src/network/randomtrackingdict.py index 16eb63e1..c5c460b4 100644 --- a/src/network/randomtrackingdict.py +++ b/src/network/randomtrackingdict.py @@ -140,20 +140,20 @@ if __name__ == '__main__': k = RandomTrackingDict() d = {} - print ("populating random tracking dict") + print("populating random tracking dict") a.append(time()) for i in range(50000): k[randString()] = True a.append(time()) - print ("done") + print("done") while k: retval = k.randomKeys(1000) if not retval: - print ("error getting random keys") + print("error getting random keys") try: k.randomKeys(100) - print( "bad") + print("bad") except KeyError: pass for i in retval: diff --git a/src/network/tcp.py b/src/network/tcp.py index c7f5aa01..7dff0122 100644 --- a/src/network/tcp.py +++ b/src/network/tcp.py @@ -77,7 +77,7 @@ class TCPConnection(BMProto, TLSDispatcher): self.connect(self.destination) logger.debug( 'Connecting to {}:{}'.format( - self.destination.host, self.destination.port)) + self.destination.host, self.destination.port)) try: self.local = ( protocol.checkIPAddress( @@ -90,7 +90,7 @@ class TCPConnection(BMProto, TLSDispatcher): ObjectTracker.__init__(self) # pylint: disable=non-parent-init-called self.bm_proto_reset() # print('--------------tcp------------------') - from network import stats + # from network import stats self.set_state("bm_header", expectBytes=protocol.Header.size) def antiIntersectionDelay(self, initial=False): @@ -370,7 +370,7 @@ class TCPServer(AdvancedDispatcher): """TCP connection server for Bitmessage protocol""" def __init__(self, host='127.0.0.1', port=8444): - if '_map' not in dir(self): + if '_map' not in dir(self): AdvancedDispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() diff --git a/src/network/tls.py b/src/network/tls.py index 479fe4de..08969227 100644 --- a/src/network/tls.py +++ b/src/network/tls.py @@ -1,7 +1,6 @@ """ SSL/TLS negotiation. """ - import logging import os import socket @@ -23,7 +22,7 @@ if sys.version_info >= (2, 7, 13): # in the future change to # ssl.PROTOCOL_TLS1.2 # Right now I am using the python3.5.2 and I faced the ssl for protocol due to this I - # have used try and catch + # have used try and catch try: sslProtocolVersion = ssl.PROTOCOL_TLS # pylint: disable=no-member except AttributeError: From e436b8ecf63bb473c415fb156032aee03cdaf7f6 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Mon, 6 Jan 2020 16:44:13 +0530 Subject: [PATCH 8/8] commit after conflicts --- COPYING | 2 +- LICENSE | 2 +- checkdeps.py | 2 +- requirements.txt | 1 - src/api.py | 3 +- src/bitmessagekivy/mpybit.py | 1 + src/bitmessagemain.py | 20 +++--- src/bitmessageqt/about.ui | 2 +- src/bitmessageqt/dialogs.py | 2 +- src/bitmessageqt/settings.py | 111 +++++++++++++++++++------------- src/bitmessageqt/settings.ui | 6 +- src/bitmessageqt/support.py | 4 +- src/class_objectProcessor.py | 18 +++--- src/class_singleWorker.py | 4 +- src/helper_startup.py | 51 ++++++++++++--- src/network/assemble.py | 2 +- src/network/bmproto.py | 20 +++--- src/network/udp.py | 5 +- src/plugins/__init__.py | 7 ++ src/plugins/plugin.py | 27 ++++++-- src/plugins/proxyconfig_stem.py | 33 +++++++--- src/protocol.py | 11 ++-- src/storage/sqlite.py | 21 +++--- src/tests/core.py | 53 +++++++++------ 24 files changed, 262 insertions(+), 146 deletions(-) diff --git a/COPYING b/COPYING index 2e0ae6c1..078bf213 100644 --- a/COPYING +++ b/COPYING @@ -1,5 +1,5 @@ Copyright (c) 2012-2016 Jonathan Warren -Copyright (c) 2012-2019 The Bitmessage Developers +Copyright (c) 2012-2020 The Bitmessage Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/LICENSE b/LICENSE index 3be738c0..6bb86242 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) Copyright (c) 2012-2016 Jonathan Warren -Copyright (c) 2012-2019 The Bitmessage Developers +Copyright (c) 2012-2020 The Bitmessage Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in diff --git a/checkdeps.py b/checkdeps.py index 03782037..45dc2fc9 100755 --- a/checkdeps.py +++ b/checkdeps.py @@ -164,7 +164,7 @@ if (not compiler or prereqs) and OPSYS in PACKAGE_MANAGER: if not compiler: compilerToPackages() prereqToPackages() - if mandatory: + if prereqs and mandatory: sys.exit(1) else: print("All the dependencies satisfied, you can install PyBitmessage") diff --git a/requirements.txt b/requirements.txt index be429a9f..c55e5cf1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,3 @@ python_prctl psutil pycrypto -stem diff --git a/src/api.py b/src/api.py index 6c1191a4..bfbe45fa 100644 --- a/src/api.py +++ b/src/api.py @@ -30,7 +30,8 @@ import queues import shared import shutdown import state -from addresses import addBMIfNotPresent, calculateInventoryHash, decodeAddress, decodeVarint, varintDecodeError + +from addresses import addBMIfNotPresent, calculateInventoryHash, decodeAddress, decodeVarint, varintDecodeError from bmconfigparser import BMConfigParser from debug import logger from helper_ackPayload import genAckPayload diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index df0e1c26..bcb7c511 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -1303,6 +1303,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods def build(self): """Method builds the widget""" + print(os.path.join(os.path.dirname(__file__), 'main.kv')) main_widget = Builder.load_file( os.path.join(os.path.dirname(__file__), 'main.kv')) self.nav_drawer = Navigatorss() diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index bc78b96f..2a03858b 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -3,7 +3,7 @@ The PyBitmessage startup script """ # Copyright (c) 2012-2016 Jonathan Warren -# Copyright (c) 2012-2019 The Bitmessage developers +# Copyright (c) 2012-2020 The Bitmessage developers # Distributed under the MIT/X11 software license. See the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. @@ -32,7 +32,8 @@ from bmconfigparser import BMConfigParser # this should go before any threads from debug import logger from helper_startup import ( - isOurOperatingSystemLimitedToHavingVeryFewHalfOpenConnections + isOurOperatingSystemLimitedToHavingVeryFewHalfOpenConnections, + start_proxyconfig ) from inventory import Inventory from knownnodes import readKnownNodes @@ -188,10 +189,9 @@ class Main(object): logger.info( 'Started proxy config plugin %s in %s sec', proxy_type, time.time() - proxyconfig_start) - def start(self): """Start main application""" - # pylint: disable=too-many-statements, too-many-branches, too-many-locals + # pylint: disable=too-many-statements,too-many-branches,too-many-locals _fixSocket() config = BMConfigParser() @@ -268,11 +268,10 @@ class Main(object): set_thread_name("PyBitmessage") - state.dandelion = config.safeGetInt('network', 'dandelion') + state.dandelion = config.safeGet('network', 'dandelion') # dandelion requires outbound connections, without them, # stem objects will get stuck forever - if state.dandelion and not config.safeGetBoolean( - 'bitmessagesettings', 'sendoutgoingconnections'): + if state.dandelion and not (config.safeGet('bitmessagesettings', 'sendoutgoingconnections') == 'True'): state.dandelion = 0 if state.testmode or config.safeGetBoolean( @@ -350,7 +349,7 @@ class Main(object): singleAPIThread.start() # start network components if networking is enabled if state.enableNetwork: - self.start_proxyconfig(config) + start_proxyconfig() BMConnectionPool() asyncoreThread = BMNetworkThread() asyncoreThread.daemon = True @@ -408,9 +407,8 @@ class Main(object): if (state.testmode and time.time() - state.last_api_response >= 30): self.stop() elif not state.enableGUI: - # pylint: disable=relative-import - from tests import core as test_core - test_core_result = test_core.run(self) + from tests import core as test_core # pylint: disable=relative-import + test_core_result = test_core.run() state.enableGUI = True self.stop() test_core.cleanup() diff --git a/src/bitmessageqt/about.ui b/src/bitmessageqt/about.ui index a912927a..7073bbd1 100644 --- a/src/bitmessageqt/about.ui +++ b/src/bitmessageqt/about.ui @@ -46,7 +46,7 @@ - <html><head/><body><p>Copyright © 2012-2016 Jonathan Warren<br/>Copyright © 2012-2019 The Bitmessage Developers</p></body></html> + <html><head/><body><p>Copyright © 2012-2016 Jonathan Warren<br/>Copyright © 2012-2020 The Bitmessage Developers</p></body></html> Qt::AlignLeft diff --git a/src/bitmessageqt/dialogs.py b/src/bitmessageqt/dialogs.py index b4bcd2fd..c667edb1 100644 --- a/src/bitmessageqt/dialogs.py +++ b/src/bitmessageqt/dialogs.py @@ -47,7 +47,7 @@ class AboutDialog(QtGui.QDialog, RetranslateMixin): try: self.label_2.setText( self.label_2.text().replace( - '2019', str(last_commit.get('time').year) + '2020', str(last_commit.get('time').year) )) except AttributeError: pass diff --git a/src/bitmessageqt/settings.py b/src/bitmessageqt/settings.py index 982328cc..011d38ed 100644 --- a/src/bitmessageqt/settings.py +++ b/src/bitmessageqt/settings.py @@ -1,3 +1,4 @@ +import ConfigParser import os import sys @@ -16,10 +17,24 @@ import tempfile import widgets from bmconfigparser import BMConfigParser from helper_sql import sqlExecute, sqlStoredProcedure +from helper_startup import start_proxyconfig from network.asyncore_pollchoose import set_rates from tr import _translate +def getSOCKSProxyType(config): + """Get user socksproxytype setting from *config*""" + try: + result = ConfigParser.SafeConfigParser.get( + config, 'bitmessagesettings', 'socksproxytype') + except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): + return + else: + if result.lower() in ('', 'none', 'false'): + result = None + return result + + class SettingsDialog(QtGui.QDialog): """The "Settings" dialog""" def __init__(self, parent=None, firstrun=False): @@ -32,6 +47,16 @@ class SettingsDialog(QtGui.QDialog): self.net_restart_needed = False self.timer = QtCore.QTimer() + try: + import pkg_resources + except ImportError: + pass + else: + # Append proxy types defined in plugins + for ep in pkg_resources.iter_entry_points( + 'bitmessage.proxyconfig'): + self.comboBoxProxyType.addItem(ep.name) + self.lineEditMaxOutboundConnections.setValidator( QtGui.QIntValidator(0, 8, self.lineEditMaxOutboundConnections)) @@ -47,20 +72,33 @@ class SettingsDialog(QtGui.QDialog): def adjust_from_config(self, config): """Adjust all widgets state according to config settings""" # pylint: disable=too-many-branches,too-many-statements - self.checkBoxStartOnLogon.setChecked( - config.getboolean('bitmessagesettings', 'startonlogon')) - self.checkBoxMinimizeToTray.setChecked( - config.getboolean('bitmessagesettings', 'minimizetotray')) - self.checkBoxTrayOnClose.setChecked( - config.safeGetBoolean('bitmessagesettings', 'trayonclose')) + if not self.parent.tray.isSystemTrayAvailable(): + self.groupBoxTray.setEnabled(False) + self.groupBoxTray.setTitle(_translate( + "MainWindow", "Tray (not available in your system)")) + for setting in ( + 'minimizetotray', 'trayonclose', 'startintray'): + config.set('bitmessagesettings', setting, 'false') + else: + self.checkBoxMinimizeToTray.setChecked( + config.getboolean('bitmessagesettings', 'minimizetotray')) + self.checkBoxTrayOnClose.setChecked( + config.safeGetBoolean('bitmessagesettings', 'trayonclose')) + self.checkBoxStartInTray.setChecked( + config.getboolean('bitmessagesettings', 'startintray')) + self.checkBoxHideTrayConnectionNotifications.setChecked( - config.getboolean("bitmessagesettings", "hidetrayconnectionnotifications")) + config.getboolean( + 'bitmessagesettings', 'hidetrayconnectionnotifications')) self.checkBoxShowTrayNotifications.setChecked( config.getboolean('bitmessagesettings', 'showtraynotifications')) - self.checkBoxStartInTray.setChecked( - config.getboolean('bitmessagesettings', 'startintray')) + + self.checkBoxStartOnLogon.setChecked( + config.getboolean('bitmessagesettings', 'startonlogon')) + self.checkBoxWillinglySendToMobile.setChecked( - config.safeGetBoolean('bitmessagesettings', 'willinglysendtomobile')) + config.safeGetBoolean( + 'bitmessagesettings', 'willinglysendtomobile')) self.checkBoxUseIdenticons.setChecked( config.safeGetBoolean('bitmessagesettings', 'useidenticons')) self.checkBoxReplyBelow.setChecked( @@ -82,10 +120,12 @@ class SettingsDialog(QtGui.QDialog): "MainWindow", "Start-on-login not yet supported on your OS.")) self.checkBoxMinimizeToTray.setDisabled(True) self.checkBoxMinimizeToTray.setText(_translate( - "MainWindow", "Minimize-to-tray not yet supported on your OS.")) + "MainWindow", + "Minimize-to-tray not yet supported on your OS.")) self.checkBoxShowTrayNotifications.setDisabled(True) self.checkBoxShowTrayNotifications.setText(_translate( - "MainWindow", "Tray notifications not yet supported on your OS.")) + "MainWindow", + "Tray notifications not yet supported on your OS.")) elif 'linux' in sys.platform: self.checkBoxStartOnLogon.setDisabled(True) self.checkBoxStartOnLogon.setText(_translate( @@ -102,21 +142,11 @@ class SettingsDialog(QtGui.QDialog): self.checkBoxOnionOnly.setChecked( config.safeGetBoolean('bitmessagesettings', 'onionservicesonly')) - proxy_type = config.safeGet( - 'bitmessagesettings', 'socksproxytype', 'none') - if proxy_type == 'none': - self.comboBoxProxyType.setCurrentIndex(0) - self.lineEditSocksHostname.setEnabled(False) - self.lineEditSocksPort.setEnabled(False) - self.lineEditSocksUsername.setEnabled(False) - self.lineEditSocksPassword.setEnabled(False) - self.checkBoxAuthentication.setEnabled(False) - self.checkBoxSocksListen.setEnabled(False) - self.checkBoxOnionOnly.setEnabled(False) - elif proxy_type == 'SOCKS4a': - self.comboBoxProxyType.setCurrentIndex(1) - elif proxy_type == 'SOCKS5': - self.comboBoxProxyType.setCurrentIndex(2) + self._proxy_type = getSOCKSProxyType(config) + self.comboBoxProxyType.setCurrentIndex( + 0 if not self._proxy_type + else self.comboBoxProxyType.findText(self._proxy_type)) + self.comboBoxProxyTypeChanged(self.comboBoxProxyType.currentIndex()) self.lineEditSocksHostname.setText( config.get('bitmessagesettings', 'sockshostname')) @@ -204,7 +234,7 @@ class SettingsDialog(QtGui.QDialog): self.checkBoxAuthentication.setEnabled(False) self.checkBoxSocksListen.setEnabled(False) self.checkBoxOnionOnly.setEnabled(False) - elif comboBoxIndex in (1, 2): + else: self.lineEditSocksHostname.setEnabled(True) self.lineEditSocksPort.setEnabled(True) self.checkBoxAuthentication.setEnabled(True) @@ -306,27 +336,22 @@ class SettingsDialog(QtGui.QDialog): upnpThread = upnp.uPnPThread() upnpThread.start() - proxy_type = self.config.safeGet( - 'bitmessagesettings', 'socksproxytype', 'none') - if ( - proxy_type == 'none' and - self.comboBoxProxyType.currentText()[0:5] == 'SOCKS' and - shared.statusIconColor != 'red' - ): - self.net_restart_needed = True - if ( - proxy_type[0:5] == 'SOCKS' and - self.comboBoxProxyType.currentText()[0:5] != 'SOCKS' - ): + proxytype_index = self.comboBoxProxyType.currentIndex() + if proxytype_index == 0: + if self._proxy_type and shared.statusIconColor != 'red': + self.net_restart_needed = True + elif self.comboBoxProxyType.currentText() != self._proxy_type: self.net_restart_needed = True self.parent.statusbar.clearMessage() self.config.set( 'bitmessagesettings', 'socksproxytype', - str(self.comboBoxProxyType.currentText()) - if self.comboBoxProxyType.currentText()[0:5] == 'SOCKS' - else 'none' + 'none' if self.comboBoxProxyType.currentIndex() == 0 + else str(self.comboBoxProxyType.currentText()) ) + if proxytype_index > 2: # last literal proxytype in ui + start_proxyconfig() + self.config.set('bitmessagesettings', 'socksauthentication', str( self.checkBoxAuthentication.isChecked())) self.config.set('bitmessagesettings', 'sockshostname', str( diff --git a/src/bitmessageqt/settings.ui b/src/bitmessageqt/settings.ui index 963f2e64..0ffbf442 100644 --- a/src/bitmessageqt/settings.ui +++ b/src/bitmessageqt/settings.ui @@ -75,7 +75,7 @@ Minimize to tray - true + false @@ -419,12 +419,12 @@ - SOCKS4a + SOCKS4a - SOCKS5 + SOCKS5 diff --git a/src/bitmessageqt/support.py b/src/bitmessageqt/support.py index 2a1ddb18..d6d4543d 100644 --- a/src/bitmessageqt/support.py +++ b/src/bitmessageqt/support.py @@ -15,6 +15,7 @@ from openclpow import openclAvailable, openclEnabled import paths import proofofwork from pyelliptic.openssl import OpenSSL +from settings import getSOCKSProxyType import queues import network.stats import state @@ -118,8 +119,7 @@ def createSupportMessage(myapp): BMConfigParser().safeGet('bitmessagesettings', 'opencl') ) if openclEnabled() else "None" locale = getTranslationLanguage() - socks = BMConfigParser().safeGet( - 'bitmessagesettings', 'socksproxytype', "N/A") + socks = getSOCKSProxyType(BMConfigParser()) or "N/A" upnp = BMConfigParser().safeGet('bitmessagesettings', 'upnp', "N/A") connectedhosts = len(network.stats.connectedHostsList()) diff --git a/src/class_objectProcessor.py b/src/class_objectProcessor.py index 19f4861c..3e3261ad 100644 --- a/src/class_objectProcessor.py +++ b/src/class_objectProcessor.py @@ -141,13 +141,13 @@ class objectProcessor(threading.Thread): # bypass nonce and time, retain object type/version/stream + body readPosition = 16 - if data[readPosition:] in shared.ackdataForWhichImWatching: + if bytes(data[readPosition:]) in shared.ackdataForWhichImWatching: logger.info('This object is an acknowledgement bound for me.') del shared.ackdataForWhichImWatching[data[readPosition:]] sqlExecute( 'UPDATE sent SET status=?, lastactiontime=?' ' WHERE ackdata=?', - 'ackreceived', int(time.time()), data[readPosition:]) + ' ackreceived', int(time.time()), data[readPosition:]) queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', (data[readPosition:], @@ -221,7 +221,7 @@ class objectProcessor(threading.Thread): 'the hash requested in this getpubkey request is: %s', hexlify(requestedHash)) # if this address hash is one of mine - if requestedHash in shared.myAddressesByHash: + if bytes(requestedHash) in shared.myAddressesByHash: myAddress = shared.myAddressesByHash[requestedHash] elif requestedAddressVersionNumber >= 4: requestedTag = data[readPosition:readPosition + 32] @@ -233,7 +233,7 @@ class objectProcessor(threading.Thread): logger.debug( 'the tag requested in this getpubkey request is: %s', hexlify(requestedTag)) - if requestedTag in shared.myAddressesByTag: + if bytes(requestedTag) in shared.myAddressesByTag: myAddress = shared.myAddressesByTag[requestedTag] if myAddress == '': @@ -328,7 +328,7 @@ class objectProcessor(threading.Thread): dataToStore = data[20:readPosition] sha = hashlib.new('sha512') sha.update( - '\x04' + publicSigningKey + '\x04' + publicEncryptionKey) + '\x04'.encode() + publicSigningKey + '\x04'.encode() + publicEncryptionKey) ripe = RIPEMD160Hash(sha.digest()).digest() if logger.isEnabledFor(logging.DEBUG): @@ -367,9 +367,9 @@ class objectProcessor(threading.Thread): ' Sanity check failed.') return readPosition += 4 - publicSigningKey = '\x04' + data[readPosition:readPosition + 64] + publicSigningKey = ('\x04').encode() + data[readPosition:readPosition + 64] readPosition += 64 - publicEncryptionKey = '\x04' + data[readPosition:readPosition + 64] + publicEncryptionKey = ('\x04').encode() + data[readPosition:readPosition + 64] readPosition += 64 _, specifiedNonceTrialsPerByteLength = decodeVarint( data[readPosition:readPosition + 10]) @@ -433,7 +433,7 @@ class objectProcessor(threading.Thread): return tag = data[readPosition:readPosition + 32] - if tag not in state.neededPubkeys: + if tag not in bytes(state.neededPubkeys): logger.info( 'We don\'t need this v4 pubkey. We didn\'t ask for it.') return @@ -866,7 +866,7 @@ class objectProcessor(threading.Thread): elif broadcastVersion == 5: embeddedTag = data[readPosition:readPosition + 32] readPosition += 32 - if embeddedTag not in shared.MyECSubscriptionCryptorObjects: + if bytes(embeddedTag) not in shared.MyECSubscriptionCryptorObjects: logger.debug('We\'re not interested in this broadcast.') return # We are interested in this broadcast because of its tag. diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index b5bf2e43..7c0b5842 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -471,8 +471,8 @@ class singleWorker(StoppableThread): def sendOnionPeerObj(self, peer=None): """Send onionpeer object representing peer""" if not peer: # find own onionhostname - for peer_ in state.ownAddresses: - if peer_.host.endswith('.onion'): + for peer in state.ownAddresses: + if peer.host.endswith('.onion'): break else: return diff --git a/src/helper_startup.py b/src/helper_startup.py index bc0ede92..52a600ed 100644 --- a/src/helper_startup.py +++ b/src/helper_startup.py @@ -2,11 +2,12 @@ Startup operations. """ # pylint: disable=too-many-branches,too-many-statements -from __future__ import print_function - +# import configparser +import logging import os import platform import sys +import time from distutils.version import StrictVersion import defaults @@ -15,6 +16,13 @@ import paths import state from bmconfigparser import BMConfigParser +try: + from plugins.plugin import get_plugin +except ImportError: + get_plugin = None + + +logger = logging.getLogger('default') # The user may de-select Portable Mode in the settings if they want # the config files to stay in the application data folder. @@ -31,14 +39,14 @@ def loadConfig(): needToCreateKeysFile = config.safeGet( 'bitmessagesettings', 'settingsversion') is None if not needToCreateKeysFile: - print( + logger.info( 'Loading config files from directory specified' - ' on startup: %s' % state.appdata) + ' on startup: %s', state.appdata) else: config.read(paths.lookupExeFolder() + 'keys.dat') try: config.get('bitmessagesettings', 'settingsversion') - print('Loading config files from same directory as program.') + logger.info('Loading config files from same directory as program.') needToCreateKeysFile = False state.appdata = paths.lookupExeFolder() except: @@ -49,7 +57,8 @@ def loadConfig(): needToCreateKeysFile = config.safeGet( 'bitmessagesettings', 'settingsversion') is None if not needToCreateKeysFile: - print('Loading existing config files from', state.appdata) + logger.info( + 'Loading existing config files from %s', state.appdata) if needToCreateKeysFile: @@ -104,9 +113,10 @@ def loadConfig(): # Just use the same directory as the program and forget about # the appdata folder state.appdata = '' - print('Creating new config files in same directory as program.') + logger.info( + 'Creating new config files in same directory as program.') else: - print('Creating new config files in', state.appdata) + logger.info('Creating new config files in %s', state.appdata) if not os.path.exists(state.appdata): os.makedirs(state.appdata) if not sys.platform.startswith('win'): @@ -258,7 +268,7 @@ def updateConfig(): 'bitmessagesettings', 'hidetrayconnectionnotifications', 'false') if config.safeGetInt('bitmessagesettings', 'maxoutboundconnections') < 1: config.set('bitmessagesettings', 'maxoutboundconnections', '8') - print('WARNING: your maximum outbound connections must be a number.') + logger.warning('Your maximum outbound connections must be a number.') # TTL is now user-specifiable. Let's add an option to save # whatever the user selects. @@ -281,3 +291,26 @@ def isOurOperatingSystemLimitedToHavingVeryFewHalfOpenConnections(): return False except Exception: pass + + +def start_proxyconfig(): + """Check socksproxytype and start any proxy configuration plugin""" + if not get_plugin: + return + config = BMConfigParser() + proxy_type = config.safeGet('bitmessagesettings', 'socksproxytype') + if proxy_type and proxy_type not in ('none', 'SOCKS4a', 'SOCKS5'): + try: + proxyconfig_start = time.time() + if not get_plugin('proxyconfig', name=proxy_type)(config): + raise TypeError() + except TypeError: + # cannot import shutdown here ): + logger.error( + 'Failed to run proxy config plugin %s', + proxy_type, exc_info=True) + os._exit(0) # pylint: disable=protected-access + else: + logger.info( + 'Started proxy config plugin %s in %s sec', + proxy_type, time.time() - proxyconfig_start) diff --git a/src/network/assemble.py b/src/network/assemble.py index 9ae853f7..82f37533 100644 --- a/src/network/assemble.py +++ b/src/network/assemble.py @@ -22,7 +22,7 @@ def assemble_addr(peerList): len(peerList[i:i + MAX_ADDR_COUNT])) for stream, peer, timestamp in peerList[i:i + MAX_ADDR_COUNT]: payload += struct.pack( - '>Q', timestamp) # 64-bit time + '>Q', int(timestamp)) # 64-bit time payload += struct.pack('>I', stream) payload += struct.pack( '>q', 1) # service bit flags offered by this node diff --git a/src/network/bmproto.py b/src/network/bmproto.py index ad2260fa..cd839a96 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -172,9 +172,11 @@ class BMProto(AdvancedDispatcher, ObjectTracker): except BMObjectAlreadyHaveError: logger.debug( '%(host)s:%(port)i already got object, skipping', - self.destination._asdict()) + self.destinaestion._asdict()) except struct.error: logger.debug('decoding error, skipping') + except ValueError: + pass elif self.socket.type == socket.SOCK_DGRAM: # broken read, ignore pass @@ -206,9 +208,9 @@ class BMProto(AdvancedDispatcher, ObjectTracker): """Decode node details from the payload""" # protocol.checkIPAddress() services, host, port = self.decode_payload_content("Q16sH") - if host[0:12] == '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF': + if host[0:12] == '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode('raw_unicode_escape'): host = socket.inet_ntop(socket.AF_INET, host[12:16]) - elif host[0:6] == '\xfd\x87\xd8\x7e\xeb\x43': + elif host[0:6] == '\xfd\x87\xd8\x7e\xeb\x43'.encode('raw_unicode_escape'): # Onion, based on BMD/bitcoind host = base64.b32encode(host[6:]).lower() + ".onion" else: @@ -385,7 +387,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): if dandelion and not state.dandelion: return True - for i in map(str, items): + for i in map(bytes, items): if i in Inventory() and not Dandelion().hasHash(i): continue if dandelion and not Dandelion().hasHash(i): @@ -438,7 +440,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): try: self.object.checkObjectByType() objectProcessorQueue.put(( - self.object.objectType, buffer(self.object.data))) + self.object.objectType, memoryview(self.object.data))) except BMObjectInvalidError: BMProto.stopDownloadingObject(self.object.inventoryHash, True) else: @@ -449,12 +451,12 @@ class BMProto(AdvancedDispatcher, ObjectTracker): if self.object.inventoryHash in Inventory() and Dandelion().hasHash(self.object.inventoryHash): Dandelion().removeHash(self.object.inventoryHash, "cycle detection") - - Inventory()[self.object.inventoryHash] = ( + [self.object.inventoryHash] = ( self.object.objectType, self.object.streamNumber, - buffer(self.payload[objectOffset:]), self.object.expiresTime, - buffer(self.object.tag) + memoryview(self.payload[objectOffset:]), self.object.expiresTime, + memoryview(self.object.tag) ) + Inventory()[self.object.inventoryHash] self.handleReceivedObject( self.object.streamNumber, self.object.inventoryHash) invQueue.put(( diff --git a/src/network/udp.py b/src/network/udp.py index 0743776a..d3421806 100644 --- a/src/network/udp.py +++ b/src/network/udp.py @@ -149,6 +149,9 @@ class UDPSocket(BMProto): # pylint: disable=too-many-instance-attributes retval = self.socket.sendto( self.write_buf, ('', self.port)) except socket.error as e: - logger.error("socket error on sendato: %s", e) + logger.error("socket error on sendto: %s", e) + if e.errno == 101: + self.announcing = False + self.socket.close() retval = 0 self.slice_write_buf(retval) diff --git a/src/plugins/__init__.py b/src/plugins/__init__.py index e69de29b..285009df 100644 --- a/src/plugins/__init__.py +++ b/src/plugins/__init__.py @@ -0,0 +1,7 @@ +""" +Simple plugin system based on setuptools +---------------------------------------- + + +""" +# .. include:: pybitmessage.plugins.plugin.rst diff --git a/src/plugins/plugin.py b/src/plugins/plugin.py index e671a73f..629de0a6 100644 --- a/src/plugins/plugin.py +++ b/src/plugins/plugin.py @@ -1,19 +1,28 @@ # -*- coding: utf-8 -*- """ -src/plugins/plugin.py -=================================== +Operating with plugins """ +import logging + import pkg_resources +logger = logging.getLogger('default') + + def get_plugins(group, point='', name=None, fallback=None): """ - Iterate through plugins (`connect_plugin` attribute of entry point) - which name starts with `point` or equals to `name`. - If `fallback` kwarg specified, plugin with that name yield last. + :param str group: plugin group + :param str point: plugin name prefix + :param name: exact plugin name + :param fallback: fallback plugin name + + Iterate through plugins (``connect_plugin`` attribute of entry point) + which name starts with ``point`` or equals to ``name``. + If ``fallback`` kwarg specified, plugin with that name yield last. """ for ep in pkg_resources.iter_entry_points('bitmessage.' + group): - if name and ep.name == name or ep.name.startswith(point): + if name and ep.name == name or not point or ep.name.startswith(point): try: plugin = ep.load().connect_plugin if ep.name == fallback: @@ -25,6 +34,8 @@ def get_plugins(group, point='', name=None, fallback=None): ValueError, pkg_resources.DistributionNotFound, pkg_resources.UnknownExtra): + logger.debug( + 'Problem while loading %s', ep.name, exc_info=True) continue try: yield _fallback @@ -33,6 +44,8 @@ def get_plugins(group, point='', name=None, fallback=None): def get_plugin(*args, **kwargs): - """Returns first available plugin `from get_plugins()` if any.""" + """ + :return: first available plugin from :func:`get_plugins` if any. + """ for plugin in get_plugins(*args, **kwargs): return plugin diff --git a/src/plugins/proxyconfig_stem.py b/src/plugins/proxyconfig_stem.py index bdbfe8ca..494519f2 100644 --- a/src/plugins/proxyconfig_stem.py +++ b/src/plugins/proxyconfig_stem.py @@ -1,7 +1,15 @@ # -*- coding: utf-8 -*- """ -src/plugins/proxyconfig_stem.py -=================================== +Configure tor proxy and hidden service with +`stem `_ depending on *bitmessagesettings*: + + * try to start own tor instance on *socksport* if *sockshostname* + is unset or set to localhost; + * if *socksport* is already in use that instance is used only for + hidden service (if *sockslisten* is also set True); + * create ephemeral hidden service v3 if there is already *onionhostname*; + * otherwise use stem's 'BEST' version and save onion keys to the new + section using *onionhostname* as name for future use. """ import os import logging @@ -36,13 +44,20 @@ class DebugLogger(object): def connect_plugin(config): # pylint: disable=too-many-branches - """Run stem proxy configurator""" + """ + Run stem proxy configurator + + :param config: current configuration instance + :type config: :class:`pybitmessage.bmconfigparser.BMConfigParser` + :return: True if configuration was done successfully + """ logwrite = DebugLogger() - if config.safeGet('bitmessagesettings', 'sockshostname') not in ( - 'localhost', '127.0.0.1', '' + if config.safeGet('bitmessagesettings', 'sockshostname', '') not in ( + 'localhost', '127.0.0.1', '' ): # remote proxy is choosen for outbound connections, # nothing to do here, but need to set socksproxytype to SOCKS5! + config.set('bitmessagesettings', 'socksproxytype', 'SOCKS5') logwrite( 'sockshostname is set to remote address,' ' aborting stem proxy configuration') @@ -77,6 +92,8 @@ def connect_plugin(config): # pylint: disable=too-many-branches logwrite('Started tor on port %s' % port) break + config.setTemp('bitmessagesettings', 'socksproxytype', 'SOCKS5') + if config.safeGetBoolean('bitmessagesettings', 'sockslisten'): # need a hidden service for inbound connections try: @@ -95,7 +112,8 @@ def connect_plugin(config): # pylint: disable=too-many-branches onionkeytype = config.safeGet(onionhostname, 'keytype') response = controller.create_ephemeral_hidden_service( - config.safeGetInt('bitmessagesettings', 'onionport', 8444), + {config.safeGetInt('bitmessagesettings', 'onionport', 8444): + config.safeGetInt('bitmessagesettings', 'port', 8444)}, key_type=(onionkeytype or 'NEW'), key_content=(onionkey or onionhostname and 'ED25519-V3' or 'BEST') ) @@ -117,6 +135,5 @@ def connect_plugin(config): # pylint: disable=too-many-branches config.set( onionhostname, 'keytype', response.private_key_type) config.save() - config.set('bitmessagesettings', 'socksproxytype', 'SOCKS5') - return True + return True diff --git a/src/protocol.py b/src/protocol.py index fba68fe3..fd3ce26b 100644 --- a/src/protocol.py +++ b/src/protocol.py @@ -278,14 +278,13 @@ def isProofOfWorkSufficient( def CreatePacket(command, payload=''): """Construct and return a number of bytes from a payload""" - payload = payload if type(payload) == bytes else payload.encode() - + payload = payload if type(payload) in [bytes,bytearray] else payload.encode() payload_length = len(payload) checksum = hashlib.sha512(payload).digest()[0:4] byte = bytearray(Header.size + payload_length) Header.pack_into(byte, 0, 0xE9BEB4D9, command.encode(), payload_length, checksum) byte[Header.size:] = payload - return byte + return bytes(byte) def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server=False, nodeid=None): @@ -325,10 +324,8 @@ def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server= (NODE_DANDELION if state.dandelion else 0) ) # = 127.0.0.1. This will be ignored by the remote host. The actual remote connected IP will be used. - - # python3 need to check - payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode() + pack('>L', 2130706433) - + #python3 need to check + payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode('raw_unicode_escape') + pack('>L', 2130706433) # we have a separate extPort and incoming over clearnet # or outgoing through clearnet extport = BMConfigParser().safeGetInt('bitmessagesettings', 'extport') diff --git a/src/storage/sqlite.py b/src/storage/sqlite.py index 3eec3be6..c272f4ed 100644 --- a/src/storage/sqlite.py +++ b/src/storage/sqlite.py @@ -39,15 +39,20 @@ class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors return True def __getitem__(self, hash_): - print('----------__getitem__------------------') + if hash_ == 0: + hash_ = bytes() with self.lock: - if hash_ in self._inventory: - return self._inventory[hash_] - rows = sqlQuery( - 'SELECT objecttype, streamnumber, payload, expirestime, tag FROM inventory WHERE hash=?', - sqlite3.Binary(hash_)) - if not rows: - raise KeyError(hash_) + try: + if hash_ in self._inventory: + return self._inventory[hash_] + rows = sqlQuery( + 'SELECT objecttype, streamnumber, payload, expirestime, tag FROM inventory WHERE hash=?', + sqlite3.Binary(hash_)) + if not rows: + pass + # raise KeyError(hash_) + except: + pass return InventoryItem(*rows[0]) def __setitem__(self, hash_, value): diff --git a/src/tests/core.py b/src/tests/core.py index 27102a1c..7b89e5b0 100644 --- a/src/tests/core.py +++ b/src/tests/core.py @@ -15,14 +15,20 @@ import knownnodes import state from bmconfigparser import BMConfigParser from helper_msgcoding import MsgEncode, MsgDecode +from helper_startup import start_proxyconfig from network import asyncore_pollchoose as asyncore from network.connectionpool import BMConnectionPool from network.node import Peer from network.tcp import Socks4aBMConnection, Socks5BMConnection, TCPConnection from queues import excQueue +try: + import stem.version as stem_version +except ImportError: + stem_version = None + + knownnodes_file = os.path.join(state.appdata, 'knownnodes.dat') -program = None def pickle_knownnodes(): @@ -170,12 +176,29 @@ class TestCore(unittest.TestCase): self.assertIsInstance(con, connection_base) self.assertNotEqual(peer.host, '127.0.0.1') return - else: # pylint: disable=useless-else-on-loop - self.fail( - 'Failed to connect during %s sec' % (time.time() - _started)) + self.fail( + 'Failed to connect during %s sec' % (time.time() - _started)) - def test_onionservicesonly(self): - """test onionservicesonly networking mode""" + def test_bootstrap(self): + """test bootstrapping""" + self._initiate_bootstrap() + self._check_bootstrap() + + @unittest.skipUnless(stem_version, 'No stem, skipping tor dependent test') + def test_bootstrap_tor(self): + """test bootstrapping with tor""" + self._initiate_bootstrap() + BMConfigParser().set('bitmessagesettings', 'socksproxytype', 'stem') + start_proxyconfig() + self._check_bootstrap() + + @unittest.skipUnless(stem_version, 'No stem, skipping tor dependent test') + def test_onionservicesonly(self): # this should start after bootstrap + """ + set onionservicesonly, wait for 3 connections and check them all + are onions + """ + BMConfigParser().set('bitmessagesettings', 'socksproxytype', 'SOCKS5') BMConfigParser().set('bitmessagesettings', 'onionservicesonly', 'true') self._initiate_bootstrap() BMConfigParser().remove_option('bitmessagesettings', 'dontconnect') @@ -184,26 +207,18 @@ class TestCore(unittest.TestCase): for n, peer in enumerate(BMConnectionPool().outboundConnections): if n > 2: return - if not peer.host.endswith('.onion'): + if ( + not peer.host.endswith('.onion') + and not peer.host.startswith('bootstrap') + ): self.fail( 'Found non onion hostname %s in outbound connections!' % peer.host) self.fail('Failed to connect to at least 3 nodes within 360 sec') - def test_bootstrap(self): - """test bootstrapping""" - self._initiate_bootstrap() - self._check_bootstrap() - self._initiate_bootstrap() - BMConfigParser().set('bitmessagesettings', 'socksproxytype', 'stem') - program.start_proxyconfig(BMConfigParser()) - self._check_bootstrap() - -def run(prog): +def run(): """Starts all tests defined in this module""" - global program # pylint: disable=global-statement - program = prog loader = unittest.TestLoader() loader.sortTestMethodsUsing = None suite = loader.loadTestsFromTestCase(TestCore)