initial commit for python forward porting

This commit is contained in:
jai.s 2019-09-26 19:38:19 +05:30
parent fad7f3aeb4
commit afb368e770
No known key found for this signature in database
GPG Key ID: 360CFA25EFC67D12
52 changed files with 187 additions and 183 deletions

View File

@ -180,7 +180,6 @@ def decodeAddress(address):
data (almost certainly a ripe hash)) data (almost certainly a ripe hash))
""" """
# pylint: disable=too-many-return-statements,too-many-statements,too-many-return-statements,too-many-branches # pylint: disable=too-many-return-statements,too-many-statements,too-many-return-statements,too-many-branches
address = str(address).strip() address = str(address).strip()
if address[:3] == 'BM-': if address[:3] == 'BM-':
@ -192,7 +191,8 @@ def decodeAddress(address):
return status, 0, 0, '' return status, 0, 0, ''
# after converting to hex, the string will be prepended # after converting to hex, the string will be prepended
# with a 0x and appended with a L # 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: if len(hexdata) % 2 != 0:
hexdata = '0' + hexdata hexdata = '0' + hexdata
@ -248,7 +248,7 @@ def decodeAddress(address):
embeddedRipeData embeddedRipeData
elif len(embeddedRipeData) == 18: elif len(embeddedRipeData) == 18:
return status, addressVersionNumber, streamNumber, \ return status, addressVersionNumber, streamNumber, \
'\x00\x00' + embeddedRipeData '\x00\x00'.encode('utf-8') + embeddedRipeData
elif len(embeddedRipeData) < 18: elif len(embeddedRipeData) < 18:
return 'ripetooshort', 0, 0, '' return 'ripetooshort', 0, 0, ''
elif len(embeddedRipeData) > 20: elif len(embeddedRipeData) > 20:

View File

@ -984,6 +984,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods
def build(self): def build(self):
"""Method builds the widget.""" """Method builds the widget."""
import os
main_widget = Builder.load_file( main_widget = Builder.load_file(
os.path.join(os.path.dirname(__file__), 'main.kv')) os.path.join(os.path.dirname(__file__), 'main.kv'))
self.nav_drawer = Navigatorss() self.nav_drawer = Navigatorss()

View File

@ -179,13 +179,13 @@ def signal_handler(signum, frame):
if shared.thisapp.daemon or not state.enableGUI: if shared.thisapp.daemon or not state.enableGUI:
shutdown.doCleanShutdown() shutdown.doCleanShutdown()
else: 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): 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: if line:
print ' %s' % line.strip() print (' {}'.format(line.strip()))
print 'Unfortunately you cannot use Ctrl+C when running the UI \ print('Unfortunately you cannot use Ctrl+C when running the UI \
because the UI captures the signal.' because the UI captures the signal.')
class Main: # pylint: disable=no-init, old-style-class class Main: # pylint: disable=no-init, old-style-class
@ -282,7 +282,7 @@ class Main: # pylint: disable=no-init, old-style-class
if daemon: if daemon:
with shared.printLock: 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.daemonize()
self.setSignalHandler() self.setSignalHandler()
@ -405,7 +405,7 @@ class Main: # pylint: disable=no-init, old-style-class
if state.curses: if state.curses:
if not depends.check_curses(): if not depends.check_curses():
sys.exit() sys.exit()
print 'Running with curses' print('Running with curses')
import bitmessagecurses import bitmessagecurses
bitmessagecurses.runwrapper() bitmessagecurses.runwrapper()
@ -498,10 +498,9 @@ class Main: # pylint: disable=no-init, old-style-class
# signal.signal(signal.SIGINT, signal.SIG_DFL) # signal.signal(signal.SIGINT, signal.SIG_DFL)
@staticmethod @staticmethod
def usage(): def usage(self):
"""After passing argument, method displays the usages""" print('Usage: ' + sys.argv[0] + ' [OPTIONS]')
print 'Usage: ' + sys.argv[0] + ' [OPTIONS]' print ('''
print '''
Options: Options:
-h, --help show this help message and exit -h, --help show this help message and exit
-c, --curses use curses (text mode) interface -c, --curses use curses (text mode) interface
@ -509,12 +508,12 @@ Options:
-t, --test dryrun, make testing -t, --test dryrun, make testing
All parameters are optional. All parameters are optional.
''' ''')
def stop(self): # pylint: disable=no-self-use def stop(self): # pylint: disable=no-self-use
"""Method helps to stop the Bitmessage Deamon""" """Method helps to stop the Bitmessage Deamon"""
with shared.printLock: with shared.printLock:
print 'Stopping Bitmessage Deamon.' print('Stopping Bitmessage Deamon.')
shutdown.doCleanShutdown() shutdown.doCleanShutdown()
# ..todo: nice function but no one is using this # ..todo: nice function but no one is using this

View File

@ -1,5 +1,5 @@
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from Queue import Queue from queue.Queue import Queue
from time import time from time import time
class BMStatusBar(QtGui.QStatusBar): class BMStatusBar(QtGui.QStatusBar):

View File

@ -2,7 +2,7 @@
BMConfigParser class definition and default configuration settings BMConfigParser class definition and default configuration settings
""" """
import ConfigParser import configparser
import shutil import shutil
import os import os
from datetime import datetime from datetime import datetime
@ -42,35 +42,35 @@ BMConfigDefaults = {
@Singleton @Singleton
class BMConfigParser(ConfigParser.SafeConfigParser): class BMConfigParser(configparser.ConfigParser):
"""Singleton class inherited from ConfigParser.SafeConfigParser """Singleton class inherited from ConfigParsedadfeConfigParser
with additional methods specific to bitmessage config.""" with additional methods specific to bitmessage config."""
_temp = {} _temp = {}
def set(self, section, option, value=None): def set(self, section, option, value=None):
if self._optcre is self.OPTCRE or value: 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") raise TypeError("option values must be strings")
if not self.validate(section, option, value): if not self.validate(section, option, value):
raise ValueError("Invalid value %s" % 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): def get(self, section, option, raw=False, variables=None):
try: try:
if section == "bitmessagesettings" and option == "timeformat": if section == "bitmessagesettings" and option == "timeformat":
return ConfigParser.ConfigParser.get( return configparser.ConfigParser.get(
self, section, option, raw, variables) self, section, option, raw=True, vars=variables)
try: try:
return self._temp[section][option] return self._temp[section][option]
except KeyError: except KeyError:
pass pass
return ConfigParser.ConfigParser.get( return configparser.ConfigParser.get(
self, section, option, True, variables) self, section, option, raw=True, vars=variables)
except ConfigParser.InterpolationError: except configparser.InterpolationError:
return ConfigParser.ConfigParser.get( return configparser.ConfigParser.get(
self, section, option, True, variables) self, section, option, raw=True, vars=variables)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) as e: except (configparser.NoSectionError, configparser.NoOptionError) as e:
try: try:
return BMConfigDefaults[section][option] return BMConfigDefaults[section][option]
except (KeyError, ValueError, AttributeError): except (KeyError, ValueError, AttributeError):
@ -84,49 +84,56 @@ class BMConfigParser(ConfigParser.SafeConfigParser):
self._temp[section] = {option: value} self._temp[section] = {option: value}
def safeGetBoolean(self, section, field): def safeGetBoolean(self, section, field):
config = configparser.ConfigParser()
try: try:
return self.getboolean(section, field) #Used in the python2.7
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError, # return self.getboolean(section, field)
#Used in the python3.5.2
return config.getboolean(section, field)
except (configparser.NoSectionError, configparser.NoOptionError,
ValueError, AttributeError): ValueError, AttributeError):
return False return False
def safeGetInt(self, section, field, default=0): def safeGetInt(self, section, field, default=0):
config = configparser.ConfigParser()
try: try:
return self.getint(section, field) #Used in the python2.7
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError, # return self.getint(section, field)
#Used in the python3.5.2
return config.getint(section, field)
except (configparser.NoSectionError, configparser.NoOptionError,
ValueError, AttributeError): ValueError, AttributeError):
return default return default
def safeGet(self, section, option, default=None): def safeGet(self, section, option, default=None):
try: try:
return self.get(section, option) return self.get(section, option)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError, except (configparser.NoSectionError, configparser.NoOptionError,
ValueError, AttributeError): ValueError, AttributeError):
return default return default
def items(self, section, raw=False, variables=None): 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): def addresses(self):
return filter( return [x for x in BMConfigParser().sections() if x.startswith('BM-')]
lambda x: x.startswith('BM-'), BMConfigParser().sections())
def read(self, filenames): def read(self, filenames):
ConfigParser.ConfigParser.read(self, filenames) configparser.ConfigParser.read(self, filenames)
for section in self.sections(): for section in self.sections():
for option in self.options(section): for option in self.options(section):
try: try:
if not self.validate( if not self.validate(
section, option, section, option,
ConfigParser.ConfigParser.get(self, section, option) configparser.ConfigParser.get(self, section, option)
): ):
try: try:
newVal = BMConfigDefaults[section][option] newVal = BMConfigDefaults[section][option]
except KeyError: except KeyError:
continue continue
ConfigParser.ConfigParser.set( configparser.ConfigParser.set(
self, section, option, newVal) self, section, option, newVal)
except ConfigParser.InterpolationError: except configparser.InterpolationError:
continue continue
def save(self): def save(self):
@ -144,7 +151,7 @@ class BMConfigParser(ConfigParser.SafeConfigParser):
# didn't exist before. # didn't exist before.
fileNameExisted = False fileNameExisted = False
# write the file # write the file
with open(fileName, 'wb') as configfile: with open(fileName, 'w') as configfile:
self.write(configfile) self.write(configfile)
# delete the backup # delete the backup
if fileNameExisted: if fileNameExisted:

View File

@ -1,4 +1,4 @@
import Queue import queue as Queue
import threading import threading
import time import time

View File

@ -70,9 +70,11 @@ class sqlThread(threading.Thread):
# If the settings version is equal to 2 or 3 then the # If the settings version is equal to 2 or 3 then the
# sqlThread will modify the pubkeys table and change # sqlThread will modify the pubkeys table and change
# the settings version to 4. # the settings version to 4.
settingsversion = BMConfigParser().getint( # settingsversion = BMConfigParser().getint('bitmessagesettings', 'settingsversion')
'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 # People running earlier versions of PyBitmessage do not have the
# usedpersonally field in their pubkeys table. Let's add it. # usedpersonally field in their pubkeys table. Let's add it.
if settingsversion == 2: if settingsversion == 2:

View File

@ -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
import logging.config import logging.config
import os import os
@ -47,12 +47,13 @@ def configureLogging():
fail_msg = '' fail_msg = ''
try: try:
logging_config = os.path.join(state.appdata, 'logging.dat') 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 ( return (
False, False,
'Loaded logger configuration from %s' % logging_config 'Loaded logger configuration from %s' % logging_config
) )
except (OSError, ConfigParser.NoSectionError): except (OSError, configparser.NoSectionError):
if os.path.isfile(logging_config): if os.path.isfile(logging_config):
fail_msg = \ fail_msg = \
'Failed to load logger configuration from %s, using default' \ 'Failed to load logger configuration from %s, using default' \

View File

@ -419,11 +419,11 @@ def check_dependencies(verbose=False, optional=False):
'PyBitmessage requires Python 2.7.4 or greater' 'PyBitmessage requires Python 2.7.4 or greater'
' (but not Python 3+)') ' (but not Python 3+)')
has_all_dependencies = False has_all_dependencies = False
if sys.hexversion >= 0x3000000: # if sys.hexversion >= 0x3000000:
logger.error( # logger.error(
'PyBitmessage does not support Python 3+. Python 2.7.4' # 'PyBitmessage does not support Python 3+. Python 2.7.4'
' or greater is required.') # ' or greater is required.')
has_all_dependencies = False # has_all_dependencies = False
check_functions = [check_ripemd160, check_sqlite, check_openssl] check_functions = [check_ripemd160, check_sqlite, check_openssl]
if optional: if optional:

View File

@ -4,7 +4,8 @@ from pyelliptic import arithmetic
# This function expects that pubkey begin with \x04 # This function expects that pubkey begin with \x04
def calculateBitcoinAddressFromPubkey(pubkey): def calculateBitcoinAddressFromPubkey(pubkey):
if len(pubkey) != 65: 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" return "error"
ripe = hashlib.new('ripemd160') ripe = hashlib.new('ripemd160')
sha = hashlib.new('sha256') sha = hashlib.new('sha256')
@ -25,7 +26,8 @@ def calculateBitcoinAddressFromPubkey(pubkey):
def calculateTestnetAddressFromPubkey(pubkey): def calculateTestnetAddressFromPubkey(pubkey):
if len(pubkey) != 65: 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" return "error"
ripe = hashlib.new('ripemd160') ripe = hashlib.new('ripemd160')
sha = hashlib.new('sha256') sha = hashlib.new('sha256')

View File

@ -1,7 +1,7 @@
"""Helper Sql performs sql operations.""" """Helper Sql performs sql operations."""
import threading import threading
import Queue import queue as Queue
sqlSubmitQueue = Queue.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. # SQLITE3 is so thread-unsafe that they won't even let you call it from different threads using your own locks.

View File

@ -7,7 +7,7 @@ Helper Start performs all the startup operations.
# pylint: disable=too-many-branches,too-many-statements # pylint: disable=too-many-branches,too-many-statements
from __future__ import print_function from __future__ import print_function
import ConfigParser import configparser
import os import os
import platform import platform
import sys import sys
@ -27,7 +27,7 @@ StoreConfigFilesInSameDirectoryAsProgramByDefault = False
def _loadTrustedPeer(): def _loadTrustedPeer():
try: try:
trustedPeer = BMConfigParser().get('bitmessagesettings', 'trustedpeer') trustedPeer = BMConfigParser().get('bitmessagesettings', 'trustedpeer')
except ConfigParser.Error: except configparser.Error:
# This probably means the trusted peer wasn't specified so we # This probably means the trusted peer wasn't specified so we
# can just leave it as None # can just leave it as None
return return
@ -137,11 +137,12 @@ def loadConfig():
_loadTrustedPeer() _loadTrustedPeer()
def updateConfig(): def updateConfig():
"""Save the config""" """Save the config"""
config = BMConfigParser() config = BMConfigParser()
settingsversion = config.getint('bitmessagesettings', 'settingsversion') # Used python2.7
# settingsversion = int(BMConfigParser().get('bitmessagesettings', 'settingsversion') \
settingsversion = BMConfigParser().safeGetInt('bitmessagesettings', 'settingsvesion')
if settingsversion == 1: if settingsversion == 1:
config.set('bitmessagesettings', 'socksproxytype', 'none') config.set('bitmessagesettings', 'socksproxytype', 'none')
config.set('bitmessagesettings', 'sockshostname', 'localhost') config.set('bitmessagesettings', 'sockshostname', 'localhost')

View File

@ -13,10 +13,11 @@ from pyelliptic import arithmetic as a
def makeCryptor(privkey): def makeCryptor(privkey):
"""Return a private pyelliptic.ECC() instance""" """Return a private pyelliptic.ECC() instance"""
# import pdb;pdb.set_trace()
private_key = a.changebase(privkey, 16, 256, minlen=32) private_key = a.changebase(privkey, 16, 256, minlen=32)
public_key = pointMult(private_key) public_key = pointMult(private_key)
privkey_bin = '\x02\xca\x00\x20' + 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) cryptor = pyelliptic.ECC(curve='secp256k1', privkey=privkey_bin, pubkey=pubkey_bin)
return cryptor return cryptor

View File

@ -40,12 +40,13 @@ def json_serialize_knownnodes(output):
Reorganize knownnodes dict and write it as JSON to output Reorganize knownnodes dict and write it as JSON to output
""" """
_serialized = [] _serialized = []
for stream, peers in knownNodes.iteritems(): for stream, peers in iter(knownNodes.items()):
for peer, info in peers.iteritems(): for peer, info in iter(peers.items()):
info.update(rating=round(info.get('rating', 0), 2)) info.update(rating=round(info.get('rating', 0), 2))
_serialized.append({ _serialized.append({
'stream': stream, 'peer': peer._asdict(), 'info': info 'stream': stream, 'peer': peer._asdict(), 'info': info
}) })
# import pdb;pdb.set_trace()
json.dump(_serialized, output, indent=4) json.dump(_serialized, output, indent=4)
@ -85,7 +86,7 @@ def saveKnownNodes(dirName=None):
if dirName is None: if dirName is None:
dirName = state.appdata dirName = state.appdata
with knownNodesLock: 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) json_serialize_knownnodes(output)

View File

@ -64,20 +64,30 @@ else:
if time_format != DEFAULT_TIME_FORMAT: if time_format != DEFAULT_TIME_FORMAT:
try: try:
#Check day names #Check day names
for i in xrange(7): new_time_format = time_format
unicode(time.strftime(time_format, (0, 0, 0, 0, 0, 0, i, 0, 0)), encoding) 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 #Check month names
for i in xrange(1, 13): for i in range(1, 13):
unicode(time.strftime(time_format, (0, i, 0, 0, 0, 0, 0, 0, 0)), encoding) # unicode(time.strftime(time_format, (0, i, 0, 0, 0, 0, 0, 0, 0)), encoding)
(time.strftime(time_format, (0, i, 0, 0, 0, 0, 0, 0, 0))).encode()
#Check AM/PM #Check AM/PM
unicode(time.strftime(time_format, (0, 0, 0, 11, 0, 0, 0, 0, 0)), encoding) (time.strftime(time_format, (0, 0, 0, 11, 0, 0, 0, 0, 0))).encode()
unicode(time.strftime(time_format, (0, 0, 0, 13, 0, 0, 0, 0, 0)), encoding) (time.strftime(time_format, (0, 0, 0, 13, 0, 0, 0, 0, 0))).encode()
#Check DST #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: except:
logger.exception('Could not decode locale formatted timestamp') logger.exception('Could not decode locale formatted timestamp')
time_format = DEFAULT_TIME_FORMAT time_format = DEFAULT_TIME_FORMAT
encoding = DEFAULT_ENCODING encoding = DEFAULT_ENCODING
time_format = new_time_format
def setlocale(category, newlocale): def setlocale(category, newlocale):
locale.setlocale(category, newlocale) locale.setlocale(category, newlocale)

View File

@ -4,7 +4,7 @@ src/messagetypes/__init__.py
""" """
from importlib import import_module from importlib import import_module
from os import path, listdir from os import path, listdir
from string import lower
try: try:
from kivy.utils import platform from kivy.utils import platform
except: except:

View File

@ -3,7 +3,7 @@ src/multiqueue.py
================= =================
""" """
import Queue import queue as Queue
from collections import deque from collections import deque
import helper_random import helper_random

View File

@ -1,4 +1,4 @@
import Queue import queue as Queue
from helper_threading import StoppableThread from helper_threading import StoppableThread
from network.connectionpool import BMConnectionPool from network.connectionpool import BMConnectionPool

View File

@ -30,7 +30,10 @@ class AdvancedDispatcher(asyncore.dispatcher):
_buf_len = 131072 # 128kB _buf_len = 131072 # 128kB
def __init__(self, sock=None): 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) asyncore.dispatcher.__init__(self, sock)
self.read_buf = bytearray() self.read_buf = bytearray()
self.write_buf = bytearray() self.write_buf = bytearray()

View File

@ -767,10 +767,11 @@ class dispatcher:
# references to the underlying socket object. # references to the underlying socket object.
def __getattr__(self, attr): def __getattr__(self, attr):
try: try:
# import pdb;pdb.set_trace()
retattr = getattr(self.socket, attr) retattr = getattr(self.socket, attr)
except AttributeError: except AttributeError:
raise AttributeError("%s instance has no attribute '%s'" raise AttributeError("{} instance has no attribute {}"
% (self.__class__.__name__, attr)) .format(self.__class__.__name__, attr))
else: else:
msg = "%(me)s.%(attr)s is deprecated; use %(me)s.socket.%(attr)s " \ msg = "%(me)s.%(attr)s is deprecated; use %(me)s.socket.%(attr)s " \
"instead" % {'me': self.__class__.__name__, 'attr': attr} "instead" % {'me': self.__class__.__name__, 'attr': attr}
@ -788,7 +789,7 @@ class dispatcher:
def log_info(self, message, log_type='info'): def log_info(self, message, log_type='info'):
"""Conditionally print a message""" """Conditionally print a message"""
if log_type not in self.ignore_log_types: 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): def handle_read_event(self):
"""Handle a read event""" """Handle a read event"""

View File

@ -11,7 +11,7 @@ import time
from binascii import hexlify from binascii import hexlify
import addresses import addresses
import connectionpool import network.connectionpool
import knownnodes import knownnodes
import protocol import protocol
import state import state
@ -26,9 +26,9 @@ from network.bmobject import (
BMObjectInvalidError, BMObjectAlreadyHaveError) BMObjectInvalidError, BMObjectAlreadyHaveError)
from network.node import Node from network.node import Node
from network.proxy import ProxyError from network.proxy import ProxyError
from objectracker import missingObjects, ObjectTracker from network.objectracker import missingObjects, ObjectTracker
from queues import objectProcessorQueue, portCheckerQueue, invQueue, addrQueue from queues import objectProcessorQueue, portCheckerQueue, invQueue, addrQueue
from randomtrackingdict import RandomTrackingDict from network.randomtrackingdict import RandomTrackingDict
class BMProtoError(ProxyError): class BMProtoError(ProxyError):

View File

@ -7,20 +7,19 @@ import re
import socket import socket
import time import time
import asyncore_pollchoose as asyncore import network.asyncore_pollchoose as asyncore
import helper_random import helper_random
import knownnodes import knownnodes
import protocol import protocol
import state import state
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
from connectionchooser import chooseConnection from network.connectionchooser import chooseConnection
from debug import logger from debug import logger
from proxy import Proxy from network.proxy import Proxy
from singleton import Singleton from singleton import Singleton
from tcp import ( from network.tcp import (
bootstrap, Socks4aBMConnection, Socks5BMConnection, TCPServer, Socks5BMConnection, Socks4aBMConnection, TCPConnection)
TCPConnection, TCPServer) from network.udp import UDPSocket
from udp import UDPSocket
@Singleton @Singleton

View File

@ -7,7 +7,7 @@ from random import choice, sample, expovariate
from threading import RLock from threading import RLock
from time import time from time import time
import connectionpool import network.connectionpool
import state import state
from debug import logging from debug import logging
from queues import invQueue from queues import invQueue

View File

@ -7,12 +7,12 @@ import time
import addresses import addresses
import helper_random import helper_random
import protocol import protocol
from dandelion import Dandelion from network.dandelion import Dandelion
from debug import logger from debug import logger
from helper_threading import StoppableThread from helper_threading import StoppableThread
from inventory import Inventory from inventory import Inventory
from network.connectionpool import BMConnectionPool from network.connectionpool import BMConnectionPool
from objectracker import missingObjects from network.objectracker import missingObjects
class DownloadThread(StoppableThread): class DownloadThread(StoppableThread):

View File

@ -2,7 +2,7 @@ import socket
from advanceddispatcher import AdvancedDispatcher from advanceddispatcher import AdvancedDispatcher
import asyncore_pollchoose as asyncore import asyncore_pollchoose as asyncore
from proxy import ProxyError from network.proxy import ProxyError
from socks5 import Socks5Connection, Socks5Resolver from socks5 import Socks5Connection, Socks5Resolver
from socks4a import Socks4aConnection, Socks4aResolver from socks4a import Socks4aConnection, Socks4aResolver

View File

@ -2,7 +2,7 @@
src/network/invthread.py src/network/invthread.py
======================== ========================
""" """
import Queue import queue as Queue
import random import random
from time import time from time import time

View File

@ -7,7 +7,7 @@ from threading import RLock
import network.connectionpool import network.connectionpool
from network.dandelion import Dandelion from network.dandelion import Dandelion
from randomtrackingdict import RandomTrackingDict from network.randomtrackingdict import RandomTrackingDict
haveBloom = False haveBloom = False

View File

@ -6,9 +6,9 @@ src/network/proxy.py
import socket import socket
import time import time
import asyncore_pollchoose as asyncore import network.asyncore_pollchoose as asyncore
import state import state
from advanceddispatcher import AdvancedDispatcher from network.advanceddispatcher import AdvancedDispatcher
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
from debug import logger from debug import logger

View File

@ -140,20 +140,20 @@ if __name__ == '__main__':
k = RandomTrackingDict() k = RandomTrackingDict()
d = {} d = {}
print "populating random tracking dict" print ("populating random tracking dict")
a.append(time()) a.append(time())
for i in range(50000): for i in range(50000):
k[randString()] = True k[randString()] = True
a.append(time()) a.append(time())
print "done" print ("done")
while k: while k:
retval = k.randomKeys(1000) retval = k.randomKeys(1000)
if not retval: if not retval:
print "error getting random keys" print ("error getting random keys")
try: try:
k.randomKeys(100) k.randomKeys(100)
print "bad" print( "bad")
except KeyError: except KeyError:
pass pass
for i in retval: for i in retval:
@ -161,4 +161,4 @@ if __name__ == '__main__':
a.append(time()) a.append(time())
for x in range(len(a) - 1): 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]))

View File

@ -1,5 +1,5 @@
import errno import errno
import Queue import queue as Queue
import socket import socket
from debug import logger from debug import logger

View File

@ -6,7 +6,7 @@ src/network/socks4a.py
import socket import socket
import struct import struct
from proxy import Proxy, ProxyError, GeneralProxyError from network.proxy import Proxy, ProxyError, GeneralProxyError
class Socks4aError(ProxyError): class Socks4aError(ProxyError):
@ -141,4 +141,4 @@ class Socks4aResolver(Socks4a):
PyBitmessage, a callback needs to be implemented which hasn't PyBitmessage, a callback needs to be implemented which hasn't
been done yet. been done yet.
""" """
print "Resolved %s as %s" % (self.host, self.proxy_sock_name()) print("Resolved {} as {}".format(self.host, self.proxy_sock_name()))

View File

@ -9,7 +9,7 @@ import socket
import struct import struct
import state import state
from proxy import GeneralProxyError, Proxy, ProxyError from network.proxy import GeneralProxyError, Proxy, ProxyError
class Socks5AuthError(ProxyError): class Socks5AuthError(ProxyError):
@ -218,4 +218,4 @@ class Socks5Resolver(Socks5):
To use this within PyBitmessage, a callback needs to be To use this within PyBitmessage, a callback needs to be
implemented which hasn't been done yet. 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()))

View File

@ -6,7 +6,7 @@ import time
import asyncore_pollchoose as asyncore import asyncore_pollchoose as asyncore
from network.connectionpool import BMConnectionPool from network.connectionpool import BMConnectionPool
from objectracker import missingObjects from network.objectracker import missingObjects
lastReceivedTimestamp = time.time() lastReceivedTimestamp = time.time()

View File

@ -10,8 +10,8 @@ import socket
import time import time
import addresses import addresses
import asyncore_pollchoose as asyncore import network.asyncore_pollchoose as asyncore
import connectionpool import network.connectionpool
import helper_random import helper_random
import knownnodes import knownnodes
import protocol import protocol

View File

@ -21,7 +21,12 @@ if sys.version_info >= (2, 7, 13):
# this means TLSv1 or higher # this means TLSv1 or higher
# in the future change to # in the future change to
# ssl.PROTOCOL_TLS1.2 # ssl.PROTOCOL_TLS1.2
# Right now I am using the python3.5.2 and I faced the ssl for protocol due to this I
# have used try and catch
try:
sslProtocolVersion = ssl.PROTOCOL_TLS # pylint: disable=no-member sslProtocolVersion = ssl.PROTOCOL_TLS # pylint: disable=no-member
except AttributeError:
sslProtocolVersion = ssl.PROTOCOL_SSLv23
elif sys.version_info >= (2, 7, 9): elif sys.version_info >= (2, 7, 9):
# this means any SSL/TLS. SSLv2 and 3 are excluded with an option after context is created # this means any SSL/TLS. SSLv2 and 3 are excluded with an option after context is created
sslProtocolVersion = ssl.PROTOCOL_SSLv23 sslProtocolVersion = ssl.PROTOCOL_SSLv23

View File

@ -7,9 +7,9 @@ import socket
import state import state
import protocol import protocol
from bmproto import BMProto from network.bmproto import BMProto
from debug import logger from debug import logger
from objectracker import ObjectTracker from network.objectracker import ObjectTracker
from queues import receiveDataQueue from queues import receiveDataQueue

View File

@ -11,7 +11,7 @@ from helper_threading import StoppableThread
from inventory import Inventory from inventory import Inventory
from network.connectionpool import BMConnectionPool from network.connectionpool import BMConnectionPool
from network.dandelion import Dandelion from network.dandelion import Dandelion
from randomtrackingdict import RandomTrackingDict from network.randomtrackingdict import RandomTrackingDict
class UploadThread(StoppableThread): class UploadThread(StoppableThread):

View File

@ -107,9 +107,10 @@ def do_opencl_pow(hash, target):
#initCL() #initCL()
if __name__ == "__main__": if __name__ == "__main__":
target = 54227212183L #in python3 I have change this 54227212183L to 54227212183
target = 54227212183
initialHash = "3758f55b5a8d902fd3597e4ce6a2d3f23daff735f65d9698c270987f4e67ad590b93f3ffeba0ef2fd08a8dc2f87b68ae5a0dc819ab57f22ad2c4c9c8618a43b3".decode("hex") initialHash = "3758f55b5a8d902fd3597e4ce6a2d3f23daff735f65d9698c270987f4e67ad590b93f3ffeba0ef2fd08a8dc2f87b68ae5a0dc819ab57f22ad2c4c9c8618a43b3".decode("hex")
nonce = do_opencl_pow(initialHash.encode("hex"), target) nonce = do_opencl_pow(initialHash.encode("hex"), target)
trialValue, = unpack('>Q',hashlib.sha512(hashlib.sha512(pack('>Q',nonce) + initialHash).digest()).digest()[0:8]) 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))

View File

@ -39,7 +39,7 @@ def encode(val, base, minlen=0):
code_string = get_code_string(base) code_string = get_code_string(base)
result = "" result = ""
while val > 0: while val > 0:
result = code_string[val % base] + result result = code_string[round(val % base)] + result
val /= base val /= base
if len(result) < minlen: if len(result) < minlen:
result = code_string[0] * (minlen - len(result)) + result result = code_string[0] * (minlen - len(result)) + result
@ -53,7 +53,7 @@ def decode(string, base):
string = string.lower() string = string.lower()
while string: while string:
result *= base result *= base
result += code_string.find(string[0]) result += code_string.find(string.decode()[0])
string = string[1:] string = string[1:]
return result return result

View File

@ -8,7 +8,7 @@ src/pyelliptic/cipher.py
# Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com> # Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com>
# See LICENSE for details. # See LICENSE for details.
from openssl import OpenSSL from .openssl import OpenSSL
# pylint: disable=redefined-builtin # pylint: disable=redefined-builtin

View File

@ -12,9 +12,9 @@ src/pyelliptic/ecc.py
from hashlib import sha512 from hashlib import sha512
from struct import pack, unpack from struct import pack, unpack
from cipher import Cipher from pyelliptic.cipher import Cipher
from hash import equals, hmac_sha256 from pyelliptic.hash import equals, hmac_sha256
from openssl import OpenSSL from pyelliptic.openssl import OpenSSL
class ECC(object): class ECC(object):
@ -130,6 +130,7 @@ class ECC(object):
@staticmethod @staticmethod
def _decode_pubkey( pubkey): def _decode_pubkey( pubkey):
pubkey = pubkey.encode()
i = 0 i = 0
curve = unpack('!H', pubkey[i:i + 2])[0] curve = unpack('!H', pubkey[i:i + 2])[0]
i += 2 i += 2

View File

@ -7,7 +7,7 @@ src/pyelliptic/hash.py
# Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com> # Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com>
# See LICENSE for details. # See LICENSE for details.
from openssl import OpenSSL from .openssl import OpenSSL
# For python3 # For python3

View File

@ -90,7 +90,7 @@ class _OpenSSL:
"""Build the wrapper""" """Build the wrapper"""
self._lib = ctypes.CDLL(library) self._lib = ctypes.CDLL(library)
self._version, self._hexversion, self._cflags = get_version(self._lib) 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.pointer = ctypes.pointer
self.c_int = ctypes.c_int self.c_int = ctypes.c_int
@ -674,6 +674,7 @@ def loadOpenSSL():
elif 'win32' in sys.platform or 'win64' in sys.platform: elif 'win32' in sys.platform or 'win64' in sys.platform:
libdir.append(path.join(sys._MEIPASS, 'libeay32.dll')) libdir.append(path.join(sys._MEIPASS, 'libeay32.dll'))
else: else:
libdir.extend([ libdir.extend([
path.join(sys._MEIPASS, 'libcrypto.so'), path.join(sys._MEIPASS, 'libcrypto.so'),
path.join(sys._MEIPASS, 'libssl.so'), path.join(sys._MEIPASS, 'libssl.so'),

View File

@ -1,4 +1,4 @@
import Queue import queue as Queue
from class_objectProcessorQueue import ObjectProcessorQueue from class_objectProcessorQueue import ObjectProcessorQueue
from multiqueue import MultiQueue from multiqueue import MultiQueue

View File

@ -174,12 +174,11 @@ def reloadBroadcastSendersForWhichImWatching():
# Now, for all addresses, even version 2 addresses, # Now, for all addresses, even version 2 addresses,
# we should create Cryptor objects in a dictionary which we will # we should create Cryptor objects in a dictionary which we will
# use to attempt to decrypt encrypted broadcast messages. # use to attempt to decrypt encrypted broadcast messages.
# import pdb;pdb.set_trace()
if addressVersionNumber <= 3: if addressVersionNumber <= 3:
privEncryptionKey = hashlib.sha512( privEncryptionKey = hashlib.sha512((encodeVarint(addressVersionNumber) \
encodeVarint(addressVersionNumber) + + encodeVarint(streamNumber) + hash)).digest()[:32]
encodeVarint(streamNumber) + hash # import pdb;pdb.set_trace()
).digest()[:32]
MyECSubscriptionCryptorObjects[hash] = \ MyECSubscriptionCryptorObjects[hash] = \
highlevelcrypto.makeCryptor(hexlify(privEncryptionKey)) highlevelcrypto.makeCryptor(hexlify(privEncryptionKey))
else: else:

View File

@ -1,5 +1,5 @@
import os import os
import Queue import queue as Queue
import threading import threading
import time import time

View File

@ -75,7 +75,7 @@ class singleinstance:
fcntl.lockf(self.fp, fcntl.LOCK_EX | fcntl.LOCK_NB) fcntl.lockf(self.fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
self.lockPid = os.getpid() self.lockPid = os.getpid()
except IOError: except IOError:
print 'Another instance of this application is already running' print ('Another instance of this application is already running')
sys.exit(-1) sys.exit(-1)
else: else:
pidLine = "%i\n" % self.lockPid pidLine = "%i\n" % self.lockPid
@ -94,11 +94,11 @@ class singleinstance:
os.close(self.fd) os.close(self.fd)
else: else:
fcntl.lockf(self.fp, fcntl.LOCK_UN) fcntl.lockf(self.fp, fcntl.LOCK_UN)
except Exception, e: except Exception as e:
pass pass
return return
print "Cleaning up lockfile" print ("Cleaning up lockfile")
try: try:
if sys.platform == 'win32': if sys.platform == 'win32':
if hasattr(self, 'fd'): if hasattr(self, 'fd'):

View File

@ -9,7 +9,7 @@ from threading import RLock
import time import time
from paths import lookupAppdataFolder 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 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( newInventory[streamNumber][hashId] = InventoryItem(
objectType, streamNumber, None, expiresTime, tag) objectType, streamNumber, None, expiresTime, tag)
except KeyError: except KeyError:
print "error loading %s" % (hexlify(hashId)) print ("error loading {}".format((hexlify(hashId))))
self._inventory = newInventory self._inventory = newInventory
# for i, v in self._inventory.items(): # for i, v in self._inventory.items():
# print "loaded stream: %s, %i items" % (i, len(v)) # print "loaded stream: %s, %i items" % (i, len(v))

View File

@ -6,6 +6,7 @@ import sqlite3
import time import time
from threading import RLock from threading import RLock
from helper_sql import sqlQuery, SqlBulkExecute, sqlExecute from helper_sql import sqlQuery, SqlBulkExecute, sqlExecute
from storage import InventoryStorage, InventoryItem from storage import InventoryStorage, InventoryItem

View File

@ -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)

View File

@ -5,7 +5,7 @@ Tests for core and those that do not work outside
import os import os
import pickle # nosec import pickle # nosec
import Queue import queue as Queue
import random # nosec import random # nosec
import string import string
import time import time

View File

@ -46,11 +46,11 @@ def translateText(context, text, n=None):
try: try:
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
except Exception as err: 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\ .You can download PyQt from http://www.riverbankcomputing.com/software/pyqt/download\
or by searching Google for \'PyQt Download\'.\ or by searching Google for \'PyQt Download\'.\
If you want to run in daemon mode, see https://bitmessage.org/wiki/Daemon' If you want to run in daemon mode, see https://bitmessage.org/wiki/Daemon')
print 'Error message:', err print ('Error message:', err)
os._exit(0) # pylint: disable=protected-access os._exit(0) # pylint: disable=protected-access
if n is None: if n is None:
return QtGui.QApplication.translate(context, text) return QtGui.QApplication.translate(context, text)