py3 fixes

This commit is contained in:
lakshyacis 2019-12-30 17:40:02 +05:30
parent 951b475ee6
commit 256ca151ab
No known key found for this signature in database
GPG Key ID: D2C539C8EC63E9EB
23 changed files with 371 additions and 386 deletions

View File

@ -37,6 +37,7 @@ from helper_ackPayload import genAckPayload
from helper_sql import SqlBulkExecute, sqlExecute, sqlQuery, sqlStoredProcedure from helper_sql import SqlBulkExecute, sqlExecute, sqlQuery, sqlStoredProcedure
from inventory import Inventory from inventory import Inventory
from network.threads import StoppableThread from network.threads import StoppableThread
# pylint: disable=unused-variable
str_chan = '[chan]' str_chan = '[chan]'
@ -275,7 +276,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data = '{"addresses":[' data = '{"addresses":['
for addressInKeysFile in BMConfigParser().addresses(): for addressInKeysFile in BMConfigParser().addresses():
# pylint: disable=unused-variable
status, addressVersionNumber, streamNumber, hash01 = decodeAddress( status, addressVersionNumber, streamNumber, hash01 = decodeAddress(
addressInKeysFile) addressInKeysFile)
if len(data) > 20: if len(data) > 20:
@ -609,7 +609,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
label = str_chan + ' ' + passphrase label = str_chan + ' ' + passphrase
except BaseException: except BaseException:
label = str_chan + ' ' + repr(passphrase) label = str_chan + ' ' + repr(passphrase)
# pylint: disable=unused-variable
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress( status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(
suppliedAddress) suppliedAddress)
suppliedAddress = addBMIfNotPresent(suppliedAddress) suppliedAddress = addBMIfNotPresent(suppliedAddress)
@ -634,7 +633,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
raise APIError(0, 'I need parameters.') raise APIError(0, 'I need parameters.')
elif len(params) == 1: elif len(params) == 1:
address, = params address, = params
# pylint: disable=unused-variable
status, addressVersionNumber, streamNumber, toRipe = \ status, addressVersionNumber, streamNumber, toRipe = \
self._verifyAddress(address) self._verifyAddress(address)
address = addBMIfNotPresent(address) address = addBMIfNotPresent(address)
@ -657,7 +655,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
raise APIError(0, 'I need parameters.') raise APIError(0, 'I need parameters.')
elif len(params) == 1: elif len(params) == 1:
address, = params address, = params
# pylint: disable=unused-variable
status, addressVersionNumber, streamNumber, toRipe = \ status, addressVersionNumber, streamNumber, toRipe = \
self._verifyAddress(address) self._verifyAddress(address)
address = addBMIfNotPresent(address) address = addBMIfNotPresent(address)
@ -878,7 +875,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data = '{"sentMessages":[' data = '{"sentMessages":['
for row in queryreturn: for row in queryreturn:
msgid, toAddress, fromAddress, subject, lastactiontime, message, \ msgid, toAddress, fromAddress, subject, lastactiontime, message, \
encodingtype, status, ackdata = row # pylint: disable=unused-variable encodingtype, status, ackdata = row
subject = shared.fixPotentiallyInvalidUTF8Data(subject) subject = shared.fixPotentiallyInvalidUTF8Data(subject)
message = shared.fixPotentiallyInvalidUTF8Data(message) message = shared.fixPotentiallyInvalidUTF8Data(message)
if len(data) > 25: if len(data) > 25:
@ -988,7 +985,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
TTL = 28 * 24 * 60 * 60 TTL = 28 * 24 * 60 * 60
toAddress = addBMIfNotPresent(toAddress) toAddress = addBMIfNotPresent(toAddress)
fromAddress = addBMIfNotPresent(fromAddress) fromAddress = addBMIfNotPresent(fromAddress)
# pylint: disable=unused-variable
status, addressVersionNumber, streamNumber, toRipe = \ status, addressVersionNumber, streamNumber, toRipe = \
self._verifyAddress(toAddress) self._verifyAddress(toAddress)
self._verifyAddress(fromAddress) self._verifyAddress(fromAddress)
@ -1165,7 +1161,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
def ListSubscriptions(self, params): def ListSubscriptions(self, params):
"""Handle a request to list susbcriptions""" """Handle a request to list susbcriptions"""
# pylint: disable=unused-variable
queryreturn = sqlQuery( queryreturn = sqlQuery(
"SELECT label, address, enabled FROM subscriptions") "SELECT label, address, enabled FROM subscriptions")
data = {'subscriptions': []} data = {'subscriptions': []}
@ -1271,7 +1266,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
pubkeyReadPosition += 8 pubkeyReadPosition += 8
else: else:
pubkeyReadPosition += 4 pubkeyReadPosition += 4
# pylint: disable=unused-variable
addressVersion, addressVersionLength = decodeVarint( addressVersion, addressVersionLength = decodeVarint(
payload[pubkeyReadPosition:pubkeyReadPosition + 10]) payload[pubkeyReadPosition:pubkeyReadPosition + 10])
pubkeyReadPosition += addressVersionLength pubkeyReadPosition += addressVersionLength

View File

@ -29,7 +29,8 @@ from bmconfigparser import BMConfigParser
api = '' api = ''
keysName = 'keys.dat' keysName = 'keys.dat'
keysPath = 'keys.dat' keysPath = 'keys.dat'
usrPrompt = 0 # 0 = First Start, 1 = prompt, 2 = no prompt if the program is starting up # 0 = First Start, 1 = prompt, 2 = no prompt if the program is starting up
usrPrompt = 0
knownAddresses = dict() knownAddresses = dict()
@ -38,7 +39,7 @@ def userInput(message):
global usrPrompt global usrPrompt
print '\n' + message print('\n' + message)
uInput = raw_input('> ') uInput = raw_input('> ')
if uInput.lower() == 'exit': # Returns the user to the main menu if uInput.lower() == 'exit': # Returns the user to the main menu
@ -46,7 +47,7 @@ def userInput(message):
main() main()
elif uInput.lower() == 'quit': # Quits the program elif uInput.lower() == 'quit': # Quits the program
print '\n Bye\n' print('\n Bye\n')
sys.exit(0) sys.exit(0)
else: else:
@ -55,9 +56,9 @@ def userInput(message):
def restartBmNotify(): def restartBmNotify():
"""Prompt the user to restart Bitmessage""" """Prompt the user to restart Bitmessage"""
print '\n *******************************************************************' print('\n *******************************************************************')
print ' WARNING: If Bitmessage is running locally, you must restart it now.' print(' WARNING: If Bitmessage is running locally, you must restart it now.')
print ' *******************************************************************\n' print(' *******************************************************************\n')
# Begin keys.dat interactions # Begin keys.dat interactions
@ -96,8 +97,8 @@ def configInit():
with open(keysName, 'wb') as configfile: with open(keysName, 'wb') as configfile:
BMConfigParser().write(configfile) BMConfigParser().write(configfile)
print '\n ' + str(keysName) + ' Initalized in the same directory as daemon.py' print('\n ' + str(keysName) + ' Initalized in the same directory as daemon.py')
print ' You will now need to configure the ' + str(keysName) + ' file.\n' print(' You will now need to configure the ' + str(keysName) + ' file.\n')
def apiInit(apiEnabled): def apiInit(apiEnabled):
@ -114,20 +115,20 @@ def apiInit(apiEnabled):
with open(keysPath, 'wb') as configfile: with open(keysPath, 'wb') as configfile:
BMConfigParser().write(configfile) BMConfigParser().write(configfile)
print 'Done' print('Done')
restartBmNotify() restartBmNotify()
return True return True
elif uInput == "n": elif uInput == "n":
print ' \n************************************************************' print(' \n************************************************************')
print ' Daemon will not work when the API is disabled. ' print(' Daemon will not work when the API is disabled. ')
print ' Please refer to the Bitmessage Wiki on how to setup the API.' print(' Please refer to the Bitmessage Wiki on how to setup the API.')
print ' ************************************************************\n' print(' ************************************************************\n')
usrPrompt = 1 usrPrompt = 1
main() main()
else: else:
print '\n Invalid Entry\n' print('\n Invalid Entry\n')
usrPrompt = 1 usrPrompt = 1
main() main()
@ -136,11 +137,11 @@ def apiInit(apiEnabled):
return True return True
else: # API information was not present. else: # API information was not present.
print '\n ' + str(keysPath) + ' not properly configured!\n' print('\n ' + str(keysPath) + ' not properly configured!\n')
uInput = userInput("Would you like to do this now, (Y)es or (N)o?").lower() uInput = userInput("Would you like to do this now, (Y)es or (N)o?").lower()
if uInput == "y": # User said yes, initalize the api by writing these values to the keys.dat file if uInput == "y": # User said yes, initalize the api by writing these values to the keys.dat file
print ' ' print(' ')
apiUsr = userInput("API Username") apiUsr = userInput("API Username")
apiPwd = userInput("API Password") apiPwd = userInput("API Password")
@ -149,11 +150,11 @@ def apiInit(apiEnabled):
daemon = userInput("Daemon mode Enabled? (True) or (False)").lower() daemon = userInput("Daemon mode Enabled? (True) or (False)").lower()
if (daemon != 'true' and daemon != 'false'): if (daemon != 'true' and daemon != 'false'):
print '\n Invalid Entry for Daemon.\n' print('\n Invalid Entry for Daemon.\n')
uInput = 1 uInput = 1
main() main()
print ' -----------------------------------\n' print(' -----------------------------------\n')
# sets the bitmessage port to stop the warning about the api not properly # sets the bitmessage port to stop the warning about the api not properly
# being setup. This is in the event that the keys.dat is in a different # being setup. This is in the event that the keys.dat is in a different
@ -168,18 +169,18 @@ def apiInit(apiEnabled):
with open(keysPath, 'wb') as configfile: with open(keysPath, 'wb') as configfile:
BMConfigParser().write(configfile) BMConfigParser().write(configfile)
print '\n Finished configuring the keys.dat file with API information.\n' print('\n Finished configuring the keys.dat file with API information.\n')
restartBmNotify() restartBmNotify()
return True return True
elif uInput == "n": elif uInput == "n":
print '\n ***********************************************************' print('\n ***********************************************************')
print ' Please refer to the Bitmessage Wiki on how to setup the API.' print(' Please refer to the Bitmessage Wiki on how to setup the API.')
print ' ***********************************************************\n' print(' ***********************************************************\n')
usrPrompt = 1 usrPrompt = 1
main() main()
else: else:
print ' \nInvalid entry\n' print(' \nInvalid entry\n')
usrPrompt = 1 usrPrompt = 1
main() main()
@ -206,11 +207,11 @@ def apiData():
BMConfigParser().get('bitmessagesettings', 'port') BMConfigParser().get('bitmessagesettings', 'port')
except: except:
# keys.dat was not there either, something is wrong. # keys.dat was not there either, something is wrong.
print '\n ******************************************************************' print('\n ******************************************************************')
print ' There was a problem trying to access the Bitmessage keys.dat file' print(' There was a problem trying to access the Bitmessage keys.dat file')
print ' or keys.dat is not set up correctly' print(' or keys.dat is not set up correctly')
print ' Make sure that daemon is in the same directory as Bitmessage. ' print(' Make sure that daemon is in the same directory as Bitmessage. ')
print ' ******************************************************************\n' print(' ******************************************************************\n')
uInput = userInput("Would you like to create a keys.dat in the local directory, (Y)es or (N)o?").lower() uInput = userInput("Would you like to create a keys.dat in the local directory, (Y)es or (N)o?").lower()
@ -220,11 +221,11 @@ def apiData():
usrPrompt = 0 usrPrompt = 0
main() main()
elif (uInput == "n" or uInput == "no"): elif (uInput == "n" or uInput == "no"):
print '\n Trying Again.\n' print('\n Trying Again.\n')
usrPrompt = 0 usrPrompt = 0
main() main()
else: else:
print '\n Invalid Input.\n' print('\n Invalid Input.\n')
usrPrompt = 1 usrPrompt = 1
main() main()
@ -249,7 +250,7 @@ def apiData():
apiUsername = BMConfigParser().get('bitmessagesettings', 'apiusername') apiUsername = BMConfigParser().get('bitmessagesettings', 'apiusername')
apiPassword = BMConfigParser().get('bitmessagesettings', 'apipassword') apiPassword = BMConfigParser().get('bitmessagesettings', 'apipassword')
print '\n API data successfully imported.\n' print('\n API data successfully imported.\n')
# Build the api credentials # Build the api credentials
return "http://" + apiUsername + ":" + apiPassword + "@" + apiInterface + ":" + str(apiPort) + "/" return "http://" + apiUsername + ":" + apiPassword + "@" + apiInterface + ":" + str(apiPort) + "/"
@ -281,7 +282,7 @@ def bmSettings():
try: try:
port = BMConfigParser().get('bitmessagesettings', 'port') port = BMConfigParser().get('bitmessagesettings', 'port')
except: except:
print '\n File not found.\n' print('\n File not found.\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -300,27 +301,27 @@ def bmSettings():
socksusername = BMConfigParser().get('bitmessagesettings', 'socksusername') socksusername = BMConfigParser().get('bitmessagesettings', 'socksusername')
sockspassword = BMConfigParser().get('bitmessagesettings', 'sockspassword') sockspassword = BMConfigParser().get('bitmessagesettings', 'sockspassword')
print '\n -----------------------------------' print('\n -----------------------------------')
print ' | Current Bitmessage Settings |' print(' | Current Bitmessage Settings |')
print ' -----------------------------------' print(' -----------------------------------')
print ' port = ' + port print(' port = ' + port)
print ' startonlogon = ' + str(startonlogon) print(' startonlogon = ' + str(startonlogon))
print ' minimizetotray = ' + str(minimizetotray) print(' minimizetotray = ' + str(minimizetotray))
print ' showtraynotifications = ' + str(showtraynotifications) print(' showtraynotifications = ' + str(showtraynotifications))
print ' startintray = ' + str(startintray) print(' startintray = ' + str(startintray))
print ' defaultnoncetrialsperbyte = ' + defaultnoncetrialsperbyte print(' defaultnoncetrialsperbyte = ' + defaultnoncetrialsperbyte)
print ' defaultpayloadlengthextrabytes = ' + defaultpayloadlengthextrabytes print(' defaultpayloadlengthextrabytes = ' + defaultpayloadlengthextrabytes)
print ' daemon = ' + str(daemon) print(' daemon = ' + str(daemon))
print '\n ------------------------------------' print('\n ------------------------------------')
print ' | Current Connection Settings |' print(' | Current Connection Settings |')
print ' -----------------------------------' print(' -----------------------------------')
print ' socksproxytype = ' + socksproxytype print(' socksproxytype = ' + socksproxytype)
print ' sockshostname = ' + sockshostname print(' sockshostname = ' + sockshostname)
print ' socksport = ' + socksport print(' socksport = ' + socksport)
print ' socksauthentication = ' + str(socksauthentication) print(' socksauthentication = ' + str(socksauthentication))
print ' socksusername = ' + socksusername print(' socksusername = ' + socksusername)
print ' sockspassword = ' + sockspassword print(' sockspassword = ' + sockspassword)
print ' ' print(' ')
uInput = userInput("Would you like to modify any of these settings, (Y)es or (N)o?").lower() uInput = userInput("Would you like to modify any of these settings, (Y)es or (N)o?").lower()
@ -328,74 +329,74 @@ def bmSettings():
while True: # loops if they mistype the setting name, they can exit the loop with 'exit' while True: # loops if they mistype the setting name, they can exit the loop with 'exit'
invalidInput = False invalidInput = False
uInput = userInput("What setting would you like to modify?").lower() uInput = userInput("What setting would you like to modify?").lower()
print ' ' print(' ')
if uInput == "port": if uInput == "port":
print ' Current port number: ' + port print(' Current port number: ' + port)
uInput = userInput("Enter the new port number.") uInput = userInput("Enter the new port number.")
BMConfigParser().set('bitmessagesettings', 'port', str(uInput)) BMConfigParser().set('bitmessagesettings', 'port', str(uInput))
elif uInput == "startonlogon": elif uInput == "startonlogon":
print ' Current status: ' + str(startonlogon) print(' Current status: ' + str(startonlogon))
uInput = userInput("Enter the new status.") uInput = userInput("Enter the new status.")
BMConfigParser().set('bitmessagesettings', 'startonlogon', str(uInput)) BMConfigParser().set('bitmessagesettings', 'startonlogon', str(uInput))
elif uInput == "minimizetotray": elif uInput == "minimizetotray":
print ' Current status: ' + str(minimizetotray) print(' Current status: ' + str(minimizetotray))
uInput = userInput("Enter the new status.") uInput = userInput("Enter the new status.")
BMConfigParser().set('bitmessagesettings', 'minimizetotray', str(uInput)) BMConfigParser().set('bitmessagesettings', 'minimizetotray', str(uInput))
elif uInput == "showtraynotifications": elif uInput == "showtraynotifications":
print ' Current status: ' + str(showtraynotifications) print(' Current status: ' + str(showtraynotifications))
uInput = userInput("Enter the new status.") uInput = userInput("Enter the new status.")
BMConfigParser().set('bitmessagesettings', 'showtraynotifications', str(uInput)) BMConfigParser().set('bitmessagesettings', 'showtraynotifications', str(uInput))
elif uInput == "startintray": elif uInput == "startintray":
print ' Current status: ' + str(startintray) print(' Current status: ' + str(startintray))
uInput = userInput("Enter the new status.") uInput = userInput("Enter the new status.")
BMConfigParser().set('bitmessagesettings', 'startintray', str(uInput)) BMConfigParser().set('bitmessagesettings', 'startintray', str(uInput))
elif uInput == "defaultnoncetrialsperbyte": elif uInput == "defaultnoncetrialsperbyte":
print ' Current default nonce trials per byte: ' + defaultnoncetrialsperbyte print(' Current default nonce trials per byte: ' + defaultnoncetrialsperbyte)
uInput = userInput("Enter the new defaultnoncetrialsperbyte.") uInput = userInput("Enter the new defaultnoncetrialsperbyte.")
BMConfigParser().set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(uInput)) BMConfigParser().set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(uInput))
elif uInput == "defaultpayloadlengthextrabytes": elif uInput == "defaultpayloadlengthextrabytes":
print ' Current default payload length extra bytes: ' + defaultpayloadlengthextrabytes print(' Current default payload length extra bytes: ' + defaultpayloadlengthextrabytes)
uInput = userInput("Enter the new defaultpayloadlengthextrabytes.") uInput = userInput("Enter the new defaultpayloadlengthextrabytes.")
BMConfigParser().set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(uInput)) BMConfigParser().set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(uInput))
elif uInput == "daemon": elif uInput == "daemon":
print ' Current status: ' + str(daemon) print(' Current status: ' + str(daemon))
uInput = userInput("Enter the new status.").lower() uInput = userInput("Enter the new status.").lower()
BMConfigParser().set('bitmessagesettings', 'daemon', str(uInput)) BMConfigParser().set('bitmessagesettings', 'daemon', str(uInput))
elif uInput == "socksproxytype": elif uInput == "socksproxytype":
print ' Current socks proxy type: ' + socksproxytype print(' Current socks proxy type: ' + socksproxytype)
print "Possibilities: 'none', 'SOCKS4a', 'SOCKS5'." print("Possibilities: 'none', 'SOCKS4a', 'SOCKS5'.")
uInput = userInput("Enter the new socksproxytype.") uInput = userInput("Enter the new socksproxytype.")
BMConfigParser().set('bitmessagesettings', 'socksproxytype', str(uInput)) BMConfigParser().set('bitmessagesettings', 'socksproxytype', str(uInput))
elif uInput == "sockshostname": elif uInput == "sockshostname":
print ' Current socks host name: ' + sockshostname print(' Current socks host name: ' + sockshostname)
uInput = userInput("Enter the new sockshostname.") uInput = userInput("Enter the new sockshostname.")
BMConfigParser().set('bitmessagesettings', 'sockshostname', str(uInput)) BMConfigParser().set('bitmessagesettings', 'sockshostname', str(uInput))
elif uInput == "socksport": elif uInput == "socksport":
print ' Current socks port number: ' + socksport print(' Current socks port number: ' + socksport)
uInput = userInput("Enter the new socksport.") uInput = userInput("Enter the new socksport.")
BMConfigParser().set('bitmessagesettings', 'socksport', str(uInput)) BMConfigParser().set('bitmessagesettings', 'socksport', str(uInput))
elif uInput == "socksauthentication": elif uInput == "socksauthentication":
print ' Current status: ' + str(socksauthentication) print(' Current status: ' + str(socksauthentication))
uInput = userInput("Enter the new status.") uInput = userInput("Enter the new status.")
BMConfigParser().set('bitmessagesettings', 'socksauthentication', str(uInput)) BMConfigParser().set('bitmessagesettings', 'socksauthentication', str(uInput))
elif uInput == "socksusername": elif uInput == "socksusername":
print ' Current socks username: ' + socksusername print(' Current socks username: ' + socksusername)
uInput = userInput("Enter the new socksusername.") uInput = userInput("Enter the new socksusername.")
BMConfigParser().set('bitmessagesettings', 'socksusername', str(uInput)) BMConfigParser().set('bitmessagesettings', 'socksusername', str(uInput))
elif uInput == "sockspassword": elif uInput == "sockspassword":
print ' Current socks password: ' + sockspassword print(' Current socks password: ' + sockspassword)
uInput = userInput("Enter the new password.") uInput = userInput("Enter the new password.")
BMConfigParser().set('bitmessagesettings', 'sockspassword', str(uInput)) BMConfigParser().set('bitmessagesettings', 'sockspassword', str(uInput))
else: else:
print "\n Invalid input. Please try again.\n" print("\n Invalid input. Please try again.\n")
invalidInput = True invalidInput = True
if invalidInput is not True: # don't prompt if they made a mistake. if invalidInput is not True: # don't prompt if they made a mistake.
uInput = userInput("Would you like to change another setting, (Y)es or (N)o?").lower() uInput = userInput("Would you like to change another setting, (Y)es or (N)o?").lower()
if uInput != "y": if uInput != "y":
print '\n Changes Made.\n' print('\n Changes Made.\n')
with open(keysPath, 'wb') as configfile: with open(keysPath, 'wb') as configfile:
BMConfigParser().write(configfile) BMConfigParser().write(configfile)
restartBmNotify() restartBmNotify()
@ -405,7 +406,7 @@ def bmSettings():
usrPrompt = 1 usrPrompt = 1
main() main()
else: else:
print "Invalid input." print("Invalid input.")
usrPrompt = 1 usrPrompt = 1
main() main()
@ -433,10 +434,10 @@ def subscribe():
if address == "c": if address == "c":
usrPrompt = 1 usrPrompt = 1
print ' ' print(' ')
main() main()
elif validAddress(address) is False: elif validAddress(address) is False:
print '\n Invalid. "c" to cancel. Please try again.\n' print('\n Invalid. "c" to cancel. Please try again.\n')
else: else:
break break
@ -444,7 +445,7 @@ def subscribe():
label = label.encode('base64') label = label.encode('base64')
api.addSubscription(address, label) api.addSubscription(address, label)
print '\n You are now subscribed to: ' + address + '\n' print('\n You are now subscribed to: ' + address + '\n')
def unsubscribe(): def unsubscribe():
@ -456,31 +457,31 @@ def unsubscribe():
if address == "c": if address == "c":
usrPrompt = 1 usrPrompt = 1
print ' ' print(' ')
main() main()
elif validAddress(address) is False: elif validAddress(address) is False:
print '\n Invalid. "c" to cancel. Please try again.\n' print('\n Invalid. "c" to cancel. Please try again.\n')
else: else:
break break
userInput("Are you sure, (Y)es or (N)o?").lower() # uInput = userInput("Are you sure, (Y)es or (N)o?").lower() # uInput =
api.deleteSubscription(address) api.deleteSubscription(address)
print '\n You are now unsubscribed from: ' + address + '\n' print('\n You are now unsubscribed from: ' + address + '\n')
def listSubscriptions(): def listSubscriptions():
"""List subscriptions""" """List subscriptions"""
global usrPrompt global usrPrompt
print '\nLabel, Address, Enabled\n' print('\nLabel, Address, Enabled\n')
try: try:
print api.listSubscriptions() print(api.listSubscriptions())
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
print ' ' print(' ')
def createChan(): def createChan():
@ -490,9 +491,9 @@ def createChan():
password = userInput("Enter channel name") password = userInput("Enter channel name")
password = password.encode('base64') password = password.encode('base64')
try: try:
print api.createChan(password) print(api.createChan(password))
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -506,19 +507,19 @@ def joinChan():
if address == "c": if address == "c":
usrPrompt = 1 usrPrompt = 1
print ' ' print(' ')
main() main()
elif validAddress(address) is False: elif validAddress(address) is False:
print '\n Invalid. "c" to cancel. Please try again.\n' print('\n Invalid. "c" to cancel. Please try again.\n')
else: else:
break break
password = userInput("Enter channel name") password = userInput("Enter channel name")
password = password.encode('base64') password = password.encode('base64')
try: try:
print api.joinChan(password, address) print(api.joinChan(password, address))
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -532,17 +533,17 @@ def leaveChan():
if address == "c": if address == "c":
usrPrompt = 1 usrPrompt = 1
print ' ' print(' ')
main() main()
elif validAddress(address) is False: elif validAddress(address) is False:
print '\n Invalid. "c" to cancel. Please try again.\n' print('\n Invalid. "c" to cancel. Please try again.\n')
else: else:
break break
try: try:
print api.leaveChan(address) print(api.leaveChan(address))
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -554,14 +555,14 @@ def listAdd():
jsonAddresses = json.loads(api.listAddresses()) jsonAddresses = json.loads(api.listAddresses())
numAddresses = len(jsonAddresses['addresses']) # Number of addresses numAddresses = len(jsonAddresses['addresses']) # Number of addresses
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
# print '\nAddress Number,Label,Address,Stream,Enabled\n' # print('\nAddress Number,Label,Address,Stream,Enabled\n')
print '\n --------------------------------------------------------------------------' print('\n --------------------------------------------------------------------------')
print ' | # | Label | Address |S#|Enabled|' print(' | # | Label | Address |S#|Enabled|')
print ' |---|-------------------|-------------------------------------|--|-------|' print(' |---|-------------------|-------------------------------------|--|-------|')
for addNum in range(0, numAddresses): # processes all of the addresses and lists them out for addNum in range(0, numAddresses): # processes all of the addresses and lists them out
label = (jsonAddresses['addresses'][addNum]['label']).encode( label = (jsonAddresses['addresses'][addNum]['label']).encode(
'utf') # may still misdiplay in some consoles 'utf') # may still misdiplay in some consoles
@ -572,7 +573,7 @@ def listAdd():
if len(label) > 19: if len(label) > 19:
label = label[:16] + '...' label = label[:16] + '...'
print ''.join([ print(''.join([
' |', ' |',
str(addNum).ljust(3), str(addNum).ljust(3),
'|', '|',
@ -584,13 +585,13 @@ def listAdd():
'|', '|',
enabled.ljust(7), enabled.ljust(7),
'|', '|',
]) ]))
print ''.join([ print(''.join([
' ', ' ',
74 * '-', 74 * '-',
'\n', '\n',
]) ]))
def genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe): def genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe):
@ -603,7 +604,7 @@ def genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe):
try: try:
generatedAddress = api.createRandomAddress(addressLabel) generatedAddress = api.createRandomAddress(addressLabel)
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -614,7 +615,7 @@ def genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe):
try: try:
generatedAddress = api.createDeterministicAddresses(passphrase, numOfAdd, addVNum, streamNum, ripe) generatedAddress = api.createDeterministicAddresses(passphrase, numOfAdd, addVNum, streamNum, ripe)
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
return generatedAddress return generatedAddress
@ -646,7 +647,7 @@ def saveFile(fileName, fileData):
with open(filePath, 'wb+') as path_to_file: with open(filePath, 'wb+') as path_to_file:
path_to_file.write(fileData.decode("base64")) path_to_file.write(fileData.decode("base64"))
print '\n Successfully saved ' + filePath + '\n' print('\n Successfully saved ' + filePath + '\n')
def attachment(): def attachment():
@ -667,26 +668,26 @@ def attachment():
with open(filePath): with open(filePath):
break break
except IOError: except IOError:
print '\n %s was not found on your filesystem or can not be opened.\n' % filePath print('\n %s was not found on your filesystem or can not be opened.\n' % filePath)
# print filesize, and encoding estimate with confirmation if file is over X size (1mb?) # print(filesize, and encoding estimate with confirmation if file is over X size (1mb?))
invSize = os.path.getsize(filePath) invSize = os.path.getsize(filePath)
invSize = (invSize / 1024) # Converts to kilobytes invSize = (invSize / 1024) # Converts to kilobytes
round(invSize, 2) # Rounds to two decimal places round(invSize, 2) # Rounds to two decimal places
if invSize > 500.0: # If over 500KB if invSize > 500.0: # If over 500KB
print ''.join([ print(''.join([
'\n WARNING:The file that you are trying to attach is ', '\n WARNING:The file that you are trying to attach is ',
invSize, invSize,
'KB and will take considerable time to send.\n' 'KB and will take considerable time to send.\n'
]) ]))
uInput = userInput('Are you sure you still want to attach it, (Y)es or (N)o?').lower() uInput = userInput('Are you sure you still want to attach it, (Y)es or (N)o?').lower()
if uInput != "y": if uInput != "y":
print '\n Attachment discarded.\n' print('\n Attachment discarded.\n')
return '' return ''
elif invSize > 184320.0: # If larger than 180MB, discard. elif invSize > 184320.0: # If larger than 180MB, discard.
print '\n Attachment too big, maximum allowed size:180MB\n' print('\n Attachment too big, maximum allowed size:180MB\n')
main() main()
pathLen = len(str(ntpath.basename(filePath))) # Gets the length of the filepath excluding the filename pathLen = len(str(ntpath.basename(filePath))) # Gets the length of the filepath excluding the filename
@ -694,17 +695,17 @@ def attachment():
filetype = imghdr.what(filePath) # Tests if it is an image file filetype = imghdr.what(filePath) # Tests if it is an image file
if filetype is not None: if filetype is not None:
print '\n ---------------------------------------------------' print('\n ---------------------------------------------------')
print ' Attachment detected as an Image.' print(' Attachment detected as an Image.')
print ' <img> tags will automatically be included,' print(' <img> tags will automatically be included,')
print ' allowing the recipient to view the image' print(' allowing the recipient to view the image')
print ' using the "View HTML code..." option in Bitmessage.' print(' using the "View HTML code..." option in Bitmessage.')
print ' ---------------------------------------------------\n' print(' ---------------------------------------------------\n')
isImage = True isImage = True
time.sleep(2) time.sleep(2)
# Alert the user that the encoding process may take some time. # Alert the user that the encoding process may take some time.
print '\n Encoding Attachment, Please Wait ...\n' print('\n Encoding Attachment, Please Wait ...\n')
with open(filePath, 'rb') as f: # Begin the actual encoding with open(filePath, 'rb') as f: # Begin the actual encoding
data = f.read(188743680) # Reads files up to 180MB, the maximum size for Bitmessage. data = f.read(188743680) # Reads files up to 180MB, the maximum size for Bitmessage.
@ -759,10 +760,10 @@ def sendMsg(toAddress, fromAddress, subject, message):
if toAddress == "c": if toAddress == "c":
usrPrompt = 1 usrPrompt = 1
print ' ' print(' ')
main() main()
elif validAddress(toAddress) is False: elif validAddress(toAddress) is False:
print '\n Invalid Address. "c" to cancel. Please try again.\n' print('\n Invalid Address. "c" to cancel. Please try again.\n')
else: else:
break break
@ -771,14 +772,14 @@ def sendMsg(toAddress, fromAddress, subject, message):
jsonAddresses = json.loads(api.listAddresses()) jsonAddresses = json.loads(api.listAddresses())
numAddresses = len(jsonAddresses['addresses']) # Number of addresses numAddresses = len(jsonAddresses['addresses']) # Number of addresses
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
if numAddresses > 1: # Ask what address to send from if multiple addresses if numAddresses > 1: # Ask what address to send from if multiple addresses
found = False found = False
while True: while True:
print ' ' print(' ')
fromAddress = userInput("Enter an Address or Address Label to send from.") fromAddress = userInput("Enter an Address or Address Label to send from.")
if fromAddress == "exit": if fromAddress == "exit":
@ -795,7 +796,7 @@ def sendMsg(toAddress, fromAddress, subject, message):
if found is False: if found is False:
if validAddress(fromAddress) is False: if validAddress(fromAddress) is False:
print '\n Invalid Address. Please try again.\n' print('\n Invalid Address. Please try again.\n')
else: else:
for addNum in range(0, numAddresses): # processes all of the addresses for addNum in range(0, numAddresses): # processes all of the addresses
@ -805,13 +806,13 @@ def sendMsg(toAddress, fromAddress, subject, message):
break break
if found is False: if found is False:
print '\n The address entered is not one of yours. Please try again.\n' print('\n The address entered is not one of yours. Please try again.\n')
if found: if found:
break # Address was found break # Address was found
else: # Only one address in address book else: # Only one address in address book
print '\n Using the only address in the addressbook to send from.\n' print('\n Using the only address in the addressbook to send from.\n')
fromAddress = jsonAddresses['addresses'][0]['address'] fromAddress = jsonAddresses['addresses'][0]['address']
if subject == '': if subject == '':
@ -828,9 +829,9 @@ def sendMsg(toAddress, fromAddress, subject, message):
try: try:
ackData = api.sendMessage(toAddress, fromAddress, subject, message) ackData = api.sendMessage(toAddress, fromAddress, subject, message)
print '\n Message Status:', api.getStatus(ackData), '\n' print('\n Message Status:', api.getStatus(ackData), '\n')
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -845,7 +846,7 @@ def sendBrd(fromAddress, subject, message):
jsonAddresses = json.loads(api.listAddresses()) jsonAddresses = json.loads(api.listAddresses())
numAddresses = len(jsonAddresses['addresses']) # Number of addresses numAddresses = len(jsonAddresses['addresses']) # Number of addresses
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -868,7 +869,7 @@ def sendBrd(fromAddress, subject, message):
if found is False: if found is False:
if validAddress(fromAddress) is False: if validAddress(fromAddress) is False:
print '\n Invalid Address. Please try again.\n' print('\n Invalid Address. Please try again.\n')
else: else:
for addNum in range(0, numAddresses): # processes all of the addresses for addNum in range(0, numAddresses): # processes all of the addresses
@ -878,13 +879,13 @@ def sendBrd(fromAddress, subject, message):
break break
if found is False: if found is False:
print '\n The address entered is not one of yours. Please try again.\n' print('\n The address entered is not one of yours. Please try again.\n')
if found: if found:
break # Address was found break # Address was found
else: # Only one address in address book else: # Only one address in address book
print '\n Using the only address in the addressbook to send from.\n' print('\n Using the only address in the addressbook to send from.\n')
fromAddress = jsonAddresses['addresses'][0]['address'] fromAddress = jsonAddresses['addresses'][0]['address']
if subject == '': if subject == '':
@ -901,9 +902,9 @@ def sendBrd(fromAddress, subject, message):
try: try:
ackData = api.sendBroadcast(fromAddress, subject, message) ackData = api.sendBroadcast(fromAddress, subject, message)
print '\n Message Status:', api.getStatus(ackData), '\n' print('\n Message Status:', api.getStatus(ackData), '\n')
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -916,7 +917,7 @@ def inbox(unreadOnly=False):
inboxMessages = json.loads(api.getAllInboxMessages()) inboxMessages = json.loads(api.getAllInboxMessages())
numMessages = len(inboxMessages['inboxMessages']) numMessages = len(inboxMessages['inboxMessages'])
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -926,16 +927,16 @@ def inbox(unreadOnly=False):
message = inboxMessages['inboxMessages'][msgNum] message = inboxMessages['inboxMessages'][msgNum]
# if we are displaying all messages or if this message is unread then display it # if we are displaying all messages or if this message is unread then display it
if not unreadOnly or not message['read']: if not unreadOnly or not message['read']:
print ' -----------------------------------\n' print(' -----------------------------------\n')
print ' Message Number:', msgNum # Message Number print(' Message Number:', msgNum) # Message Number
print ' To:', getLabelForAddress(message['toAddress']) # Get the to address print(' To:', getLabelForAddress(message['toAddress'])) # Get the to address
print ' From:', getLabelForAddress(message['fromAddress']) # Get the from address print(' From:', getLabelForAddress(message['fromAddress'])) # Get the from address
print ' Subject:', message['subject'].decode('base64') # Get the subject print(' Subject:', message['subject'].decode('base64')) # Get the subject
print ''.join([ print(''.join([
' Received:', ' Received:',
datetime.datetime.fromtimestamp( datetime.datetime.fromtimestamp(
float(message['receivedTime'])).strftime('%Y-%m-%d %H:%M:%S'), float(message['receivedTime'])).strftime('%Y-%m-%d %H:%M:%S'),
]) ]))
messagesPrinted += 1 messagesPrinted += 1
if not message['read']: if not message['read']:
messagesUnread += 1 messagesUnread += 1
@ -943,9 +944,9 @@ def inbox(unreadOnly=False):
if messagesPrinted % 20 == 0 and messagesPrinted != 0: if messagesPrinted % 20 == 0 and messagesPrinted != 0:
userInput('(Press Enter to continue or type (Exit) to return to the main menu.)').lower() # uInput = userInput('(Press Enter to continue or type (Exit) to return to the main menu.)').lower() # uInput =
print '\n -----------------------------------' print('\n -----------------------------------')
print ' There are %d unread messages of %d messages in the inbox.' % (messagesUnread, numMessages) print(' There are %d unread messages of %d messages in the inbox.' % (messagesUnread, numMessages))
print ' -----------------------------------\n' print(' -----------------------------------\n')
def outbox(): def outbox():
@ -956,32 +957,32 @@ def outbox():
outboxMessages = json.loads(api.getAllSentMessages()) outboxMessages = json.loads(api.getAllSentMessages())
numMessages = len(outboxMessages['sentMessages']) numMessages = len(outboxMessages['sentMessages'])
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
for msgNum in range(0, numMessages): # processes all of the messages in the outbox for msgNum in range(0, numMessages): # processes all of the messages in the outbox
print '\n -----------------------------------\n' print('\n -----------------------------------\n')
print ' Message Number:', msgNum # Message Number print(' Message Number:', msgNum) # Message Number
# print ' Message ID:', outboxMessages['sentMessages'][msgNum]['msgid'] # print(' Message ID:', outboxMessages['sentMessages'][msgNum]['msgid'])
print ' To:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['toAddress']) # Get the to address # Get the to address
print(' To:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['toAddress']))
# Get the from address # Get the from address
print ' From:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['fromAddress']) print(' From:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['fromAddress']))
print ' Subject:', outboxMessages['sentMessages'][msgNum]['subject'].decode('base64') # Get the subject print(' Subject:', outboxMessages['sentMessages'][msgNum]['subject'].decode('base64')) # Get the subject
print ' Status:', outboxMessages['sentMessages'][msgNum]['status'] # Get the subject print(' Status:', outboxMessages['sentMessages'][msgNum]['status']) # Get the subject
print(''.join([
print ''.join([
' Last Action Time:', ' Last Action Time:',
datetime.datetime.fromtimestamp( datetime.datetime.fromtimestamp(
float(outboxMessages['sentMessages'][msgNum]['lastActionTime'])).strftime('%Y-%m-%d %H:%M:%S'), float(outboxMessages['sentMessages'][msgNum]['lastActionTime'])).strftime('%Y-%m-%d %H:%M:%S'),
]) ]))
if msgNum % 20 == 0 and msgNum != 0: if msgNum % 20 == 0 and msgNum != 0:
userInput('(Press Enter to continue or type (Exit) to return to the main menu.)').lower() # uInput = userInput('(Press Enter to continue or type (Exit) to return to the main menu.)').lower() # uInput =
print '\n -----------------------------------' print('\n -----------------------------------')
print ' There are ', numMessages, ' messages in the outbox.' print(' There are ', numMessages, ' messages in the outbox.')
print ' -----------------------------------\n' print(' -----------------------------------\n')
def readSentMsg(msgNum): def readSentMsg(msgNum):
@ -992,14 +993,14 @@ def readSentMsg(msgNum):
outboxMessages = json.loads(api.getAllSentMessages()) outboxMessages = json.loads(api.getAllSentMessages())
numMessages = len(outboxMessages['sentMessages']) numMessages = len(outboxMessages['sentMessages'])
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
print ' ' print(' ')
if msgNum >= numMessages: if msgNum >= numMessages:
print '\n Invalid Message Number.\n' print('\n Invalid Message Number.\n')
main() main()
# Begin attachment detection # Begin attachment detection
@ -1035,19 +1036,19 @@ def readSentMsg(msgNum):
# End attachment Detection # End attachment Detection
print '\n To:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['toAddress']) # Get the to address print('\n To:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['toAddress'])) # Get the to address
# Get the from address # Get the from address
print ' From:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['fromAddress']) print(' From:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['fromAddress']))
print ' Subject:', outboxMessages['sentMessages'][msgNum]['subject'].decode('base64') # Get the subject print(' Subject:', outboxMessages['sentMessages'][msgNum]['subject'].decode('base64')) # Get the subject
print ' Status:', outboxMessages['sentMessages'][msgNum]['status'] # Get the subject print(' Status:', outboxMessages['sentMessages'][msgNum]['status']) # Get the subject
print ''.join([ print(''.join([
' Last Action Time:', ' Last Action Time:',
datetime.datetime.fromtimestamp( datetime.datetime.fromtimestamp(
float(outboxMessages['sentMessages'][msgNum]['lastActionTime'])).strftime('%Y-%m-%d %H:%M:%S'), float(outboxMessages['sentMessages'][msgNum]['lastActionTime'])).strftime('%Y-%m-%d %H:%M:%S'),
]) ]))
print ' Message:\n' print(' Message:\n')
print message # inboxMessages['inboxMessages'][msgNum]['message'].decode('base64') print(message) # inboxMessages['inboxMessages'][msgNum]['message'].decode('base64')
print ' ' print(' ')
def readMsg(msgNum): def readMsg(msgNum):
@ -1057,12 +1058,12 @@ def readMsg(msgNum):
inboxMessages = json.loads(api.getAllInboxMessages()) inboxMessages = json.loads(api.getAllInboxMessages())
numMessages = len(inboxMessages['inboxMessages']) numMessages = len(inboxMessages['inboxMessages'])
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
if msgNum >= numMessages: if msgNum >= numMessages:
print '\n Invalid Message Number.\n' print('\n Invalid Message Number.\n')
main() main()
# Begin attachment detection # Begin attachment detection
@ -1097,17 +1098,17 @@ def readMsg(msgNum):
break break
# End attachment Detection # End attachment Detection
print '\n To:', getLabelForAddress(inboxMessages['inboxMessages'][msgNum]['toAddress']) # Get the to address print('\n To:', getLabelForAddress(inboxMessages['inboxMessages'][msgNum]['toAddress'])) # Get the to address
# Get the from address # Get the from address
print ' From:', getLabelForAddress(inboxMessages['inboxMessages'][msgNum]['fromAddress']) print(' From:', getLabelForAddress(inboxMessages['inboxMessages'][msgNum]['fromAddress']))
print ' Subject:', inboxMessages['inboxMessages'][msgNum]['subject'].decode('base64') # Get the subject print(' Subject:', inboxMessages['inboxMessages'][msgNum]['subject'].decode('base64')) # Get the subject
print ''.join([ print(''.join([
' Received:', datetime.datetime.fromtimestamp( ' Received:', datetime.datetime.fromtimestamp(
float(inboxMessages['inboxMessages'][msgNum]['receivedTime'])).strftime('%Y-%m-%d %H:%M:%S'), float(inboxMessages['inboxMessages'][msgNum]['receivedTime'])).strftime('%Y-%m-%d %H:%M:%S'),
]) ]))
print ' Message:\n' print(' Message:\n')
print message # inboxMessages['inboxMessages'][msgNum]['message'].decode('base64') print(message) # inboxMessages['inboxMessages'][msgNum]['message'].decode('base64')
print ' ' print(' ')
return inboxMessages['inboxMessages'][msgNum]['msgid'] return inboxMessages['inboxMessages'][msgNum]['msgid']
@ -1119,7 +1120,7 @@ def replyMsg(msgNum, forwardORreply):
try: try:
inboxMessages = json.loads(api.getAllInboxMessages()) inboxMessages = json.loads(api.getAllInboxMessages())
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -1141,14 +1142,14 @@ def replyMsg(msgNum, forwardORreply):
if toAdd == "c": if toAdd == "c":
usrPrompt = 1 usrPrompt = 1
print ' ' print(' ')
main() main()
elif validAddress(toAdd) is False: elif validAddress(toAdd) is False:
print '\n Invalid Address. "c" to cancel. Please try again.\n' print('\n Invalid Address. "c" to cancel. Please try again.\n')
else: else:
break break
else: else:
print '\n Invalid Selection. Reply or Forward only' print('\n Invalid Selection. Reply or Forward only')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -1180,7 +1181,7 @@ def delMsg(msgNum):
msgAck = api.trashMessage(msgId) msgAck = api.trashMessage(msgId)
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -1197,7 +1198,7 @@ def delSentMsg(msgNum):
msgId = outboxMessages['sentMessages'][int(msgNum)]['msgid'] msgId = outboxMessages['sentMessages'][int(msgNum)]['msgid']
msgAck = api.trashSentMessage(msgId) msgAck = api.trashSentMessage(msgId)
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -1233,7 +1234,7 @@ def buildKnownAddresses():
if entry['address'] not in knownAddresses: if entry['address'] not in knownAddresses:
knownAddresses[entry['address']] = "%s (%s)" % (entry['label'].decode('base64'), entry['address']) knownAddresses[entry['address']] = "%s (%s)" % (entry['label'].decode('base64'), entry['address'])
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -1248,7 +1249,7 @@ def buildKnownAddresses():
if entry['address'] not in knownAddresses: if entry['address'] not in knownAddresses:
knownAddresses[entry['address']] = "%s (%s)" % (entry['label'].decode('base64'), entry['address']) knownAddresses[entry['address']] = "%s (%s)" % (entry['label'].decode('base64'), entry['address'])
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -1263,21 +1264,20 @@ def listAddressBookEntries():
if "API Error" in response: if "API Error" in response:
return getAPIErrorCode(response) return getAPIErrorCode(response)
addressBook = json.loads(response) addressBook = json.loads(response)
print print()
print ' --------------------------------------------------------------' print(' --------------------------------------------------------------')
print ' | Label | Address |' print(' | Label | Address |')
print ' |--------------------|---------------------------------------|' print(' |--------------------|---------------------------------------|')
for entry in addressBook['addresses']: for entry in addressBook['addresses']:
label = entry['label'].decode('base64') label = entry['label'].decode('base64')
address = entry['address'] address = entry['address']
if len(label) > 19: if len(label) > 19:
label = label[:16] + '...' label = label[:16] + '...'
print ' | ' + label.ljust(19) + '| ' + address.ljust(37) + ' |' print(' | ' + label.ljust(19) + '| ' + address.ljust(37) + ' |')
print ' --------------------------------------------------------------' print(' --------------------------------------------------------------')
print print()
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -1292,7 +1292,7 @@ def addAddressToAddressBook(address, label):
if "API Error" in response: if "API Error" in response:
return getAPIErrorCode(response) return getAPIErrorCode(response)
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -1307,7 +1307,7 @@ def deleteAddressFromAddressBook(address):
if "API Error" in response: if "API Error" in response:
return getAPIErrorCode(response) return getAPIErrorCode(response)
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -1331,7 +1331,7 @@ def markMessageRead(messageID):
if "API Error" in response: if "API Error" in response:
return getAPIErrorCode(response) return getAPIErrorCode(response)
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -1346,7 +1346,7 @@ def markMessageUnread(messageID):
if "API Error" in response: if "API Error" in response:
return getAPIErrorCode(response) return getAPIErrorCode(response)
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
@ -1359,7 +1359,7 @@ def markAllMessagesRead():
try: try:
inboxMessages = json.loads(api.getAllInboxMessages())['inboxMessages'] inboxMessages = json.loads(api.getAllInboxMessages())['inboxMessages']
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
for message in inboxMessages: for message in inboxMessages:
@ -1375,7 +1375,7 @@ def markAllMessagesUnread():
try: try:
inboxMessages = json.loads(api.getAllInboxMessages())['inboxMessages'] inboxMessages = json.loads(api.getAllInboxMessages())['inboxMessages']
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
for message in inboxMessages: for message in inboxMessages:
@ -1391,15 +1391,15 @@ def clientStatus():
try: try:
client_status = json.loads(api.clientStatus()) client_status = json.loads(api.clientStatus())
except: except:
print '\n Connection Error\n' print('\n Connection Error\n')
usrPrompt = 0 usrPrompt = 0
main() main()
print "\nnetworkStatus: " + client_status['networkStatus'] + "\n" print("\nnetworkStatus: " + client_status['networkStatus'] + "\n")
print "\nnetworkConnections: " + str(client_status['networkConnections']) + "\n" print("\nnetworkConnections: " + str(client_status['networkConnections']) + "\n")
print "\nnumberOfPubkeysProcessed: " + str(client_status['numberOfPubkeysProcessed']) + "\n" print("\nnumberOfPubkeysProcessed: " + str(client_status['numberOfPubkeysProcessed']) + "\n")
print "\nnumberOfMessagesProcessed: " + str(client_status['numberOfMessagesProcessed']) + "\n" print("\nnumberOfMessagesProcessed: " + str(client_status['numberOfMessagesProcessed']) + "\n")
print "\nnumberOfBroadcastsProcessed: " + str(client_status['numberOfBroadcastsProcessed']) + "\n" print("\nnumberOfBroadcastsProcessed: " + str(client_status['numberOfBroadcastsProcessed']) + "\n")
def shutdown(): def shutdown():
@ -1409,7 +1409,7 @@ def shutdown():
api.shutdown() api.shutdown()
except socket.error: except socket.error:
pass pass
print "\nShutdown command relayed\n" print("\nShutdown command relayed\n")
def UI(usrInput): def UI(usrInput):
@ -1418,75 +1418,75 @@ def UI(usrInput):
global usrPrompt global usrPrompt
if usrInput == "help" or usrInput == "h" or usrInput == "?": if usrInput == "help" or usrInput == "h" or usrInput == "?":
print ' ' print(' ')
print ' -------------------------------------------------------------------------' print(' -------------------------------------------------------------------------')
print ' | https://github.com/Dokument/PyBitmessage-Daemon |' print(' | https://github.com/Dokument/PyBitmessage-Daemon |')
print ' |-----------------------------------------------------------------------|' print(' |-----------------------------------------------------------------------|')
print ' | Command | Description |' print(' | Command | Description |')
print ' |------------------------|----------------------------------------------|' print(' |------------------------|----------------------------------------------|')
print ' | help | This help file. |' print(' | help | This help file. |')
print ' | apiTest | Tests the API |' print(' | apiTest | Tests the API |')
print ' | addInfo | Returns address information (If valid) |' print(' | addInfo | Returns address information (If valid) |')
print ' | bmSettings | BitMessage settings |' print(' | bmSettings | BitMessage settings |')
print ' | exit | Use anytime to return to main menu |' print(' | exit | Use anytime to return to main menu |')
print ' | quit | Quits the program |' print(' | quit | Quits the program |')
print ' |------------------------|----------------------------------------------|' print(' |------------------------|----------------------------------------------|')
print ' | listAddresses | Lists all of the users addresses |' print(' | listAddresses | Lists all of the users addresses |')
print ' | generateAddress | Generates a new address |' print(' | generateAddress | Generates a new address |')
print ' | getAddress | Get determinist address from passphrase |' print(' | getAddress | Get determinist address from passphrase |')
print ' |------------------------|----------------------------------------------|' print(' |------------------------|----------------------------------------------|')
print ' | listAddressBookEntries | Lists entries from the Address Book |' print(' | listAddressBookEntries | Lists entries from the Address Book |')
print ' | addAddressBookEntry | Add address to the Address Book |' print(' | addAddressBookEntry | Add address to the Address Book |')
print ' | deleteAddressBookEntry | Deletes address from the Address Book |' print(' | deleteAddressBookEntry | Deletes address from the Address Book |')
print ' |------------------------|----------------------------------------------|' print(' |------------------------|----------------------------------------------|')
print ' | subscribe | Subscribes to an address |' print(' | subscribe | Subscribes to an address |')
print ' | unsubscribe | Unsubscribes from an address |' print(' | unsubscribe | Unsubscribes from an address |')
print ' |------------------------|----------------------------------------------|' print(' |------------------------|----------------------------------------------|')
print ' | create | Creates a channel |' print(' | create | Creates a channel |')
print ' | join | Joins a channel |' print(' | join | Joins a channel |')
print ' | leave | Leaves a channel |' print(' | leave | Leaves a channel |')
print ' |------------------------|----------------------------------------------|' print(' |------------------------|----------------------------------------------|')
print ' | inbox | Lists the message information for the inbox |' print(' | inbox | Lists the message information for the inbox |')
print ' | outbox | Lists the message information for the outbox |' print(' | outbox | Lists the message information for the outbox |')
print ' | send | Send a new message or broadcast |' print(' | send | Send a new message or broadcast |')
print ' | unread | Lists all unread inbox messages |' print(' | unread | Lists all unread inbox messages |')
print ' | read | Reads a message from the inbox or outbox |' print(' | read | Reads a message from the inbox or outbox |')
print ' | save | Saves message to text file |' print(' | save | Saves message to text file |')
print ' | delete | Deletes a message or all messages |' print(' | delete | Deletes a message or all messages |')
print ' -------------------------------------------------------------------------' print(' -------------------------------------------------------------------------')
print ' ' print(' ')
main() main()
elif usrInput == "apitest": # tests the API Connection. elif usrInput == "apitest": # tests the API Connection.
if apiTest(): if apiTest():
print '\n API connection test has: PASSED\n' print('\n API connection test has: PASSED\n')
else: else:
print '\n API connection test has: FAILED\n' print('\n API connection test has: FAILED\n')
main() main()
elif usrInput == "addinfo": elif usrInput == "addinfo":
tmp_address = userInput('\nEnter the Bitmessage Address.') tmp_address = userInput('\nEnter the Bitmessage Address.')
address_information = json.loads(api.decodeAddress(tmp_address)) address_information = json.loads(api.decodeAddress(tmp_address))
print '\n------------------------------' print('\n------------------------------')
if 'success' in str(address_information['status']).lower(): if 'success' in str(address_information['status']).lower():
print ' Valid Address' print(' Valid Address')
print ' Address Version: %s' % str(address_information['addressVersion']) print(' Address Version: %s' % str(address_information['addressVersion']))
print ' Stream Number: %s' % str(address_information['streamNumber']) print(' Stream Number: %s' % str(address_information['streamNumber']))
else: else:
print ' Invalid Address !' print(' Invalid Address !')
print '------------------------------\n' print('------------------------------\n')
main() main()
elif usrInput == "bmsettings": # tests the API Connection. elif usrInput == "bmsettings": # tests the API Connection.
bmSettings() bmSettings()
print ' ' print(' ')
main() main()
elif usrInput == "quit": # Quits the application elif usrInput == "quit": # Quits the application
print '\n Bye\n' print('\n Bye\n')
sys.exit(0) sys.exit(0)
elif usrInput == "listaddresses": # Lists all of the identities in the addressbook elif usrInput == "listaddresses": # Lists all of the identities in the addressbook
@ -1508,17 +1508,17 @@ def UI(usrInput):
if isRipe == "y": if isRipe == "y":
ripe = True ripe = True
print genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe) print(genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe))
main() main()
elif isRipe == "n": elif isRipe == "n":
ripe = False ripe = False
print genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe) print(genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe))
main() main()
elif isRipe == "exit": elif isRipe == "exit":
usrPrompt = 1 usrPrompt = 1
main() main()
else: else:
print '\n Invalid input\n' print('\n Invalid input\n')
main() main()
elif uInput == "r" or uInput == "random": # Creates a random address with user-defined label elif uInput == "r" or uInput == "random": # Creates a random address with user-defined label
@ -1526,18 +1526,18 @@ def UI(usrInput):
null = '' null = ''
lbl = userInput('Enter the label for the new address.') lbl = userInput('Enter the label for the new address.')
print genAdd(lbl, deterministic, null, null, null, null, null) print(genAdd(lbl, deterministic, null, null, null, null, null))
main() main()
else: else:
print '\n Invalid input\n' print('\n Invalid input\n')
main() main()
elif usrInput == "getaddress": # Gets the address for/from a passphrase elif usrInput == "getaddress": # Gets the address for/from a passphrase
phrase = userInput("Enter the address passphrase.") phrase = userInput("Enter the address passphrase.")
print '\n Working...\n' print('\n Working...\n')
address = getAddress(phrase, 4, 1) # ,vNumber,sNumber) address = getAddress(phrase, 4, 1) # ,vNumber,sNumber)
print '\n Address: ' + address + '\n' print('\n Address: ' + address + '\n')
usrPrompt = 1 usrPrompt = 1
main() main()
@ -1572,17 +1572,17 @@ def UI(usrInput):
main() main()
elif usrInput == "inbox": elif usrInput == "inbox":
print '\n Loading...\n' print('\n Loading...\n')
inbox() inbox()
main() main()
elif usrInput == "unread": elif usrInput == "unread":
print '\n Loading...\n' print('\n Loading...\n')
inbox(True) inbox(True)
main() main()
elif usrInput == "outbox": elif usrInput == "outbox":
print '\n Loading...\n' print('\n Loading...\n')
outbox() outbox()
main() main()
@ -1603,14 +1603,14 @@ def UI(usrInput):
uInput = userInput("Would you like to read a message from the (I)nbox or (O)utbox?").lower() uInput = userInput("Would you like to read a message from the (I)nbox or (O)utbox?").lower()
if (uInput != 'i' and uInput != 'inbox' and uInput != 'o' and uInput != 'outbox'): if (uInput != 'i' and uInput != 'inbox' and uInput != 'o' and uInput != 'outbox'):
print '\n Invalid Input.\n' print('\n Invalid Input.\n')
usrPrompt = 1 usrPrompt = 1
main() main()
msgNum = int(userInput("What is the number of the message you wish to open?")) msgNum = int(userInput("What is the number of the message you wish to open?"))
if (uInput == 'i' or uInput == 'inbox'): if (uInput == 'i' or uInput == 'inbox'):
print '\n Loading...\n' print('\n Loading...\n')
messageID = readMsg(msgNum) messageID = readMsg(msgNum)
uInput = userInput("\nWould you like to keep this message unread, (Y)es or (N)o?").lower() uInput = userInput("\nWould you like to keep this message unread, (Y)es or (N)o?").lower()
@ -1622,14 +1622,14 @@ def UI(usrInput):
uInput = userInput("\nWould you like to (D)elete, (F)orward, (R)eply to, or (Exit) this message?").lower() uInput = userInput("\nWould you like to (D)elete, (F)orward, (R)eply to, or (Exit) this message?").lower()
if uInput in ['r', 'reply']: if uInput in ['r', 'reply']:
print '\n Loading...\n' print('\n Loading...\n')
print ' ' print(' ')
replyMsg(msgNum, 'reply') replyMsg(msgNum, 'reply')
usrPrompt = 1 usrPrompt = 1
elif uInput == 'f' or uInput == 'forward': elif uInput == 'f' or uInput == 'forward':
print '\n Loading...\n' print('\n Loading...\n')
print ' ' print(' ')
replyMsg(msgNum, 'forward') replyMsg(msgNum, 'forward')
usrPrompt = 1 usrPrompt = 1
@ -1638,12 +1638,12 @@ def UI(usrInput):
if uInput == "y": if uInput == "y":
delMsg(msgNum) delMsg(msgNum)
print '\n Message Deleted.\n' print('\n Message Deleted.\n')
usrPrompt = 1 usrPrompt = 1
else: else:
usrPrompt = 1 usrPrompt = 1
else: else:
print '\n Invalid entry\n' print('\n Invalid entry\n')
usrPrompt = 1 usrPrompt = 1
elif (uInput == 'o' or uInput == 'outbox'): elif (uInput == 'o' or uInput == 'outbox'):
@ -1657,12 +1657,12 @@ def UI(usrInput):
if uInput == "y": if uInput == "y":
delSentMsg(msgNum) delSentMsg(msgNum)
print '\n Message Deleted.\n' print('\n Message Deleted.\n')
usrPrompt = 1 usrPrompt = 1
else: else:
usrPrompt = 1 usrPrompt = 1
else: else:
print '\n Invalid Entry\n' print('\n Invalid Entry\n')
usrPrompt = 1 usrPrompt = 1
main() main()
@ -1672,7 +1672,7 @@ def UI(usrInput):
uInput = userInput("Would you like to save a message from the (I)nbox or (O)utbox?").lower() uInput = userInput("Would you like to save a message from the (I)nbox or (O)utbox?").lower()
if uInput not in ['i', 'inbox', 'o', 'outbox']: if uInput not in ['i', 'inbox', 'o', 'outbox']:
print '\n Invalid Input.\n' print('\n Invalid Input.\n')
usrPrompt = 1 usrPrompt = 1
main() main()
@ -1684,7 +1684,7 @@ def UI(usrInput):
msgNum = int(userInput("What is the number of the message you wish to save?")) msgNum = int(userInput("What is the number of the message you wish to save?"))
if msgNum >= numMessages: if msgNum >= numMessages:
print '\n Invalid Message Number.\n' print('\n Invalid Message Number.\n')
else: else:
break break
@ -1700,7 +1700,7 @@ def UI(usrInput):
msgNum = int(userInput("What is the number of the message you wish to save?")) msgNum = int(userInput("What is the number of the message you wish to save?"))
if msgNum >= numMessages: if msgNum >= numMessages:
print '\n Invalid Message Number.\n' print('\n Invalid Message Number.\n')
else: else:
break break
@ -1729,7 +1729,7 @@ def UI(usrInput):
if msgNum == 'a' or msgNum == 'all': if msgNum == 'a' or msgNum == 'all':
break break
elif int(msgNum) >= numMessages: elif int(msgNum) >= numMessages:
print '\n Invalid Message Number.\n' print('\n Invalid Message Number.\n')
else: else:
break break
@ -1737,17 +1737,17 @@ def UI(usrInput):
if uInput == "y": if uInput == "y":
if msgNum in ['a', 'all']: if msgNum in ['a', 'all']:
print ' ' print(' ')
for msgNum in range(0, numMessages): # processes all of the messages in the inbox for msgNum in range(0, numMessages): # processes all of the messages in the inbox
print ' Deleting message ', msgNum + 1, ' of ', numMessages print(' Deleting message ', msgNum + 1, ' of ', numMessages)
delMsg(0) delMsg(0)
print '\n Inbox is empty.' print('\n Inbox is empty.')
usrPrompt = 1 usrPrompt = 1
else: else:
delMsg(int(msgNum)) delMsg(int(msgNum))
print '\n Notice: Message numbers may have changed.\n' print('\n Notice: Message numbers may have changed.\n')
main() main()
else: else:
usrPrompt = 1 usrPrompt = 1
@ -1763,7 +1763,7 @@ def UI(usrInput):
if msgNum in ['a', 'all']: if msgNum in ['a', 'all']:
break break
elif int(msgNum) >= numMessages: elif int(msgNum) >= numMessages:
print '\n Invalid Message Number.\n' print('\n Invalid Message Number.\n')
else: else:
break break
@ -1771,33 +1771,33 @@ def UI(usrInput):
if uInput == "y": if uInput == "y":
if msgNum in ['a', 'all']: if msgNum in ['a', 'all']:
print ' ' print(' ')
for msgNum in range(0, numMessages): # processes all of the messages in the outbox for msgNum in range(0, numMessages): # processes all of the messages in the outbox
print ' Deleting message ', msgNum + 1, ' of ', numMessages print(' Deleting message ', msgNum + 1, ' of ', numMessages)
delSentMsg(0) delSentMsg(0)
print '\n Outbox is empty.' print('\n Outbox is empty.')
usrPrompt = 1 usrPrompt = 1
else: else:
delSentMsg(int(msgNum)) delSentMsg(int(msgNum))
print '\n Notice: Message numbers may have changed.\n' print('\n Notice: Message numbers may have changed.\n')
main() main()
else: else:
usrPrompt = 1 usrPrompt = 1
else: else:
print '\n Invalid Entry.\n' print('\n Invalid Entry.\n')
usrPrompt = 1 usrPrompt = 1
main() main()
elif usrInput == "exit": elif usrInput == "exit":
print '\n You are already at the main menu. Use "quit" to quit.\n' print('\n You are already at the main menu. Use "quit" to quit.\n')
usrPrompt = 1 usrPrompt = 1
main() main()
elif usrInput == "listaddressbookentries": elif usrInput == "listaddressbookentries":
res = listAddressBookEntries() res = listAddressBookEntries()
if res == 20: if res == 20:
print '\n Error: API function not supported.\n' print('\n Error: API function not supported.\n')
usrPrompt = 1 usrPrompt = 1
main() main()
@ -1806,9 +1806,9 @@ def UI(usrInput):
label = userInput('Enter label') label = userInput('Enter label')
res = addAddressToAddressBook(address, label) res = addAddressToAddressBook(address, label)
if res == 16: if res == 16:
print '\n Error: Address already exists in Address Book.\n' print('\n Error: Address already exists in Address Book.\n')
if res == 20: if res == 20:
print '\n Error: API function not supported.\n' print('\n Error: API function not supported.\n')
usrPrompt = 1 usrPrompt = 1
main() main()
@ -1816,7 +1816,7 @@ def UI(usrInput):
address = userInput('Enter address') address = userInput('Enter address')
res = deleteAddressFromAddressBook(address) res = deleteAddressFromAddressBook(address)
if res == 20: if res == 20:
print '\n Error: API function not supported.\n' print('\n Error: API function not supported.\n')
usrPrompt = 1 usrPrompt = 1
main() main()
@ -1841,7 +1841,7 @@ def UI(usrInput):
main() main()
else: else:
print '\n "', usrInput, '" is not a command.\n' print('\n "', usrInput, '" is not a command.\n')
usrPrompt = 1 usrPrompt = 1
main() main()
@ -1853,24 +1853,24 @@ def main():
global usrPrompt global usrPrompt
if usrPrompt == 0: if usrPrompt == 0:
print '\n ------------------------------' print('\n ------------------------------')
print ' | Bitmessage Daemon by .dok |' print(' | Bitmessage Daemon by .dok |')
print ' | Version 0.3.1 for BM 0.6.2 |' print(' | Version 0.3.1 for BM 0.6.2 |')
print ' ------------------------------' print(' ------------------------------')
api = xmlrpclib.ServerProxy(apiData()) # Connect to BitMessage using these api credentials api = xmlrpclib.ServerProxy(apiData()) # Connect to BitMessage using these api credentials
if apiTest() is False: if apiTest() is False:
print '\n ****************************************************************' print('\n ****************************************************************')
print ' WARNING: You are not connected to the Bitmessage client.' print(' WARNING: You are not connected to the Bitmessage client.')
print ' Either Bitmessage is not running or your settings are incorrect.' print(' Either Bitmessage is not running or your settings are incorrect.')
print ' Use the command "apiTest" or "bmSettings" to resolve this issue.' print(' Use the command "apiTest" or "bmSettings" to resolve this issue.')
print ' ****************************************************************\n' print(' ****************************************************************\n')
print 'Type (H)elp for a list of commands.' # Startup message print('Type (H)elp for a list of commands.') # Startup message
usrPrompt = 2 usrPrompt = 2
elif usrPrompt == 1: elif usrPrompt == 1:
print '\nType (H)elp for a list of commands.' # Startup message print('\nType (H)elp for a list of commands.') # Startup message
usrPrompt = 2 usrPrompt = 2
try: try:

View File

@ -34,7 +34,8 @@ import tr
from fallback import RIPEMD160Hash from fallback import RIPEMD160Hash
import l10n import l10n
# pylint: disable=too-many-locals, too-many-return-statements, too-many-branches, too-many-statements # pylint: disable=too-many-locals, too-many-return-statements
# pylint: disable=too-many-branches, too-many-statements
logger = logging.getLogger('default') logger = logging.getLogger('default')
@ -644,7 +645,8 @@ class objectProcessor(threading.Thread):
if decodeAddress(toAddress)[1] >= 3 \ if decodeAddress(toAddress)[1] >= 3 \
and not BMConfigParser().safeGetBoolean(toAddress, 'chan'): and not BMConfigParser().safeGetBoolean(toAddress, 'chan'):
# If I'm not friendly with this person: # If I'm not friendly with this person:
if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(fromAddress): if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(
fromAddress):
requiredNonceTrialsPerByte = BMConfigParser().getint( requiredNonceTrialsPerByte = BMConfigParser().getint(
toAddress, 'noncetrialsperbyte') toAddress, 'noncetrialsperbyte')
requiredPayloadLengthExtraBytes = BMConfigParser().getint( requiredPayloadLengthExtraBytes = BMConfigParser().getint(

View File

@ -114,8 +114,9 @@ class smtpServerPyBitmessage(smtpd.SMTPServer):
return ret return ret
def process_message(self, peer, mailfrom, rcpttos, data): # pylint: disable=too-many-locals, too-many-branches def process_message(self, peer, mailfrom, rcpttos, data):
"""Process an email""" """Process an email"""
# pylint: disable=too-many-locals, too-many-branches
# print 'Receiving message from:', peer # print 'Receiving message from:', peer
p = re.compile(".*<([^>]+)>") p = re.compile(".*<([^>]+)>")
if not hasattr(self.channel, "auth") or not self.channel.auth: if not hasattr(self.channel, "auth") or not self.channel.auth:

View File

@ -231,12 +231,13 @@ def check_sqlite():
conn.close() conn.close()
def check_openssl(): # pylint: disable=too-many-branches, too-many-return-statements def check_openssl():
"""Do openssl dependency check. """Do openssl dependency check.
Here we are checking for openssl with its all dependent libraries Here we are checking for openssl with its all dependent libraries
and version checking. and version checking.
""" """
# pylint: disable=too-many-branches, too-many-return-statements
# pylint: disable=protected-access, redefined-outer-name # pylint: disable=protected-access, redefined-outer-name
ctypes = try_import('ctypes') ctypes = try_import('ctypes')
if not ctypes: if not ctypes:
@ -365,6 +366,7 @@ def check_pyqt():
Here we are checking for PyQt4 with its version, as for it require Here we are checking for PyQt4 with its version, as for it require
PyQt 4.8 or later. PyQt 4.8 or later.
""" """
QtCore = try_import( QtCore = try_import(
'PyQt4.QtCore', 'PyBitmessage requires PyQt 4.8 or later and Qt 4.7 or later.') 'PyQt4.QtCore', 'PyBitmessage requires PyQt 4.8 or later and Qt 4.7 or later.')

View File

@ -22,7 +22,7 @@ def genAckPayload(streamNumber=1, stealthLevel=0):
- level 1: a getpubkey request for a (random) dummy key hash - level 1: a getpubkey request for a (random) dummy key hash
- level 2: a standard message, encrypted to a random pubkey - level 2: a standard message, encrypted to a random pubkey
""" """
if stealthLevel == 2: # Generate privacy-enhanced payload if stealthLevel == 2: # Generate privacy-enhanced payload
# Generate a dummy privkey and derive the pubkey # Generate a dummy privkey and derive the pubkey
dummyPubKeyHex = highlevelcrypto.privToPub( dummyPubKeyHex = highlevelcrypto.privToPub(
hexlify(helper_random.randomBytes(32))) hexlify(helper_random.randomBytes(32)))
@ -35,12 +35,12 @@ def genAckPayload(streamNumber=1, stealthLevel=0):
acktype = 2 # message acktype = 2 # message
version = 1 version = 1
elif stealthLevel == 1: # Basic privacy payload (random getpubkey) elif stealthLevel == 1: # Basic privacy payload (random getpubkey)
ackdata = helper_random.randomBytes(32) ackdata = helper_random.randomBytes(32)
acktype = 0 # getpubkey acktype = 0 # getpubkey
version = 4 version = 4
else: # Minimum viable payload (non stealth) else: # Minimum viable payload (non stealth)
ackdata = helper_random.randomBytes(32) ackdata = helper_random.randomBytes(32)
acktype = 2 # message acktype = 2 # message
version = 1 version = 1

View File

@ -53,3 +53,4 @@ def calculateTestnetAddressFromPubkey(pubkey):
numberOfZeroBytesOnBinaryBitcoinAddress += 1 numberOfZeroBytesOnBinaryBitcoinAddress += 1
binaryBitcoinAddress = binaryBitcoinAddress[1:] binaryBitcoinAddress = binaryBitcoinAddress[1:]
base58encoded = arithmetic.changebase(binaryBitcoinAddress, 256, 58) base58encoded = arithmetic.changebase(binaryBitcoinAddress, 256, 58)
return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded

View File

@ -7,6 +7,7 @@ try:
haveQt = True haveQt = True
except ImportError: except ImportError:
haveQt = False haveQt = False
# pylint: disable=too-many-arguments
def search_translate(context, text): def search_translate(context, text):
@ -18,7 +19,7 @@ def search_translate(context, text):
def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, what=None, unreadOnly=False): def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, what=None, unreadOnly=False):
"""Perform a search in mailbox tables""" """Perform a search in mailbox tables"""
# pylint: disable=too-many-arguments, too-many-branches # pylint: disable=too-many-branches
if what is not None and what != "": if what is not None and what != "":
what = "%" + what + "%" what = "%" + what + "%"
if where == search_translate("MainWindow", "To"): if where == search_translate("MainWindow", "To"):
@ -75,7 +76,6 @@ def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, w
def check_match(toAddress, fromAddress, subject, message, where=None, what=None): def check_match(toAddress, fromAddress, subject, message, where=None, what=None):
"""Check if a single message matches a filter (used when new messages are added to messagelists)""" """Check if a single message matches a filter (used when new messages are added to messagelists)"""
# pylint: disable=too-many-arguments
if what is not None and what != "": if what is not None and what != "":
if where in (search_translate("MainWindow", "To"), search_translate("MainWindow", "All")): if where in (search_translate("MainWindow", "To"), search_translate("MainWindow", "All")):
if what.lower() not in toAddress.lower(): if what.lower() not in toAddress.lower():

View File

@ -1,8 +1,8 @@
""" """
Insert values into sent table Insert values into sent table
""" """
from helper_sql import sqlExecute
from helper_sql import *
def insert(t): def insert(t):
"""Perform an insert into the `sent` table""" """Perform an insert into the `sent` table"""

View File

@ -101,7 +101,7 @@ def sqlStoredProcedure(procName):
sqlLock.release() sqlLock.release()
class SqlBulkExecute(object): class SqlBulkExecute(object): # pylint: disable=no-init
"""This is used when you have to execute the same statement in a cycle.""" """This is used when you have to execute the same statement in a cycle."""
def __enter__(self): def __enter__(self):

View File

@ -4,7 +4,6 @@ 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 os import os
import platform import platform
import sys import sys
@ -21,6 +20,7 @@ from bmconfigparser import BMConfigParser
# the config files to stay in the application data folder. # the config files to stay in the application data folder.
StoreConfigFilesInSameDirectoryAsProgramByDefault = False StoreConfigFilesInSameDirectoryAsProgramByDefault = False
def loadConfig(): def loadConfig():
"""Load the config""" """Load the config"""
config = BMConfigParser() config = BMConfigParser()
@ -116,7 +116,6 @@ def loadConfig():
updateConfig() updateConfig()
def updateConfig(): def updateConfig():
"""Save the config""" """Save the config"""
config = BMConfigParser() config = BMConfigParser()

View File

@ -1,8 +1,8 @@
"""The Inventory singleton""" """The Inventory singleton"""
# TODO make this dynamic, and watch out for frozen, like with messagetypes # TODO make this dynamic, and watch out for frozen, like with messagetypes
import storage.sqlite
import storage.filesystem import storage.filesystem
import storage.sqlite
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
from singleton import Singleton from singleton import Singleton

View File

@ -64,25 +64,25 @@ else:
# comprehensive decoding tests # comprehensive decoding tests
if time_format != DEFAULT_TIME_FORMAT: if time_format != DEFAULT_TIME_FORMAT:
try: try:
#Check day names # Check day names
new_time_format = time_format new_time_format = time_format
import sys import sys
if sys.version_info >= (3, 0, 0) and time_format == '%%c': if sys.version_info >= (3, 0, 0) and time_format == '%%c':
time_format = '%c' time_format = '%c'
for i in range(7): for i in range(7):
#this work for python2.7 # this work for python2.7
# unicode(time.strftime(time_format, (0, 0, 0, 0, 0, 0, i, 0, 0)), encoding) # unicode(time.strftime(time_format, (0, 0, 0, 0, 0, 0, i, 0, 0)), encoding)
#this code for the python3 # this code for the python3
(time.strftime(time_format, (0, 0, 0, 0, 0, 0, i, 0, 0))).encode() (time.strftime(time_format, (0, 0, 0, 0, 0, 0, i, 0, 0))).encode()
#Check month names # Check month names
for i in range(1, 13): 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() (time.strftime(time_format, (0, i, 0, 0, 0, 0, 0, 0, 0))).encode()
#Check AM/PM # Check AM/PM
(time.strftime(time_format, (0, 0, 0, 11, 0, 0, 0, 0, 0))).encode() (time.strftime(time_format, (0, 0, 0, 11, 0, 0, 0, 0, 0))).encode()
(time.strftime(time_format, (0, 0, 0, 13, 0, 0, 0, 0, 0))).encode() (time.strftime(time_format, (0, 0, 0, 13, 0, 0, 0, 0, 0))).encode()
#Check DST # Check DST
(time.strftime(time_format, (0, 0, 0, 0, 0, 0, 0, 0, 1))).encode() (time.strftime(time_format, (0, 0, 0, 0, 0, 0, 0, 0, 1))).encode()
except: except:

View File

@ -119,4 +119,4 @@ if __name__ == "__main__":
nonce = do_opencl_pow(initialHash.encode("hex"), target_) nonce = do_opencl_pow(initialHash.encode("hex"), target_)
trialValue, = unpack( trialValue, = unpack(
'>Q', hashlib.sha512(hashlib.sha512(pack('>Q', nonce) + initialHash).digest()).digest()[0:8]) '>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

@ -294,7 +294,7 @@ def init():
global bitmsglib, bmpow global bitmsglib, bmpow
openclpow.initCL() openclpow.initCL()
if "win32" == sys.platform: if sys.platform == "win32":
if ctypes.sizeof(ctypes.c_voidp) == 4: if ctypes.sizeof(ctypes.c_voidp) == 4:
bitmsglib = 'bitmsghash32.dll' bitmsglib = 'bitmsghash32.dll'
else: else:
@ -323,7 +323,7 @@ def init():
elif platform == "android": elif platform == "android":
try: try:
bso = ctypes.CDLL('libbitmsghash.so') bso = ctypes.CDLL('libbitmsghash.so')
except Exception as e: except Exception:
bso = None bso = None
else: else:

View File

@ -185,7 +185,8 @@ def checkIPv4Address(host, hostStandardFormat, private=False):
logger.debug( logger.debug(
'Ignoring IP address in private range: %s', hostStandardFormat) 'Ignoring IP address in private range: %s', hostStandardFormat)
return hostStandardFormat if private else False return hostStandardFormat if private else False
if host[0:2] >= '\xAC\x10'.encode('raw_unicode_escape') and host[0:2] < '\xAC\x20'.encode('raw_unicode_escape'): # 172.16/12 # 172.16/12
if host[0:2] >= '\xAC\x10'.encode('raw_unicode_escape') and host[0:2] < '\xAC\x20'.encode('raw_unicode_escape'):
if not private: if not private:
logger.debug( logger.debug(
'Ignoring IP address in private range: %s', hostStandardFormat) 'Ignoring IP address in private range: %s', hostStandardFormat)
@ -198,15 +199,15 @@ def checkIPv6Address(host, hostStandardFormat, private=False):
if host == ('\x00'.encode() * 15) + '\x01'.encode(): if host == ('\x00'.encode() * 15) + '\x01'.encode():
if not private: if not private:
logger.debug('Ignoring loopback address: {}'.format( hostStandardFormat)) logger.debug('Ignoring loopback address: {}'.format(hostStandardFormat))
return False return False
if host[0] == '\xFE' and (ord(host[1]) & 0xc0) == 0x80: if host[0] == '\xFE' and (ord(host[1]) & 0xc0) == 0x80:
if not private: if not private:
logger.debug('Ignoring local address: {}'.format( hostStandardFormat)) logger.debug('Ignoring local address: {}'.format(hostStandardFormat))
return hostStandardFormat if private else False return hostStandardFormat if private else False
if (ord(host[0:1]) & 0xfe) == 0xfc: if (ord(host[0:1]) & 0xfe) == 0xfc:
if not private: if not private:
logger.debug('Ignoring unique local address: {}'.format( hostStandardFormat)) logger.debug('Ignoring unique local address: {}'.format(hostStandardFormat))
return hostStandardFormat if private else False return hostStandardFormat if private else False
return False if private else hostStandardFormat return False if private else hostStandardFormat
@ -325,7 +326,7 @@ def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server=
) )
# = 127.0.0.1. This will be ignored by the remote host. The actual remote connected IP will be used. # = 127.0.0.1. This will be ignored by the remote host. The actual remote connected IP will be used.
#python3 need to check # python3 need to check
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode() + pack('>L', 2130706433) payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode() + pack('>L', 2130706433)
# we have a separate extPort and incoming over clearnet # we have a separate extPort and incoming over clearnet
@ -338,11 +339,10 @@ def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server=
): ):
payload += pack('>H', extport) payload += pack('>H', extport)
elif checkSocksIP(remoteHost) and server: # incoming connection over Tor elif checkSocksIP(remoteHost) and server: # incoming connection over Tor
payload += pack('>H', int(BMConfigParser().safeGet('bitmessagesettings', 'onionport'))) payload += pack('>H', int(BMConfigParser().safeGet('bitmessagesettings', 'onionport')))
else: # no extport and not incoming over Tor else: # no extport and not incoming over Tor
payload += pack('>H', int(BMConfigParser().safeGet('bitmessagesettings', 'port'))) payload += pack('>H', int(BMConfigParser().safeGet('bitmessagesettings', 'port')))
if nodeid is not None: if nodeid is not None:
payload += nodeid[0:8] payload += nodeid[0:8]
else: else:
@ -374,7 +374,7 @@ def assembleErrorMessage(fatal=0, banTime=0, inventoryVector='', errorText=''):
payload += encodeVarint(len(inventoryVector)) payload += encodeVarint(len(inventoryVector))
payload += inventoryVector.encode() if type(payload) == bytes else inventoryVector payload += inventoryVector.encode() if type(payload) == bytes else inventoryVector
payload += encodeVarint(len(errorText)) payload += encodeVarint(len(errorText))
payload += errorText.encode() if type(payload)== bytes else errorText payload += errorText.encode() if type(payload) == bytes else errorText
return CreatePacket('error', payload) return CreatePacket('error', payload)

View File

@ -1,6 +1,5 @@
import queue as Queue
"""Most of the queues used by bitmessage threads are defined here.""" """Most of the queues used by bitmessage threads are defined here."""
import queue as Queue
import threading import threading
import time import time

View File

@ -1,3 +1,3 @@
from threading import Semaphore from threading import Semaphore
kivyuisignaler = Semaphore(0) kivyuisignaler = Semaphore(0)

View File

@ -101,6 +101,7 @@ def isAddressInMyAddressBookSubscriptionsListOrWhitelist(address):
return True return True
return False return False
def decodeWalletImportFormat(WIFstring): def decodeWalletImportFormat(WIFstring):
# pylint: disable=inconsistent-return-statements # pylint: disable=inconsistent-return-statements
""" """
@ -116,7 +117,7 @@ def decodeWalletImportFormat(WIFstring):
' 6 characters of the PRIVATE key: {}'.format(str(WIFstring)[:6]) ' 6 characters of the PRIVATE key: {}'.format(str(WIFstring)[:6])
) )
os._exit(0) os._exit(0) # pylint: disable=protected-access
if privkey[0:1] == '\x80'.encode()[1:]: # checksum passed if privkey[0:1] == '\x80'.encode()[1:]: # checksum passed
return privkey[1:] return privkey[1:]

View File

@ -75,7 +75,7 @@ class singleinstance(object):
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
@ -95,10 +95,10 @@ class singleinstance(object):
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 as e: except Exception:
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

@ -109,4 +109,4 @@ availabe_credit = 0
in_sent_method = False in_sent_method = False
in_search_mode = False in_search_mode = False

View File

@ -6,17 +6,17 @@ import os
import state import state
class translateClass: class translateClass(object):
""" """
This is used so that the translateText function can be used This is used so that the translateText function can be used
when we are in daemon mode and not using any QT functions. when we are in daemon mode and not using any QT functions.
""" """
# pylint: disable=old-style-class,too-few-public-methods # pylint: disable=too-few-public-methods
def __init__(self, context, text): def __init__(self, context, text):
self.context = context self.context = context
self.text = text self.text = text
def arg(self, argument): # pylint: disable=unused-argument def arg(self, _):
"""Replace argument placeholders""" """Replace argument placeholders"""
if '%' in self.text: if '%' in self.text:
return translateClass(self.context, self.text.replace('%', '', 1)) return translateClass(self.context, self.text.replace('%', '', 1))
@ -25,7 +25,7 @@ class translateClass:
return self.text return self.text
def _translate(context, text, disambiguation=None, encoding=None, n=None): # pylint: disable=unused-argument def _translate(context, text, disambiguation=None, encoding=None, n=None): # pylint: disable=unused-argument
return translateText(context, text, n) return translateText(context, text, n)
@ -39,12 +39,12 @@ 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)

View File

@ -1,8 +1,8 @@
# pylint: disable=too-many-statements,too-many-branches,protected-access,no-self-use """
"""
Complete UPnP port forwarding implementation in separate thread. Complete UPnP port forwarding implementation in separate thread.
Reference: http://mattscodecave.com/posts/using-python-and-upnp-to-forward-a-port Reference: http://mattscodecave.com/posts/using-python-and-upnp-to-forward-a-port
""" """
# pylint: disable=too-many-statements,too-many-branches,protected-access,no-self-use
import httplib import httplib
import socket import socket
@ -19,8 +19,8 @@ import tr
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
from debug import logger from debug import logger
from network.connectionpool import BMConnectionPool from network.connectionpool import BMConnectionPool
from network.threads import StoppableThread
from network.node import Peer from network.node import Peer
from network.threads import StoppableThread
def createRequestXML(service, action, arguments=None): def createRequestXML(service, action, arguments=None):
@ -83,6 +83,7 @@ class UPnPError(Exception):
class Router: # pylint: disable=old-style-class class Router: # pylint: disable=old-style-class
"""Encapulate routing""" """Encapulate routing"""
name = "" name = ""
path = "" path = ""
address = None address = None
@ -152,7 +153,6 @@ class Router: # pylint: disable=old-style-class
def DeletePortMapping(self, externalPort, protocol): def DeletePortMapping(self, externalPort, protocol):
"""Delete UPnP port mapping""" """Delete UPnP port mapping"""
resp = self.soapRequest(self.upnp_schema + ':1', 'DeletePortMapping', [ resp = self.soapRequest(self.upnp_schema + ':1', 'DeletePortMapping', [
('NewRemoteHost', ''), ('NewRemoteHost', ''),
('NewExternalPort', str(externalPort)), ('NewExternalPort', str(externalPort)),
@ -163,16 +163,12 @@ class Router: # pylint: disable=old-style-class
def GetExternalIPAddress(self): def GetExternalIPAddress(self):
"""Get the external address""" """Get the external address"""
resp = self.soapRequest(self.upnp_schema + ':1', 'GetExternalIPAddress')
resp = self.soapRequest(
self.upnp_schema + ':1', 'GetExternalIPAddress')
dom = parseString(resp.read()) dom = parseString(resp.read())
return dom.getElementsByTagName( return dom.getElementsByTagName('NewExternalIPAddress')[0].childNodes[0].data
'NewExternalIPAddress')[0].childNodes[0].data
def soapRequest(self, service, action, arguments=None): def soapRequest(self, service, action, arguments=None):
"""Make a request to a router""" """Make a request to a router"""
conn = httplib.HTTPConnection(self.routerPath.hostname, self.routerPath.port) conn = httplib.HTTPConnection(self.routerPath.hostname, self.routerPath.port)
conn.request( conn.request(
'POST', 'POST',
@ -223,7 +219,6 @@ class uPnPThread(StoppableThread):
def run(self): def run(self):
"""Start the thread to manage UPnP activity""" """Start the thread to manage UPnP activity"""
logger.debug("Starting UPnP thread") logger.debug("Starting UPnP thread")
logger.debug("Local IP: %s", self.localIP) logger.debug("Local IP: %s", self.localIP)
lastSent = 0 lastSent = 0
@ -261,16 +256,12 @@ class uPnPThread(StoppableThread):
self.routers.append(newRouter) self.routers.append(newRouter)
self.createPortMapping(newRouter) self.createPortMapping(newRouter)
try: try:
self_peer = Peer( self_peer = Peer(newRouter.GetExternalIPAddress(), self.extPort)
newRouter.GetExternalIPAddress(),
self.extPort
)
except: except:
logger.debug('Failed to get external IP') logger.debug('Failed to get external IP')
else: else:
with knownnodes.knownNodesLock: with knownnodes.knownNodesLock:
knownnodes.addKnownNode( knownnodes.addKnownNode(1, self_peer, is_self=True)
1, self_peer, is_self=True)
queues.UISignalQueue.put(('updateStatusBar', tr._translate( queues.UISignalQueue.put(('updateStatusBar', tr._translate(
"MainWindow", 'UPnP port mapping established on port %1' "MainWindow", 'UPnP port mapping established on port %1'
).arg(str(self.extPort)))) ).arg(str(self.extPort))))
@ -296,12 +287,12 @@ class uPnPThread(StoppableThread):
deleted = True deleted = True
self.deletePortMapping(router) self.deletePortMapping(router)
if deleted: if deleted:
queues.UISignalQueue.put(('updateStatusBar', tr._translate("MainWindow", 'UPnP port mapping removed'))) queues.UISignalQueue.put(
('updateStatusBar', tr._translate("MainWindow", 'UPnP port mapping removed')))
logger.debug("UPnP thread done") logger.debug("UPnP thread done")
def getLocalIP(self): def getLocalIP(self):
"""Get the local IP of the node""" """Get the local IP of the node"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.connect((uPnPThread.GOOGLE_DNS, 1)) s.connect((uPnPThread.GOOGLE_DNS, 1))
@ -309,7 +300,6 @@ class uPnPThread(StoppableThread):
def sendSearchRouter(self): def sendSearchRouter(self):
"""Querying for UPnP services""" """Querying for UPnP services"""
ssdpRequest = "M-SEARCH * HTTP/1.1\r\n" + \ ssdpRequest = "M-SEARCH * HTTP/1.1\r\n" + \
"HOST: %s:%d\r\n" % (uPnPThread.SSDP_ADDR, uPnPThread.SSDP_PORT) + \ "HOST: %s:%d\r\n" % (uPnPThread.SSDP_ADDR, uPnPThread.SSDP_PORT) + \
"MAN: \"ssdp:discover\"\r\n" + \ "MAN: \"ssdp:discover\"\r\n" + \
@ -324,7 +314,6 @@ class uPnPThread(StoppableThread):
def createPortMapping(self, router): def createPortMapping(self, router):
"""Add a port mapping""" """Add a port mapping"""
for i in range(50): for i in range(50):
try: try:
localIP = self.localIP localIP = self.localIP
@ -336,10 +325,7 @@ class uPnPThread(StoppableThread):
extPort = randint(32767, 65535) extPort = randint(32767, 65535)
logger.debug( logger.debug(
"Attempt %i, requesting UPnP mapping for %s:%i on external port %i", "Attempt %i, requesting UPnP mapping for %s:%i on external port %i",
i, i, localIP, self.localPort, extPort)
localIP,
self.localPort,
extPort)
router.AddPortMapping(extPort, self.localPort, localIP, 'TCP', 'BitMessage') router.AddPortMapping(extPort, self.localPort, localIP, 'TCP', 'BitMessage')
self.extPort = extPort self.extPort = extPort
BMConfigParser().set('bitmessagesettings', 'extport', str(extPort)) BMConfigParser().set('bitmessagesettings', 'extport', str(extPort))