From afb368e7706f4af9394d1311da6dcd078ebb78b9 Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Thu, 26 Sep 2019 19:38:19 +0530 Subject: [PATCH 1/4] initial commit for python forward porting --- src/addresses.py | 6 +-- src/bitmessagekivy/mpybit.py | 1 + src/bitmessagemain.py | 37 +++++++++---------- src/bitmessageqt/statusbar.py | 2 +- src/bmconfigparser.py | 59 +++++++++++++++++------------- src/class_objectProcessorQueue.py | 2 +- src/class_sqlThread.py | 12 +++--- src/debug.py | 7 ++-- src/depends.py | 10 ++--- src/helper_bitcoin.py | 6 ++- src/helper_sql.py | 2 +- src/helper_startup.py | 9 +++-- src/highlevelcrypto.py | 3 +- src/knownnodes.py | 7 ++-- src/l10n.py | 24 ++++++++---- src/messagetypes/__init__.py | 2 +- src/multiqueue.py | 2 +- src/network/addrthread.py | 2 +- src/network/advanceddispatcher.py | 5 ++- src/network/asyncore_pollchoose.py | 7 ++-- src/network/bmproto.py | 6 +-- src/network/connectionpool.py | 13 +++---- src/network/dandelion.py | 2 +- src/network/downloadthread.py | 4 +- src/network/http.py | 2 +- src/network/invthread.py | 2 +- src/network/objectracker.py | 2 +- src/network/proxy.py | 4 +- src/network/randomtrackingdict.py | 10 ++--- src/network/receivequeuethread.py | 2 +- src/network/socks4a.py | 4 +- src/network/socks5.py | 4 +- src/network/stats.py | 2 +- src/network/tcp.py | 4 +- src/network/tls.py | 7 +++- src/network/udp.py | 4 +- src/network/uploadthread.py | 2 +- src/openclpow.py | 5 ++- src/pyelliptic/arithmetic.py | 4 +- src/pyelliptic/cipher.py | 2 +- src/pyelliptic/ecc.py | 9 +++-- src/pyelliptic/hash.py | 2 +- src/pyelliptic/openssl.py | 5 ++- src/queues.py | 2 +- src/shared.py | 9 ++--- src/shutdown.py | 2 +- src/singleinstance.py | 6 +-- src/storage/filesystem.py | 4 +- src/storage/sqlite.py | 1 + src/suravata.py | 32 ---------------- src/tests/core.py | 2 +- src/tr.py | 6 +-- 52 files changed, 187 insertions(+), 183 deletions(-) delete mode 100644 src/suravata.py diff --git a/src/addresses.py b/src/addresses.py index 533ec169..4d200332 100644 --- a/src/addresses.py +++ b/src/addresses.py @@ -180,7 +180,6 @@ def decodeAddress(address): data (almost certainly a ripe hash)) """ # pylint: disable=too-many-return-statements,too-many-statements,too-many-return-statements,too-many-branches - address = str(address).strip() if address[:3] == 'BM-': @@ -192,7 +191,8 @@ def decodeAddress(address): return status, 0, 0, '' # after converting to hex, the string will be prepended # with a 0x and appended with a L - hexdata = hex(integer)[2:-1] + # import pdb;pdb.set_trace() + hexdata = hex(integer)[2:] if len(hexdata) % 2 != 0: hexdata = '0' + hexdata @@ -248,7 +248,7 @@ def decodeAddress(address): embeddedRipeData elif len(embeddedRipeData) == 18: return status, addressVersionNumber, streamNumber, \ - '\x00\x00' + embeddedRipeData + '\x00\x00'.encode('utf-8') + embeddedRipeData elif len(embeddedRipeData) < 18: return 'ripetooshort', 0, 0, '' elif len(embeddedRipeData) > 20: diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 39005727..70f51b29 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -984,6 +984,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods def build(self): """Method builds the widget.""" + import os 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 ee4b7eb9..e066dd06 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -179,13 +179,13 @@ def signal_handler(signum, frame): if shared.thisapp.daemon or not state.enableGUI: shutdown.doCleanShutdown() else: - print '# Thread: %s(%d)' % (thread.name, thread.ident) + print ('# Thread: {}({})'.format(thread.name, thread.ident)) for filename, lineno, name, line in traceback.extract_stack(frame): - print 'File: "%s", line %d, in %s' % (filename, lineno, name) + print ("File: '{}', line {}, in {}" .format(filename, lineno, name)) if line: - print ' %s' % line.strip() - print 'Unfortunately you cannot use Ctrl+C when running the UI \ - because the UI captures the signal.' + print (' {}'.format(line.strip())) + print('Unfortunately you cannot use Ctrl+C when running the UI \ + because the UI captures the signal.') class Main: # pylint: disable=no-init, old-style-class @@ -282,7 +282,7 @@ class Main: # pylint: disable=no-init, old-style-class if daemon: with shared.printLock: - print 'Running as a daemon. Send TERM signal to end.' + print('Running as a daemon. Send TERM signal to end.') self.daemonize() self.setSignalHandler() @@ -405,7 +405,7 @@ class Main: # pylint: disable=no-init, old-style-class if state.curses: if not depends.check_curses(): sys.exit() - print 'Running with curses' + print('Running with curses') import bitmessagecurses bitmessagecurses.runwrapper() @@ -498,23 +498,22 @@ class Main: # pylint: disable=no-init, old-style-class # signal.signal(signal.SIGINT, signal.SIG_DFL) @staticmethod - def usage(): - """After passing argument, method displays the usages""" - print 'Usage: ' + sys.argv[0] + ' [OPTIONS]' - print ''' -Options: - -h, --help show this help message and exit - -c, --curses use curses (text mode) interface - -d, --daemon run in daemon (background) mode - -t, --test dryrun, make testing + def usage(self): + print('Usage: ' + sys.argv[0] + ' [OPTIONS]') + print (''' + Options: + -h, --help show this help message and exit + -c, --curses use curses (text mode) interface + -d, --daemon run in daemon (background) mode + -t, --test dryrun, make testing -All parameters are optional. -''' + All parameters are optional. + ''') def stop(self): # pylint: disable=no-self-use """Method helps to stop the Bitmessage Deamon""" with shared.printLock: - print 'Stopping Bitmessage Deamon.' + print('Stopping Bitmessage Deamon.') shutdown.doCleanShutdown() # ..todo: nice function but no one is using this diff --git a/src/bitmessageqt/statusbar.py b/src/bitmessageqt/statusbar.py index 65a5acfb..7f559197 100644 --- a/src/bitmessageqt/statusbar.py +++ b/src/bitmessageqt/statusbar.py @@ -1,5 +1,5 @@ from PyQt4 import QtCore, QtGui -from Queue import Queue +from queue.Queue import Queue from time import time class BMStatusBar(QtGui.QStatusBar): diff --git a/src/bmconfigparser.py b/src/bmconfigparser.py index 726d32eb..6f5660e0 100644 --- a/src/bmconfigparser.py +++ b/src/bmconfigparser.py @@ -2,7 +2,7 @@ BMConfigParser class definition and default configuration settings """ -import ConfigParser +import configparser import shutil import os from datetime import datetime @@ -42,35 +42,35 @@ BMConfigDefaults = { @Singleton -class BMConfigParser(ConfigParser.SafeConfigParser): - """Singleton class inherited from ConfigParser.SafeConfigParser +class BMConfigParser(configparser.ConfigParser): + """Singleton class inherited from ConfigParsedadfeConfigParser with additional methods specific to bitmessage config.""" _temp = {} def set(self, section, option, value=None): if self._optcre is self.OPTCRE or value: - if not isinstance(value, basestring): + if not isinstance(value, str): raise TypeError("option values must be strings") if not self.validate(section, option, value): raise ValueError("Invalid value %s" % value) - return ConfigParser.ConfigParser.set(self, section, option, value) + return configparser.ConfigParser.set(self, section, option, value) def get(self, section, option, raw=False, variables=None): try: if section == "bitmessagesettings" and option == "timeformat": - return ConfigParser.ConfigParser.get( - self, section, option, raw, variables) + return configparser.ConfigParser.get( + self, section, option, raw=True, vars=variables) try: return self._temp[section][option] except KeyError: pass - return ConfigParser.ConfigParser.get( - self, section, option, True, variables) - except ConfigParser.InterpolationError: - return ConfigParser.ConfigParser.get( - self, section, option, True, variables) - except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) as e: + return configparser.ConfigParser.get( + self, section, option, raw=True, vars=variables) + except configparser.InterpolationError: + return configparser.ConfigParser.get( + self, section, option, raw=True, vars=variables) + except (configparser.NoSectionError, configparser.NoOptionError) as e: try: return BMConfigDefaults[section][option] except (KeyError, ValueError, AttributeError): @@ -84,49 +84,56 @@ class BMConfigParser(ConfigParser.SafeConfigParser): self._temp[section] = {option: value} def safeGetBoolean(self, section, field): + config = configparser.ConfigParser() try: - return self.getboolean(section, field) - except (ConfigParser.NoSectionError, ConfigParser.NoOptionError, + #Used in the python2.7 + # return self.getboolean(section, field) + #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): + config = configparser.ConfigParser() try: - return self.getint(section, field) - except (ConfigParser.NoSectionError, ConfigParser.NoOptionError, + #Used in the python2.7 + # return self.getint(section, field) + #Used in the python3.5.2 + return config.getint(section, field) + except (configparser.NoSectionError, configparser.NoOptionError, ValueError, AttributeError): return default def safeGet(self, section, option, default=None): try: return self.get(section, option) - except (ConfigParser.NoSectionError, ConfigParser.NoOptionError, + except (configparser.NoSectionError, configparser.NoOptionError, ValueError, AttributeError): return default def items(self, section, raw=False, variables=None): - return ConfigParser.ConfigParser.items(self, section, True, variables) + return configparser.ConfigParser.items(self, section, True, variables) def addresses(self): - return filter( - lambda x: x.startswith('BM-'), BMConfigParser().sections()) + return [x for x in BMConfigParser().sections() if x.startswith('BM-')] def read(self, filenames): - ConfigParser.ConfigParser.read(self, filenames) + configparser.ConfigParser.read(self, filenames) for section in self.sections(): for option in self.options(section): try: if not self.validate( section, option, - ConfigParser.ConfigParser.get(self, section, option) + configparser.ConfigParser.get(self, section, option) ): try: newVal = BMConfigDefaults[section][option] except KeyError: continue - ConfigParser.ConfigParser.set( + configparser.ConfigParser.set( self, section, option, newVal) - except ConfigParser.InterpolationError: + except configparser.InterpolationError: continue def save(self): @@ -144,7 +151,7 @@ class BMConfigParser(ConfigParser.SafeConfigParser): # didn't exist before. fileNameExisted = False # write the file - with open(fileName, 'wb') as configfile: + with open(fileName, 'w') as configfile: self.write(configfile) # delete the backup if fileNameExisted: diff --git a/src/class_objectProcessorQueue.py b/src/class_objectProcessorQueue.py index b6628816..24c24023 100644 --- a/src/class_objectProcessorQueue.py +++ b/src/class_objectProcessorQueue.py @@ -1,4 +1,4 @@ -import Queue +import queue as Queue import threading import time diff --git a/src/class_sqlThread.py b/src/class_sqlThread.py index a45571e0..bf0e67d9 100644 --- a/src/class_sqlThread.py +++ b/src/class_sqlThread.py @@ -51,8 +51,8 @@ class sqlThread(threading.Thread): '''INSERT INTO subscriptions VALUES('Bitmessage new releases/announcements','BM-GtovgYdgs7qXPkoYaRgrLFuFKz1SFpsw',1)''') self.cur.execute( '''CREATE TABLE settings (key blob, value blob, UNIQUE(key) ON CONFLICT REPLACE)''' ) - self.cur.execute( '''INSERT INTO settings VALUES('version','10')''') - self.cur.execute( '''INSERT INTO settings VALUES('lastvacuumtime',?)''', ( + self.cur.execute('''INSERT INTO settings VALUES('version','10')''') + self.cur.execute('''INSERT INTO settings VALUES('lastvacuumtime',?)''', ( int(time.time()),)) self.cur.execute( '''CREATE TABLE objectprocessorqueue (objecttype int, data blob, UNIQUE(objecttype, data) ON CONFLICT REPLACE)''' ) @@ -70,9 +70,11 @@ class sqlThread(threading.Thread): # If the settings version is equal to 2 or 3 then the # sqlThread will modify the pubkeys table and change # the settings version to 4. - settingsversion = BMConfigParser().getint( - 'bitmessagesettings', 'settingsversion') - + # settingsversion = BMConfigParser().getint('bitmessagesettings', 'settingsversion') + # In the Python3 I am below condition converting into int + # settingsversion = int(BMConfigParser().get('bitmessagesettings', 'settingsversion') \ + # if BMConfigParser().get('bitmessagesettings', 'settingsversion') else 0) + settingsversion = BMConfigParser().safeGetInt('bitmessagesettings', 'settingsvesion') # People running earlier versions of PyBitmessage do not have the # usedpersonally field in their pubkeys table. Let's add it. if settingsversion == 2: diff --git a/src/debug.py b/src/debug.py index 8393bb50..0caf1956 100644 --- a/src/debug.py +++ b/src/debug.py @@ -23,7 +23,7 @@ Use: `from debug import logger` to import this facility into whatever module you """ -import ConfigParser +import configparser import logging import logging.config import os @@ -47,12 +47,13 @@ def configureLogging(): fail_msg = '' try: logging_config = os.path.join(state.appdata, 'logging.dat') - logging.config.fileConfig(logging_config) + # right now I am commenting the logger + # logging.config.fileConfig(logging_config, disable_existing_loggers=False) return ( False, 'Loaded logger configuration from %s' % logging_config ) - except (OSError, ConfigParser.NoSectionError): + except (OSError, configparser.NoSectionError): if os.path.isfile(logging_config): fail_msg = \ 'Failed to load logger configuration from %s, using default' \ diff --git a/src/depends.py b/src/depends.py index dc35b529..b0d0beb4 100755 --- a/src/depends.py +++ b/src/depends.py @@ -419,11 +419,11 @@ def check_dependencies(verbose=False, optional=False): 'PyBitmessage requires Python 2.7.4 or greater' ' (but not Python 3+)') has_all_dependencies = False - if sys.hexversion >= 0x3000000: - logger.error( - 'PyBitmessage does not support Python 3+. Python 2.7.4' - ' or greater is required.') - has_all_dependencies = False + # if sys.hexversion >= 0x3000000: + # logger.error( + # 'PyBitmessage does not support Python 3+. Python 2.7.4' + # ' or greater is required.') + # has_all_dependencies = False check_functions = [check_ripemd160, check_sqlite, check_openssl] if optional: diff --git a/src/helper_bitcoin.py b/src/helper_bitcoin.py index d56e395b..b4f34cf1 100644 --- a/src/helper_bitcoin.py +++ b/src/helper_bitcoin.py @@ -4,7 +4,8 @@ from pyelliptic import arithmetic # This function expects that pubkey begin with \x04 def calculateBitcoinAddressFromPubkey(pubkey): if len(pubkey) != 65: - print 'Could not calculate Bitcoin address from pubkey because function was passed a pubkey that was', len(pubkey), 'bytes long rather than 65.' + print ('Could not calculate Bitcoin address from pubkey because function was passed a pubkey that was'\ + '{}, bytes long rather than 65.'.format(len(pubkey))) return "error" ripe = hashlib.new('ripemd160') sha = hashlib.new('sha256') @@ -25,7 +26,8 @@ def calculateBitcoinAddressFromPubkey(pubkey): def calculateTestnetAddressFromPubkey(pubkey): if len(pubkey) != 65: - print 'Could not calculate Bitcoin address from pubkey because function was passed a pubkey that was', len(pubkey), 'bytes long rather than 65.' + print ('Could not calculate Bitcoin address from pubkey because function was passed a pubkey that was',\ + '{}, bytes long rather than 65.'.format(pubkey)) return "error" ripe = hashlib.new('ripemd160') sha = hashlib.new('sha256') diff --git a/src/helper_sql.py b/src/helper_sql.py index 2b558f62..8bf6ce4d 100644 --- a/src/helper_sql.py +++ b/src/helper_sql.py @@ -1,7 +1,7 @@ """Helper Sql performs sql operations.""" import threading -import Queue +import queue as Queue sqlSubmitQueue = Queue.Queue() # SQLITE3 is so thread-unsafe that they won't even let you call it from different threads using your own locks. diff --git a/src/helper_startup.py b/src/helper_startup.py index 5d1614c7..0d3523e3 100644 --- a/src/helper_startup.py +++ b/src/helper_startup.py @@ -7,7 +7,7 @@ Helper Start performs all the startup operations. # pylint: disable=too-many-branches,too-many-statements from __future__ import print_function -import ConfigParser +import configparser import os import platform import sys @@ -27,7 +27,7 @@ StoreConfigFilesInSameDirectoryAsProgramByDefault = False def _loadTrustedPeer(): try: trustedPeer = BMConfigParser().get('bitmessagesettings', 'trustedpeer') - except ConfigParser.Error: + except configparser.Error: # This probably means the trusted peer wasn't specified so we # can just leave it as None return @@ -137,11 +137,12 @@ def loadConfig(): _loadTrustedPeer() - def updateConfig(): """Save the config""" config = BMConfigParser() - settingsversion = config.getint('bitmessagesettings', 'settingsversion') + # Used python2.7 + # settingsversion = int(BMConfigParser().get('bitmessagesettings', 'settingsversion') \ + settingsversion = BMConfigParser().safeGetInt('bitmessagesettings', 'settingsvesion') if settingsversion == 1: config.set('bitmessagesettings', 'socksproxytype', 'none') config.set('bitmessagesettings', 'sockshostname', 'localhost') diff --git a/src/highlevelcrypto.py b/src/highlevelcrypto.py index 02fb85ab..c235072c 100644 --- a/src/highlevelcrypto.py +++ b/src/highlevelcrypto.py @@ -13,10 +13,11 @@ from pyelliptic import arithmetic as a def makeCryptor(privkey): """Return a private pyelliptic.ECC() instance""" + # import pdb;pdb.set_trace() private_key = a.changebase(privkey, 16, 256, minlen=32) public_key = pointMult(private_key) privkey_bin = '\x02\xca\x00\x20' + private_key - pubkey_bin = '\x02\xca\x00\x20' + public_key[1:-32] + '\x00\x20' + public_key[-32:] + pubkey_bin = '\x02\xca\x00\x20' + public_key[1:-32].decode() + '\x00\x20' + public_key[-32:].decode() cryptor = pyelliptic.ECC(curve='secp256k1', privkey=privkey_bin, pubkey=pubkey_bin) return cryptor diff --git a/src/knownnodes.py b/src/knownnodes.py index ba21bac7..b30ca770 100644 --- a/src/knownnodes.py +++ b/src/knownnodes.py @@ -40,12 +40,13 @@ def json_serialize_knownnodes(output): Reorganize knownnodes dict and write it as JSON to output """ _serialized = [] - for stream, peers in knownNodes.iteritems(): - for peer, info in peers.iteritems(): + for stream, peers in iter(knownNodes.items()): + for peer, info in iter(peers.items()): info.update(rating=round(info.get('rating', 0), 2)) _serialized.append({ 'stream': stream, 'peer': peer._asdict(), 'info': info }) + # import pdb;pdb.set_trace() json.dump(_serialized, output, indent=4) @@ -85,7 +86,7 @@ def saveKnownNodes(dirName=None): if dirName is None: dirName = state.appdata with knownNodesLock: - with open(os.path.join(dirName, 'knownnodes.dat'), 'wb') as output: + with open(os.path.join(dirName, 'knownnodes.dat'), 'w') as output: json_serialize_knownnodes(output) diff --git a/src/l10n.py b/src/l10n.py index b3b16341..890f9491 100644 --- a/src/l10n.py +++ b/src/l10n.py @@ -64,20 +64,30 @@ else: if time_format != DEFAULT_TIME_FORMAT: try: #Check day names - for i in xrange(7): - unicode(time.strftime(time_format, (0, 0, 0, 0, 0, 0, i, 0, 0)), encoding) + 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 + # unicode(time.strftime(time_format, (0, 0, 0, 0, 0, 0, i, 0, 0)), encoding) + #this code for the python3 + (time.strftime(time_format, (0, 0, 0, 0, 0, 0, i, 0, 0))).encode() #Check month names - for i in xrange(1, 13): - unicode(time.strftime(time_format, (0, i, 0, 0, 0, 0, 0, 0, 0)), encoding) + 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 - unicode(time.strftime(time_format, (0, 0, 0, 11, 0, 0, 0, 0, 0)), encoding) - unicode(time.strftime(time_format, (0, 0, 0, 13, 0, 0, 0, 0, 0)), encoding) + (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 - unicode(time.strftime(time_format, (0, 0, 0, 0, 0, 0, 0, 0, 1)), encoding) + (time.strftime(time_format, (0, 0, 0, 0, 0, 0, 0, 0, 1))).encode() except: logger.exception('Could not decode locale formatted timestamp') time_format = DEFAULT_TIME_FORMAT encoding = DEFAULT_ENCODING + time_format = new_time_format def setlocale(category, newlocale): locale.setlocale(category, newlocale) diff --git a/src/messagetypes/__init__.py b/src/messagetypes/__init__.py index 53d23de7..ea3de756 100644 --- a/src/messagetypes/__init__.py +++ b/src/messagetypes/__init__.py @@ -4,7 +4,7 @@ src/messagetypes/__init__.py """ from importlib import import_module from os import path, listdir -from string import lower + try: from kivy.utils import platform except: diff --git a/src/multiqueue.py b/src/multiqueue.py index 8c64d33d..a41e2033 100644 --- a/src/multiqueue.py +++ b/src/multiqueue.py @@ -3,7 +3,7 @@ src/multiqueue.py ================= """ -import Queue +import queue as Queue from collections import deque import helper_random diff --git a/src/network/addrthread.py b/src/network/addrthread.py index 9f516e80..76f1c184 100644 --- a/src/network/addrthread.py +++ b/src/network/addrthread.py @@ -1,4 +1,4 @@ -import Queue +import queue as Queue from helper_threading import StoppableThread from network.connectionpool import BMConnectionPool diff --git a/src/network/advanceddispatcher.py b/src/network/advanceddispatcher.py index c8f125f0..bec91c60 100644 --- a/src/network/advanceddispatcher.py +++ b/src/network/advanceddispatcher.py @@ -30,7 +30,10 @@ class AdvancedDispatcher(asyncore.dispatcher): _buf_len = 131072 # 128kB def __init__(self, sock=None): - if not hasattr(self, '_map'): + # python 2 below condition is used + # if not hasattr(self, '_map'): + # python 3 below condition is used + if not '_map' in dir(self): asyncore.dispatcher.__init__(self, sock) self.read_buf = bytearray() self.write_buf = bytearray() diff --git a/src/network/asyncore_pollchoose.py b/src/network/asyncore_pollchoose.py index 3337c0f0..3137797c 100644 --- a/src/network/asyncore_pollchoose.py +++ b/src/network/asyncore_pollchoose.py @@ -767,10 +767,11 @@ class dispatcher: # references to the underlying socket object. def __getattr__(self, attr): try: + # import pdb;pdb.set_trace() retattr = getattr(self.socket, attr) except AttributeError: - raise AttributeError("%s instance has no attribute '%s'" - % (self.__class__.__name__, attr)) + raise AttributeError("{} instance has no attribute {}" + .format(self.__class__.__name__, attr)) else: msg = "%(me)s.%(attr)s is deprecated; use %(me)s.socket.%(attr)s " \ "instead" % {'me': self.__class__.__name__, 'attr': attr} @@ -788,7 +789,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 '%s: %s' % (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 0a2cdc7e..813d5b97 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -11,7 +11,7 @@ import time from binascii import hexlify import addresses -import connectionpool +import network.connectionpool import knownnodes import protocol import state @@ -26,9 +26,9 @@ from network.bmobject import ( BMObjectInvalidError, BMObjectAlreadyHaveError) from network.node import Node from network.proxy import ProxyError -from objectracker import missingObjects, ObjectTracker +from network.objectracker import missingObjects, ObjectTracker from queues import objectProcessorQueue, portCheckerQueue, invQueue, addrQueue -from randomtrackingdict import RandomTrackingDict +from network.randomtrackingdict import RandomTrackingDict class BMProtoError(ProxyError): diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index 4d16df49..a50d83b6 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -7,20 +7,19 @@ import re import socket import time -import asyncore_pollchoose as asyncore +import network.asyncore_pollchoose as asyncore import helper_random import knownnodes import protocol import state from bmconfigparser import BMConfigParser -from connectionchooser import chooseConnection +from network.connectionchooser import chooseConnection from debug import logger -from proxy import Proxy +from network.proxy import Proxy from singleton import Singleton -from tcp import ( - bootstrap, Socks4aBMConnection, Socks5BMConnection, - TCPConnection, TCPServer) -from udp import UDPSocket +from network.tcp import ( + TCPServer, Socks5BMConnection, Socks4aBMConnection, TCPConnection) +from network.udp import UDPSocket @Singleton diff --git a/src/network/dandelion.py b/src/network/dandelion.py index fa9081cb..abba16ba 100644 --- a/src/network/dandelion.py +++ b/src/network/dandelion.py @@ -7,7 +7,7 @@ from random import choice, sample, expovariate from threading import RLock from time import time -import connectionpool +import network.connectionpool import state from debug import logging from queues import invQueue diff --git a/src/network/downloadthread.py b/src/network/downloadthread.py index a4b58862..a09d0c1d 100644 --- a/src/network/downloadthread.py +++ b/src/network/downloadthread.py @@ -7,12 +7,12 @@ import time import addresses import helper_random import protocol -from dandelion import Dandelion +from network.dandelion import Dandelion from debug import logger from helper_threading import StoppableThread from inventory import Inventory from network.connectionpool import BMConnectionPool -from objectracker import missingObjects +from network.objectracker import missingObjects class DownloadThread(StoppableThread): diff --git a/src/network/http.py b/src/network/http.py index 8bba38ac..fdfe8370 100644 --- a/src/network/http.py +++ b/src/network/http.py @@ -2,7 +2,7 @@ import socket from advanceddispatcher import AdvancedDispatcher import asyncore_pollchoose as asyncore -from proxy import ProxyError +from network.proxy import ProxyError from socks5 import Socks5Connection, Socks5Resolver from socks4a import Socks4aConnection, Socks4aResolver diff --git a/src/network/invthread.py b/src/network/invthread.py index ad3a0764..1d2b790d 100644 --- a/src/network/invthread.py +++ b/src/network/invthread.py @@ -2,7 +2,7 @@ src/network/invthread.py ======================== """ -import Queue +import queue as Queue import random from time import time diff --git a/src/network/objectracker.py b/src/network/objectracker.py index a8e3292a..40a0f582 100644 --- a/src/network/objectracker.py +++ b/src/network/objectracker.py @@ -7,7 +7,7 @@ from threading import RLock import network.connectionpool from network.dandelion import Dandelion -from randomtrackingdict import RandomTrackingDict +from network.randomtrackingdict import RandomTrackingDict haveBloom = False diff --git a/src/network/proxy.py b/src/network/proxy.py index 479663d3..c3f13ad2 100644 --- a/src/network/proxy.py +++ b/src/network/proxy.py @@ -6,9 +6,9 @@ src/network/proxy.py import socket import time -import asyncore_pollchoose as asyncore +import network.asyncore_pollchoose as asyncore import state -from advanceddispatcher import AdvancedDispatcher +from network.advanceddispatcher import AdvancedDispatcher from bmconfigparser import BMConfigParser from debug import logger diff --git a/src/network/randomtrackingdict.py b/src/network/randomtrackingdict.py index 6c3300ab..16eb63e1 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: @@ -161,4 +161,4 @@ if __name__ == '__main__': a.append(time()) for x in range(len(a) - 1): - print "%i: %.3f" % (x, a[x + 1] - a[x]) + print("{}i: {}.3f".format(x, a[x + 1] - a[x])) diff --git a/src/network/receivequeuethread.py b/src/network/receivequeuethread.py index 5d8cbd37..f836b74b 100644 --- a/src/network/receivequeuethread.py +++ b/src/network/receivequeuethread.py @@ -1,5 +1,5 @@ import errno -import Queue +import queue as Queue import socket from debug import logger diff --git a/src/network/socks4a.py b/src/network/socks4a.py index f0b234f5..b92e53a5 100644 --- a/src/network/socks4a.py +++ b/src/network/socks4a.py @@ -6,7 +6,7 @@ src/network/socks4a.py import socket import struct -from proxy import Proxy, ProxyError, GeneralProxyError +from network.proxy import Proxy, ProxyError, GeneralProxyError class Socks4aError(ProxyError): @@ -141,4 +141,4 @@ class Socks4aResolver(Socks4a): PyBitmessage, a callback needs to be implemented which hasn't been done yet. """ - print "Resolved %s as %s" % (self.host, self.proxy_sock_name()) + print("Resolved {} as {}".format(self.host, self.proxy_sock_name())) diff --git a/src/network/socks5.py b/src/network/socks5.py index e0cb7202..8a7d922e 100644 --- a/src/network/socks5.py +++ b/src/network/socks5.py @@ -9,7 +9,7 @@ import socket import struct import state -from proxy import GeneralProxyError, Proxy, ProxyError +from network.proxy import GeneralProxyError, Proxy, ProxyError class Socks5AuthError(ProxyError): @@ -218,4 +218,4 @@ class Socks5Resolver(Socks5): To use this within PyBitmessage, a callback needs to be implemented which hasn't been done yet. """ - print "Resolved %s as %s" % (self.host, self.proxy_sock_name()) + print("Resolved {} as {}".format(self.host, self.proxy_sock_name())) diff --git a/src/network/stats.py b/src/network/stats.py index fedfbbc1..7b9a1e0d 100644 --- a/src/network/stats.py +++ b/src/network/stats.py @@ -6,7 +6,7 @@ import time import asyncore_pollchoose as asyncore from network.connectionpool import BMConnectionPool -from objectracker import missingObjects +from network.objectracker import missingObjects lastReceivedTimestamp = time.time() diff --git a/src/network/tcp.py b/src/network/tcp.py index da02df2f..31346e22 100644 --- a/src/network/tcp.py +++ b/src/network/tcp.py @@ -10,8 +10,8 @@ import socket import time import addresses -import asyncore_pollchoose as asyncore -import connectionpool +import network.asyncore_pollchoose as asyncore +import network.connectionpool import helper_random import knownnodes import protocol diff --git a/src/network/tls.py b/src/network/tls.py index 17b1ee1f..5f4be3b9 100644 --- a/src/network/tls.py +++ b/src/network/tls.py @@ -21,7 +21,12 @@ if sys.version_info >= (2, 7, 13): # this means TLSv1 or higher # in the future change to # ssl.PROTOCOL_TLS1.2 - sslProtocolVersion = ssl.PROTOCOL_TLS # pylint: disable=no-member + # 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 + try: + sslProtocolVersion = ssl.PROTOCOL_TLS # pylint: disable=no-member + except AttributeError: + sslProtocolVersion = ssl.PROTOCOL_SSLv23 elif sys.version_info >= (2, 7, 9): # this means any SSL/TLS. SSLv2 and 3 are excluded with an option after context is created sslProtocolVersion = ssl.PROTOCOL_SSLv23 diff --git a/src/network/udp.py b/src/network/udp.py index 01dc1f7b..c3e4ce44 100644 --- a/src/network/udp.py +++ b/src/network/udp.py @@ -7,9 +7,9 @@ import socket import state import protocol -from bmproto import BMProto +from network.bmproto import BMProto from debug import logger -from objectracker import ObjectTracker +from network.objectracker import ObjectTracker from queues import receiveDataQueue diff --git a/src/network/uploadthread.py b/src/network/uploadthread.py index 9b29ef0a..1b06af23 100644 --- a/src/network/uploadthread.py +++ b/src/network/uploadthread.py @@ -11,7 +11,7 @@ from helper_threading import StoppableThread from inventory import Inventory from network.connectionpool import BMConnectionPool from network.dandelion import Dandelion -from randomtrackingdict import RandomTrackingDict +from network.randomtrackingdict import RandomTrackingDict class UploadThread(StoppableThread): diff --git a/src/openclpow.py b/src/openclpow.py index eb91a07f..e56c04c1 100644 --- a/src/openclpow.py +++ b/src/openclpow.py @@ -107,9 +107,10 @@ def do_opencl_pow(hash, target): #initCL() if __name__ == "__main__": - target = 54227212183L + #in python3 I have change this 54227212183L to 54227212183 + target = 54227212183 initialHash = "3758f55b5a8d902fd3597e4ce6a2d3f23daff735f65d9698c270987f4e67ad590b93f3ffeba0ef2fd08a8dc2f87b68ae5a0dc819ab57f22ad2c4c9c8618a43b3".decode("hex") 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/pyelliptic/arithmetic.py b/src/pyelliptic/arithmetic.py index 95c85b93..43166006 100644 --- a/src/pyelliptic/arithmetic.py +++ b/src/pyelliptic/arithmetic.py @@ -39,7 +39,7 @@ def encode(val, base, minlen=0): code_string = get_code_string(base) result = "" while val > 0: - result = code_string[val % base] + result + result = code_string[round(val % base)] + result val /= base if len(result) < minlen: result = code_string[0] * (minlen - len(result)) + result @@ -53,7 +53,7 @@ def decode(string, base): string = string.lower() while string: result *= base - result += code_string.find(string[0]) + result += code_string.find(string.decode()[0]) string = string[1:] return result diff --git a/src/pyelliptic/cipher.py b/src/pyelliptic/cipher.py index d02b743a..e0bb9ac9 100644 --- a/src/pyelliptic/cipher.py +++ b/src/pyelliptic/cipher.py @@ -8,7 +8,7 @@ src/pyelliptic/cipher.py # Copyright (C) 2011 Yann GUIBET # See LICENSE for details. -from openssl import OpenSSL +from .openssl import OpenSSL # pylint: disable=redefined-builtin diff --git a/src/pyelliptic/ecc.py b/src/pyelliptic/ecc.py index 2de0bfe9..14adca42 100644 --- a/src/pyelliptic/ecc.py +++ b/src/pyelliptic/ecc.py @@ -12,9 +12,9 @@ src/pyelliptic/ecc.py from hashlib import sha512 from struct import pack, unpack -from cipher import Cipher -from hash import equals, hmac_sha256 -from openssl import OpenSSL +from pyelliptic.cipher import Cipher +from pyelliptic.hash import equals, hmac_sha256 +from pyelliptic.openssl import OpenSSL class ECC(object): @@ -129,7 +129,8 @@ class ECC(object): )) @staticmethod - def _decode_pubkey(pubkey): + def _decode_pubkey( pubkey): + pubkey = pubkey.encode() i = 0 curve = unpack('!H', pubkey[i:i + 2])[0] i += 2 diff --git a/src/pyelliptic/hash.py b/src/pyelliptic/hash.py index c21dd6a4..9ea8eb6d 100644 --- a/src/pyelliptic/hash.py +++ b/src/pyelliptic/hash.py @@ -7,7 +7,7 @@ src/pyelliptic/hash.py # Copyright (C) 2011 Yann GUIBET # See LICENSE for details. -from openssl import OpenSSL +from .openssl import OpenSSL # For python3 diff --git a/src/pyelliptic/openssl.py b/src/pyelliptic/openssl.py index 6c5c4a84..35e7933a 100644 --- a/src/pyelliptic/openssl.py +++ b/src/pyelliptic/openssl.py @@ -90,7 +90,7 @@ class _OpenSSL: """Build the wrapper""" self._lib = ctypes.CDLL(library) self._version, self._hexversion, self._cflags = get_version(self._lib) - self._libreSSL = self._version.startswith("LibreSSL") + self._libreSSL = (self._version).decode("utf-8").startswith("OpenSSL") self.pointer = ctypes.pointer self.c_int = ctypes.c_int @@ -674,6 +674,7 @@ def loadOpenSSL(): elif 'win32' in sys.platform or 'win64' in sys.platform: libdir.append(path.join(sys._MEIPASS, 'libeay32.dll')) else: + libdir.extend([ path.join(sys._MEIPASS, 'libcrypto.so'), path.join(sys._MEIPASS, 'libssl.so'), @@ -709,7 +710,7 @@ def loadOpenSSL(): pass elif 'win32' in sys.platform or 'win64' in sys.platform: libdir.append(find_library('libeay32')) - for library in libdir: + for library in libdir: try: OpenSSL = _OpenSSL(library) return diff --git a/src/queues.py b/src/queues.py index 7b6bbade..1bdcd9fb 100644 --- a/src/queues.py +++ b/src/queues.py @@ -1,4 +1,4 @@ -import Queue +import queue as Queue from class_objectProcessorQueue import ObjectProcessorQueue from multiqueue import MultiQueue diff --git a/src/shared.py b/src/shared.py index dacd4a5f..2a53452a 100644 --- a/src/shared.py +++ b/src/shared.py @@ -174,12 +174,11 @@ def reloadBroadcastSendersForWhichImWatching(): # Now, for all addresses, even version 2 addresses, # we should create Cryptor objects in a dictionary which we will # use to attempt to decrypt encrypted broadcast messages. - + # import pdb;pdb.set_trace() if addressVersionNumber <= 3: - privEncryptionKey = hashlib.sha512( - encodeVarint(addressVersionNumber) + - encodeVarint(streamNumber) + hash - ).digest()[:32] + privEncryptionKey = hashlib.sha512((encodeVarint(addressVersionNumber) \ + + encodeVarint(streamNumber) + hash)).digest()[:32] + # import pdb;pdb.set_trace() MyECSubscriptionCryptorObjects[hash] = \ highlevelcrypto.makeCryptor(hexlify(privEncryptionKey)) else: diff --git a/src/shutdown.py b/src/shutdown.py index f136ac75..418d3b37 100644 --- a/src/shutdown.py +++ b/src/shutdown.py @@ -1,5 +1,5 @@ import os -import Queue +import queue as Queue import threading import time diff --git a/src/singleinstance.py b/src/singleinstance.py index a495bea0..554ce826 100644 --- a/src/singleinstance.py +++ b/src/singleinstance.py @@ -75,7 +75,7 @@ class singleinstance: 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 @@ -94,11 +94,11 @@ class singleinstance: os.close(self.fd) else: fcntl.lockf(self.fp, fcntl.LOCK_UN) - except Exception, e: + except Exception as e: pass return - print "Cleaning up lockfile" + print ("Cleaning up lockfile") try: if sys.platform == 'win32': if hasattr(self, 'fd'): diff --git a/src/storage/filesystem.py b/src/storage/filesystem.py index 43ba03fc..74aee4fa 100644 --- a/src/storage/filesystem.py +++ b/src/storage/filesystem.py @@ -9,7 +9,7 @@ from threading import RLock import time from paths import lookupAppdataFolder -from storage import InventoryStorage, InventoryItem +from storage.storage import InventoryStorage, InventoryItem class FilesystemInventory(InventoryStorage): # pylint: disable=too-many-ancestors, abstract-method @@ -144,7 +144,7 @@ class FilesystemInventory(InventoryStorage): # pylint: disable=too-many-ances newInventory[streamNumber][hashId] = InventoryItem( objectType, streamNumber, None, expiresTime, tag) except KeyError: - print "error loading %s" % (hexlify(hashId)) + print ("error loading {}".format((hexlify(hashId)))) self._inventory = newInventory # for i, v in self._inventory.items(): # print "loaded stream: %s, %i items" % (i, len(v)) diff --git a/src/storage/sqlite.py b/src/storage/sqlite.py index 0c2b4afa..54913830 100644 --- a/src/storage/sqlite.py +++ b/src/storage/sqlite.py @@ -6,6 +6,7 @@ import sqlite3 import time from threading import RLock + from helper_sql import sqlQuery, SqlBulkExecute, sqlExecute from storage import InventoryStorage, InventoryItem diff --git a/src/suravata.py b/src/suravata.py deleted file mode 100644 index 18541989..00000000 --- a/src/suravata.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -# Import the libraries. -import pdb;pdb.set_trace() -import pydenticon100000000000000000000000 -import hashlib -# Set-up some test data. -users = ["alice", "bob", "eve", "dave"] -# Set-up a list of foreground colours (taken from Sigil). -foreground = ["rgb(45,79,255)", - "rgb(254,180,44)", - "rgb(226,121,234)", - "rgb(30,179,253)", - "rgb(232,77,65)", - "rgb(49,203,115)", - "rgb(141,69,170)"] -# Set-up a background colour (taken from Sigil). -background = "rgb(224,224,224)" -# Set-up the padding (top, bottom, left, right) in pixels. -padding = (20, 20, 20, 20) -# Instantiate a generator that will create 5x5 block identicons using SHA1 -# digest. -generator = pydenticon.Generator(5, 5, digest=hashlib.sha1, foreground=foreground, background=background) - -# identicon_ascii = generator.generate("john.doe@example.com", 200, 200, -# output_format="ascii") - -# print identicon_ascii -for user in users: - identicon = generator.generate(user, 200, 200, padding=padding, output_format="png") - filename = user + ".png" - with open(filename, "wb") as f: - f.write(identicon) \ No newline at end of file diff --git a/src/tests/core.py b/src/tests/core.py index b01c6b69..9021e4ff 100644 --- a/src/tests/core.py +++ b/src/tests/core.py @@ -5,7 +5,7 @@ Tests for core and those that do not work outside import os import pickle # nosec -import Queue +import queue as Queue import random # nosec import string import time diff --git a/src/tr.py b/src/tr.py index 5ce623cd..577354cc 100644 --- a/src/tr.py +++ b/src/tr.py @@ -46,11 +46,11 @@ 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 + 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 if n is None: return QtGui.QApplication.translate(context, text) From 42ee9d910b205028e5c6127245f632dddd27439b Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Tue, 1 Oct 2019 20:19:03 +0530 Subject: [PATCH 2/4] launch py3 convert app for first phase(need to do more checks) --- src/bitmessagekivy/identiconGeneration.py | 4 +- src/bitmessagekivy/main.kv | 236 +++++++--------------- src/bitmessagekivy/mpybit.py | 50 ++--- src/bitmessagemain.py | 5 +- src/helper_startup.py | 7 +- src/highlevelcrypto.py | 5 +- src/knownnodes.py | 3 +- src/network/connectionpool.py | 9 +- src/network/stats.py | 7 +- src/pyelliptic/arithmetic.py | 18 +- src/pyelliptic/ecc.py | 37 ++-- src/storage/sqlite.py | 2 +- 12 files changed, 167 insertions(+), 216 deletions(-) diff --git a/src/bitmessagekivy/identiconGeneration.py b/src/bitmessagekivy/identiconGeneration.py index a5dcf3d0..14a31403 100644 --- a/src/bitmessagekivy/identiconGeneration.py +++ b/src/bitmessagekivy/identiconGeneration.py @@ -46,13 +46,13 @@ def generate_hash(string): # make input case insensitive string = str.lower(string) hash_object = hashlib.md5(str.encode(string)) - print hash_object.hexdigest() + 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." + print("Error: Please enter a string as an argument.") def random_color(hash_string): diff --git a/src/bitmessagekivy/main.kv b/src/bitmessagekivy/main.kv index be6f76e9..18f1ac6a 100644 --- a/src/bitmessagekivy/main.kv +++ b/src/bitmessagekivy/main.kv @@ -1,43 +1,38 @@ -#:import Toolbar kivymd.toolbar.Toolbar +#:import MDToolbar kivymd.uix.toolbar.MDToolbar #:import ThemeManager kivymd.theming.ThemeManager -#:import MDNavigationDrawer kivymd.navigationdrawer.MDNavigationDrawer -#:import NavigationLayout kivymd.navigationdrawer.NavigationLayout -#:import NavigationDrawerDivider kivymd.navigationdrawer.NavigationDrawerDivider -#:import NavigationDrawerToolbar kivymd.navigationdrawer.NavigationDrawerToolbar -#:import NavigationDrawerSubheader kivymd.navigationdrawer.NavigationDrawerSubheader -#:import MDCheckbox kivymd.selectioncontrols.MDCheckbox -#:import MDSwitch kivymd.selectioncontrols.MDSwitch -#:import MDList kivymd.list.MDList -#:import OneLineListItem kivymd.list.OneLineListItem -#:import TwoLineListItem kivymd.list.TwoLineListItem -#:import ThreeLineListItem kivymd.list.ThreeLineListItem -#:import OneLineAvatarListItem kivymd.list.OneLineAvatarListItem -#:import OneLineIconListItem kivymd.list.OneLineIconListItem -#:import OneLineAvatarIconListItem kivymd.list.OneLineAvatarIconListItem -#:import MDTextField kivymd.textfields.MDTextField -#:import MDSpinner kivymd.spinner.MDSpinner -#:import MDCard kivymd.card.MDCard -#:import MDSeparator kivymd.card.MDSeparator -#:import MDDropdownMenu kivymd.menu.MDDropdownMenu +#:import MDNavigationDrawer kivymd.uix.navigationdrawer.MDNavigationDrawer +#:import NavigationLayout kivymd.uix.navigationdrawer.NavigationLayout +#:import NavigationDrawerDivider kivymd.uix.navigationdrawer.NavigationDrawerDivider +#:import NavigationDrawerToolbar kivymd.uix.navigationdrawer.NavigationDrawerToolbar +#:import NavigationDrawerSubheader kivymd.uix.navigationdrawer.NavigationDrawerSubheader +#:import MDCheckbox kivymd.uix.selectioncontrol.MDCheckbox +#:import MDSwitch kivymd.uix.selectioncontrol.MDSwitch +#:import MDList kivymd.uix.list.MDList +#:import OneLineListItem kivymd.uix.list.OneLineListItem +#:import TwoLineListItem kivymd.uix.list.TwoLineListItem +#:import ThreeLineListItem kivymd.uix.list.ThreeLineListItem +#:import OneLineAvatarListItem kivymd.uix.list.OneLineAvatarListItem +#:import OneLineIconListItem kivymd.uix.list.OneLineIconListItem +#:import OneLineAvatarIconListItem kivymd.uix.list.OneLineAvatarIconListItem +#:import MDTextField kivymd.uix.textfield.MDTextField +#:import MDSpinner kivymd.uix.spinner.MDSpinner +#:import MDCard kivymd.uix.card.MDCard +#:import MDSeparator kivymd.uix.card.MDSeparator +#:import MDDropdownMenu kivymd.uix.menu.MDDropdownMenu #:import get_color_from_hex kivy.utils.get_color_from_hex #:import colors kivymd.color_definitions.colors -#:import SmartTile kivymd.grid.SmartTile -#:import MDSlider kivymd.slider.MDSlider -#:import MDTabbedPanel kivymd.tabs.MDTabbedPanel -#:import MDTab kivymd.tabs.MDTab -#:import MDProgressBar kivymd.progressbar.MDProgressBar -#:import MDAccordion kivymd.accordion.MDAccordion -#:import MDAccordionItem kivymd.accordion.MDAccordionItem -#:import MDAccordionSubItem kivymd.accordion.MDAccordionSubItem -#:import MDThemePicker kivymd.theme_picker.MDThemePicker -#:import MDBottomNavigation kivymd.tabs.MDBottomNavigation -#:import MDBottomNavigationItem kivymd.tabs.MDBottomNavigationItem -#:import MDFloatingActionButton kivymd.button.MDFloatingActionButton +#:import MDSlider kivymd.uix.slider.MDSlider +#:import MDTabs kivymd.uix.tab.MDTabs +#:import MDProgressBar kivymd.uix.progressbar.MDProgressBar +#:import MDAccordion kivymd.uix.accordion.MDAccordion +#:import MDAccordionItem kivymd.uix.accordion.MDAccordionItem +#:import MDAccordionSubItem kivymd.uix.accordion.MDAccordionSubItem +#:import MDFloatingActionButton kivymd.uix.button.MDFloatingActionButton #:import Factory kivy.factory.Factory -#:import MDTextButton kivymd.button.MDTextButton +#:import MDTextButton kivymd.uix.button.MDTextButton #:import FadeTransition kivy.uix.screenmanager.FadeTransition -#:import MDScrollViewRefreshLayout kivymd.refreshlayout.MDScrollViewRefreshLayout +#:import MDScrollViewRefreshLayout kivymd.uix.refreshlayout.MDScrollViewRefreshLayout #:set color_button (0.784, 0.443, 0.216, 1) # brown #:set color_button_pressed (0.659, 0.522, 0.431, 1) # darker brown @@ -176,7 +171,7 @@ NavigationLayout: BoxLayout: id: box_layout orientation: 'vertical' - Toolbar: + MDToolbar: id: toolbar title: app.current_address_label() opacity: 1 if app.addressexist() else 0 @@ -342,7 +337,7 @@ NavigationLayout: size_hint: .6, .35 height: dp(40) MDLabel: - font_style: 'Title' + font_style: 'H4' text: root.available_credits font_size: '13sp' color: (1,1,1,1) @@ -423,7 +418,7 @@ NavigationLayout: height: dp(40) on_press: root.reset_composer() MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'reset' font_size: '13sp' color: (1,1,1,1) @@ -521,7 +516,7 @@ NavigationLayout: height: dp(40) on_press: app.root.ids.scr_mngr.current = 'random' MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'proceed' font_size: '13sp' color: (1,1,1,1) @@ -566,7 +561,7 @@ NavigationLayout: on_release: root.generateaddress(app) opposite_colors: True MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'next' font_size: '13sp' color: (1,1,1,1) @@ -594,7 +589,7 @@ NavigationLayout: size_hint: .6, .55 height: dp(40) MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Server' font_size: '13sp' color: (1,1,1,1) @@ -607,7 +602,7 @@ NavigationLayout: size_hint: .6, .55 height: dp(40) MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Import or export data' font_size: '13sp' color: (1,1,1,1) @@ -620,7 +615,7 @@ NavigationLayout: size_hint: .6, .55 height: dp(40) MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Restart background service' font_size: '13sp' color: (1,1,1,1) @@ -698,20 +693,20 @@ NavigationLayout: size: self.size MDLabel: size_hint_y: None - font_style: 'Headline' + font_style: 'Subtitle1' theme_text_color: 'Primary' text: 'Platinum' halign: 'center' color: 1,1,1,1 MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: 'We provide subscriptions for proof of work calculation for first month. ' halign: 'center' color: 1,1,1,1 MDLabel: id: free_pak - font_style: 'Headline' + font_style: 'Subtitle1' theme_text_color: 'Primary' text: '€ 50.0' halign: 'center' @@ -727,7 +722,7 @@ NavigationLayout: height: dp(40) on_press: root.get_available_credits(self) MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Get Free Credits' font_size: '13sp' color: (0,0,0,1) @@ -744,19 +739,19 @@ NavigationLayout: size: self.size MDLabel: size_hint_y: None - font_style: 'Headline' + font_style: 'Subtitle1' theme_text_color: 'Primary' text: 'Silver' halign: 'center' color: 1,1,1,1 MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: 'We provide for proof of work calculation for six month. ' halign: 'center' color: 1,1,1,1 MDLabel: - font_style: 'Headline' + font_style: 'Subtitle1' theme_text_color: 'Primary' text: '€ 100.0' halign: 'center' @@ -771,7 +766,7 @@ NavigationLayout: size_hint: 1, None height: dp(40) MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Get Monthly Credits' font_size: '13sp' color: (0,0,0,1) @@ -788,19 +783,19 @@ NavigationLayout: size: self.size MDLabel: size_hint_y: None - font_style: 'Headline' + font_style: 'Subtitle1' theme_text_color: 'Primary' text: 'Gold' halign: 'center' color: 1,1,1,1 MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: 'We provide for proof of work calculation for 1years. ' halign: 'center' color: 1,1,1,1 MDLabel: - font_style: 'Headline' + font_style: 'Subtitle1' theme_text_color: 'Primary' text: '€ 500.0' halign: 'center' @@ -815,7 +810,7 @@ NavigationLayout: size_hint: 1, None height: dp(40) MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Get Yearly Credits' font_size: '13sp' color: (0,0,0,1) @@ -862,7 +857,7 @@ NavigationLayout: on_release: root.savecontact() MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Save' font_size: '13sp' color: (1,1,1,1) @@ -873,7 +868,7 @@ NavigationLayout: on_press: root.dismiss() on_press: root.close_pop() MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Cancel' font_size: '13sp' color: (1,1,1,1) @@ -882,7 +877,7 @@ NavigationLayout: size_hint: 2, None height: dp(40) MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Scan QR code' font_size: '13sp' color: (1,1,1,1) @@ -891,93 +886,8 @@ NavigationLayout: : name: 'networkstat' - MDTabbedPanel: - id: tab_panel - tab_display_mode:'text' - - MDTab: - name: 'connections' - text: "Total connections" - ScrollView: - do_scroll_x: False - MDList: - id: ml - size_hint_y: None - height: dp(200) - OneLineListItem: - text: "Total Connections" - BoxLayout: - AnchorLayout: - MDRaisedButton: - size_hint: .6, .35 - height: dp(40) - MDLabel: - font_style: 'Title' - text: root.text_variable_1 - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - MDTab: - name: 'processes' - text: 'Processes' - ScrollView: - do_scroll_x: False - MDList: - id: ml - size_hint_y: None - height: dp(500) - OneLineListItem: - text: "person-to-person" - BoxLayout: - AnchorLayout: - MDRaisedButton: - size_hint: .7, .6 - height: dp(40) - MDLabel: - font_style: 'Title' - text: root.text_variable_2 - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - OneLineListItem: - text: "Brodcast" - BoxLayout: - AnchorLayout: - MDRaisedButton: - size_hint: .7, .6 - height: dp(40) - MDLabel: - font_style: 'Title' - text: root.text_variable_3 - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - OneLineListItem: - text: "publickeys" - BoxLayout: - AnchorLayout: - MDRaisedButton: - size_hint: .7, .6 - height: dp(40) - MDLabel: - font_style: 'Title' - text: root.text_variable_4 - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - OneLineListItem: - text: "objects" - BoxLayout: - AnchorLayout: - MDRaisedButton: - size_hint: .7, .6 - height: dp(40) - MDLabel: - font_style: 'Title' - text: root.text_variable_5 - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' + Label: + text:"surbhi" : name: 'mailDetail' @@ -989,31 +899,31 @@ NavigationLayout: height: dp(500) + self.minimum_height padding: dp(32) MDLabel: - font_style: 'Headline' + font_style: 'Subtitle1' theme_text_color: 'Primary' text: root.subject halign: 'left' font_size: '20sp' CopyTextBtn: MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: "From: " + root.from_addr halign: 'left' CopyTextBtn: MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: "To: " + root.to_addr halign: 'left' CopyTextBtn: MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: root.status halign: 'left' MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: root.message halign: 'left' @@ -1072,25 +982,25 @@ NavigationLayout: spacing:dp(25) MDLabel: id: myaddr_label - font_style: 'Title' + font_style: 'H4' theme_text_color: 'Primary' text: "Label" font_size: '17sp' halign: 'left' MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: root.address_label font_size: '15sp' halign: 'left' MDLabel: - font_style: 'Title' + font_style: 'H4' theme_text_color: 'Primary' text: "Address" font_size: '17sp' halign: 'left' MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: root.address font_size: '15sp' @@ -1104,7 +1014,7 @@ NavigationLayout: height: dp(40) on_press: root.send_message_from() MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Send message from' font_size: '13sp' color: (1,1,1,1) @@ -1116,7 +1026,7 @@ NavigationLayout: on_press: app.root.ids.scr_mngr.current = 'showqrcode' on_press: app.root.ids.sc15.qrdisplay() MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Show QR code' font_size: '13sp' color: (1,1,1,1) @@ -1127,7 +1037,7 @@ NavigationLayout: on_press: root.dismiss() on_press: root.close_pop() MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Cancel' font_size: '13sp' color: (1,1,1,1) @@ -1151,14 +1061,14 @@ NavigationLayout: orientation: 'vertical' spacing:dp(20) MDLabel: - font_style: 'Title' + font_style: 'H4' theme_text_color: 'Primary' text: "Label" font_size: '17sp' halign: 'left' MDTextField: id: add_label - font_style: 'Subhead' + font_style: 'H4' font_size: '15sp' halign: 'left' text: root.address_label @@ -1166,13 +1076,13 @@ NavigationLayout: required: True helper_text_mode: "on_error" MDLabel: - font_style: 'Title' + font_style: 'H4' theme_text_color: 'Primary' text: "Address" font_size: '17sp' halign: 'left' MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: root.address font_size: '15sp' @@ -1186,7 +1096,7 @@ NavigationLayout: height: dp(40) on_press: root.send_message_to() MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Send message to' font_size: '13sp' color: (1,1,1,1) @@ -1197,7 +1107,7 @@ NavigationLayout: font_size: '10sp' on_press: root.update_addbook_label(root.address) MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Save' font_size: '13sp' color: (1,1,1,1) @@ -1208,7 +1118,7 @@ NavigationLayout: on_press: root.dismiss() on_press: root.close_pop() MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Cancel' font_size: '13sp' color: (1,1,1,1) diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 70f51b29..6f7b1cc6 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -35,27 +35,31 @@ from kivy.uix.screenmanager import Screen from kivy.uix.spinner import Spinner from kivy.uix.textinput import TextInput from kivy.utils import platform -import kivy_helper_search -from kivymd.button import MDIconButton -from kivymd.dialog import MDDialog -from kivymd.label import MDLabel -from kivymd.list import ( +from bitmessagekivy import kivy_helper_search +from kivymd.uix.dialog import MDDialog +from kivymd.uix.button import MDIconButton +from kivymd.uix.label import MDLabel +from kivymd.uix.list import ( ILeftBody, ILeftBodyTouch, IRightBodyTouch, TwoLineAvatarIconListItem, TwoLineListItem) -from kivymd.navigationdrawer import ( +from kivymd.uix.navigationdrawer import ( MDNavigationDrawer, NavigationDrawerHeaderBase) -from kivymd.selectioncontrols import MDCheckbox +from kivymd.uix.selectioncontrol import MDCheckbox from kivymd.theming import ThemeManager import queues from semaphores import kivyuisignaler import state -from uikivysignaler import UIkivySignaler -import identiconGeneration +from bitmessagekivy.uikivysignaler import UIkivySignaler +# pylint: disable=unused-argument, too-few-public-methods, import-error + +from bitmessagekivy import identiconGeneration +import os +from kivy.core.clipboard import Clipboard # pylint: disable=unused-argument, too-few-public-methods @@ -89,7 +93,7 @@ class Inbox(Screen): def init_ui(self, dt=0): """Clock Schdule for method inbox accounts.""" self.inboxaccounts() - print dt + print (dt) def inboxaccounts(self): """Load inbox accounts.""" @@ -329,7 +333,7 @@ class AddressBook(Screen): def init_ui(self, dt=0): """Clock Schdule for method AddressBook.""" self.loadAddresslist(None, 'All', '') - print dt + print (dt) def loadAddresslist(self, account, where="", what=""): """Clock Schdule for method AddressBook.""" @@ -428,7 +432,7 @@ class SelectableLabel(RecycleDataViewBehavior, Label): """Respond to the selection of items in the view.""" self.selected = is_selected if is_selected: - print "selection changed to {0}".format(rv.data[index]) + print("selection changed to {0}".format(rv.data[index])) rv.parent.txt_input.text = rv.parent.txt_input.text.replace( rv.parent.txt_input.text, rv.data[index]['text']) @@ -455,7 +459,7 @@ class DropDownWidget(BoxLayout): subject = self.ids.subject.text.encode('utf-8').strip() message = self.ids.body.text.encode('utf-8').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: @@ -483,12 +487,12 @@ class DropDownWidget(BoxLayout): toAddress = addBMIfNotPresent(toAddress) 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 @@ -523,7 +527,7 @@ class DropDownWidget(BoxLayout): toLabel = '' queues.workerQueue.put(('sendmessage', toAddress)) - print "sqlExecute successfully #######################" + print ("sqlExecute successfully #######################") self.parent.parent.current = 'inbox' state.in_composer = True navApp.back_press() @@ -718,7 +722,7 @@ class Sent(Screen): def init_ui(self, dt=0): """Clock Schdule for method sent accounts.""" self.sentaccounts() - print dt + print(dt) def sentaccounts(self): """Load sent accounts.""" @@ -1088,7 +1092,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(): @@ -1179,7 +1183,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() @@ -1633,7 +1637,7 @@ class Draft(Screen): def init_ui(self, dt=0): """Clock Schdule for method draft accounts.""" self.sentaccounts() - print dt + print (dt) def sentaccounts(self): """Load draft accounts.""" @@ -1801,7 +1805,7 @@ class Allmails(Screen): def init_ui(self, dt=0): """Clock Schdule for method all mails.""" self.mailaccounts() - print dt + print (dt) def mailaccounts(self): """Load all mails for account.""" diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index e066dd06..6e8206ef 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -200,6 +200,7 @@ class Main: # pylint: disable=no-init, old-style-class from plugins.plugin import get_plugin try: proxyconfig_start = time.time() + import pdb;pdb.set_trace if not get_plugin('proxyconfig', name=proxy_type)(config): raise TypeError except TypeError: @@ -358,7 +359,7 @@ class Main: # pylint: disable=no-init, old-style-class # Not needed if objproc disabled if state.enableObjProc: shared.reloadMyAddressHashes() - shared.reloadBroadcastSendersForWhichImWatching() + # shared.reloadBroadcastSendersForWhichImWatching() # API is also objproc dependent if config.safeGetBoolean('bitmessagesettings', 'apienabled'): import api # pylint: disable=relative-import @@ -373,7 +374,7 @@ class Main: # pylint: disable=no-init, old-style-class asyncoreThread = BMNetworkThread() asyncoreThread.daemon = True asyncoreThread.start() - for i in range(config.getint('threads', 'receive')): + for i in range(config.safeGet('threads', 'receive')): receiveQueueThread = ReceiveQueueThread(i) receiveQueueThread.daemon = True receiveQueueThread.start() diff --git a/src/helper_startup.py b/src/helper_startup.py index 0d3523e3..f0457638 100644 --- a/src/helper_startup.py +++ b/src/helper_startup.py @@ -25,6 +25,7 @@ StoreConfigFilesInSameDirectoryAsProgramByDefault = False def _loadTrustedPeer(): + trustedPeer = '' try: trustedPeer = BMConfigParser().get('bitmessagesettings', 'trustedpeer') except configparser.Error: @@ -32,13 +33,15 @@ def _loadTrustedPeer(): # can just leave it as None return try: - host, port = trustedPeer.split(':') + # import pdb;pdb.set_trace() + if trustedPeer != None: + host, port = trustedPeer.split(':') + state.trustedPeer = state.Peer(host, int(port)) except ValueError: sys.exit( 'Bad trustedpeer config setting! It should be set as' ' trustedpeer=:' ) - state.trustedPeer = state.Peer(host, int(port)) def loadConfig(): diff --git a/src/highlevelcrypto.py b/src/highlevelcrypto.py index c235072c..648e11a7 100644 --- a/src/highlevelcrypto.py +++ b/src/highlevelcrypto.py @@ -16,8 +16,9 @@ def makeCryptor(privkey): # import pdb;pdb.set_trace() private_key = a.changebase(privkey, 16, 256, minlen=32) public_key = pointMult(private_key) - privkey_bin = '\x02\xca\x00\x20' + private_key - pubkey_bin = '\x02\xca\x00\x20' + public_key[1:-32].decode() + '\x00\x20' + public_key[-32:].decode() + privkey_bin = '\x02\xca\x00\x20'.encode('utf-8') + private_key + pubkey_bin = '\x02\xca\x00\x20'.encode('utf-8') + public_key[1:-32] + '\x00\x20'.encode('utf-8') + public_key[-32:] + import pdb;pdb.set_trace() cryptor = pyelliptic.ECC(curve='secp256k1', privkey=privkey_bin, pubkey=pubkey_bin) return cryptor diff --git a/src/knownnodes.py b/src/knownnodes.py index b30ca770..35d105bc 100644 --- a/src/knownnodes.py +++ b/src/knownnodes.py @@ -55,6 +55,7 @@ def json_deserialize_knownnodes(source): Read JSON from source and make knownnodes dict """ global knownNodesActual # pylint: disable=global-statement + # import pdb;pdb.set_trace() for node in json.load(source): peer = node['peer'] info = node['info'] @@ -107,7 +108,7 @@ def createDefaultKnownNodes(): def readKnownNodes(): try: - with open(state.appdata + 'knownnodes.dat', 'rb') as source: + with open(state.appdata + 'knownnodes.dat', 'r') as source: with knownNodesLock: try: json_deserialize_knownnodes(source) diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index a50d83b6..313f3924 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -274,10 +274,15 @@ class BMConnectionPool(object): continue self.lastSpawned = time.time() + + print('++++++++++++++++++++++++++++++++++++++++++') + print('self.inboundConnections.values()-{}'.format(self.inboundConnections.values())) + print('self.outboundConnections.values() -{}'.format(self.outboundConnections.values())) + print('+++++++++++++++++++++++++++++++++++++++++++') else: for i in ( - self.inboundConnections.values() + - self.outboundConnections.values() + list(self.inboundConnections.values()) + + list(self.outboundConnections.values()) ): # FIXME: rating will be increased after next connection i.handle_close() diff --git a/src/network/stats.py b/src/network/stats.py index 7b9a1e0d..31ffcbf3 100644 --- a/src/network/stats.py +++ b/src/network/stats.py @@ -4,7 +4,7 @@ src/network/stats.py """ import time -import asyncore_pollchoose as asyncore +from network import asyncore_pollchoose as asyncore from network.connectionpool import BMConnectionPool from network.objectracker import missingObjects @@ -20,8 +20,9 @@ currentSentSpeed = 0 def connectedHostsList(): """List of all the connected hosts""" retval = [] - for i in BMConnectionPool().inboundConnections.values() + \ - BMConnectionPool().outboundConnections.values(): + # import pdb;pdb.set_trace() + for i in list(BMConnectionPool().inboundConnections.values()) + \ + list(BMConnectionPool().outboundConnections.values()): if not i.fullyEstablished: continue try: diff --git a/src/pyelliptic/arithmetic.py b/src/pyelliptic/arithmetic.py index 43166006..7b7a477b 100644 --- a/src/pyelliptic/arithmetic.py +++ b/src/pyelliptic/arithmetic.py @@ -30,7 +30,9 @@ def get_code_string(base): elif base == 58: return "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" elif base == 256: - return ''.join([chr(x) for x in range(256)]) + '''raw_unicode_escape is used because in the python3 after range(161) its genreate the' + the speical character so avoiding that function we have used the raw_unicode method ''' + return ''.join([chr(x) for x in range(256)]).encode('raw_unicode_escape') else: raise ValueError("Invalid base!") @@ -38,9 +40,16 @@ def get_code_string(base): def encode(val, base, minlen=0): code_string = get_code_string(base) result = "" + result = str.encode(result) + count = 0 + # import pdb;pdb.set_trace() while val > 0: - result = code_string[round(val % base)] + result - val /= base + count += 1 + # import pdb;pdb.set_trace() + result = code_string[int(val) % base:int(val) % base + 1] + result + # print('the value of the result-{}'.format(result)) + val = int(val / base) + # import pdb;pdb.set_trace() if len(result) < minlen: result = code_string[0] * (minlen - len(result)) + result return result @@ -48,10 +57,12 @@ def encode(val, base, minlen=0): def decode(string, base): code_string = get_code_string(base) + string.decode() result = 0 if base == 16: string = string.lower() while string: + # import pdb;pdb.set_trace() result *= base result += code_string.find(string.decode()[0]) string = string[1:] @@ -59,6 +70,7 @@ def decode(string, base): def changebase(string, frm, to, minlen=0): + # import pdb;pdb.set_trace() return encode(decode(string, frm), to, minlen) diff --git a/src/pyelliptic/ecc.py b/src/pyelliptic/ecc.py index 14adca42..63748287 100644 --- a/src/pyelliptic/ecc.py +++ b/src/pyelliptic/ecc.py @@ -74,11 +74,13 @@ class ECC(object): if curve != curve2: raise Exception("Bad ECC keys ...") self.curve = curve + import pdb;pdb.set_trace() self._set_keys(pubkey_x, pubkey_y, raw_privkey) else: self.privkey, self.pubkey_x, self.pubkey_y = self._generate() def _set_keys(self, pubkey_x, pubkey_y, privkey): + import pdb;pdb.set_trace() if self.raw_check_key(privkey, pubkey_x, pubkey_y) < 0: self.pubkey_x = None self.pubkey_y = None @@ -114,7 +116,7 @@ class ECC(object): pack('!H', len(self.pubkey_x)), self.pubkey_x, pack('!H', len(self.pubkey_y)), - self.pubkey_y, + self.pubkey_y, )) def get_privkey(self): @@ -129,27 +131,37 @@ class ECC(object): )) @staticmethod - def _decode_pubkey( pubkey): - pubkey = pubkey.encode() + def _decode_pubkey(pubkey): + # pubkey = pubkey.encode() + import pdb;pdb.set_trace() i = 0 - curve = unpack('!H', pubkey[i:i + 2])[0] + # curve = unpack('!H', pubkey[i:i + 2])[0] + curve = pack('!s', pubkey[i:i + 1])[0] + i += 2 - tmplen = unpack('!H', pubkey[i:i + 2])[0] + # tmplen = unpack('!H', pubkey[i:i + 2])[0] + tmplen = pack('!s', pubkey[i:i + 1])[0] i += 2 pubkey_x = pubkey[i:i + tmplen] - i += tmplen - tmplen = unpack('!H', pubkey[i:i + 2])[0] - i += 2 + # i += tmplen + i += int(tmplen / 3) + # tmplen = unpack('!H', pubkey[i:i + 2])[0] + tmplen = pack('!s', pubkey[i:i + 1])[0] + # i += 2 pubkey_y = pubkey[i:i + tmplen] - i += tmplen - return curve, pubkey_x, pubkey_y, i + # i += tmplen + return curve, pubkey_x, pubkey_y, int(i) @staticmethod def _decode_privkey(privkey): i = 0 - curve = unpack('!H', privkey[i:i + 2])[0] + # import pdb;pdb.set_trace() + # curve = unpack('!H', privkey[i:i + 2])[0] + curve = pack('!s', privkey[i:i + 1])[0] + i += 2 - tmplen = unpack('!H', privkey[i:i + 2])[0] + # tmplen = unpack('!H', privkey[i:i + 2])[0] + tmplen = pack('!s', privkey[i:i + 1])[0] i += 2 privkey = privkey[i:i + tmplen] i += tmplen @@ -276,6 +288,7 @@ class ECC(object): return self.raw_check_key(raw_privkey, pubkey_x, pubkey_y, curve) def raw_check_key(self, privkey, pubkey_x, pubkey_y, curve=None): + import pdb;pdb.set_trace() """Check key validity, key is supplied as binary data""" # pylint: disable=too-many-branches if curve is None: diff --git a/src/storage/sqlite.py b/src/storage/sqlite.py index 54913830..03265fd1 100644 --- a/src/storage/sqlite.py +++ b/src/storage/sqlite.py @@ -8,7 +8,7 @@ from threading import RLock from helper_sql import sqlQuery, SqlBulkExecute, sqlExecute -from storage import InventoryStorage, InventoryItem +from storage.storage import InventoryStorage, InventoryItem class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors From c813f679ae82fc4b802c896b5d5f75cd8e21700f Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Thu, 3 Oct 2019 20:27:22 +0530 Subject: [PATCH 3/4] Solved bmconfigparser python3 incompatibility issue and removed unrequired comment and line of code which are added during python3 plotting --- src/addresses.py | 1 - src/bitmessagekivy/mpybit.py | 3 ++- src/bitmessagemain.py | 1 - src/bmconfigparser.py | 6 ++++-- src/helper_startup.py | 2 +- src/highlevelcrypto.py | 2 -- src/knownnodes.py | 2 -- src/network/asyncore_pollchoose.py | 1 - src/network/connectionpool.py | 2 +- src/network/dandelion.py | 18 +++++++++--------- src/network/downloadthread.py | 4 ++-- src/network/stats.py | 1 - src/network/uploadthread.py | 4 ++-- src/pyelliptic/arithmetic.py | 6 ------ src/pyelliptic/ecc.py | 27 +++++++-------------------- src/shared.py | 2 -- 16 files changed, 28 insertions(+), 54 deletions(-) diff --git a/src/addresses.py b/src/addresses.py index 4d200332..a55fc415 100644 --- a/src/addresses.py +++ b/src/addresses.py @@ -191,7 +191,6 @@ def decodeAddress(address): return status, 0, 0, '' # after converting to hex, the string will be prepended # with a 0x and appended with a L - # import pdb;pdb.set_trace() hexdata = hex(integer)[2:] if len(hexdata) % 2 != 0: diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 6f7b1cc6..aa55d35b 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -93,7 +93,7 @@ class Inbox(Screen): def init_ui(self, dt=0): """Clock Schdule for method inbox accounts.""" self.inboxaccounts() - print (dt) + print(dt) def inboxaccounts(self): """Load inbox accounts.""" @@ -309,6 +309,7 @@ class MyAddress(Screen): self.init_ui() self.ids.refresh_layout.refresh_done() self.tick = 0 + Clock.schedule_once(refresh_callback, 1) @staticmethod diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 6e8206ef..dcf03118 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -200,7 +200,6 @@ class Main: # pylint: disable=no-init, old-style-class from plugins.plugin import get_plugin try: proxyconfig_start = time.time() - import pdb;pdb.set_trace if not get_plugin('proxyconfig', name=proxy_type)(config): raise TypeError except TypeError: diff --git a/src/bmconfigparser.py b/src/bmconfigparser.py index 6f5660e0..d05787d9 100644 --- a/src/bmconfigparser.py +++ b/src/bmconfigparser.py @@ -125,10 +125,12 @@ class BMConfigParser(configparser.ConfigParser): try: if not self.validate( section, option, - configparser.ConfigParser.get(self, section, option) + self[section][option] ): try: newVal = BMConfigDefaults[section][option] + except configparser.NoSectionError: + continue except KeyError: continue configparser.ConfigParser.set( @@ -159,7 +161,7 @@ class BMConfigParser(configparser.ConfigParser): def validate(self, section, option, value): try: - return getattr(self, 'validate_%s_%s' % (section, option))(value) + return getattr(self, 'validate_{}_{}'.format(section, option))(value) except AttributeError: return True diff --git a/src/helper_startup.py b/src/helper_startup.py index f0457638..110110b6 100644 --- a/src/helper_startup.py +++ b/src/helper_startup.py @@ -33,7 +33,7 @@ def _loadTrustedPeer(): # can just leave it as None return try: - # import pdb;pdb.set_trace() + if trustedPeer != None: host, port = trustedPeer.split(':') state.trustedPeer = state.Peer(host, int(port)) diff --git a/src/highlevelcrypto.py b/src/highlevelcrypto.py index 648e11a7..512c55b5 100644 --- a/src/highlevelcrypto.py +++ b/src/highlevelcrypto.py @@ -13,12 +13,10 @@ from pyelliptic import arithmetic as a def makeCryptor(privkey): """Return a private pyelliptic.ECC() instance""" - # import pdb;pdb.set_trace() private_key = a.changebase(privkey, 16, 256, minlen=32) public_key = pointMult(private_key) privkey_bin = '\x02\xca\x00\x20'.encode('utf-8') + private_key pubkey_bin = '\x02\xca\x00\x20'.encode('utf-8') + public_key[1:-32] + '\x00\x20'.encode('utf-8') + public_key[-32:] - import pdb;pdb.set_trace() cryptor = pyelliptic.ECC(curve='secp256k1', privkey=privkey_bin, pubkey=pubkey_bin) return cryptor diff --git a/src/knownnodes.py b/src/knownnodes.py index 35d105bc..4052e3ae 100644 --- a/src/knownnodes.py +++ b/src/knownnodes.py @@ -46,7 +46,6 @@ def json_serialize_knownnodes(output): _serialized.append({ 'stream': stream, 'peer': peer._asdict(), 'info': info }) - # import pdb;pdb.set_trace() json.dump(_serialized, output, indent=4) @@ -55,7 +54,6 @@ def json_deserialize_knownnodes(source): Read JSON from source and make knownnodes dict """ global knownNodesActual # pylint: disable=global-statement - # import pdb;pdb.set_trace() for node in json.load(source): peer = node['peer'] info = node['info'] diff --git a/src/network/asyncore_pollchoose.py b/src/network/asyncore_pollchoose.py index 3137797c..1c93283f 100644 --- a/src/network/asyncore_pollchoose.py +++ b/src/network/asyncore_pollchoose.py @@ -767,7 +767,6 @@ class dispatcher: # references to the underlying socket object. def __getattr__(self, attr): try: - # import pdb;pdb.set_trace() retattr = getattr(self.socket, attr) except AttributeError: raise AttributeError("{} instance has no attribute {}" diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index 313f3924..adc8cf51 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -236,7 +236,7 @@ class BMConnectionPool(object): except ValueError: Proxy.onion_proxy = None established = sum( - 1 for c in self.outboundConnections.values() + 1 for c in list(self.outboundConnections.values()) if (c.connected and c.fullyEstablished)) pending = len(self.outboundConnections) - established if established < BMConfigParser().safeGetInt( diff --git a/src/network/dandelion.py b/src/network/dandelion.py index abba16ba..e51df5d1 100644 --- a/src/network/dandelion.py +++ b/src/network/dandelion.py @@ -99,12 +99,12 @@ class Dandelion(): # pylint: disable=old-style-class with self.lock: if len(self.stem) < MAX_STEMS: self.stem.append(connection) - for k in (k for k, v in self.nodeMap.iteritems() if v is None): + for k in (k for k, v in iter(self.nodeMap.items()) if v is None): self.nodeMap[k] = connection - for k, v in { - k: v for k, v in self.hashMap.iteritems() + for k, v in iter({ + k: v for k, v in iter(self.hashMap.items()) if v.child is None - }.iteritems(): + }).items(): self.hashMap[k] = Stem( connection, v.stream, self.poissonTimeout()) invQueue.put((v.stream, k, v.child)) @@ -120,13 +120,13 @@ class Dandelion(): # pylint: disable=old-style-class self.stem.remove(connection) # active mappings to pointing to the removed node for k in ( - k for k, v in self.nodeMap.iteritems() if v == connection + k for k, v in iter(self.nodeMap.items()) if v == connection ): self.nodeMap[k] = None - for k, v in { - k: v for k, v in self.hashMap.iteritems() + for k, v in iter({ + k: v for k, v in iter(self.hashMap.items()) if v.child == connection - }.iteritems(): + }).items(): self.hashMap[k] = Stem( None, v.stream, self.poissonTimeout()) @@ -167,7 +167,7 @@ class Dandelion(): # pylint: disable=old-style-class with self.lock: deadline = time() toDelete = [ - [v.stream, k, v.child] for k, v in self.hashMap.iteritems() + [v.stream, k, v.child] for k, v in iter(self.hashMap.items()) if v.timeout < deadline ] diff --git a/src/network/downloadthread.py b/src/network/downloadthread.py index a09d0c1d..561fd342 100644 --- a/src/network/downloadthread.py +++ b/src/network/downloadthread.py @@ -32,7 +32,7 @@ class DownloadThread(StoppableThread): """Expire pending downloads eventually""" deadline = time.time() - DownloadThread.requestExpires try: - toDelete = [k for k, v in missingObjects.iteritems() if v < deadline] + toDelete = [k for k, v in iter(missingObjects.items()) if v < deadline] except RuntimeError: pass else: @@ -46,7 +46,7 @@ class DownloadThread(StoppableThread): # Choose downloading peers randomly connections = [ x for x in - BMConnectionPool().inboundConnections.values() + BMConnectionPool().outboundConnections.values() + list(BMConnectionPool().inboundConnections.values()) + list(BMConnectionPool().outboundConnections.values()) if x.fullyEstablished] helper_random.randomshuffle(connections) try: diff --git a/src/network/stats.py b/src/network/stats.py index 31ffcbf3..1a57629d 100644 --- a/src/network/stats.py +++ b/src/network/stats.py @@ -20,7 +20,6 @@ currentSentSpeed = 0 def connectedHostsList(): """List of all the connected hosts""" retval = [] - # import pdb;pdb.set_trace() for i in list(BMConnectionPool().inboundConnections.values()) + \ list(BMConnectionPool().outboundConnections.values()): if not i.fullyEstablished: diff --git a/src/network/uploadthread.py b/src/network/uploadthread.py index 1b06af23..a0329c83 100644 --- a/src/network/uploadthread.py +++ b/src/network/uploadthread.py @@ -26,8 +26,8 @@ class UploadThread(StoppableThread): while not self._stopped: uploaded = 0 # Choose downloading peers randomly - connections = [x for x in BMConnectionPool().inboundConnections.values() + - BMConnectionPool().outboundConnections.values() if x.fullyEstablished] + connections = [x for x in list(BMConnectionPool().inboundConnections.values()) + + list(BMConnectionPool().outboundConnections.values()) if x.fullyEstablished] helper_random.randomshuffle(connections) for i in connections: now = time.time() diff --git a/src/pyelliptic/arithmetic.py b/src/pyelliptic/arithmetic.py index 7b7a477b..f5106768 100644 --- a/src/pyelliptic/arithmetic.py +++ b/src/pyelliptic/arithmetic.py @@ -42,14 +42,10 @@ def encode(val, base, minlen=0): result = "" result = str.encode(result) count = 0 - # import pdb;pdb.set_trace() while val > 0: count += 1 - # import pdb;pdb.set_trace() result = code_string[int(val) % base:int(val) % base + 1] + result - # print('the value of the result-{}'.format(result)) val = int(val / base) - # import pdb;pdb.set_trace() if len(result) < minlen: result = code_string[0] * (minlen - len(result)) + result return result @@ -62,7 +58,6 @@ def decode(string, base): if base == 16: string = string.lower() while string: - # import pdb;pdb.set_trace() result *= base result += code_string.find(string.decode()[0]) string = string[1:] @@ -70,7 +65,6 @@ def decode(string, base): def changebase(string, frm, to, minlen=0): - # import pdb;pdb.set_trace() return encode(decode(string, frm), to, minlen) diff --git a/src/pyelliptic/ecc.py b/src/pyelliptic/ecc.py index 63748287..f0cba579 100644 --- a/src/pyelliptic/ecc.py +++ b/src/pyelliptic/ecc.py @@ -74,13 +74,11 @@ class ECC(object): if curve != curve2: raise Exception("Bad ECC keys ...") self.curve = curve - import pdb;pdb.set_trace() self._set_keys(pubkey_x, pubkey_y, raw_privkey) else: self.privkey, self.pubkey_x, self.pubkey_y = self._generate() def _set_keys(self, pubkey_x, pubkey_y, privkey): - import pdb;pdb.set_trace() if self.raw_check_key(privkey, pubkey_x, pubkey_y) < 0: self.pubkey_x = None self.pubkey_y = None @@ -132,35 +130,25 @@ class ECC(object): @staticmethod def _decode_pubkey(pubkey): - # pubkey = pubkey.encode() - import pdb;pdb.set_trace() i = 0 - # curve = unpack('!H', pubkey[i:i + 2])[0] - curve = pack('!s', pubkey[i:i + 1])[0] - + curve = unpack('!H', pubkey[i:i + 2])[0] i += 2 - # tmplen = unpack('!H', pubkey[i:i + 2])[0] - tmplen = pack('!s', pubkey[i:i + 1])[0] + tmplen = unpack('!H', pubkey[i:i + 2])[0] i += 2 pubkey_x = pubkey[i:i + tmplen] - # i += tmplen + i += tmplen i += int(tmplen / 3) - # tmplen = unpack('!H', pubkey[i:i + 2])[0] - tmplen = pack('!s', pubkey[i:i + 1])[0] - # i += 2 + tmplen = unpack('!H', pubkey[i:i + 2])[0] + i += 2 pubkey_y = pubkey[i:i + tmplen] - # i += tmplen + i += tmplen return curve, pubkey_x, pubkey_y, int(i) @staticmethod def _decode_privkey(privkey): i = 0 - # import pdb;pdb.set_trace() - # curve = unpack('!H', privkey[i:i + 2])[0] - curve = pack('!s', privkey[i:i + 1])[0] - + curve = unpack('!H', privkey[i:i + 2])[0] i += 2 - # tmplen = unpack('!H', privkey[i:i + 2])[0] tmplen = pack('!s', privkey[i:i + 1])[0] i += 2 privkey = privkey[i:i + tmplen] @@ -288,7 +276,6 @@ class ECC(object): return self.raw_check_key(raw_privkey, pubkey_x, pubkey_y, curve) def raw_check_key(self, privkey, pubkey_x, pubkey_y, curve=None): - import pdb;pdb.set_trace() """Check key validity, key is supplied as binary data""" # pylint: disable=too-many-branches if curve is None: diff --git a/src/shared.py b/src/shared.py index 2a53452a..60c35096 100644 --- a/src/shared.py +++ b/src/shared.py @@ -174,11 +174,9 @@ def reloadBroadcastSendersForWhichImWatching(): # Now, for all addresses, even version 2 addresses, # we should create Cryptor objects in a dictionary which we will # use to attempt to decrypt encrypted broadcast messages. - # import pdb;pdb.set_trace() if addressVersionNumber <= 3: privEncryptionKey = hashlib.sha512((encodeVarint(addressVersionNumber) \ + encodeVarint(streamNumber) + hash)).digest()[:32] - # import pdb;pdb.set_trace() MyECSubscriptionCryptorObjects[hash] = \ highlevelcrypto.makeCryptor(hexlify(privEncryptionKey)) else: From 95990d8deff7fa205dfde9b37cc260f8258eeb8d Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Wed, 9 Oct 2019 18:21:29 +0530 Subject: [PATCH 4/4] Solved new address creations issues --- src/addresses.py | 5 +++-- src/bitmessagekivy/main.kv | 24 ------------------------ src/class_addressGenerator.py | 8 ++++---- src/class_singleCleaner.py | 4 ++-- src/network/bmproto.py | 2 +- src/network/connectionpool.py | 12 ++++++------ src/network/dandelion.py | 6 +++--- src/network/tcp.py | 2 +- src/protocol.py | 4 ++-- src/pyelliptic/arithmetic.py | 9 +++++---- src/shared.py | 2 +- 11 files changed, 28 insertions(+), 50 deletions(-) diff --git a/src/addresses.py b/src/addresses.py index a55fc415..c0903841 100644 --- a/src/addresses.py +++ b/src/addresses.py @@ -158,7 +158,7 @@ def encodeAddress(version, stream, ripe): raise Exception( 'Programming error in encodeAddress: The length of' ' a given ripe hash was not 20.') - ripe = ripe.lstrip('\x00') + ripe = ripe.lstrip('\x00'.encode('utf-8')) storedBinaryData = encodeVarint(version) + encodeVarint(stream) + ripe @@ -264,7 +264,8 @@ def decodeAddress(address): return 'ripetoolong', 0, 0, '' elif len(embeddedRipeData) < 4: return 'ripetooshort', 0, 0, '' - x00string = '\x00' * (20 - len(embeddedRipeData)) + x00string = '\x00'.encode('utf-8') * (20 - len(embeddedRipeData)) + return status, addressVersionNumber, streamNumber, \ x00string + embeddedRipeData diff --git a/src/bitmessagekivy/main.kv b/src/bitmessagekivy/main.kv index 18f1ac6a..93d12393 100644 --- a/src/bitmessagekivy/main.kv +++ b/src/bitmessagekivy/main.kv @@ -334,7 +334,6 @@ NavigationLayout: BoxLayout: AnchorLayout: MDRaisedButton: - size_hint: .6, .35 height: dp(40) MDLabel: font_style: 'H4' @@ -383,7 +382,6 @@ NavigationLayout: txt_input: txt_input rv: rv size : (890, 60) - size_hint: 1,1 MyTextInput: id: txt_input size_hint_y: None @@ -414,7 +412,6 @@ NavigationLayout: spacing:50 AnchorLayout: MDRaisedButton: - size_hint: 1, None height: dp(40) on_press: root.reset_composer() MDLabel: @@ -512,7 +509,6 @@ NavigationLayout: BoxLayout: AnchorLayout: MDRaisedButton: - size_hint: .5, .35 height: dp(40) on_press: app.root.ids.scr_mngr.current = 'random' MDLabel: @@ -556,7 +552,6 @@ NavigationLayout: BoxLayout: AnchorLayout: MDRaisedButton: - size_hint: .5, None height: dp(40) on_release: root.generateaddress(app) opposite_colors: True @@ -586,7 +581,6 @@ NavigationLayout: BoxLayout: AnchorLayout: MDRaisedButton: - size_hint: .6, .55 height: dp(40) MDLabel: font_style: 'H4' @@ -599,7 +593,6 @@ NavigationLayout: BoxLayout: AnchorLayout: MDRaisedButton: - size_hint: .6, .55 height: dp(40) MDLabel: font_style: 'H4' @@ -612,7 +605,6 @@ NavigationLayout: BoxLayout: AnchorLayout: MDRaisedButton: - size_hint: .6, .55 height: dp(40) MDLabel: font_style: 'H4' @@ -633,7 +625,6 @@ NavigationLayout: BoxLayout: MDCheckbox: id: chkbox - size_hint: None, None size: dp(48), dp(64) active: True MDLabel: @@ -718,7 +709,6 @@ NavigationLayout: Rectangle: pos: self.pos size: self.size - size_hint: 1, None height: dp(40) on_press: root.get_available_credits(self) MDLabel: @@ -763,7 +753,6 @@ NavigationLayout: Rectangle: pos: self.pos size: self.size - size_hint: 1, None height: dp(40) MDLabel: font_style: 'H4' @@ -807,7 +796,6 @@ NavigationLayout: Rectangle: pos: self.pos size: self.size - size_hint: 1, None height: dp(40) MDLabel: font_style: 'H4' @@ -819,7 +807,6 @@ NavigationLayout: : id: popup - size_hint : (None,None) height: 2*(label.height + address.height) + 10 width :app.window_size[0] - app.window_size[0]/10 title: 'add contact\'s' @@ -852,7 +839,6 @@ NavigationLayout: orientation: 'horizontal' MDRaisedButton: id: save_addr - size_hint: 1.5, None height: dp(40) on_release: root.savecontact() @@ -863,7 +849,6 @@ NavigationLayout: color: (1,1,1,1) halign: 'center' MDRaisedButton: - size_hint: 1.5, None height: dp(40) on_press: root.dismiss() on_press: root.close_pop() @@ -874,7 +859,6 @@ NavigationLayout: color: (1,1,1,1) halign: 'center' MDRaisedButton: - size_hint: 2, None height: dp(40) MDLabel: font_style: 'H4' @@ -965,7 +949,6 @@ 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 background: './images/popup.jpeg' @@ -1010,7 +993,6 @@ NavigationLayout: spacing:5 orientation: 'horizontal' MDRaisedButton: - size_hint: 2, None height: dp(40) on_press: root.send_message_from() MDLabel: @@ -1020,7 +1002,6 @@ NavigationLayout: color: (1,1,1,1) halign: 'center' MDRaisedButton: - size_hint: 1.5, None height: dp(40) on_press: root.dismiss() on_press: app.root.ids.scr_mngr.current = 'showqrcode' @@ -1032,7 +1013,6 @@ NavigationLayout: color: (1,1,1,1) halign: 'center' MDRaisedButton: - size_hint: 1.5, None height: dp(40) on_press: root.dismiss() on_press: root.close_pop() @@ -1045,7 +1025,6 @@ NavigationLayout: : id: addbook_popup - size_hint : (None,None) height: 4*(add_label.height) width :app.window_size[0] - app.window_size[0]/10 background: './images/popup.jpeg' @@ -1092,7 +1071,6 @@ NavigationLayout: spacing:5 orientation: 'horizontal' MDRaisedButton: - size_hint: 2, None height: dp(40) on_press: root.send_message_to() MDLabel: @@ -1102,7 +1080,6 @@ NavigationLayout: color: (1,1,1,1) halign: 'center' MDRaisedButton: - size_hint: 1.5, None height: dp(40) font_size: '10sp' on_press: root.update_addbook_label(root.address) @@ -1113,7 +1090,6 @@ NavigationLayout: color: (1,1,1,1) halign: 'center' MDRaisedButton: - size_hint: 1.5, None height: dp(40) on_press: root.dismiss() on_press: root.close_pop() diff --git a/src/class_addressGenerator.py b/src/class_addressGenerator.py index b5c0cbcd..e4bf1d13 100644 --- a/src/class_addressGenerator.py +++ b/src/class_addressGenerator.py @@ -29,7 +29,6 @@ class addressGenerator(StoppableThread): super(addressGenerator, self).stopThread() def run(self): - while state.shutdown == 0: queueValue = queues.addressGeneratorQueue.get() nonceTrialsPerByte = 0 @@ -134,7 +133,7 @@ class addressGenerator(StoppableThread): ripe = RIPEMD160Hash(sha.digest()).digest() if ( ripe[:numberOfNullBytesDemandedOnFrontOfRipeHash] == - '\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash + '\x00'.encode('utf-8') * numberOfNullBytesDemandedOnFrontOfRipeHash ): break logger.info( @@ -151,19 +150,20 @@ class addressGenerator(StoppableThread): # The user must have a pretty fast computer. # time.time() - startTime equaled zero. pass + address = encodeAddress( addressVersionNumber, streamNumber, ripe) # An excellent way for us to store our keys # is in Wallet Import Format. Let us convert now. # https://en.bitcoin.it/wiki/Wallet_import_format - privSigningKey = '\x80' + potentialPrivSigningKey + privSigningKey = '\x80'.encode('utf-8') + potentialPrivSigningKey checksum = hashlib.sha256(hashlib.sha256( privSigningKey).digest()).digest()[0:4] privSigningKeyWIF = arithmetic.changebase( privSigningKey + checksum, 256, 58) - privEncryptionKey = '\x80' + potentialPrivEncryptionKey + privEncryptionKey = '\x80'.encode('utf-8') + potentialPrivEncryptionKey checksum = hashlib.sha256(hashlib.sha256( privEncryptionKey).digest()).digest()[0:4] privEncryptionKeyWIF = arithmetic.changebase( diff --git a/src/class_singleCleaner.py b/src/class_singleCleaner.py index 9a2916c7..de7508ef 100644 --- a/src/class_singleCleaner.py +++ b/src/class_singleCleaner.py @@ -143,8 +143,8 @@ class singleCleaner(StoppableThread): # inv/object tracking for connection in \ - BMConnectionPool().inboundConnections.values() + \ - BMConnectionPool().outboundConnections.values(): + list(BMConnectionPool().inboundConnections.values()) + \ + list(BMConnectionPool().outboundConnections.values()): connection.clean() # discovery tracking diff --git a/src/network/bmproto.py b/src/network/bmproto.py index 813d5b97..cfd6672f 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -86,7 +86,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): """Process incoming header""" self.magic, self.command, self.payloadLength, self.checksum = \ protocol.Header.unpack(self.read_buf[:protocol.Header.size]) - self.command = self.command.rstrip('\x00') + self.command = self.command.rstrip('\x00'.encode('utf-8')) if self.magic != 0xE9BEB4D9: # skip 1 byte in order to sync self.set_state("bm_header", length=1) diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index adc8cf51..aad45e59 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -328,8 +328,8 @@ class BMConnectionPool(object): reaper = [] for i in ( - self.inboundConnections.values() + - self.outboundConnections.values() + list(self.inboundConnections.values()) + + list(self.outboundConnections.values()) ): minTx = time.time() - 20 if i.fullyEstablished: @@ -342,10 +342,10 @@ class BMConnectionPool(object): time.time() - i.lastTx) i.set_state("close") for i in ( - self.inboundConnections.values() + - self.outboundConnections.values() + - self.listeningSockets.values() + - self.udpSockets.values() + list(self.inboundConnections.values()) + + list(self.outboundConnections.values()) + + list(self.listeningSockets.values()) + + list(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 e51df5d1..2c23da5d 100644 --- a/src/network/dandelion.py +++ b/src/network/dandelion.py @@ -7,7 +7,7 @@ from random import choice, sample, expovariate from threading import RLock from time import time -import network.connectionpool +from network import connectionpool import state from debug import logging from queues import invQueue @@ -182,8 +182,8 @@ class Dandelion(): # pylint: disable=old-style-class try: # random two connections self.stem = sample( - connectionpool.BMConnectionPool( - ).outboundConnections.values(), MAX_STEMS) + list(connectionpool.BMConnectionPool( + ).outboundConnections.values()), MAX_STEMS) # not enough stems available except ValueError: self.stem = connectionpool.BMConnectionPool( diff --git a/src/network/tcp.py b/src/network/tcp.py index 31346e22..3ed19462 100644 --- a/src/network/tcp.py +++ b/src/network/tcp.py @@ -362,7 +362,7 @@ class TCPServer(AdvancedDispatcher): """TCP connection server for Bitmessage protocol""" def __init__(self, host='127.0.0.1', port=8444): - if not hasattr(self, '_map'): + if not '_map' in dir(self): AdvancedDispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() diff --git a/src/protocol.py b/src/protocol.py index 1031b950..abb310db 100644 --- a/src/protocol.py +++ b/src/protocol.py @@ -94,9 +94,9 @@ def isBitSetWithinBitfield(fourByteString, n): def encodeHost(host): """Encode a given host to be used in low-level socket operations""" if host.find('.onion') > -1: - return '\xfd\x87\xd8\x7e\xeb\x43' + base64.b32decode(host.split(".")[0], True) + return '\xfd\x87\xd8\x7e\xeb\x43'.encode('utf-8') + base64.b32decode(host.split(".")[0], True) elif host.find(':') == -1: - return '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + \ + return '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode('utf-8') + \ socket.inet_aton(host) return socket.inet_pton(socket.AF_INET6, host) diff --git a/src/pyelliptic/arithmetic.py b/src/pyelliptic/arithmetic.py index f5106768..1c9dcec4 100644 --- a/src/pyelliptic/arithmetic.py +++ b/src/pyelliptic/arithmetic.py @@ -39,11 +39,13 @@ def get_code_string(base): def encode(val, base, minlen=0): code_string = get_code_string(base) - result = "" - result = str.encode(result) + result = '' + # result = str.encode(result) count = 0 while val > 0: count += 1 + print(f'code_string[int(val) % base:int(val) % base + 1] -{code_string[int(val) % base:int(val) % base + 1]}') + print(f'result-{result}') result = code_string[int(val) % base:int(val) % base + 1] + result val = int(val / base) if len(result) < minlen: @@ -53,13 +55,12 @@ def encode(val, base, minlen=0): def decode(string, base): code_string = get_code_string(base) - string.decode() result = 0 if base == 16: string = string.lower() while string: result *= base - result += code_string.find(string.decode()[0]) + result += code_string.find(string[0]) string = string[1:] return result diff --git a/src/shared.py b/src/shared.py index 60c35096..8cd86e6c 100644 --- a/src/shared.py +++ b/src/shared.py @@ -125,7 +125,7 @@ def reloadMyAddressHashes(): keyfileSecure = checkSensitiveFilePermissions(state.appdata + 'keys.dat') hasEnabledKeys = False for addressInKeysFile in BMConfigParser().addresses(): - isEnabled = BMConfigParser().getboolean(addressInKeysFile, 'enabled') + isEnabled = BMConfigParser().safeGet(addressInKeysFile, 'enabled') if isEnabled: hasEnabledKeys = True # status