Updated origin and solved conflicts

This commit is contained in:
jai.s 2020-01-08 17:05:29 +05:30
commit fdbc175769
No known key found for this signature in database
GPG Key ID: 360CFA25EFC67D12
60 changed files with 927 additions and 850 deletions

View File

@ -2,7 +2,6 @@
Operations with addresses Operations with addresses
""" """
# pylint: disable=redefined-outer-name,inconsistent-return-statements # pylint: disable=redefined-outer-name,inconsistent-return-statements
import hashlib import hashlib
from binascii import hexlify, unhexlify from binascii import hexlify, unhexlify
from struct import pack, unpack from struct import pack, unpack
@ -46,7 +45,8 @@ def decodeBase58(string, alphabet=ALPHABET):
for char in string: for char in string:
num *= base num *= base
num += alphabet.index(char) num += alphabet.index(char)
except: # ValueError # ValueError
except:
# character not found (like a space character or a 0) # character not found (like a space character or a 0)
return 0 return 0
return num return num
@ -85,13 +85,13 @@ def decodeVarint(data):
the minimum amount of data possible or else it is malformed. the minimum amount of data possible or else it is malformed.
Returns a tuple: (theEncodedValue, theSizeOfTheVarintInBytes) Returns a tuple: (theEncodedValue, theSizeOfTheVarintInBytes)
""" """
if not data: if not data:
return (0, 0) return (0, 0)
firstByte, = unpack('>B', data[0:1]) firstByte, = unpack('>B', data[0:1])
if firstByte < 253: if firstByte < 253:
# encodes 0 to 252 # encodes 0 to 252
return (firstByte, 1) # the 1 is the length of the varint # the 1 is the length of the varint
return (firstByte, 1)
if firstByte == 253: if firstByte == 253:
# encodes 253 to 65535 # encodes 253 to 65535
if len(data) < 3: if len(data) < 3:
@ -180,7 +180,8 @@ def decodeAddress(address):
returns (status, address version number, stream number, returns (status, address version number, stream number,
data (almost certainly a ripe hash)) data (almost certainly a ripe hash))
""" """
# pylint: disable=too-many-return-statements,too-many-statements,too-many-return-statements,too-many-branches # pylint: disable=too-many-return-statements,too-many-statements
# pylint: disable=too-many-branches
address = str(address).strip() address = str(address).strip()
if address[:3] == 'BM-': if address[:3] == 'BM-':
@ -237,7 +238,8 @@ def decodeAddress(address):
status = 'success' status = 'success'
if addressVersionNumber == 1: if addressVersionNumber == 1:
return status, addressVersionNumber, streamNumber, data[-24:-4] return status, addressVersionNumber, streamNumber, data[-24:-4]
elif addressVersionNumber == 2 or addressVersionNumber == 3: # elif addressVersionNumber == 2 or addressVersionNumber == 3:
elif addressVersionNumber in (2, 3):
embeddedRipeData = \ embeddedRipeData = \
data[bytesUsedByVersionNumber + bytesUsedByStreamNumber:-4] data[bytesUsedByVersionNumber + bytesUsedByStreamNumber:-4]
if len(embeddedRipeData) == 19: if len(embeddedRipeData) == 19:

View File

@ -1,15 +1,12 @@
# pylint: disable=too-many-locals,too-many-lines,no-self-use,too-many-public-methods,too-many-branches
# pylint: disable=too-many-statements
# Copyright (c) 2012-2016 Jonathan Warren
# Copyright (c) 2012-2020 The Bitmessage developers
""" """
This is not what you run to run the Bitmessage API. Instead, enable the API This is not what you run to run the Bitmessage API. Instead, enable the API
( https://bitmessage.org/wiki/API ) and optionally enable daemon mode ( https://bitmessage.org/wiki/API ) and optionally enable daemon mode
( https://bitmessage.org/wiki/Daemon ) then run bitmessagemain.py. ( https://bitmessage.org/wiki/Daemon ) then run bitmessagemain.py.
""" """
# pylint: disable=too-many-locals,too-many-lines,no-self-use,unused-argument
# pylint: disable=too-many-statements,too-many-public-methods,too-many-branches
# Copyright (c) 2012-2016 Jonathan Warren
# Copyright (c) 2012-2019 The Bitmessage developers
import base64 import base64
import errno import errno
import hashlib import hashlib
@ -33,13 +30,15 @@ import queues
import shared import shared
import shutdown import shutdown
import state import state
from addresses import addBMIfNotPresent, calculateInventoryHash, decodeAddress, decodeVarint, varintDecodeError
from addresses import addBMIfNotPresent, calculateInventoryHash, decodeAddress, decodeVarint, varintDecodeError
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
from debug import logger from debug import logger
from helper_ackPayload import genAckPayload 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]'
@ -58,6 +57,7 @@ class APIError(Exception):
class StoppableXMLRPCServer(SimpleXMLRPCServer): class StoppableXMLRPCServer(SimpleXMLRPCServer):
"""A SimpleXMLRPCServer that honours state.shutdown""" """A SimpleXMLRPCServer that honours state.shutdown"""
# pylint:disable=too-few-public-methods
allow_reuse_address = True allow_reuse_address = True
def serve_forever(self): def serve_forever(self):
@ -150,7 +150,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
Note: this method is the same as in SimpleXMLRPCRequestHandler, Note: this method is the same as in SimpleXMLRPCRequestHandler,
just hacked to handle cookies just hacked to handle cookies
""" """
# Check that the path is legal # Check that the path is legal
if not self.is_rpc_path_valid(): if not self.is_rpc_path_valid():
self.report_404() self.report_404()
@ -175,10 +174,12 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
# SimpleXMLRPCDispatcher. To maintain backwards compatibility, # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
# check to see if a subclass implements _dispatch and dispatch # check to see if a subclass implements _dispatch and dispatch
# using that method if present. # using that method if present.
response = self.server._marshaled_dispatch( # pylint: disable=protected-access # pylint: disable=protected-access
response = self.server._marshaled_dispatch(
data, getattr(self, '_dispatch', None) data, getattr(self, '_dispatch', None)
) )
except BaseException: # This should only happen if the module is buggy # This should only happen if the module is buggy
except BaseException:
# internal error, report as HTTP server error # internal error, report as HTTP server error
self.send_response(500) self.send_response(500)
self.end_headers() self.end_headers()
@ -251,7 +252,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
if status == 'invalidcharacters': if status == 'invalidcharacters':
raise APIError(9, 'Invalid characters in address: ' + address) raise APIError(9, 'Invalid characters in address: ' + address)
if status == 'versiontoohigh': if status == 'versiontoohigh':
raise APIError(10, 'Address version number too high (or zero) in address: ' + address) raise APIError(
10, 'Address version number too high (or zero) in address: ' + address)
if status == 'varintmalformed': if status == 'varintmalformed':
raise APIError(26, 'Malformed varint in address: ' + address) raise APIError(26, 'Malformed varint in address: ' + address)
raise APIError(7, 'Could not decode address: %s : %s' % (address, status)) raise APIError(7, 'Could not decode address: %s : %s' % (address, status))
@ -275,7 +277,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data = '{"addresses":[' data = '{"addresses":['
for addressInKeysFile in BMConfigParser().addresses(): for addressInKeysFile in BMConfigParser().addresses():
status, addressVersionNumber, streamNumber, hash01 = decodeAddress( # pylint: disable=unused-variable status, addressVersionNumber, streamNumber, hash01 = decodeAddress(
addressInKeysFile) addressInKeysFile)
if len(data) > 20: if len(data) > 20:
data += ',' data += ','
@ -485,7 +487,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
# 0 means "just use the proper addressVersionNumber" # 0 means "just use the proper addressVersionNumber"
if addressVersionNumber == 0: if addressVersionNumber == 0:
addressVersionNumber = 4 addressVersionNumber = 4
if addressVersionNumber != 3 and addressVersionNumber != 4: # if addressVersionNumber != 3 and addressVersionNumber != 4:
if addressVersionNumber not in (3, 4):
raise APIError( raise APIError(
2, 'The address version number currently must be 3, 4, or 0' 2, 'The address version number currently must be 3, 4, or 0'
' (which means auto-select). %i isn\'t supported.' % ' (which means auto-select). %i isn\'t supported.' %
@ -536,7 +539,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
if not passphrase: if not passphrase:
raise APIError(1, 'The specified passphrase is blank.') raise APIError(1, 'The specified passphrase is blank.')
passphrase = self._decode(passphrase, "base64") passphrase = self._decode(passphrase, "base64")
if addressVersionNumber != 3 and addressVersionNumber != 4: # if addressVersionNumber != 3 and addressVersionNumber != 4:
if addressVersionNumber not in (3, 4):
raise APIError( raise APIError(
2, 'The address version number currently must be 3 or 4. %i' 2, 'The address version number currently must be 3 or 4. %i'
' isn\'t supported.' % addressVersionNumber) ' isn\'t supported.' % addressVersionNumber)
@ -606,8 +610,7 @@ 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)
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress( # pylint: disable=unused-variable
suppliedAddress) suppliedAddress)
suppliedAddress = addBMIfNotPresent(suppliedAddress) suppliedAddress = addBMIfNotPresent(suppliedAddress)
queues.apiAddressGeneratorReturnQueue.queue.clear() queues.apiAddressGeneratorReturnQueue.queue.clear()
@ -631,8 +634,8 @@ 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)
if not BMConfigParser().has_section(address): if not BMConfigParser().has_section(address):
raise APIError( raise APIError(
@ -653,8 +656,8 @@ 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)
if not BMConfigParser().has_section(address): if not BMConfigParser().has_section(address):
raise APIError( raise APIError(
@ -666,7 +669,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
shared.reloadMyAddressHashes() shared.reloadMyAddressHashes()
return 'success' return 'success'
def HandleGetAllInboxMessages(self, params): # pylint: disable=unused-argument def HandleGetAllInboxMessages(self, params):
"""Handle a request to get all inbox messages""" """Handle a request to get all inbox messages"""
queryreturn = sqlQuery( queryreturn = sqlQuery(
@ -694,7 +697,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data += ']}' data += ']}'
return data return data
def HandleGetAllInboxMessageIds(self, params): # pylint: disable=unused-argument def HandleGetAllInboxMessageIds(self, params):
"""Handle a request to get all inbox message IDs""" """Handle a request to get all inbox message IDs"""
queryreturn = sqlQuery( queryreturn = sqlQuery(
@ -753,7 +756,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data += ']}' data += ']}'
return data return data
def HandleGetAllSentMessages(self, params): # pylint: disable=unused-argument def HandleGetAllSentMessages(self, params):
"""Handle a request to get all sent messages""" """Handle a request to get all sent messages"""
queryreturn = sqlQuery( queryreturn = sqlQuery(
@ -782,7 +785,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data += ']}' data += ']}'
return data return data
def HandleGetAllSentMessageIds(self, params): # pylint: disable=unused-argument def HandleGetAllSentMessageIds(self, params):
"""Handle a request to get all sent message IDs""" """Handle a request to get all sent message IDs"""
queryreturn = sqlQuery( queryreturn = sqlQuery(
@ -873,7 +876,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:
@ -983,7 +986,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)
@ -1157,10 +1159,9 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
queues.UISignalQueue.put(('rerenderSubscriptions', '')) queues.UISignalQueue.put(('rerenderSubscriptions', ''))
return 'Deleted subscription if it existed.' return 'Deleted subscription if it existed.'
def ListSubscriptions(self, params): # pylint: disable=unused-argument 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': []}
@ -1206,7 +1207,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
initialHash = hashlib.sha512(encryptedPayload).digest() initialHash = hashlib.sha512(encryptedPayload).digest()
trialValue, nonce = proofofwork.run(target, initialHash) trialValue, nonce = proofofwork.run(target, initialHash)
with shared.printLock: with shared.printLock:
print '(For msg message via API) Found proof of work', trialValue, 'Nonce:', nonce print('(For msg message via API) Found proof of work', trialValue, 'Nonce:', nonce)
try: try:
print( print(
'POW took', int(time.time() - powStartTime), 'seconds.', 'POW took', int(time.time() - powStartTime), 'seconds.',
@ -1224,7 +1225,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
int(time.time()) + TTL, '' int(time.time()) + TTL, ''
) )
with shared.printLock: with shared.printLock:
print 'Broadcasting inv for msg(API disseminatePreEncryptedMsg command):', hexlify(inventoryHash) print('Broadcasting inv for msg(API disseminatePreEncryptedMsg command):', hexlify(inventoryHash))
queues.invQueue.put((toStreamNumber, inventoryHash)) queues.invQueue.put((toStreamNumber, inventoryHash))
def HandleTrashSentMessageByAckDAta(self, params): def HandleTrashSentMessageByAckDAta(self, params):
@ -1237,7 +1238,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
sqlExecute("UPDATE sent SET folder='trash' WHERE ackdata=?", ackdata) sqlExecute("UPDATE sent SET folder='trash' WHERE ackdata=?", ackdata)
return 'Trashed sent message (assuming message existed).' return 'Trashed sent message (assuming message existed).'
def HandleDissimatePubKey(self, params): # pylint: disable=unused-argument def HandleDissimatePubKey(self, params):
"""Handle a request to disseminate a public key""" """Handle a request to disseminate a public key"""
# The device issuing this command to PyBitmessage supplies a pubkey # The device issuing this command to PyBitmessage supplies a pubkey
@ -1254,10 +1255,10 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
target = 2 ** 64 / (( target = 2 ** 64 / ((
len(payload) + defaults.networkDefaultPayloadLengthExtraBytes + 8 len(payload) + defaults.networkDefaultPayloadLengthExtraBytes + 8
) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte) ) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)
print '(For pubkey message via API) Doing proof of work...' print('(For pubkey message via API) Doing proof of work...')
initialHash = hashlib.sha512(payload).digest() initialHash = hashlib.sha512(payload).digest()
trialValue, nonce = proofofwork.run(target, initialHash) trialValue, nonce = proofofwork.run(target, initialHash)
print '(For pubkey message via API) Found proof of work', trialValue, 'Nonce:', nonce print('(For pubkey message via API) Found proof of work', trialValue, 'Nonce:', nonce)
payload = pack('>Q', nonce) + payload payload = pack('>Q', nonce) + payload
pubkeyReadPosition = 8 # bypass the nonce pubkeyReadPosition = 8 # bypass the nonce
@ -1266,7 +1267,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
@ -1279,7 +1279,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
objectType, pubkeyStreamNumber, payload, int(time.time()) + TTL, '' objectType, pubkeyStreamNumber, payload, int(time.time()) + TTL, ''
) )
with shared.printLock: with shared.printLock:
print 'broadcasting inv within API command disseminatePubkey with hash:', hexlify(inventoryHash) print('broadcasting inv within API command disseminatePubkey with hash:', hexlify(inventoryHash))
queues.invQueue.put((pubkeyStreamNumber, inventoryHash)) queues.invQueue.put((pubkeyStreamNumber, inventoryHash))
def HandleGetMessageDataByDestinationHash(self, params): def HandleGetMessageDataByDestinationHash(self, params):
@ -1325,7 +1325,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data += ']}' data += ']}'
return data return data
def HandleClientStatus(self, params): # pylint: disable=unused-argument def HandleClientStatus(self, params):
"""Handle a request to get the status of the client""" """Handle a request to get the status of the client"""
connections_num = len(network.stats.connectedHostsList()) connections_num = len(network.stats.connectedHostsList())

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

@ -1010,7 +1010,7 @@ def sendMessage(sender="", recv="", broadcast=None, subject="", body="", reply=F
def loadInbox(): def loadInbox():
"""Load the list of messages""" """Load the list of messages"""
sys.stdout = sys.__stdout__ sys.stdout = sys.__stdout__
print "Loading inbox messages..." print("Loading inbox messages...")
sys.stdout = printlog sys.stdout = printlog
where = "toaddress || fromaddress || subject || message" where = "toaddress || fromaddress || subject || message"
@ -1062,7 +1062,7 @@ def loadInbox():
def loadSent(): def loadSent():
"""Load the messages that sent""" """Load the messages that sent"""
sys.stdout = sys.__stdout__ sys.stdout = sys.__stdout__
print "Loading sent messages..." print("Loading sent messages...")
sys.stdout = printlog sys.stdout = printlog
where = "toaddress || fromaddress || subject || message" where = "toaddress || fromaddress || subject || message"
@ -1148,7 +1148,7 @@ def loadSent():
def loadAddrBook(): def loadAddrBook():
"""Load address book""" """Load address book"""
sys.stdout = sys.__stdout__ sys.stdout = sys.__stdout__
print "Loading address book..." print("Loading address book...")
sys.stdout = printlog sys.stdout = printlog
ret = sqlQuery("SELECT label, address FROM addressbook") ret = sqlQuery("SELECT label, address FROM addressbook")
@ -1254,7 +1254,7 @@ def run(stdscr):
def doShutdown(): def doShutdown():
"""Shutting the app down""" """Shutting the app down"""
sys.stdout = sys.__stdout__ sys.stdout = sys.__stdout__
print "Shutting down..." print("Shutting down...")
sys.stdout = printlog sys.stdout = printlog
shutdown.doCleanShutdown() shutdown.doCleanShutdown()
sys.stdout = sys.__stdout__ sys.stdout = sys.__stdout__

View File

@ -2,7 +2,6 @@
Core classes for loading images and converting them to a Texture. Core classes for loading images and converting them to a Texture.
The raw image data can be keep in memory for further access The raw image data can be keep in memory for further access
""" """
import hashlib import hashlib
from io import BytesIO from io import BytesIO
@ -26,7 +25,6 @@ def generate(Generate_string=None):
image = Image.new(MODE, V_RESOLUTION, BACKGROUND_COLOR) image = Image.new(MODE, V_RESOLUTION, BACKGROUND_COLOR)
image = generate_image(image, color, hash_string) image = generate_image(image, color, hash_string)
image = image.resize(RESOLUTION, 0) image = image.resize(RESOLUTION, 0)
data = BytesIO() data = BytesIO()
image.save(data, format='png') image.save(data, format='png')
data.seek(0) data.seek(0)
@ -46,10 +44,8 @@ def generate_hash(string):
string = str.lower(string) string = str.lower(string)
hash_object = hashlib.md5(str.encode(string)) hash_object = hashlib.md5(str.encode(string))
print(hash_object.hexdigest()) print(hash_object.hexdigest())
# returned object is a hex string # returned object is a hex string
return hash_object.hexdigest() return hash_object.hexdigest()
except IndexError: except IndexError:
print("Error: Please enter a string as an argument.") print("Error: Please enter a string as an argument.")
@ -59,29 +55,24 @@ def random_color(hash_string):
# remove first three digits from hex string # remove first three digits from hex string
split = 6 split = 6
rgb = hash_string[:split] rgb = hash_string[:split]
split = 2 split = 2
r = rgb[:split] r = rgb[:split]
g = rgb[split:2 * split] g = rgb[split:2 * split]
b = rgb[2 * split:3 * split] b = rgb[2 * split:3 * split]
color = (int(r, 16), int(g, 16), color = (int(r, 16), int(g, 16),
int(b, 16), 0xFF) int(b, 16), 0xFF)
return color return color
def generate_image(image, color, hash_string): def generate_image(image, color, hash_string):
"""Generating images""" """Generating images"""
hash_string = hash_string[6:] hash_string = hash_string[6:]
lower_x = 1 lower_x = 1
lower_y = 1 lower_y = 1
upper_x = int(V_RESOLUTION[0] / 2) + 1 upper_x = int(V_RESOLUTION[0] / 2) + 1
upper_y = V_RESOLUTION[1] - 1 upper_y = V_RESOLUTION[1] - 1
limit_x = V_RESOLUTION[0] - 1 limit_x = V_RESOLUTION[0] - 1
index = 0 index = 0
for x in range(lower_x, upper_x): for x in range(lower_x, upper_x):
for y in range(lower_y, upper_y): for y in range(lower_y, upper_y):
if int(hash_string[index], 16) % 2 == 0: if int(hash_string[index], 16) % 2 == 0:
@ -89,5 +80,4 @@ def generate_image(image, color, hash_string):
image.putpixel((limit_x - x, y), color) image.putpixel((limit_x - x, y), color)
index = index + 1 index = index + 1
return image return image

View File

@ -4,25 +4,25 @@ Sql queries for bitmessagekivy
from helper_sql import sqlQuery from helper_sql import sqlQuery
def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, what=None, unreadOnly=False, start_indx=0, end_indx=20): def search_sql(
xAddress="toaddress", account=None, folder="inbox", where=None,
what=None, unreadOnly=False, start_indx=0, end_indx=20):
"""Method helping for searching mails""" """Method helping for searching mails"""
# pylint: disable=too-many-arguments, too-many-branches # pylint: disable=too-many-arguments, too-many-branches
if what is not None and what != "": if what is not None and what != "":
what = "%" + what + "%" what = "%" + what + "%"
else: else:
what = None what = None
if folder == "sent" or folder == "draft": if folder == "sent" or folder == "draft":
sqlStatementBase = ( sqlStatementBase = (
'''SELECT toaddress, fromaddress, subject, message, status, ackdata,''' '''SELECT toaddress, fromaddress, subject, message, status,'''
''' lastactiontime FROM sent ''') ''' ackdata, lastactiontime FROM sent ''')
elif folder == "addressbook": elif folder == "addressbook":
sqlStatementBase = '''SELECT label, address From addressbook ''' sqlStatementBase = '''SELECT label, address From addressbook '''
else: else:
sqlStatementBase = ( sqlStatementBase = (
'''SELECT folder, msgid, toaddress, message, fromaddress, subject,''' '''SELECT folder, msgid, toaddress, message, fromaddress,'''
''' received, read FROM inbox ''') ''' subject, received, read FROM inbox ''')
sqlStatementParts = [] sqlStatementParts = []
sqlArguments = [] sqlArguments = []
if account is not None: if account is not None:
@ -58,10 +58,15 @@ def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, w
sqlStatementParts.append("read = 0") sqlStatementParts.append("read = 0")
if sqlStatementParts: if sqlStatementParts:
sqlStatementBase += "WHERE " + " AND ".join(sqlStatementParts) sqlStatementBase += "WHERE " + " AND ".join(sqlStatementParts)
# if folder in ("sent", "draft"):
if folder == "sent" or folder == "draft": if folder == "sent" or folder == "draft":
sqlStatementBase += " ORDER BY lastactiontime DESC limit {0}, {1}".format(start_indx, end_indx) sqlStatementBase += \
"ORDER BY lastactiontime DESC limit {0}, {1}".format(
start_indx, end_indx)
elif folder == "inbox": elif folder == "inbox":
sqlStatementBase += " ORDER BY received DESC limit {0}, {1}".format(start_indx, end_indx) sqlStatementBase += \
"ORDER BY received DESC limit {0}, {1}".format(
start_indx, end_indx)
# elif folder == "addressbook": # elif folder == "addressbook":
# sqlStatementBase += " limit {0}, {1}".format(start_indx, end_indx) # sqlStatementBase += " limit {0}, {1}".format(start_indx, end_indx)
return sqlQuery(sqlStatementBase, sqlArguments) return sqlQuery(sqlStatementBase, sqlArguments)

View File

@ -25,7 +25,8 @@
#:set color_font (0.957, 0.890, 0.843, 1) # off white #:set color_font (0.957, 0.890, 0.843, 1) # off white
<MyNavigationDrawerIconButton@NavigationDrawerIconButton>: <MyNavigationDrawerIconButton@NavigationDrawerIconButton>:
icon: 'checkbox-blank-circle' font_style: 'Body1'
theme_text_color: 'Secondary'
<MySpinnerOption@SpinnerOption>: <MySpinnerOption@SpinnerOption>:
font_size: '12.5sp' font_size: '12.5sp'
@ -39,7 +40,7 @@
height: dp(7) height: dp(7)
NavigationDrawerSubheader: NavigationDrawerSubheader:
text: "Accounts" text: "Accounts"
NavigationDrawerIconButton: AddressDropdown:
CustomSpinner: CustomSpinner:
id: btn id: btn
pos_hint:{"x":0,"y":.25} pos_hint:{"x":0,"y":.25}
@ -57,47 +58,48 @@
y: self.parent.y + self.parent.height/4 y: self.parent.y + self.parent.height/4
size: self.parent.height/2, self.parent.height/2 size: self.parent.height/2, self.parent.height/2
ArrowImg: ArrowImg:
NavigationDrawerIconButton: MyNavigationDrawerIconButton:
id: inbox_cnt id: inbox_cnt
icon: 'email-open' icon: 'email-open'
text: "Inbox" text: "Inbox"
on_release: app.root.ids.scr_mngr.current = 'inbox' on_release: app.root.ids.scr_mngr.current = 'inbox'
badge_text: "0" badge_text: "0"
on_press: app.load_screen(self) on_press: app.load_screen(self)
NavigationDrawerIconButton: MyNavigationDrawerIconButton:
id: send_cnt id: send_cnt
icon: 'send' icon: 'send'
text: "Sent" text: "Sent"
#use_active: False
on_release: app.root.ids.scr_mngr.current = 'sent' on_release: app.root.ids.scr_mngr.current = 'sent'
badge_text: "0" badge_text: "0"
NavigationDrawerIconButton: MyNavigationDrawerIconButton:
id: draft_cnt id: draft_cnt
icon: 'message-draw' icon: 'message-draw'
text: "Draft" text: "Draft"
on_release: app.root.ids.scr_mngr.current = 'draft' on_release: app.root.ids.scr_mngr.current = 'draft'
badge_text: "0" badge_text: "0"
#NavigationDrawerIconButton: #MyNavigationDrawerIconButton:
#text: "Starred" #text: "Starred"
#icon:'star' #icon:'star'
#on_release: app.root.ids.scr_mngr.current = 'starred' #on_release: app.root.ids.scr_mngr.current = 'starred'
#badge_text: "0" #badge_text: "0"
#NavigationDrawerIconButton: #MyNavigationDrawerIconButton:
#icon: 'archive' #icon: 'archive'
#text: "Archieve" #text: "Archieve"
#on_release: app.root.ids.scr_mngr.current = 'archieve' #on_release: app.root.ids.scr_mngr.current = 'archieve'
#badge_text: "0" #badge_text: "0"
#NavigationDrawerIconButton: #MyNavigationDrawerIconButton:
#icon: 'email-open-outline' #icon: 'email-open-outline'
#text: "Spam" #text: "Spam"
#on_release: app.root.ids.scr_mngr.current = 'spam' #on_release: app.root.ids.scr_mngr.current = 'spam'
#badge_text: "0" #badge_text: "0"
NavigationDrawerIconButton: MyNavigationDrawerIconButton:
id: trash_cnt id: trash_cnt
icon: 'delete' icon: 'delete'
text: "Trash" text: "Trash"
on_release: app.root.ids.scr_mngr.current = 'trash' on_release: app.root.ids.scr_mngr.current = 'trash'
badge_text: "0" badge_text: "0"
NavigationDrawerIconButton: MyNavigationDrawerIconButton:
id: allmail_cnt id: allmail_cnt
text: "All Mails" text: "All Mails"
icon:'contact-mail' icon:'contact-mail'
@ -107,31 +109,31 @@
NavigationDrawerDivider: NavigationDrawerDivider:
NavigationDrawerSubheader: NavigationDrawerSubheader:
text: "All labels" text: "All labels"
NavigationDrawerIconButton: MyNavigationDrawerIconButton:
text: "Address Book" text: "Address Book"
icon:'book-multiple' icon:'book-multiple'
on_release: app.root.ids.scr_mngr.current = 'addressbook' on_release: app.root.ids.scr_mngr.current = 'addressbook'
NavigationDrawerIconButton: MyNavigationDrawerIconButton:
text: "Settings" text: "Settings"
icon:'settings' icon:'settings'
on_release: app.root.ids.scr_mngr.current = 'set' on_release: app.root.ids.scr_mngr.current = 'set'
NavigationDrawerIconButton: MyNavigationDrawerIconButton:
text: "Subscriptions/Payment" text: "Subscriptions/Payment"
icon:'bell' icon:'bell'
on_release: app.root.ids.scr_mngr.current = 'payment' on_release: app.root.ids.scr_mngr.current = 'payment'
NavigationDrawerIconButton: MyNavigationDrawerIconButton:
text: "Credits" text: "Credits"
icon:'wallet' icon:'wallet'
on_release: app.root.ids.scr_mngr.current = 'credits' on_release: app.root.ids.scr_mngr.current = 'credits'
NavigationDrawerIconButton: MyNavigationDrawerIconButton:
text: "new address" text: "new address"
icon:'account-plus' icon:'account-plus'
on_release: app.root.ids.scr_mngr.current = 'login' on_release: app.root.ids.scr_mngr.current = 'login'
NavigationDrawerIconButton: MyNavigationDrawerIconButton:
text: "Network Status" text: "Network Status"
icon:'server-network' icon:'server-network'
on_release: app.root.ids.scr_mngr.current = 'networkstat' on_release: app.root.ids.scr_mngr.current = 'networkstat'
NavigationDrawerIconButton: MyNavigationDrawerIconButton:
text: "My Addresses" text: "My Addresses"
icon:'account-multiple' icon:'account-multiple'
on_release: app.root.ids.scr_mngr.current = 'myaddress' on_release: app.root.ids.scr_mngr.current = 'myaddress'
@ -206,8 +208,17 @@ NavigationLayout:
transition: NoTransition() transition: NoTransition()
BoxLayout: BoxLayout:
orientation: 'vertical' orientation: 'vertical'
spacing: dp(10) spacing: dp(5)
SearchBar: SearchBar:
GridLayout:
id: identi_tag
padding: [20, 0, 0, 5]
cols: 1
size_hint_y: None
height: self.minimum_height
MDLabel:
text: ''
font_style: 'Subtitle2'
#FloatLayout: #FloatLayout:
# MDScrollViewRefreshLayout: # MDScrollViewRefreshLayout:
# id: refresh_layout # id: refresh_layout
@ -229,7 +240,17 @@ NavigationLayout:
name: 'sent' name: 'sent'
BoxLayout: BoxLayout:
orientation: 'vertical' orientation: 'vertical'
spacing: dp(5)
SearchBar: SearchBar:
GridLayout:
id: identi_tag
padding: [20, 0, 0, 5]
cols: 1
size_hint_y: None
height: self.minimum_height
MDLabel:
text: ''
font_style: 'Subtitle2'
BoxLayout: BoxLayout:
orientation:'vertical' orientation:'vertical'
ScrollView: ScrollView:
@ -242,21 +263,50 @@ NavigationLayout:
<Trash>: <Trash>:
name: 'trash' name: 'trash'
ScrollView: BoxLayout:
id: scroll_y orientation: 'vertical'
do_scroll_x: False spacing: dp(5)
MDList: GridLayout:
id: ml id: identi_tag
padding: [20, 20, 0, 5]
spacing: dp(5)
cols: 1
size_hint_y: None
height: self.minimum_height
MDLabel:
text: ''
font_style: 'Subtitle2'
BoxLayout:
orientation:'vertical'
ScrollView:
id: scroll_y
do_scroll_x: False
MDList:
id: ml
Loader: Loader:
ComposerButton: ComposerButton:
<Draft>: <Draft>:
name: 'draft' name: 'draft'
ScrollView: BoxLayout:
id: scroll_y orientation: 'vertical'
do_scroll_x: False spacing: dp(5)
MDList: GridLayout:
id: ml id: identi_tag
padding: [20, 20, 0, 5]
cols: 1
size_hint_y: None
height: self.minimum_height
MDLabel:
text: ''
font_style: 'Subtitle2'
BoxLayout:
orientation:'vertical'
ScrollView:
id: scroll_y
do_scroll_x: False
MDList:
id: ml
ComposerButton: ComposerButton:
<Starred>: <Starred>:
@ -293,12 +343,25 @@ NavigationLayout:
# MDList: # MDList:
# id: ml # id: ml
BoxLayout: BoxLayout:
orientation:'vertical' orientation: 'vertical'
ScrollView: spacing: dp(5)
id: scroll_y GridLayout:
do_scroll_x: False id: identi_tag
MDList: padding: [20, 20, 0, 5]
id: ml spacing: dp(5)
cols: 1
size_hint_y: None
height: self.minimum_height
MDLabel:
text: ''
font_style: 'Subtitle2'
BoxLayout:
orientation:'vertical'
ScrollView:
id: scroll_y
do_scroll_x: False
MDList:
id: ml
Loader: Loader:
ComposerButton: ComposerButton:
@ -545,12 +608,6 @@ NavigationLayout:
color: (1,1,1,1) color: (1,1,1,1)
halign: 'center' halign: 'center'
<AddressSuccessful>:
name: 'add_sucess'
Label:
text: 'Successfully created a new bit address'
color: 0,0,0,1
<Setting>: <Setting>:
name: 'set' name: 'set'
ScrollView: ScrollView:
@ -624,7 +681,17 @@ NavigationLayout:
name: 'myaddress' name: 'myaddress'
BoxLayout: BoxLayout:
orientation: 'vertical' orientation: 'vertical'
spacing: dp(5)
SearchBar: SearchBar:
GridLayout:
id: identi_tag
padding: [20, 0, 0, 5]
cols: 1
size_hint_y: None
height: self.minimum_height
MDLabel:
text: 'My Addresses'
font_style: 'Subtitle2'
FloatLayout: FloatLayout:
MDScrollViewRefreshLayout: MDScrollViewRefreshLayout:
id: refresh_layout id: refresh_layout
@ -639,7 +706,17 @@ NavigationLayout:
name: 'addressbook' name: 'addressbook'
BoxLayout: BoxLayout:
orientation: 'vertical' orientation: 'vertical'
spacing: dp(5)
SearchBar: SearchBar:
GridLayout:
id: identi_tag
padding: [20, 0, 0, 5]
cols: 1
size_hint_y: None
height: self.minimum_height
MDLabel:
text: ''
font_style: 'Subtitle2'
BoxLayout: BoxLayout:
orientation:'vertical' orientation:'vertical'
ScrollView: ScrollView:
@ -800,7 +877,7 @@ NavigationLayout:
id: popup id: popup
size_hint : (None,None) size_hint : (None,None)
height: 2*(label.height + address.height) + 10 height: 2*(label.height + address.height) + 10
width :app.window_size[0] - app.window_size[0]/10 width :app.window_size[0] - (app.window_size[0]/10 if app.app_platform == 'android' else app.window_size[0]/4)
title: 'add contact\'s' title: 'add contact\'s'
background: './images/popup.jpeg' background: './images/popup.jpeg'
title_size: sp(20) title_size: sp(20)
@ -1031,7 +1108,7 @@ NavigationLayout:
id: myadd_popup id: myadd_popup
size_hint : (None,None) size_hint : (None,None)
height: 4.5*(myaddr_label.height+ my_add_btn.children[0].height) height: 4.5*(myaddr_label.height+ my_add_btn.children[0].height)
width :app.window_size[0] - app.window_size[0]/10 width :app.window_size[0] - (app.window_size[0]/10 if app.app_platform == 'android' else app.window_size[0]/4)
background: './images/popup.jpeg' background: './images/popup.jpeg'
auto_dismiss: False auto_dismiss: False
separator_height: 0 separator_height: 0
@ -1111,7 +1188,7 @@ NavigationLayout:
id: addbook_popup id: addbook_popup
size_hint : (None,None) size_hint : (None,None)
height: 4*(add_label.height) height: 4*(add_label.height)
width :app.window_size[0] - app.window_size[0]/10 width :app.window_size[0] - (app.window_size[0]/10 if app.app_platform == 'android' else app.window_size[0]/4)
background: './images/popup.jpeg' background: './images/popup.jpeg'
separator_height: 0 separator_height: 0
auto_dismiss: False auto_dismiss: False

View File

@ -1,8 +1,9 @@
""" """
Bitmessage android(mobile) interface src/bitmessagekivy/mpybit.py
=================================
""" """
# pylint: disable=relative-import, import-error, no-name-in-module # pylint: disable=import-error, no-name-in-module, too-many-lines
# pylint: disable=too-few-public-methods, too-many-lines, unused-argument # pylint: disable=too-few-public-methods, unused-argument, too-many-ancestors
import os import os
import time import time
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
@ -36,9 +37,7 @@ from kivy.uix.screenmanager import Screen
from kivy.uix.spinner import Spinner from kivy.uix.spinner import Spinner
from kivy.uix.textinput import TextInput from kivy.uix.textinput import TextInput
from kivy.utils import platform from kivy.utils import platform
from bitmessagekivy import kivy_helper_search
from bitmessagekivy import kivy_helper_search
from kivymd.uix.button import MDIconButton from kivymd.uix.button import MDIconButton
from kivymd.uix.dialog import MDDialog from kivymd.uix.dialog import MDDialog
from kivymd.uix.label import MDLabel from kivymd.uix.label import MDLabel
@ -48,7 +47,7 @@ from kivymd.uix.list import (
IRightBodyTouch, IRightBodyTouch,
TwoLineAvatarIconListItem, TwoLineAvatarIconListItem,
TwoLineListItem, TwoLineListItem,
OneLineIconListItem OneLineIconListItem,
) )
from kivymd.uix.navigationdrawer import ( from kivymd.uix.navigationdrawer import (
MDNavigationDrawer, MDNavigationDrawer,
@ -60,35 +59,36 @@ import queues
from semaphores import kivyuisignaler from semaphores import kivyuisignaler
import state import state
from bitmessagekivy.uikivysignaler import UIkivySignaler
from bitmessagekivy.uikivysignaler import UIkivySignaler
from bitmessagekivy import identiconGeneration from bitmessagekivy import identiconGeneration
from addresses import addBMIfNotPresent, decodeAddress from addresses import addBMIfNotPresent, decodeAddress, encodeVarint
# pylint: disable=unused-argument, too-few-public-methods
def toast(text): def toast(text):
"""Function displays toast message""" """Method will display the toast message"""
# pylint: disable=redefined-outer-name from kivymd.toast.kivytoast import toast # pylint: disable=redefined-outer-name
from kivymd.toast.kivytoast import toast
toast(text) toast(text)
return return
class Navigatorss(MDNavigationDrawer): class Navigatorss(MDNavigationDrawer):
"""Navigator class (image, title and logo)""" """Navigators class contains image, title and logo"""
image_source = StringProperty('images/qidenticon_two.png') image_source = StringProperty('images/qidenticon_two.png')
title = StringProperty('Navigation') title = StringProperty('Navigation')
drawer_logo = StringProperty() drawer_logo = StringProperty()
class Inbox(Screen): class Inbox(Screen):
"""Inbox Screen uses screen to show widgets of screens.""" """Inbox Screen uses screen to show widgets of screens"""
queryreturn = ListProperty() queryreturn = ListProperty()
has_refreshed = True has_refreshed = True
account = StringProperty() account = StringProperty()
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
"""Method Parsing the address.""" """Method Parsing the address"""
super(Inbox, self).__init__(*args, **kwargs) super(Inbox, self).__init__(*args, **kwargs)
Clock.schedule_once(self.init_ui, 0) Clock.schedule_once(self.init_ui, 0)
@ -100,11 +100,11 @@ class Inbox(Screen):
state.association = BMConfigParser().addresses()[0] state.association = BMConfigParser().addresses()[0]
def init_ui(self, dt=0): def init_ui(self, dt=0):
"""Clock schdule for method inbox accounts.""" """Clock schdule for method inbox accounts"""
self.loadMessagelist() self.loadMessagelist()
def loadMessagelist(self, where="", what=""): def loadMessagelist(self, where="", what=""):
"""Load Inbox list for Inbox messages.""" """Load Inbox list for Inbox messages"""
# pylint: disable=too-many-locals # pylint: disable=too-many-locals
self.set_defaultAddress() self.set_defaultAddress()
self.account = state.association self.account = state.association
@ -260,6 +260,8 @@ class Inbox(Screen):
int(state.trash_count) + 1) int(state.trash_count) + 1)
state.all_count = str( state.all_count = str(
int(state.all_count) - 1) int(state.all_count) - 1)
if int(state.inbox_count) <= 0:
self.ids.identi_tag.children[0].text = ''
self.ids.ml.remove_widget( self.ids.ml.remove_widget(
instance.parent.parent) instance.parent.parent)
toast('Deleted') toast('Deleted')
@ -303,13 +305,13 @@ class Inbox(Screen):
class MyAddress(Screen): class MyAddress(Screen):
"""MyAddress screen uses screen to show widgets of screens.""" """MyAddress screen uses screen to show widgets of screens"""
addresses_list = ListProperty() addresses_list = ListProperty()
has_refreshed = True has_refreshed = True
is_add_created = False is_add_created = False
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
"""Clock schdule for method Myaddress accounts.""" """Clock schdule for method Myaddress accounts"""
super(MyAddress, self).__init__(*args, **kwargs) super(MyAddress, self).__init__(*args, **kwargs)
Clock.schedule_once(self.init_ui, 0) Clock.schedule_once(self.init_ui, 0)
@ -319,12 +321,12 @@ class MyAddress(Screen):
self.addresses_list = state.kivyapp.variable_1 self.addresses_list = state.kivyapp.variable_1
if state.searcing_text: if state.searcing_text:
self.ids.refresh_layout.scroll_y = 1.0 self.ids.refresh_layout.scroll_y = 1.0
filtered_list = filter( filtered_list = [x for x in BMConfigParser().addresses() if self.filter_address(x)]
lambda addr: self.filter_address(
addr), BMConfigParser().addresses())
self.addresses_list = filtered_list self.addresses_list = filtered_list
self.addresses_list = [obj for obj in reversed(self.addresses_list)] self.addresses_list = [obj for obj in reversed(self.addresses_list)]
self.ids.identi_tag.children[0].text = ''
if self.addresses_list: if self.addresses_list:
self.ids.identi_tag.children[0].text = 'My Addresses'
self.has_refreshed = True self.has_refreshed = True
self.set_mdList(0, 15) self.set_mdList(0, 15)
self.ids.refresh_layout.bind(scroll_y=self.check_scroll_y) self.ids.refresh_layout.bind(scroll_y=self.check_scroll_y)
@ -395,7 +397,7 @@ class MyAddress(Screen):
"""Method used for loading the myaddress screen data""" """Method used for loading the myaddress screen data"""
state.searcing_text = '' state.searcing_text = ''
state.kivyapp.root.ids.sc10.children[2].active = False state.kivyapp.root.ids.sc10.children[2].active = False
self.children[2].children[1].ids.search_field.text = '' self.children[2].children[2].ids.search_field.text = ''
self.has_refreshed = True self.has_refreshed = True
self.ids.ml.clear_widgets() self.ids.ml.clear_widgets()
self.init_ui() self.init_ui()
@ -406,9 +408,7 @@ class MyAddress(Screen):
@staticmethod @staticmethod
def filter_address(address): def filter_address(address):
"""Method will filter the my address list data""" """Method will filter the my address list data"""
if filter(lambda x: (state.searcing_text).lower() in x, [ if [x for x in [BMConfigParser().get(address, 'label').lower(), address.lower()] if (state.searcing_text).lower() in x]:
BMConfigParser().get(
address, 'label').lower(), address.lower()]):
return True return True
return False return False
@ -439,10 +439,12 @@ class AddressBook(Screen):
where = ['label', 'address'] where = ['label', 'address']
what = state.searcing_text what = state.searcing_text
xAddress = '' xAddress = ''
self.ids.identi_tag.children[0].text = ''
self.queryreturn = kivy_helper_search.search_sql( self.queryreturn = kivy_helper_search.search_sql(
xAddress, account, "addressbook", where, what, False) xAddress, account, "addressbook", where, what, False)
self.queryreturn = [obj for obj in reversed(self.queryreturn)] self.queryreturn = [obj for obj in reversed(self.queryreturn)]
if self.queryreturn: if self.queryreturn:
self.ids.identi_tag.children[0].text = 'Address Book'
self.has_refreshed = True self.has_refreshed = True
self.set_mdList(0, 20) self.set_mdList(0, 20)
self.ids.scroll_y.bind(scroll_y=self.check_scroll_y) self.ids.scroll_y.bind(scroll_y=self.check_scroll_y)
@ -518,19 +520,22 @@ class AddressBook(Screen):
def delete_address(self, address, instance, *args): def delete_address(self, address, instance, *args):
"""Delete inbox mail from inbox listing""" """Delete inbox mail from inbox listing"""
self.ids.ml.remove_widget(instance.parent.parent) self.ids.ml.remove_widget(instance.parent.parent)
if len(self.ids.ml.children) == 0:
self.ids.identi_tag.children[0].text = ''
sqlExecute( sqlExecute(
"DELETE FROM addressbook WHERE address = '{}';".format(address)) "DELETE FROM addressbook WHERE address = '{}';".format(address))
class SelectableRecycleBoxLayout( class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout): RecycleBoxLayout):
"""Adds selection and focus behaviour to the view""" """Adds selection and focus behaviour to the view"""
# pylint: disable = too-many-ancestors, duplicate-bases # pylint: disable = duplicate-bases
pass pass
class SelectableLabel(RecycleDataViewBehavior, Label): class SelectableLabel(RecycleDataViewBehavior, Label):
"""Add selection support to the Label""" """Add selection support to the Label"""
index = None index = None
selected = BooleanProperty(False) selected = BooleanProperty(False)
selectable = BooleanProperty(True) selectable = BooleanProperty(True)
@ -541,7 +546,6 @@ class SelectableLabel(RecycleDataViewBehavior, Label):
return super(SelectableLabel, self).refresh_view_attrs( return super(SelectableLabel, self).refresh_view_attrs(
rv, index, data) rv, index, data)
# pylint: disable=inconsistent-return-statements
def on_touch_down(self, touch): def on_touch_down(self, touch):
"""Add selection on touch down""" """Add selection on touch down"""
if super(SelectableLabel, self).on_touch_down(touch): if super(SelectableLabel, self).on_touch_down(touch):
@ -560,7 +564,8 @@ class SelectableLabel(RecycleDataViewBehavior, Label):
class RV(RecycleView): class RV(RecycleView):
"""Recycling View""" """Recycling View"""
def __init__(self, **kwargs): # pylint: disable=useless-super-delegation
def __init__(self, **kwargs): # pylint: disable=useless-super-delegation
"""Recycling Method""" """Recycling Method"""
super(RV, self).__init__(**kwargs) super(RV, self).__init__(**kwargs)
@ -568,7 +573,6 @@ class RV(RecycleView):
class DropDownWidget(BoxLayout): class DropDownWidget(BoxLayout):
"""Adding Dropdown Widget""" """Adding Dropdown Widget"""
# pylint: disable=too-many-statements, too-many-locals # pylint: disable=too-many-statements, too-many-locals
# pylint: disable=inconsistent-return-statements
txt_input = ObjectProperty() txt_input = ObjectProperty()
rv = ObjectProperty() rv = ObjectProperty()
@ -579,10 +583,11 @@ class DropDownWidget(BoxLayout):
subject = self.ids.subject.text.strip() subject = self.ids.subject.text.strip()
message = self.ids.subject.text.strip() message = self.ids.subject.text.strip()
encoding = 3 encoding = 3
print ("message: ", self.ids.body.text) print("message: ", self.ids.body.text)
sendMessageToPeople = True sendMessageToPeople = True
if sendMessageToPeople: if sendMessageToPeople:
if toAddress != '' and subject and message: if toAddress != '' and subject and message:
from addresses import decodeAddress
status, addressVersionNumber, streamNumber, ripe = ( status, addressVersionNumber, streamNumber, ripe = (
decodeAddress(toAddress)) decodeAddress(toAddress))
if status == 'success': if status == 'success':
@ -601,17 +606,19 @@ class DropDownWidget(BoxLayout):
state.send_draft_mail) state.send_draft_mail)
self.parent.parent.screens[15].clear_widgets() self.parent.parent.screens[15].clear_widgets()
self.parent.parent.screens[15].add_widget(Draft()) self.parent.parent.screens[15].add_widget(Draft())
# state.detailPageType = ''
# state.send_draft_mail = None
else: else:
from addresses import addBMIfNotPresent
toAddress = addBMIfNotPresent(toAddress) toAddress = addBMIfNotPresent(toAddress)
statusIconColor = 'red' statusIconColor = 'red'
if (addressVersionNumber > 4) or ( if (addressVersionNumber > 4) or (
addressVersionNumber <= 1): addressVersionNumber <= 1):
print ("addressVersionNumber > 4"\ print("addressVersionNumber > 4 or addressVersionNumber <= 1")
" or addressVersionNumber <= 1")
if streamNumber > 1 or streamNumber == 0: if streamNumber > 1 or streamNumber == 0:
print ("streamNumber > 1 or streamNumber == 0") print("streamNumber > 1 or streamNumber == 0")
if statusIconColor == 'red': if statusIconColor == 'red':
print ("shared.statusIconColor == 'red'") print("shared.statusIconColor == 'red'")
stealthLevel = BMConfigParser().safeGetInt( stealthLevel = BMConfigParser().safeGetInt(
'bitmessagesettings', 'ackstealthlevel') 'bitmessagesettings', 'ackstealthlevel')
from helper_ackPayload import genAckPayload from helper_ackPayload import genAckPayload
@ -652,7 +659,7 @@ class DropDownWidget(BoxLayout):
# self.parent.parent.screens[16].add_widget(Allmails()) # self.parent.parent.screens[16].add_widget(Allmails())
Clock.schedule_once(self.callback_for_msgsend, 3) Clock.schedule_once(self.callback_for_msgsend, 3)
queues.workerQueue.put(('sendmessage', toAddress)) queues.workerQueue.put(('sendmessage', toAddress))
print ("sqlExecute successfully #######################") print("sqlExecute successfully #######################")
state.in_composer = True state.in_composer = True
return return
else: else:
@ -674,9 +681,10 @@ class DropDownWidget(BoxLayout):
# pylint: disable=attribute-defined-outside-init # pylint: disable=attribute-defined-outside-init
def address_error_message(self, msg): def address_error_message(self, msg):
"""Generates error message""" """Generates error message"""
width = .8 if platform == 'android' else .55
msg_dialog = MDDialog( msg_dialog = MDDialog(
text=msg, text=msg,
title='', size_hint=(.8, .25), text_button_ok='Ok', title='', size_hint=(width, .25), text_button_ok='Ok',
events_callback=self.callback_for_menu_items) events_callback=self.callback_for_menu_items)
msg_dialog.open() msg_dialog.open()
@ -702,13 +710,14 @@ class DropDownWidget(BoxLayout):
class MyTextInput(TextInput): class MyTextInput(TextInput):
"""Takes the text input in the field""" """Takes the text input in the field"""
txt_input = ObjectProperty() txt_input = ObjectProperty()
flt_list = ObjectProperty() flt_list = ObjectProperty()
word_list = ListProperty() word_list = ListProperty()
starting_no = NumericProperty(3) starting_no = NumericProperty(3)
suggestion_text = '' suggestion_text = ''
def __init__(self, **kwargs): # pylint: disable=useless-super-delegation def __init__(self, **kwargs): # pylint: disable=useless-super-delegation
"""Getting Text Input.""" """Getting Text Input."""
super(MyTextInput, self).__init__(**kwargs) super(MyTextInput, self).__init__(**kwargs)
@ -757,12 +766,14 @@ class Payment(Screen):
class Credits(Screen): class Credits(Screen):
"""Credits Module""" """Credits Method"""
available_credits = StringProperty('{0}'.format('0')) available_credits = StringProperty(
'{0}'.format('0'))
class Login(Screen): class Login(Screen):
"""Login Screeen""" """Login Screeen"""
pass pass
@ -802,6 +813,7 @@ class NetworkStat(Screen):
class ContentNavigationDrawer(Navigatorss): class ContentNavigationDrawer(Navigatorss):
"""Navigate Content Drawer""" """Navigate Content Drawer"""
# pylint: disable=too-many-arguments
pass pass
@ -872,7 +884,7 @@ class Sent(Screen):
account = StringProperty() account = StringProperty()
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
"""Association with the screen.""" """Association with the screen"""
super(Sent, self).__init__(*args, **kwargs) super(Sent, self).__init__(*args, **kwargs)
if state.association == '': if state.association == '':
if BMConfigParser().addresses(): if BMConfigParser().addresses():
@ -885,7 +897,7 @@ class Sent(Screen):
print(dt) print(dt)
def loadSent(self, where="", what=""): def loadSent(self, where="", what=""):
"""Load Sent list for Sent messages.""" """Load Sent list for Sent messages"""
self.account = state.association self.account = state.association
if state.searcing_text: if state.searcing_text:
self.ids.scroll_y.scroll_y = 1.0 self.ids.scroll_y.scroll_y = 1.0
@ -893,8 +905,10 @@ class Sent(Screen):
what = state.searcing_text what = state.searcing_text
xAddress = 'fromaddress' xAddress = 'fromaddress'
data = [] data = []
self.ids.identi_tag.children[0].text = ''
self.sentDataQuery(xAddress, where, what) self.sentDataQuery(xAddress, where, what)
if self.queryreturn: if self.queryreturn:
self.ids.identi_tag.children[0].text = 'Sent'
self.set_sentCount(state.sent_count) self.set_sentCount(state.sent_count)
for mail in self.queryreturn: for mail in self.queryreturn:
data.append({ data.append({
@ -923,7 +937,7 @@ class Sent(Screen):
self.queryreturn = kivy_helper_search.search_sql( self.queryreturn = kivy_helper_search.search_sql(
xAddress, xAddress,
self.account, self.account,
"sent", 'sent',
where, where,
what, what,
False, False,
@ -1056,6 +1070,8 @@ class Sent(Screen):
state.sent_count = str(int(state.sent_count) - 1) state.sent_count = str(int(state.sent_count) - 1)
state.trash_count = str(int(state.trash_count) + 1) state.trash_count = str(int(state.trash_count) + 1)
state.all_count = str(int(state.all_count) - 1) state.all_count = str(int(state.all_count) - 1)
if int(state.sent_count) <= 0:
self.ids.identi_tag.children[0].text = ''
sqlExecute( sqlExecute(
"UPDATE sent SET folder = 'trash'" "UPDATE sent SET folder = 'trash'"
" WHERE ackdata = ?;", data_index) " WHERE ackdata = ?;", data_index)
@ -1089,7 +1105,7 @@ class Trash(Screen):
"""Trash Screen uses screen to show widgets of screens""" """Trash Screen uses screen to show widgets of screens"""
trash_messages = ListProperty() trash_messages = ListProperty()
has_refreshed = True has_refreshed = True
delete_index = StringProperty() # delete_index = StringProperty()
table_name = StringProperty() table_name = StringProperty()
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -1098,12 +1114,14 @@ class Trash(Screen):
Clock.schedule_once(self.init_ui, 0) Clock.schedule_once(self.init_ui, 0)
def init_ui(self, dt=0): def init_ui(self, dt=0):
"""Clock Schdule for method trash screen.""" """Clock Schdule for method trash screen"""
if state.association == '': if state.association == '':
if BMConfigParser().addresses(): if BMConfigParser().addresses():
state.association = BMConfigParser().addresses()[0] state.association = BMConfigParser().addresses()[0]
self.ids.identi_tag.children[0].text = ''
self.trashDataQuery(0, 20) self.trashDataQuery(0, 20)
if self.trash_messages: if self.trash_messages:
self.ids.identi_tag.children[0].text = 'Trash'
src_mng_obj = state.kivyapp.root.children[2].children[0].ids src_mng_obj = state.kivyapp.root.children[2].children[0].ids
src_mng_obj.trash_cnt.badge_text = state.trash_count src_mng_obj.trash_cnt.badge_text = state.trash_count
self.set_mdList() self.set_mdList()
@ -1194,17 +1212,18 @@ class Trash(Screen):
def delete_confirmation(self): def delete_confirmation(self):
"""Show confirmation delete popup""" """Show confirmation delete popup"""
width = .8 if platform == 'android' else .55
delete_msg_dialog = MDDialog( delete_msg_dialog = MDDialog(
text='Are you sure you want to delete this' text='Are you sure you want to delete this'
' message permanently from trash?', ' message permanently from trash?',
title='', title='',
size_hint=(.8, .25), size_hint=(width, .25),
text_button_ok='Yes', text_button_ok='Yes',
text_button_cancel='No', text_button_cancel='No',
events_callback=self.callback_for_delete_msg) events_callback=self.callback_for_delete_msg)
delete_msg_dialog.open() delete_msg_dialog.open()
def callback_for_delete_msg(self, text_item): def callback_for_delete_msg(self, text_item, *arg):
"""Getting the callback of alert box""" """Getting the callback of alert box"""
if text_item == 'Yes': if text_item == 'Yes':
self.delete_message_from_trash() self.delete_message_from_trash()
@ -1215,11 +1234,9 @@ class Trash(Screen):
"""Deleting message from trash""" """Deleting message from trash"""
self.children[1].active = True self.children[1].active = True
if self.table_name == 'inbox': if self.table_name == 'inbox':
sqlExecute("DELETE FROM inbox WHERE msgid = ?;", str( sqlExecute("DELETE FROM inbox WHERE msgid = ?;", self.delete_index)
self.delete_index))
elif self.table_name == 'sent': elif self.table_name == 'sent':
sqlExecute("DELETE FROM sent WHERE ackdata = ?;", str( sqlExecute("DELETE FROM sent WHERE ackdata = ?;", self.delete_index)
self.delete_index))
msg_count_objs = state.kivyapp.root.children[2].children[0].ids msg_count_objs = state.kivyapp.root.children[2].children[0].ids
if int(state.trash_count) > 0: if int(state.trash_count) > 0:
msg_count_objs.trash_cnt.badge_text = str( msg_count_objs.trash_cnt.badge_text = str(
@ -1230,6 +1247,7 @@ class Trash(Screen):
class Page(Screen): class Page(Screen):
"""Page Screen show widgets of page""" """Page Screen show widgets of page"""
pass pass
@ -1249,6 +1267,7 @@ class Create(Screen):
class Setting(Screen): class Setting(Screen):
"""Setting the Screen components""" """Setting the Screen components"""
pass pass
@ -1261,6 +1280,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods
nav_drawer = ObjectProperty() nav_drawer = ObjectProperty()
state.screen_density = Window.size state.screen_density = Window.size
window_size = state.screen_density window_size = state.screen_density
app_platform = platform
title = "PyBitmessage" title = "PyBitmessage"
imgstatus = False imgstatus = False
count = 0 count = 0
@ -1283,7 +1303,6 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods
def build(self): def build(self):
"""Method builds the widget""" """Method builds the widget"""
print("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSss")
print(os.path.join(os.path.dirname(__file__), 'main.kv')) print(os.path.join(os.path.dirname(__file__), 'main.kv'))
main_widget = Builder.load_file( main_widget = Builder.load_file(
os.path.join(os.path.dirname(__file__), 'main.kv')) os.path.join(os.path.dirname(__file__), 'main.kv'))
@ -1327,12 +1346,12 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods
Clock.schedule_once(self.setCurrentAccountData, 0.5) Clock.schedule_once(self.setCurrentAccountData, 0.5)
def setCurrentAccountData(self, dt=0): def setCurrentAccountData(self, dt=0):
"""This method set the current accout data on all the screens.""" """This method set the current accout data on all the screens"""
self.root.ids.sc1.ids.ml.clear_widgets() self.root.ids.sc1.ids.ml.clear_widgets()
self.root.ids.sc1.loadMessagelist(state.association) self.root.ids.sc1.loadMessagelist(state.association)
self.root.ids.sc4.ids.ml.clear_widgets() self.root.ids.sc4.ids.ml.clear_widgets()
self.root.ids.sc4.children[2].children[1].ids.search_field.text = '' self.root.ids.sc4.children[2].children[2].ids.search_field.text = ''
self.root.ids.sc4.loadSent(state.association) self.root.ids.sc4.loadSent(state.association)
self.root.ids.sc16.clear_widgets() self.root.ids.sc16.clear_widgets()
@ -1385,7 +1404,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods
if not os.path.exists(directory): if not os.path.exists(directory):
os.makedirs(directory) os.makedirs(directory)
except OSError: except OSError:
print ('Error: Creating directory. ' + directory) print('Error: Creating directory. ' + directory)
@staticmethod @staticmethod
def get_default_image(): def get_default_image():
@ -1586,7 +1605,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods
@staticmethod @staticmethod
def on_stop(): def on_stop():
"""On stop methos is used for stoping the runing script""" """On stop methos is used for stoping the runing script"""
print ("*******************EXITING FROM APPLICATION*******************") print("*******************EXITING FROM APPLICATION*******************")
import shutdown import shutdown
shutdown.doCleanShutdown() shutdown.doCleanShutdown()
@ -1636,30 +1655,30 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods
if state.search_screen == 'inbox': if state.search_screen == 'inbox':
try: try:
self.root.ids.sc1.children[ self.root.ids.sc1.children[
3].children[1].ids.search_field.text = '' 3].children[2].ids.search_field.text = ''
except Exception: except Exception:
self.root.ids.sc1.children[ self.root.ids.sc1.children[
2].children[1].ids.search_field.text = '' 2].children[2].ids.search_field.text = ''
self.root.ids.sc1.children[1].active = True self.root.ids.sc1.children[1].active = True
Clock.schedule_once(self.search_callback, 0.5) Clock.schedule_once(self.search_callback, 0.5)
elif state.search_screen == 'addressbook': elif state.search_screen == 'addressbook':
self.root.ids.sc11.children[ self.root.ids.sc11.children[
2].children[1].ids.search_field.text = '' 2].children[2].ids.search_field.text = ''
self.root.ids.sc11.children[ self.root.ids.sc11.children[
1].active = True 1].active = True
Clock.schedule_once(self.search_callback, 0.5) Clock.schedule_once(self.search_callback, 0.5)
elif state.search_screen == 'myaddress': elif state.search_screen == 'myaddress':
try: try:
self.root.ids.sc10.children[ self.root.ids.sc10.children[
3].children[1].ids.search_field.text = '' 3].children[2].ids.search_field.text = ''
except Exception: except Exception:
self.root.ids.sc10.children[ self.root.ids.sc10.children[
2].children[1].ids.search_field.text = '' 2].children[2].ids.search_field.text = ''
self.root.ids.sc10.children[1].active = True self.root.ids.sc10.children[1].active = True
Clock.schedule_once(self.search_callback, 0.5) Clock.schedule_once(self.search_callback, 0.5)
else: else:
self.root.ids.sc4.children[ self.root.ids.sc4.children[
2].children[1].ids.search_field.text = '' 2].children[2].ids.search_field.text = ''
self.root.ids.sc4.children[1].active = True self.root.ids.sc4.children[1].active = True
Clock.schedule_once(self.search_callback, 0.5) Clock.schedule_once(self.search_callback, 0.5)
return return
@ -1699,7 +1718,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods
self.root.ids.scr_mngr.current = 'allmails' self.root.ids.scr_mngr.current = 'allmails'
try: try:
self.root.ids.sc17.children[1].active = True self.root.ids.sc17.children[1].active = True
except Exception as e: except Exception:
self.root.ids.sc17.children[0].children[1].active = True self.root.ids.sc17.children[0].children[1].active = True
Clock.schedule_once(partial(self.load_screen_callback, instance), 1) Clock.schedule_once(partial(self.load_screen_callback, instance), 1)
@ -1710,11 +1729,15 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods
self.root.ids.sc1.loadMessagelist(state.association) self.root.ids.sc1.loadMessagelist(state.association)
self.root.ids.sc1.children[1].active = False self.root.ids.sc1.children[1].active = False
elif instance.text == 'All Mails': elif instance.text == 'All Mails':
self.root.ids.sc17.clear_widgets() if len(self.root.ids.sc17.ids.ml.children) <= 2:
self.root.ids.sc17.add_widget(Allmails()) self.root.ids.sc17.clear_widgets()
self.root.ids.sc17.add_widget(Allmails())
else:
self.root.ids.sc17.ids.ml.clear_widgets()
self.root.ids.sc17.loadMessagelist()
try: try:
self.root.ids.sc17.children[1].active = False self.root.ids.sc17.children[1].active = False
except Exception as e: except Exception:
self.root.ids.sc17.children[0].children[1].active = False self.root.ids.sc17.children[0].children[1].active = False
@ -1753,26 +1776,6 @@ class GrashofPopup(Popup):
self.parent.children[1].ids.scr_mngr.current = 'addressbook' self.parent.children[1].ids.scr_mngr.current = 'addressbook'
toast('Saved') toast('Saved')
# pylint: disable=attribute-defined-outside-init
def show_error_message(self):
"""Showing error message"""
content = MDLabel(
font_style='Body1',
theme_text_color='Secondary',
text="Hey you are not allowed to save blank address contact. "
"That's wrong!",
size_hint_y=None,
valign='top')
content.bind(texture_size=content.setter('size'))
self.dialog = MDDialog(content=content,
size_hint=(.8, None),
height=dp(200),
auto_dismiss=False)
self.dialog.add_action_button("ok",
action=lambda *x: self.dialog.dismiss())
self.dialog.open()
@staticmethod @staticmethod
def close_pop(): def close_pop():
"""Pop is Canceled""" """Pop is Canceled"""
@ -1834,8 +1837,7 @@ class GrashofPopup(Popup):
elif status == 'checksumfailed': elif status == 'checksumfailed':
text = "The address is not typed or copied correctly(the checksum failed)." text = "The address is not typed or copied correctly(the checksum failed)."
elif status == 'versiontoohigh': elif status == 'versiontoohigh':
text = "The version number of this address is higher"\ text = "The version number of this address is higher than this software can support. Please upgrade Bitmessage."
" than this software can support. Please upgrade Bitmessage."
elif status == 'invalidcharacters': elif status == 'invalidcharacters':
text = "The address contains invalid characters." text = "The address contains invalid characters."
elif status == 'ripetooshort': elif status == 'ripetooshort':
@ -1849,22 +1851,26 @@ class GrashofPopup(Popup):
class AvatarSampleWidget(ILeftBody, Image): class AvatarSampleWidget(ILeftBody, Image):
"""Avatar Sample Widget""" """Avatar Sample Widget"""
pass pass
class IconLeftSampleWidget(ILeftBodyTouch, MDIconButton): class IconLeftSampleWidget(ILeftBodyTouch, MDIconButton):
"""Left icon sample widget""" """Left icon sample widget"""
pass pass
class IconRightSampleWidget(IRightBodyTouch, MDCheckbox): class IconRightSampleWidget(IRightBodyTouch, MDCheckbox):
"""Right icon sample widget""" """Right icon sample widget"""
pass pass
class NavigationDrawerTwoLineListItem( class NavigationDrawerTwoLineListItem(
TwoLineListItem, NavigationDrawerHeaderBase): TwoLineListItem, NavigationDrawerHeaderBase):
"""Navigation Drawer in Listitems""" """Navigation Drawer in Listitems"""
address_property = StringProperty() address_property = StringProperty()
def __init__(self, **kwargs): def __init__(self, **kwargs):
@ -1940,7 +1946,7 @@ class MailDetail(Screen):
self.children[0].children[0].active = True self.children[0].children[0].active = True
if state.detailPageType == 'sent': if state.detailPageType == 'sent':
state.kivyapp.root.ids.sc4.children[ state.kivyapp.root.ids.sc4.children[
2].children[1].ids.search_field.text = '' 2].children[2].ids.search_field.text = ''
sqlExecute( sqlExecute(
"UPDATE sent SET folder = 'trash' WHERE" "UPDATE sent SET folder = 'trash' WHERE"
" ackdata = ?;", state.mail_id) " ackdata = ?;", state.mail_id)
@ -1950,12 +1956,12 @@ class MailDetail(Screen):
self.parent.screens[3].loadSent(state.association) self.parent.screens[3].loadSent(state.association)
elif state.detailPageType == 'inbox': elif state.detailPageType == 'inbox':
state.kivyapp.root.ids.sc1.children[ state.kivyapp.root.ids.sc1.children[
2].children[1].ids.search_field.text = '' 2].children[2].ids.search_field.text = ''
self.parent.screens[0].children[2].children[ self.parent.screens[0].children[2].children[
1].ids.search_field.text = '' 2].ids.search_field.text = ''
sqlExecute( sqlExecute(
"UPDATE inbox SET folder = 'trash' WHERE" "UPDATE inbox SET folder = 'trash' WHERE"
" msgid = ?;", str(state.mail_id)) " msgid = ?;", state.mail_id)
msg_count_objs.inbox_cnt.badge_text = str( msg_count_objs.inbox_cnt.badge_text = str(
int(state.inbox_count) - 1) int(state.inbox_count) - 1)
state.inbox_count = str(int(state.inbox_count) - 1) state.inbox_count = str(int(state.inbox_count) - 1)
@ -1963,8 +1969,7 @@ class MailDetail(Screen):
self.parent.screens[0].loadMessagelist(state.association) self.parent.screens[0].loadMessagelist(state.association)
elif state.detailPageType == 'draft': elif state.detailPageType == 'draft':
sqlExecute("DELETE FROM sent WHERE ackdata = ?;", str( sqlExecute("DELETE FROM sent WHERE ackdata = ?;", state.mail_id)
state.mail_id))
msg_count_objs.draft_cnt.badge_text = str( msg_count_objs.draft_cnt.badge_text = str(
int(state.draft_count) - 1) int(state.draft_count) - 1)
state.draft_count = str(int(state.draft_count) - 1) state.draft_count = str(int(state.draft_count) - 1)
@ -1982,8 +1987,8 @@ class MailDetail(Screen):
state.all_count = str(int(state.all_count) - 1) state.all_count = str(int(state.all_count) - 1)
self.parent.screens[4].clear_widgets() self.parent.screens[4].clear_widgets()
self.parent.screens[4].add_widget(Trash()) self.parent.screens[4].add_widget(Trash())
self.parent.screens[16].ids.ml.clear_widgets() self.parent.screens[16].clear_widgets()
self.parent.screens[16].init_ui(dt=0) self.parent.screens[16].add_widget(Allmails())
Clock.schedule_once(self.callback_for_delete, 4) Clock.schedule_once(self.callback_for_delete, 4)
def callback_for_delete(self, dt=0): def callback_for_delete(self, dt=0):
@ -1999,7 +2004,7 @@ class MailDetail(Screen):
"""Reply inbox messages""" """Reply inbox messages"""
data = sqlQuery( data = sqlQuery(
"select toaddress, fromaddress, subject, message from inbox where" "select toaddress, fromaddress, subject, message from inbox where"
" msgid = ?;", str(state.mail_id)) " msgid = ?;", state.mail_id)
composer_obj = self.parent.screens[2].children[1].ids composer_obj = self.parent.screens[2].children[1].ids
composer_obj.ti.text = data[0][0] composer_obj.ti.text = data[0][0]
composer_obj.btn.text = data[0][0] composer_obj.btn.text = data[0][0]
@ -2138,7 +2143,7 @@ class ShowQRCode(Screen):
"""ShowQRCode Screen uses to show the detail of mails""" """ShowQRCode Screen uses to show the detail of mails"""
def qrdisplay(self): def qrdisplay(self):
"""Showing QR Code""" """Method used for showing QR Code"""
# self.manager.parent.parent.parent.ids.search_bar.clear_widgets() # self.manager.parent.parent.parent.ids.search_bar.clear_widgets()
self.ids.qr.clear_widgets() self.ids.qr.clear_widgets()
from kivy.garden.qrcode import QRCodeWidget from kivy.garden.qrcode import QRCodeWidget
@ -2168,18 +2173,20 @@ class Draft(Screen):
print(dt) print(dt)
def sentaccounts(self): def sentaccounts(self):
"""Load draft accounts.""" """Load draft accounts"""
self.account = state.association self.account = state.association
self.loadDraft() self.loadDraft()
def loadDraft(self, where="", what=""): def loadDraft(self, where="", what=""):
"""Load draft list for Draft messages.""" """Load draft list for Draft messages"""
xAddress = 'fromaddress' xAddress = 'fromaddress'
self.ids.identi_tag.children[0].text = ''
self.draftDataQuery(xAddress, where, what) self.draftDataQuery(xAddress, where, what)
if state.msg_counter_objs: if state.msg_counter_objs:
state.msg_counter_objs.draft_cnt.badge_text = str( state.msg_counter_objs.draft_cnt.badge_text = str(
len(self.queryreturn)) len(self.queryreturn))
if self.queryreturn: if self.queryreturn:
self.ids.identi_tag.children[0].text = 'Draft'
src_mng_obj = state.kivyapp.root.children[2].children[0].ids src_mng_obj = state.kivyapp.root.children[2].children[0].ids
src_mng_obj.draft_cnt.badge_text = state.draft_count src_mng_obj.draft_cnt.badge_text = state.draft_count
self.set_mdList() self.set_mdList()
@ -2276,12 +2283,10 @@ class Draft(Screen):
def delete_draft(self, data_index, instance, *args): def delete_draft(self, data_index, instance, *args):
"""Delete draft message permanently""" """Delete draft message permanently"""
sqlExecute("DELETE FROM sent WHERE ackdata = ?;", str( sqlExecute("DELETE FROM sent WHERE ackdata = ?;", data_index)
data_index))
try: try:
msg_count_objs = ( msg_count_objs = (
self.parent.parent.parent.parent.parent.parent.children[ self.parent.parent.parent.parent.parent.children[2].children[0].ids)
2].children[0].ids)
except Exception: except Exception:
msg_count_objs = self.parent.parent.parent.parent.parent.parent.children[ msg_count_objs = self.parent.parent.parent.parent.parent.parent.children[
2].children[0].ids 2].children[0].ids
@ -2291,6 +2296,8 @@ class Draft(Screen):
msg_count_objs.draft_cnt.badge_text = str( msg_count_objs.draft_cnt.badge_text = str(
int(state.draft_count) - 1) int(state.draft_count) - 1)
state.draft_count = str(int(state.draft_count) - 1) state.draft_count = str(int(state.draft_count) - 1)
if int(state.draft_count) <= 0:
self.ids.identi_tag.children[0].text = ''
self.ids.ml.remove_widget(instance.parent.parent) self.ids.ml.remove_widget(instance.parent.parent)
toast('Deleted') toast('Deleted')
@ -2305,7 +2312,9 @@ class Draft(Screen):
encoding = 3 encoding = 3
sendMessageToPeople = True sendMessageToPeople = True
if sendMessageToPeople: if sendMessageToPeople:
from addresses import decodeAddress
streamNumber, ripe = decodeAddress(toAddress)[2:] streamNumber, ripe = decodeAddress(toAddress)[2:]
from addresses import addBMIfNotPresent
toAddress = addBMIfNotPresent(toAddress) toAddress = addBMIfNotPresent(toAddress)
stealthLevel = BMConfigParser().safeGetInt( stealthLevel = BMConfigParser().safeGetInt(
'bitmessagesettings', 'ackstealthlevel') 'bitmessagesettings', 'ackstealthlevel')
@ -2328,9 +2337,7 @@ class Draft(Screen):
0, 0,
'draft', 'draft',
encoding, encoding,
int(BMConfigParser().safeGet( int(BMConfigParser().safeGet('bitmessagesettings', 'ttl')))
'bitmessagesettings', 'ttl')))
state.msg_counter_objs = src_object.children[2].children[0].ids state.msg_counter_objs = src_object.children[2].children[0].ids
state.draft_count = str(int(state.draft_count) + 1) state.draft_count = str(int(state.draft_count) + 1)
src_object.ids.sc16.clear_widgets() src_object.ids.sc16.clear_widgets()
@ -2343,7 +2350,7 @@ class CustomSpinner(Spinner):
"""This class is used for setting spinner size""" """This class is used for setting spinner size"""
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
"""Setting size of spinner""" """Method used for setting size of spinner"""
super(CustomSpinner, self).__init__(*args, **kwargs) super(CustomSpinner, self).__init__(*args, **kwargs)
self.dropdown_cls.max_height = Window.size[1] / 3 self.dropdown_cls.max_height = Window.size[1] / 3
@ -2356,7 +2363,7 @@ class Allmails(Screen):
account = StringProperty() account = StringProperty()
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
"""Method Parsing the address.""" """Method Parsing the address"""
super(Allmails, self).__init__(*args, **kwargs) super(Allmails, self).__init__(*args, **kwargs)
if state.association == '': if state.association == '':
if BMConfigParser().addresses(): if BMConfigParser().addresses():
@ -2366,13 +2373,15 @@ class Allmails(Screen):
def init_ui(self, dt=0): def init_ui(self, dt=0):
"""Clock Schdule for method all mails""" """Clock Schdule for method all mails"""
self.loadMessagelist() self.loadMessagelist()
print (dt) print(dt)
def loadMessagelist(self): def loadMessagelist(self):
"""Load Inbox, Sent anf Draft list of messages.""" """Load Inbox, Sent anf Draft list of messages"""
self.account = state.association self.account = state.association
self.ids.identi_tag.children[0].text = ''
self.allMessageQuery(0, 20) self.allMessageQuery(0, 20)
if self.all_mails: if self.all_mails:
self.ids.identi_tag.children[0].text = 'All Mails'
state.kivyapp.get_inbox_count() state.kivyapp.get_inbox_count()
state.kivyapp.get_sent_count() state.kivyapp.get_sent_count()
state.all_count = str( state.all_count = str(
@ -2502,6 +2511,8 @@ class Allmails(Screen):
int(state.all_count) - 1) int(state.all_count) - 1)
state.trash_count = str(int(state.trash_count) + 1) state.trash_count = str(int(state.trash_count) + 1)
state.all_count = str(int(state.all_count) - 1) state.all_count = str(int(state.all_count) - 1)
if int(state.all_count) <= 0:
self.ids.identi_tag.children[0].text = ''
nav_lay_obj.sc5.clear_widgets() nav_lay_obj.sc5.clear_widgets()
nav_lay_obj.sc5.add_widget(Trash()) nav_lay_obj.sc5.add_widget(Trash())
nav_lay_obj.sc17.remove_widget(instance.parent.parent) nav_lay_obj.sc17.remove_widget(instance.parent.parent)
@ -2547,16 +2558,19 @@ def avatarImageFirstLetter(letter_string):
class Starred(Screen): class Starred(Screen):
"""Starred Screen show widgets of page""" """Starred Screen show widgets of page"""
pass pass
class Archieve(Screen): class Archieve(Screen):
"""Archieve Screen show widgets of page""" """Archieve Screen show widgets of page"""
pass pass
class Spam(Screen): class Spam(Screen):
"""Spam Screen show widgets of page""" """Spam Screen show widgets of page"""
pass pass
@ -2571,3 +2585,8 @@ class LoadingPopup(Popup):
def dismiss_popup(self, dt): def dismiss_popup(self, dt):
"""Dismiss popups""" """Dismiss popups"""
self.dismiss() self.dismiss()
class AddressDropdown(OneLineIconListItem):
"""AddressDropdown showns all the addresses"""
pass

View File

@ -1,12 +1,15 @@
"""
Ui Singnaler for kivy interface
"""
from threading import Thread from threading import Thread
import state
import queues import queues
import state
from semaphores import kivyuisignaler from semaphores import kivyuisignaler
from helper_sql import SqlBulkExecute, sqlExecute, sqlQuery, sqlStoredProcedure
class UIkivySignaler(Thread): class UIkivySignaler(Thread):
"""Kivy ui signaler"""
def run(self): def run(self):
kivyuisignaler.acquire() kivyuisignaler.acquire()
@ -14,13 +17,12 @@ class UIkivySignaler(Thread):
try: try:
command, data = queues.UISignalQueue.get() command, data = queues.UISignalQueue.get()
if command == 'writeNewAddressToTable': if command == 'writeNewAddressToTable':
label, address, streamNumber = data address = data[1]
state.kivyapp.variable_1.append(address) state.kivyapp.variable_1.append(address)
# elif command == 'rerenderAddressBook': # elif command == 'rerenderAddressBook':
# state.kivyapp.obj_1.refreshs() # state.kivyapp.obj_1.refreshs()
# Need to discuss this # Need to discuss this
elif command == 'updateSentItemStatusByAckdata': elif command == 'updateSentItemStatusByAckdata':
state.kivyapp.status_dispatching(data) state.kivyapp.status_dispatching(data)
except Exception as e: except Exception as e:
print(e) print(e)

View File

@ -9,7 +9,6 @@ The PyBitmessage startup script
# Right now, PyBitmessage only support connecting to stream 1. It doesn't # Right now, PyBitmessage only support connecting to stream 1. It doesn't
# yet contain logic to expand into further streams. # yet contain logic to expand into further streams.
import os import os
import sys import sys
import ctypes import ctypes
@ -30,7 +29,8 @@ import state
import shutdown import shutdown
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
from debug import logger # this should go before any threads # this should go before any threads
from debug import logger
from helper_startup import ( from helper_startup import (
isOurOperatingSystemLimitedToHavingVeryFewHalfOpenConnections, isOurOperatingSystemLimitedToHavingVeryFewHalfOpenConnections,
start_proxyconfig start_proxyconfig
@ -157,11 +157,11 @@ def signal_handler(signum, frame):
if shared.thisapp.daemon or not state.enableGUI: if shared.thisapp.daemon or not state.enableGUI:
shutdown.doCleanShutdown() shutdown.doCleanShutdown()
else: else:
print ('# Thread: {}({})'.format(thread.name, thread.ident)) print('# Thread: {}({})'.format(thread.name, thread.ident))
for filename, lineno, name, line in traceback.extract_stack(frame): for filename, lineno, name, line in traceback.extract_stack(frame):
print ("File: '{}', line {}, in {}" .format(filename, lineno, name)) print("File: '{}', line {}, in {}" .format(filename, lineno, name))
if line: if line:
print (' {}'.format(line.strip())) print(' {}'.format(line.strip()))
print('Unfortunately you cannot use Ctrl+C when running the UI \ print('Unfortunately you cannot use Ctrl+C when running the UI \
because the UI captures the signal.') because the UI captures the signal.')
@ -198,7 +198,8 @@ class Main(object):
if os.path.isfile(os.path.join( if os.path.isfile(os.path.join(
state.appdata, 'unittest.lock')): state.appdata, 'unittest.lock')):
daemon = True daemon = True
state.enableGUI = False # run without a UI # run without a UI
state.enableGUI = False
# Fallback: in case when no api command was issued # Fallback: in case when no api command was issued
state.last_api_response = time.time() state.last_api_response = time.time()
# Apply special settings # Apply special settings
@ -214,7 +215,8 @@ class Main(object):
) )
if daemon: if daemon:
state.enableGUI = False # run without a UI # run without a UI
state.enableGUI = False
# is the application already running? If yes then exit. # is the application already running? If yes then exit.
if state.enableGUI and not state.curses and not state.kivy and not depends.check_pyqt(): if state.enableGUI and not state.curses and not state.kivy and not depends.check_pyqt():
@ -245,11 +247,10 @@ class Main(object):
set_thread_name("PyBitmessage") set_thread_name("PyBitmessage")
state.dandelion = config.safeGetInt('network', 'dandelion') state.dandelion = config.safeGet('network', 'dandelion')
# dandelion requires outbound connections, without them, # dandelion requires outbound connections, without them,
# stem objects will get stuck forever # stem objects will get stuck forever
if state.dandelion and not config.safeGetBoolean( if state.dandelion and not (config.safeGet('bitmessagesettings', 'sendoutgoingconnections') == 'True'):
'bitmessagesettings', 'sendoutgoingconnections'):
state.dandelion = 0 state.dandelion = 0
if state.testmode or config.safeGetBoolean( if state.testmode or config.safeGetBoolean(
@ -261,7 +262,6 @@ class Main(object):
readKnownNodes() readKnownNodes()
# Not needed if objproc is disabled # Not needed if objproc is disabled
if state.enableObjProc: if state.enableObjProc:
@ -320,7 +320,8 @@ class Main(object):
shared.reloadBroadcastSendersForWhichImWatching() shared.reloadBroadcastSendersForWhichImWatching()
# API is also objproc dependent # API is also objproc dependent
if config.safeGetBoolean('bitmessagesettings', 'apienabled'): if config.safeGetBoolean('bitmessagesettings', 'apienabled'):
import api # pylint: disable=relative-import # pylint: disable=relative-import
import api
singleAPIThread = api.singleAPI() singleAPIThread = api.singleAPI()
# close the main program even if there are threads left # close the main program even if there are threads left
singleAPIThread.daemon = True singleAPIThread.daemon = True
@ -409,13 +410,14 @@ class Main(object):
while True: while True:
time.sleep(1) time.sleep(1)
os._exit(0) # pylint: disable=protected-access os._exit(0) # pylint: disable=protected-access
except AttributeError: except AttributeError:
# fork not implemented # fork not implemented
pass pass
else: else:
parentPid = os.getpid() parentPid = os.getpid()
shared.thisapp.lock() # relock # relock
shared.thisapp.lock()
os.umask(0) os.umask(0)
try: try:
@ -430,14 +432,16 @@ class Main(object):
# wait until child ready # wait until child ready
while True: while True:
time.sleep(1) time.sleep(1)
# pylint: disable=protected-access
os._exit(0) # pylint: disable=protected-access os._exit(0)
except AttributeError: except AttributeError:
# fork not implemented # fork not implemented
pass pass
else: else:
shared.thisapp.lock() # relock # relock
shared.thisapp.lockPid = None # indicate we're the final child shared.thisapp.lock()
# indicate we're the final child
shared.thisapp.lockPid = None
sys.stdout.flush() sys.stdout.flush()
sys.stderr.flush() sys.stderr.flush()
if not sys.platform.startswith('win'): if not sys.platform.startswith('win'):
@ -460,7 +464,6 @@ class Main(object):
# signal.signal(signal.SIGINT, signal.SIG_DFL) # signal.signal(signal.SIGINT, signal.SIG_DFL)
@staticmethod @staticmethod
def usage(): def usage():
"""Displaying the usages""" """Displaying the usages"""
print('Usage: ' + sys.argv[0] + ' [OPTIONS]') print('Usage: ' + sys.argv[0] + ' [OPTIONS]')

View File

@ -1,7 +1,7 @@
""" """
BMConfigParser class definition and default configuration settings BMConfigParser class definition and default configuration settings
""" """
# pylint: disable=no-self-use, arguments-differ
import configparser import configparser
import shutil import shutil
import os import os
@ -45,7 +45,7 @@ BMConfigDefaults = {
class BMConfigParser(configparser.ConfigParser): class BMConfigParser(configparser.ConfigParser):
"""Singleton class inherited from ConfigParsedadfeConfigParser """Singleton class inherited from ConfigParsedadfeConfigParser
with additional methods specific to bitmessage config.""" with additional methods specific to bitmessage config."""
# pylint: disable=too-many-ancestors
_temp = {} _temp = {}
def set(self, section, option, value=None): def set(self, section, option, value=None):
@ -56,7 +56,8 @@ class BMConfigParser(configparser.ConfigParser):
raise ValueError("Invalid value %s" % value) raise ValueError("Invalid value %s" % value)
return configparser.ConfigParser.set(self, section, option, value) return configparser.ConfigParser.set(self, section, option, value)
def get(self, section, option, raw=False, variables=None): # pylint: disable=arguments-differ def get(self, section, option, raw=False, variables=None):
# pylint: disable=unused-argument
try: try:
if section == "bitmessagesettings" and option == "timeformat": if section == "bitmessagesettings" and option == "timeformat":
return configparser.ConfigParser.get( return configparser.ConfigParser.get(
@ -84,24 +85,26 @@ class BMConfigParser(configparser.ConfigParser):
self._temp[section] = {option: value} self._temp[section] = {option: value}
def safeGetBoolean(self, section, field): def safeGetBoolean(self, section, field):
"""Return value as boolean, False on exceptions"""
config = configparser.ConfigParser() config = configparser.ConfigParser()
try: try:
#Used in the python2.7 # Used in the python2.7
# return self.getboolean(section, field) # return self.getboolean(section, field)
#Used in the python3.5.2 # Used in the python3.5.2
return config.getboolean(section, field) return config.getboolean(section, field)
except (configparser.NoSectionError, configparser.NoOptionError, except (configparser.NoSectionError, configparser.NoOptionError,
ValueError, AttributeError): ValueError, AttributeError):
return False return False
def safeGetInt(self, section, field, default=0): def safeGetInt(self, section, field, default=0):
"""Return value as integer, default on exceptions,
0 if default missing"""
config = configparser.ConfigParser() config = configparser.ConfigParser()
try: try:
#Used in the python2.7 # Used in the python2.7
# return self.getint(section, field) # return self.getint(section, field)
#Used in the python3.5.2 # Used in the python3.5.2
return config.getint(section, field) return config.getint(section, field)
except (configparser.NoSectionError, configparser.NoOptionError, except (configparser.NoSectionError, configparser.NoOptionError,
ValueError, AttributeError): ValueError, AttributeError):
@ -116,12 +119,14 @@ class BMConfigParser(configparser.ConfigParser):
return default return default
def items(self, section, raw=False, variables=None): def items(self, section, raw=False, variables=None):
"""Return section variables as parent,
but override the "raw" argument to always True"""
return configparser.ConfigParser.items(self, section, True, variables) return configparser.ConfigParser.items(self, section, True, variables)
def addresses(self): def addresses(self):
"""Return a list of local bitmessage addresses (from section labels)"""
return [x for x in BMConfigParser().sections() if x.startswith('BM-')] return [x for x in BMConfigParser().sections() if x.startswith('BM-')]
def read(self, filenames): def read(self, filenames):
configparser.ConfigParser.read(self, filenames) configparser.ConfigParser.read(self, filenames)
for section in self.sections(): for section in self.sections():
@ -167,7 +172,8 @@ class BMConfigParser(configparser.ConfigParser):
def validate(self, section, option, value): def validate(self, section, option, value):
"""Input validator interface (using factory pattern)""" """Input validator interface (using factory pattern)"""
try: try:
return getattr(self, 'validate_{}_{}'.format(section, option))(value) return getattr(self, 'validate_{}_{}'.format(
section, option))(value)
except AttributeError: except AttributeError:
return True return True

View File

@ -13,8 +13,14 @@ DATA_FILES = [
('bitmsghash', ['bitmsghash/bitmsghash.cl', 'bitmsghash/bitmsghash.so']), ('bitmsghash', ['bitmsghash/bitmsghash.cl', 'bitmsghash/bitmsghash.so']),
('translations', glob('translations/*.qm')), ('translations', glob('translations/*.qm')),
('ui', glob('bitmessageqt/*.ui')), ('ui', glob('bitmessageqt/*.ui')),
('translations', glob(str(QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath)) + '/qt_??.qm')), ('translations', glob(
('translations', glob(str(QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath)) + '/qt_??_??.qm')), str(
QtCore.QLibraryInfo.location(
QtCore.QLibraryInfo.TranslationsPath)) + '/qt_??.qm')),
('translations', glob(
str(
QtCore.QLibraryInfo.location(
QtCore.QLibraryInfo.TranslationsPath)) + '/qt_??_??.qm')),
] ]
setup( setup(

View File

@ -20,7 +20,6 @@ from network.threads import StoppableThread
class addressGenerator(StoppableThread): class addressGenerator(StoppableThread):
"""A thread for creating addresses""" """A thread for creating addresses"""
name = "addressGenerator" name = "addressGenerator"
def stopThread(self): def stopThread(self):
@ -35,7 +34,8 @@ class addressGenerator(StoppableThread):
Process the requests for addresses generation Process the requests for addresses generation
from `.queues.addressGeneratorQueue` from `.queues.addressGeneratorQueue`
""" """
# pylint: disable=too-many-locals, too-many-branches, protected-access, too-many-statements # pylint: disable=too-many-locals, too-many-branches
# pylint: disable=protected-access, too-many-statements
while state.shutdown == 0: while state.shutdown == 0:
queueValue = queues.addressGeneratorQueue.get() queueValue = queues.addressGeneratorQueue.get()
nonceTrialsPerByte = 0 nonceTrialsPerByte = 0
@ -140,7 +140,7 @@ class addressGenerator(StoppableThread):
ripe = RIPEMD160Hash(sha.digest()).digest() ripe = RIPEMD160Hash(sha.digest()).digest()
if ( if (
ripe[:numberOfNullBytesDemandedOnFrontOfRipeHash] == ripe[:numberOfNullBytesDemandedOnFrontOfRipeHash] ==
'\x00'.encode('utf-8') * numberOfNullBytesDemandedOnFrontOfRipeHash '\x00'.encode('utf-8') * numberOfNullBytesDemandedOnFrontOfRipeHash
): ):
break break
self.logger.info( self.logger.info(
@ -206,9 +206,14 @@ class addressGenerator(StoppableThread):
queues.workerQueue.put(( queues.workerQueue.put((
'sendOutOrStoreMyV4Pubkey', address)) 'sendOutOrStoreMyV4Pubkey', address))
elif command == 'createDeterministicAddresses' \ # elif command == 'createDeterministicAddresses' \
or command == 'getDeterministicAddress' \ # or command == 'getDeterministicAddress' \
or command == 'createChan' or command == 'joinChan': # or command == 'createChan' or command == 'joinChan':
elif command in (
'createDeterministicAddresses',
'getDeterministicAddress',
'createChan',
'joinChan'):
if not deterministicPassphrase: if not deterministicPassphrase:
self.logger.warning( self.logger.warning(
'You are creating deterministic' 'You are creating deterministic'
@ -333,8 +338,8 @@ class addressGenerator(StoppableThread):
BMConfigParser().set(address, 'label', label) BMConfigParser().set(address, 'label', label)
BMConfigParser().set(address, 'enabled', 'true') BMConfigParser().set(address, 'enabled', 'true')
BMConfigParser().set(address, 'decoy', 'false') BMConfigParser().set(address, 'decoy', 'false')
if command == 'joinChan' \ # if command == 'joinChan' or command == 'createChan':
or command == 'createChan': if command in ('joinChan', 'createChan'):
BMConfigParser().set(address, 'chan', 'true') BMConfigParser().set(address, 'chan', 'true')
BMConfigParser().set( BMConfigParser().set(
address, 'noncetrialsperbyte', address, 'noncetrialsperbyte',
@ -385,8 +390,12 @@ class addressGenerator(StoppableThread):
address) address)
# Done generating addresses. # Done generating addresses.
if command == 'createDeterministicAddresses' \ # if command == 'createDeterministicAddresses' \
or command == 'joinChan' or command == 'createChan': # or command == 'joinChan' or command == 'createChan':
if command in (
'createDeterministicAddresses',
'joinChan',
'createChan'):
queues.apiAddressGeneratorReturnQueue.put( queues.apiAddressGeneratorReturnQueue.put(
listOfNewAddressesToSendOutThroughTheAPI) listOfNewAddressesToSendOutThroughTheAPI)
elif command == 'getDeterministicAddress': elif command == 'getDeterministicAddress':

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')
@ -140,21 +141,20 @@ class objectProcessor(threading.Thread):
# bypass nonce and time, retain object type/version/stream + body # bypass nonce and time, retain object type/version/stream + body
readPosition = 16 readPosition = 16
if data[readPosition:] in shared.ackdataForWhichImWatching: if bytes(data[readPosition:]) in shared.ackdataForWhichImWatching:
logger.info('This object is an acknowledgement bound for me.') logger.info('This object is an acknowledgement bound for me.')
del shared.ackdataForWhichImWatching[data[readPosition:]] del shared.ackdataForWhichImWatching[data[readPosition:]]
sqlExecute( sqlExecute(
'UPDATE sent SET status=?, lastactiontime=?' 'UPDATE sent SET status=?, lastactiontime=?'
' WHERE ackdata=?', ' WHERE ackdata=?',
'ackreceived', int(time.time()), data[readPosition:]) ' ackreceived', int(time.time()), data[readPosition:])
queues.UISignalQueue.put(( queues.UISignalQueue.put((
'updateSentItemStatusByAckdata', 'updateSentItemStatusByAckdata',
(data[readPosition:], (data[readPosition:],
tr._translate( tr._translate(
"MainWindow", "MainWindow",
"Acknowledgement of the message received %1" "Acknowledgement of the message received %1").arg(
).arg(l10n.formatTimestamp())) l10n.formatTimestamp()))))
))
else: else:
logger.debug('This object is not an acknowledgement bound for me.') logger.debug('This object is not an acknowledgement bound for me.')
@ -221,7 +221,7 @@ class objectProcessor(threading.Thread):
'the hash requested in this getpubkey request is: %s', 'the hash requested in this getpubkey request is: %s',
hexlify(requestedHash)) hexlify(requestedHash))
# if this address hash is one of mine # if this address hash is one of mine
if requestedHash in shared.myAddressesByHash: if bytes(requestedHash) in shared.myAddressesByHash:
myAddress = shared.myAddressesByHash[requestedHash] myAddress = shared.myAddressesByHash[requestedHash]
elif requestedAddressVersionNumber >= 4: elif requestedAddressVersionNumber >= 4:
requestedTag = data[readPosition:readPosition + 32] requestedTag = data[readPosition:readPosition + 32]
@ -233,7 +233,7 @@ class objectProcessor(threading.Thread):
logger.debug( logger.debug(
'the tag requested in this getpubkey request is: %s', 'the tag requested in this getpubkey request is: %s',
hexlify(requestedTag)) hexlify(requestedTag))
if requestedTag in shared.myAddressesByTag: if bytes(requestedTag) in shared.myAddressesByTag:
myAddress = shared.myAddressesByTag[requestedTag] myAddress = shared.myAddressesByTag[requestedTag]
if myAddress == '': if myAddress == '':
@ -328,7 +328,7 @@ class objectProcessor(threading.Thread):
dataToStore = data[20:readPosition] dataToStore = data[20:readPosition]
sha = hashlib.new('sha512') sha = hashlib.new('sha512')
sha.update( sha.update(
'\x04' + publicSigningKey + '\x04' + publicEncryptionKey) '\x04'.encode() + publicSigningKey + '\x04'.encode() + publicEncryptionKey)
ripe = RIPEMD160Hash(sha.digest()).digest() ripe = RIPEMD160Hash(sha.digest()).digest()
if logger.isEnabledFor(logging.DEBUG): if logger.isEnabledFor(logging.DEBUG):
@ -367,9 +367,9 @@ class objectProcessor(threading.Thread):
' Sanity check failed.') ' Sanity check failed.')
return return
readPosition += 4 readPosition += 4
publicSigningKey = '\x04' + data[readPosition:readPosition + 64] publicSigningKey = ('\x04').encode() + data[readPosition:readPosition + 64]
readPosition += 64 readPosition += 64
publicEncryptionKey = '\x04' + data[readPosition:readPosition + 64] publicEncryptionKey = ('\x04').encode() + data[readPosition:readPosition + 64]
readPosition += 64 readPosition += 64
_, specifiedNonceTrialsPerByteLength = decodeVarint( _, specifiedNonceTrialsPerByteLength = decodeVarint(
data[readPosition:readPosition + 10]) data[readPosition:readPosition + 10])
@ -433,7 +433,7 @@ class objectProcessor(threading.Thread):
return return
tag = data[readPosition:readPosition + 32] tag = data[readPosition:readPosition + 32]
if tag not in state.neededPubkeys: if tag not in bytes(state.neededPubkeys):
logger.info( logger.info(
'We don\'t need this v4 pubkey. We didn\'t ask for it.') 'We don\'t need this v4 pubkey. We didn\'t ask for it.')
return return
@ -645,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(
@ -865,7 +866,7 @@ class objectProcessor(threading.Thread):
elif broadcastVersion == 5: elif broadcastVersion == 5:
embeddedTag = data[readPosition:readPosition + 32] embeddedTag = data[readPosition:readPosition + 32]
readPosition += 32 readPosition += 32
if embeddedTag not in shared.MyECSubscriptionCryptorObjects: if bytes(embeddedTag) not in shared.MyECSubscriptionCryptorObjects:
logger.debug('We\'re not interested in this broadcast.') logger.debug('We\'re not interested in this broadcast.')
return return
# We are interested in this broadcast because of its tag. # We are interested in this broadcast because of its tag.

View File

@ -1,24 +0,0 @@
import queue as Queue
import threading
import time
class ObjectProcessorQueue(Queue.Queue):
maxSize = 32000000
def __init__(self):
Queue.Queue.__init__(self)
self.sizeLock = threading.Lock()
self.curSize = 0 # in Bytes. We maintain this to prevent nodes from flooing us with objects which take up too much memory. If this gets too big we'll sleep before asking for further objects.
def put(self, item, block = True, timeout = None):
while self.curSize >= self.maxSize:
time.sleep(1)
with self.sizeLock:
self.curSize += len(item[1])
Queue.Queue.put(self, item, block, timeout)
def get(self, block = True, timeout = None):
item = Queue.Queue.get(self, block, timeout)
with self.sizeLock:
self.curSize -= len(item[1])
return item

View File

@ -35,6 +35,7 @@ from inventory import Inventory
from network.connectionpool import BMConnectionPool from network.connectionpool import BMConnectionPool
from network.threads import StoppableThread from network.threads import StoppableThread
class singleCleaner(StoppableThread): class singleCleaner(StoppableThread):
"""The singleCleaner thread class""" """The singleCleaner thread class"""
name = "singleCleaner" name = "singleCleaner"
@ -200,6 +201,10 @@ def deleteTrashMsgPermonantly():
"""This method is used to delete old messages""" """This method is used to delete old messages"""
ndays_before_time = datetime.now() - timedelta(days=30) ndays_before_time = datetime.now() - timedelta(days=30)
old_messages = time.mktime(ndays_before_time.timetuple()) old_messages = time.mktime(ndays_before_time.timetuple())
sqlExecute("delete from sent where folder = 'trash' and lastactiontime <= ?;", int(old_messages)) sqlExecute(
sqlExecute("delete from inbox where folder = 'trash' and received <= ?;", int(old_messages)) "delete from sent where folder = 'trash' and lastactiontime <= ?;",
int(old_messages))
sqlExecute(
"delete from inbox where folder = 'trash' and received <= ?;",
int(old_messages))
return return

View File

@ -23,7 +23,8 @@ import queues
import shared import shared
import state import state
import tr import tr
from addresses import calculateInventoryHash, decodeAddress, decodeVarint, encodeVarint from addresses import (
calculateInventoryHash, decodeAddress, decodeVarint, encodeVarint)
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
from helper_sql import sqlExecute, sqlQuery from helper_sql import sqlExecute, sqlQuery
from inventory import Inventory from inventory import Inventory

View File

@ -3,7 +3,6 @@ src/class_smtpDeliver.py
======================== ========================
""" """
# pylint: disable=unused-variable # pylint: disable=unused-variable
import smtplib import smtplib
import urlparse import urlparse
from email.header import Header from email.header import Header
@ -24,7 +23,8 @@ class smtpDeliver(StoppableThread):
def stopThread(self): def stopThread(self):
try: try:
queues.UISignallerQueue.put(("stopThread", "data")) # pylint: disable=no-member # pylint: disable=no-member
queues.UISignallerQueue.put(("stopThread", "data"))
except: except:
pass pass
super(smtpDeliver, self).stopThread() super(smtpDeliver, self).stopThread()
@ -50,23 +50,27 @@ class smtpDeliver(StoppableThread):
ackData, message = data ackData, message = data
elif command == 'displayNewInboxMessage': elif command == 'displayNewInboxMessage':
inventoryHash, toAddress, fromAddress, subject, body = data inventoryHash, toAddress, fromAddress, subject, body = data
dest = BMConfigParser().safeGet("bitmessagesettings", "smtpdeliver", '') dest = BMConfigParser().safeGet(
"bitmessagesettings", "smtpdeliver", '')
if dest == '': if dest == '':
continue continue
try: try:
# pylint: disable=deprecated-lambda
u = urlparse.urlparse(dest) u = urlparse.urlparse(dest)
to = urlparse.parse_qs(u.query)['to'] to = urlparse.parse_qs(u.query)['to']
client = smtplib.SMTP(u.hostname, u.port) client = smtplib.SMTP(u.hostname, u.port)
msg = MIMEText(body, 'plain', 'utf-8') msg = MIMEText(body, 'plain', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8') msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = fromAddress + '@' + SMTPDOMAIN msg['From'] = fromAddress + '@' + SMTPDOMAIN
toLabel = map( # pylint: disable=deprecated-lambda toLabel = map(
lambda y: BMConfigParser().safeGet(y, "label"), lambda y: BMConfigParser().safeGet(y, "label"),
filter( # pylint: disable=deprecated-lambda filter(
lambda x: x == toAddress, BMConfigParser().addresses()) lambda x: x == toAddress, BMConfigParser().addresses())
) )
if toLabel: if toLabel:
msg['To'] = "\"%s\" <%s>" % (Header(toLabel[0], 'utf-8'), toAddress + '@' + SMTPDOMAIN) msg['To'] = "\"%s\" <%s>" % (
Header(toLabel[0], 'utf-8'),
toAddress + '@' + SMTPDOMAIN)
else: else:
msg['To'] = toAddress + '@' + SMTPDOMAIN msg['To'] = toAddress + '@' + SMTPDOMAIN
client.ehlo() client.ehlo()
@ -80,7 +84,8 @@ class smtpDeliver(StoppableThread):
except: except:
self.logger.error('smtp delivery error', exc_info=True) self.logger.error('smtp delivery error', exc_info=True)
elif command == 'displayNewSentMessage': elif command == 'displayNewSentMessage':
toAddress, fromLabel, fromAddress, subject, message, ackdata = data toAddress, fromLabel, fromAddress, subject, message, ackdata = \
data
elif command == 'updateNetworkStatusTab': elif command == 'updateNetworkStatusTab':
pass pass
elif command == 'updateNumberOfMessagesProcessed': elif command == 'updateNumberOfMessagesProcessed':

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

@ -214,7 +214,8 @@ class sqlThread(threading.Thread):
parameters = '' parameters = ''
self.cur.execute(item, parameters) self.cur.execute(item, parameters)
currentVersion = int(self.cur.fetchall()[0][0]) currentVersion = int(self.cur.fetchall()[0][0])
if currentVersion == 1 or currentVersion == 3: # if currentVersion == 1 or currentVersion == 3:
if currentVersion in (1, 3):
logger.debug( logger.debug(
'In messages.dat database, adding tag field to' 'In messages.dat database, adding tag field to'
' the inventory table.') ' the inventory table.')
@ -572,23 +573,10 @@ class sqlThread(threading.Thread):
rowcount = 0 rowcount = 0
# print 'item', item # print 'item', item
# print 'parameters', parameters # print 'parameters', parameters
# print('++++454++++++++++++++++++++++++')
# print ('parameters')
# print (parameters)
# print ('+++++++++++++++++++++++++++++')
try:
if 'sent' == parameters[1] and 'B' in parameters[0]:
item = '''SELECT toaddress, fromaddress, subject, message, status, ackdata, lastactiontime FROM sent WHERE fromaddress = ? ORDER BY lastactiontime DESC '''
parameters = (parameters[0],)
except (IndexError,TypeError) as e:
pass
try: try:
self.cur.execute(item, parameters) self.cur.execute(item, parameters)
rowcount = self.cur.rowcount rowcount = self.cur.rowcount
except Exception as err: except Exception as err:
print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')
print('inside the expectation')
print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')
if str(err) == 'database or disk is full': if str(err) == 'database or disk is full':
logger.fatal( logger.fatal(
'(while cur.execute) Alert: Your disk or data storage volume is full.' '(while cur.execute) Alert: Your disk or data storage volume is full.'

View File

@ -151,7 +151,7 @@ def resetLogging():
try: try:
preconfigured, msg = configureLogging() preconfigured, msg = configureLogging()
if msg: if msg:
logger.log(logging.WARNING if preconfigured else logging.INFO, msg) logger.log(logging.WARNING if preconfigured else logging.INFO, msg)
except: except:
pass pass

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

@ -3,9 +3,7 @@ Startup operations.
""" """
# pylint: disable=too-many-branches,too-many-statements # pylint: disable=too-many-branches,too-many-statements
# import configparser
import logging import logging
import os import os
import platform import platform
import sys import sys
@ -30,6 +28,7 @@ logger = logging.getLogger('default')
# 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()
@ -127,7 +126,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

@ -1,13 +1,13 @@
from .addrthread import AddrThread from network.addrthread import AddrThread
from .announcethread import AnnounceThread from network.announcethread import AnnounceThread
from .connectionpool import BMConnectionPool from network.connectionpool import BMConnectionPool
from .dandelion import Dandelion from network.dandelion import Dandelion
from .downloadthread import DownloadThread from network.downloadthread import DownloadThread
from .invthread import InvThread from network.invthread import InvThread
from .networkthread import BMNetworkThread from network.networkthread import BMNetworkThread
from .receivequeuethread import ReceiveQueueThread from network.receivequeuethread import ReceiveQueueThread
from .threads import StoppableThread from network.threads import StoppableThread
from .uploadthread import UploadThread from network.uploadthread import UploadThread
__all__ = [ __all__ = [

View File

@ -1,4 +1,3 @@
# import queue as Queue
""" """
Announce addresses as they are received from other hosts Announce addresses as they are received from other hosts
""" """

View File

@ -3,7 +3,6 @@ src/network/advanceddispatcher.py
================================= =================================
""" """
# pylint: disable=attribute-defined-outside-init # pylint: disable=attribute-defined-outside-init
# import pdb;pdb.set_trace()
import socket import socket
import threading import threading
import time import time
@ -32,7 +31,7 @@ class AdvancedDispatcher(asyncore.dispatcher):
# python 2 below condition is used # python 2 below condition is used
# if not hasattr(self, '_map'): # if not hasattr(self, '_map'):
# python 3 below condition is used # python 3 below condition is used
if not '_map' in dir(self): if '_map' not in dir(self):
asyncore.dispatcher.__init__(self, sock) asyncore.dispatcher.__init__(self, sock)
self.read_buf = bytearray() self.read_buf = bytearray()
self.write_buf = bytearray() self.write_buf = bytearray()

View File

@ -11,7 +11,7 @@ from bmconfigparser import BMConfigParser
from network.assemble import assemble_addr from network.assemble import assemble_addr
from network.connectionpool import BMConnectionPool from network.connectionpool import BMConnectionPool
from network.udp import UDPSocket from network.udp import UDPSocket
from .node import Peer from network.node import Peer
from network.threads import StoppableThread from network.threads import StoppableThread
@ -32,17 +32,15 @@ class AnnounceThread(StoppableThread):
@staticmethod @staticmethod
def announceSelf(): def announceSelf():
"""Announce our presence""" """Announce our presence"""
for connection in [ udpSockets for udpSockets in BMConnectionPool().udpSockets.values()]: for connection in [udpSockets for udpSockets in BMConnectionPool().udpSockets.values()]:
if not connection.announcing: if not connection.announcing:
continue continue
for stream in state.streamsInWhichIAmParticipating: for stream in state.streamsInWhichIAmParticipating:
addr = ( addr = (
stream, stream,
# state.Peer('127.0.0.1',int( BMConfigParser().safeGet("bitmessagesettings", "port"))),
# state.Peer('127.0.0.1',int( BMConfigParser().safeGet("bitmessagesettings", "port"))), # int(time.time()))
# int(time.time())) # connection.append_write_buf(BMProto.assembleAddr([addr]))
# connection.append_write_buf(BMProto.assembleAddr([addr]))
Peer( Peer(
'127.0.0.1', '127.0.0.1',
BMConfigParser().safeGetInt('bitmessagesettings', 'port')), BMConfigParser().safeGetInt('bitmessagesettings', 'port')),

View File

@ -13,7 +13,7 @@ from protocol import CreatePacket, encodeHost
def assemble_addr(peerList): def assemble_addr(peerList):
"""Create address command""" """Create address command"""
if isinstance(peerList, Peer): if isinstance(peerList, Peer):
peerList = (peerList) peerList = [peerList]
if not peerList: if not peerList:
return b'' return b''
retval = b'' retval = b''
@ -22,7 +22,7 @@ def assemble_addr(peerList):
len(peerList[i:i + MAX_ADDR_COUNT])) len(peerList[i:i + MAX_ADDR_COUNT]))
for stream, peer, timestamp in peerList[i:i + MAX_ADDR_COUNT]: for stream, peer, timestamp in peerList[i:i + MAX_ADDR_COUNT]:
payload += struct.pack( payload += struct.pack(
'>Q', timestamp) # 64-bit time '>Q', int(timestamp)) # 64-bit time
payload += struct.pack('>I', stream) payload += struct.pack('>I', stream)
payload += struct.pack( payload += struct.pack(
'>q', 1) # service bit flags offered by this node '>q', 1) # service bit flags offered by this node

View File

@ -102,7 +102,9 @@ def _strerror(err):
return os.strerror(err) return os.strerror(err)
except (ValueError, OverflowError, NameError): except (ValueError, OverflowError, NameError):
if err in errorcode: if err in errorcode:
ret18 ("Unknown error {}".format(err)) return errorcode[err]
return "Unknown error %s" % err
# ret18 ("Unknown error {}".format(err))
class ExitNow(Exception): class ExitNow(Exception):
@ -477,7 +479,7 @@ def kqueue_poller(timeout=0.0, map=None):
current_thread().stop.wait(timeout) current_thread().stop.wait(timeout)
def loop(timeout=30.0, use_poll=False, map=None, count=None, poller=None): def loop(timeout=30.0, _=False, map=None, count=None, poller=None):
"""Poll in a loop, until count or timeout is reached""" """Poll in a loop, until count or timeout is reached"""
# pylint: disable=redefined-builtin # pylint: disable=redefined-builtin
@ -518,7 +520,7 @@ def loop(timeout=30.0, use_poll=False, map=None, count=None, poller=None):
count = count - 1 count = count - 1
class dispatcher: class dispatcher(object):
"""Dispatcher for socket objects""" """Dispatcher for socket objects"""
# pylint: disable=too-many-public-methods,too-many-instance-attributes,old-style-class # pylint: disable=too-many-public-methods,too-many-instance-attributes,old-style-class
@ -786,7 +788,7 @@ class dispatcher:
def log_info(self, message, log_type='info'): def log_info(self, message, log_type='info'):
"""Conditionally print a message""" """Conditionally print a message"""
if log_type not in self.ignore_log_types: if log_type not in self.ignore_log_types:
print ('{}: {}'.format(log_type, message)) print('{}: {}'.format(log_type, message))
def handle_read_event(self): def handle_read_event(self):
"""Handle a read event""" """Handle a read event"""

View File

@ -32,7 +32,7 @@ from network.bmobject import (
BMObjectInvalidError, BMObjectAlreadyHaveError) BMObjectInvalidError, BMObjectAlreadyHaveError)
from network.proxy import ProxyError from network.proxy import ProxyError
from network.objectracker import missingObjects, ObjectTracker from network.objectracker import missingObjects, ObjectTracker
from .node import Node, Peer from network.node import Node, Peer
from queues import objectProcessorQueue, portCheckerQueue, invQueue, addrQueue from queues import objectProcessorQueue, portCheckerQueue, invQueue, addrQueue
from network.randomtrackingdict import RandomTrackingDict from network.randomtrackingdict import RandomTrackingDict
@ -52,6 +52,7 @@ count = 0
logger = logging.getLogger('default') logger = logging.getLogger('default')
class BMProtoError(ProxyError): class BMProtoError(ProxyError):
"""A Bitmessage Protocol Base Error""" """A Bitmessage Protocol Base Error"""
errorCodes = ("Protocol error") errorCodes = ("Protocol error")
@ -94,30 +95,30 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
self.object = None self.object = None
def state_bm_header(self): def state_bm_header(self):
"""Process incoming header""" """Process incoming header"""
self.magic, self.command, self.payloadLength, self.checksum = \ self.magic, self.command, self.payloadLength, self.checksum = \
protocol.Header.unpack(self.read_buf[:protocol.Header.size]) protocol.Header.unpack(self.read_buf[:protocol.Header.size])
#its shoule be in string # its shoule be in string
self.command = self.command.rstrip('\x00'.encode('utf-8')) self.command = self.command.rstrip('\x00'.encode('utf-8'))
global count,addr_version,addr_count,addr_verack # pylint: disable=global-statement
count+=1 global count, addr_version, addr_count, addr_verack
count += 1
if self.command == 'verack'.encode(): if self.command == 'verack'.encode():
addr_verack+=1 addr_verack += 1
# print('the addr_verack count are -{}'.format(addr_verack)) # print('the addr_verack count are -{}'.format(addr_verack))
if self.command == 'version'.encode(): if self.command == 'version'.encode():
addr_version+=1 addr_version += 1
# print('the addr_version count are -{}'.format(addr_version)) # print('the addr_version count are -{}'.format(addr_version))
if self.command == 'addr'.encode(): if self.command == 'addr'.encode():
addr_count+=1 addr_count += 1
# print('the addr_count count are -{}'.format(addr_count)) # print('the addr_count count are -{}'.format(addr_count))
if self.magic != 0xE9BEB4D9: if self.magic != 0xE9BEB4D9:
# skip 1 byte in order to sync # skip 1 byte in order to sync
#in the advancedispatched and length commend's # in the advancedispatched and length commend's
#escape the 1 length # escape the 1 length
self.set_state("bm_header", length=1) self.set_state("bm_header", length=1)
self.bm_proto_reset() self.bm_proto_reset()
logger.debug('Bad magic') logger.debug('Bad magic')
@ -132,7 +133,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
length=protocol.Header.size, expectBytes=self.payloadLength) length=protocol.Header.size, expectBytes=self.payloadLength)
return True return True
def state_bm_command(self): # pylint: disable=too-many-branches def state_bm_command(self): # pylint: disable=too-many-branches, too-many-statements
"""Process incoming command""" """Process incoming command"""
self.payload = self.read_buf[:self.payloadLength] self.payload = self.read_buf[:self.payloadLength]
if self.checksum != hashlib.sha512(self.payload).digest()[0:4]: if self.checksum != hashlib.sha512(self.payload).digest()[0:4]:
@ -143,14 +144,14 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
"error".encode(), "version".encode(), "verack".encode()): "error".encode(), "version".encode(), "verack".encode()):
logger.error( logger.error(
'Received command {} before connection was fully' 'Received command {} before connection was fully'
' established, ignoring'.format (self.command)) ' established, ignoring'.format(self.command))
self.invalid = True self.invalid = True
if not self.invalid: if not self.invalid:
try: try:
command = self.command.decode() if self.command else self.command command = self.command.decode() if self.command else self.command
retval = getattr( retval = getattr(
self, "bm_command_" +command)() self, "bm_command_" + command)()
except AttributeError: except AttributeError:
# unimplemented command # unimplemented command
logger.debug('unimplemented command %s', self.command) logger.debug('unimplemented command %s', self.command)
@ -171,9 +172,11 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
except BMObjectAlreadyHaveError: except BMObjectAlreadyHaveError:
logger.debug( logger.debug(
'%(host)s:%(port)i already got object, skipping', '%(host)s:%(port)i already got object, skipping',
self.destination._asdict()) self.destinaestion._asdict())
except struct.error: except struct.error:
logger.debug('decoding error, skipping') logger.debug('decoding error, skipping')
except ValueError:
pass
elif self.socket.type == socket.SOCK_DGRAM: elif self.socket.type == socket.SOCK_DGRAM:
# broken read, ignore # broken read, ignore
pass pass
@ -205,9 +208,9 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
"""Decode node details from the payload""" """Decode node details from the payload"""
# protocol.checkIPAddress() # protocol.checkIPAddress()
services, host, port = self.decode_payload_content("Q16sH") services, host, port = self.decode_payload_content("Q16sH")
if host[0:12] == '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF': if host[0:12] == '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode('raw_unicode_escape'):
host = socket.inet_ntop(socket.AF_INET, host[12:16]) host = socket.inet_ntop(socket.AF_INET, host[12:16])
elif host[0:6] == '\xfd\x87\xd8\x7e\xeb\x43': elif host[0:6] == '\xfd\x87\xd8\x7e\xeb\x43'.encode('raw_unicode_escape'):
# Onion, based on BMD/bitcoind # Onion, based on BMD/bitcoind
host = base64.b32encode(host[6:]).lower() + ".onion" host = base64.b32encode(host[6:]).lower() + ".onion"
else: else:
@ -346,8 +349,11 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
def bm_command_error(self): def bm_command_error(self):
"""Decode an error message and log it""" """Decode an error message and log it"""
fatalStatus, banTime, inventoryVector, errorText = \ err_values = self.decode_payload_content("vvlsls")
self.decode_payload_content("vvlsls") fatalStatus = err_values[0]
# banTime = err_values[1]
# inventoryVector = err_values[2]
errorText = err_values[3]
logger.error( logger.error(
'%s:%i error: %i, %s', self.destination.host, '%s:%i error: %i, %s', self.destination.host,
self.destination.port, fatalStatus, errorText) self.destination.port, fatalStatus, errorText)
@ -359,7 +365,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
If we have them and some other conditions are fulfilled, If we have them and some other conditions are fulfilled,
append them to the write queue. append them to the write queue.
""" """
#32 an array bit long strings # 32 an array bit long strings
items = self.decode_payload_content("l32s") items = self.decode_payload_content("l32s")
# skip? # skip?
now = time.time() now = time.time()
@ -381,7 +387,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
if dandelion and not state.dandelion: if dandelion and not state.dandelion:
return True return True
for i in map(str, items): for i in map(bytes, items):
if i in Inventory() and not Dandelion().hasHash(i): if i in Inventory() and not Dandelion().hasHash(i):
continue continue
if dandelion and not Dandelion().hasHash(i): if dandelion and not Dandelion().hasHash(i):
@ -434,7 +440,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
try: try:
self.object.checkObjectByType() self.object.checkObjectByType()
objectProcessorQueue.put(( objectProcessorQueue.put((
self.object.objectType, buffer(self.object.data))) self.object.objectType, memoryview(self.object.data)))
except BMObjectInvalidError: except BMObjectInvalidError:
BMProto.stopDownloadingObject(self.object.inventoryHash, True) BMProto.stopDownloadingObject(self.object.inventoryHash, True)
else: else:
@ -445,12 +451,12 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
if self.object.inventoryHash in Inventory() and Dandelion().hasHash(self.object.inventoryHash): if self.object.inventoryHash in Inventory() and Dandelion().hasHash(self.object.inventoryHash):
Dandelion().removeHash(self.object.inventoryHash, "cycle detection") Dandelion().removeHash(self.object.inventoryHash, "cycle detection")
[self.object.inventoryHash] = (
Inventory()[self.object.inventoryHash] = (
self.object.objectType, self.object.streamNumber, self.object.objectType, self.object.streamNumber,
buffer(self.payload[objectOffset:]), self.object.expiresTime, memoryview(self.payload[objectOffset:]), self.object.expiresTime,
buffer(self.object.tag) memoryview(self.object.tag)
) )
Inventory()[self.object.inventoryHash]
self.handleReceivedObject( self.handleReceivedObject(
self.object.streamNumber, self.object.inventoryHash) self.object.streamNumber, self.object.inventoryHash)
invQueue.put(( invQueue.put((
@ -463,11 +469,11 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
def bm_command_addr(self): def bm_command_addr(self):
# print('+++++++++++++++++++++++++++\ # print('+++++++++++++++++++++++++++\
# bm_command_addr bm_command_addr bm_command_addr ++++++++++++++++') # bm_command_addr bm_command_addr bm_command_addr ++++++++++++++++')
"""Incoming addresses, process them""" """Incoming addresses, process them"""
addresses = self._decode_addr() # pylint: disable=redefined-outer-name addresses = self._decode_addr() # pylint: disable=redefined-outer-name
for i in addresses: for i in addresses:
seenTime, stream, services, ip, port = i seenTime, stream, _, ip, port = i
decodedIP = protocol.checkIPAddress(ip) decodedIP = protocol.checkIPAddress(ip)
if stream not in state.streamsInWhichIAmParticipating: if stream not in state.streamsInWhichIAmParticipating:
continue continue
@ -533,6 +539,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
"tls_init" if self.isSSL else "connection_fully_established", "tls_init" if self.isSSL else "connection_fully_established",
length=self.payloadLength, expectBytes=0) length=self.payloadLength, expectBytes=0)
return False return False
def bm_command_version(self): def bm_command_version(self):
# print('inside the bmproto ') # print('inside the bmproto ')
""" """
@ -566,7 +573,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
logger.debug( logger.debug(
'%(host)s:%(port)i sending version', '%(host)s:%(port)i sending version',
self.destination._asdict()) self.destination._asdict())
if ((self.services & protocol.NODE_SSL == protocol.NODE_SSL)): if self.services & protocol.NODE_SSL == protocol.NODE_SSL:
# self.isSSL = True # self.isSSL = True
pass pass
if not self.verackReceived: if not self.verackReceived:
@ -625,7 +632,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
if not protocol.checkSocksIP(self.destination.host): if not protocol.checkSocksIP(self.destination.host):
self.append_write_buf(protocol.assembleErrorMessage( self.append_write_buf(protocol.assembleErrorMessage(
errorText="Too many connections from your IP." errorText="Too many connections from your IP."
" Closing connection.", fatal=2)) " Closing connection.", fatal=2))
logger.debug( logger.debug(
'Closed connection to {} because we are already connected' 'Closed connection to {} because we are already connected'
' to that IP.'.format(self.destination)) ' to that IP.'.format(self.destination))
@ -660,10 +667,8 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
"Closed connection to %s because I'm connected to myself.", "Closed connection to %s because I'm connected to myself.",
self.destination) self.destination)
return False return False
return True return True
@staticmethod @staticmethod
def stopDownloadingObject(hashId, forwardAnyway=False): def stopDownloadingObject(hashId, forwardAnyway=False):
"""Stop downloading an object""" """Stop downloading an object"""

View File

@ -39,7 +39,7 @@ def chooseConnection(stream):
# discovered peers are already filtered by allowed streams # discovered peers are already filtered by allowed streams
return getDiscoveredPeer() return getDiscoveredPeer()
for _ in range(50): for _ in range(50):
peer = random.choice([key for key in knownnodes.knownNodes[stream].keys()]) peer = random.choice([key for key in knownnodes.knownNodes[stream].keys()])
try: try:
peer_info = knownnodes.knownNodes[stream][peer] peer_info = knownnodes.knownNodes[stream][peer]
if peer_info.get('self'): if peer_info.get('self'):

View File

@ -17,11 +17,11 @@ from bmconfigparser import BMConfigParser
from network.connectionchooser import chooseConnection from network.connectionchooser import chooseConnection
from network.proxy import Proxy from network.proxy import Proxy
from .node import Peer
from singleton import Singleton
from network.tcp import ( from network.tcp import (
TCPServer, Socks5BMConnection, Socks4aBMConnection, TCPConnection,bootstrap) TCPServer, Socks5BMConnection, Socks4aBMConnection, TCPConnection, bootstrap)
from network.udp import UDPSocket from network.udp import UDPSocket
from singleton import Singleton
from .node import Peer
logger = logging.getLogger('default') logger = logging.getLogger('default')
@ -78,8 +78,8 @@ class BMConnectionPool(object):
`inboundConnections` and `outboundConnections` dicts `inboundConnections` and `outboundConnections` dicts
""" """
inboundConnections = [inboundConnections for inboundConnections in self.inboundConnections.values()] inboundConnections = [inboundConnections for inboundConnections in self.inboundConnections.values()]
outboundConnections = [outboundConnections for outboundConnections in self.outboundConnections.values()] outboundConnections = [outboundConnections for outboundConnections in self.outboundConnections.values()]
return [ connections for connections in inboundConnections +outboundConnections] return [connections for connections in inboundConnections + outboundConnections]
def establishedConnections(self): def establishedConnections(self):
"""Shortcut for list of connections having fullyEstablished == True""" """Shortcut for list of connections having fullyEstablished == True"""
@ -292,7 +292,7 @@ class BMConnectionPool(object):
except ValueError: except ValueError:
Proxy.onion_proxy = None Proxy.onion_proxy = None
established = sum( established = sum(
1 for c in [outboundConnections for outboundConnections in self.outboundConnections.values()] 1 for c in [outboundConnections for outboundConnections in self.outboundConnections.values()]
if (c.connected and c.fullyEstablished)) if (c.connected and c.fullyEstablished))
pending = len(self.outboundConnections) - established pending = len(self.outboundConnections) - established
if established < int(BMConfigParser().safeGet( if established < int(BMConfigParser().safeGet(
@ -430,14 +430,13 @@ class BMConnectionPool(object):
# list(self.udpSockets.values()) # list(self.udpSockets.values())
# ): # ):
for i in ( for i in (
# [inboundConnections for inboundConnections in self.inboundConnections.values()] +
# [inboundConnections for inboundConnections in self.inboundConnections.values()] + # [outboundConnections for outboundConnections in self.outboundConnections.values()] +
# [outboundConnections for outboundConnections in self.outboundConnections.values()] + # [listeningSockets for listeningSockets in self.listeningSockets.values()] +
# [listeningSockets for listeningSockets in self.listeningSockets.values()] + # [udpSockets for udpSockets in self.udpSockets.values()]
# [udpSockets for udpSockets in self.udpSockets.values()] self.connections() +
[listeningSockets for listeningSockets in self.listeningSockets.values()] +
self.connections() [udpSockets for udpSockets in self.udpSockets.values()]
+ [listeningSockets for listeningSockets in self.listeningSockets.values()] + [udpSockets for udpSockets in self.udpSockets.values()]
): ):
if not (i.accepting or i.connecting or i.connected): if not (i.accepting or i.connecting or i.connected):
reaper.append(i) reaper.append(i)

View File

@ -28,7 +28,7 @@ logger = logging.getLogger('default')
@Singleton @Singleton
class Dandelion(): # pylint: disable=old-style-class class Dandelion(object):
"""Dandelion class for tracking stem/fluff stages.""" """Dandelion class for tracking stem/fluff stages."""
def __init__(self): def __init__(self):
# currently assignable child stems # currently assignable child stems
@ -104,12 +104,12 @@ class Dandelion(): # pylint: disable=old-style-class
self.stem.append(connection) self.stem.append(connection)
for k in (k for k, v in iter(self.nodeMap.items()) if v is None): for k in (k for k, v in iter(self.nodeMap.items()) if v is None):
self.nodeMap[k] = connection self.nodeMap[k] = connection
#The Purpose of adding this condition that if self # The Purpose of adding this condition that if self
#hashMap is has any value # hashMap is has any value
# if not [hasmap for hasmap in self.hashMap.items()] ==[]: # if not [hasmap for hasmap in self.hashMap.items()] ==[]:
try: try:
for k, v in { for k, v in {
k: v for k, v in iter([hasmap for hasmap in self.hashMap.items()]) k: v for k, v in iter([hasmap for hasmap in self.hashMap.items()])
if v.child is None if v.child is None
}.items(): }.items():
self.hashMap[k] = Stem( self.hashMap[k] = Stem(
@ -142,7 +142,7 @@ class Dandelion(): # pylint: disable=old-style-class
): ):
self.nodeMap[k] = None self.nodeMap[k] = None
for k, v in { for k, v in {
k: v for k, v in iter(iter([hasmap for hasmap in self.hashMap.items()])) k: v for k, v in iter(iter([hasmap for hasmap in self.hashMap.items()]))
if v.child == connection if v.child == connection
}.items(): }.items():
self.hashMap[k] = Stem( self.hashMap[k] = Stem(

View File

@ -44,7 +44,8 @@ class DownloadThread(StoppableThread):
# Choose downloading peers randomly # Choose downloading peers randomly
# connections = [ # connections = [
# x for x in # x for x in
# list(BMConnectionPool().inboundConnections.values()) + list(BMConnectionPool().outboundConnections.values()) # list(BMConnectionPool().inboundConnections.values()) +
# list(BMConnectionPool().outboundConnections.values())
# if x.fullyEstablished] # if x.fullyEstablished]
connections = BMConnectionPool().establishedConnections() connections = BMConnectionPool().establishedConnections()

View File

@ -1,3 +1,4 @@
# pylint: disable=redefined-outer-name, too-many-ancestors, missing-docstring
import socket import socket
from advanceddispatcher import AdvancedDispatcher from advanceddispatcher import AdvancedDispatcher
@ -12,7 +13,7 @@ class HttpError(ProxyError):
class HttpConnection(AdvancedDispatcher): class HttpConnection(AdvancedDispatcher):
def __init__(self, host, path="/"): # pylint: disable=redefined-outer-name def __init__(self, host, path="/"):
AdvancedDispatcher.__init__(self) AdvancedDispatcher.__init__(self)
self.path = path self.path = path
self.destination = (host, 80) self.destination = (host, 80)
@ -38,7 +39,7 @@ class HttpConnection(AdvancedDispatcher):
class Socks5HttpConnection(Socks5Connection, HttpConnection): class Socks5HttpConnection(Socks5Connection, HttpConnection):
def __init__(self, host, path="/"): # pylint: disable=super-init-not-called, redefined-outer-name def __init__(self, host, path="/"): # pylint: disable=super-init-not-called
self.path = path self.path = path
Socks5Connection.__init__(self, address=(host, 80)) Socks5Connection.__init__(self, address=(host, 80))
@ -48,7 +49,7 @@ class Socks5HttpConnection(Socks5Connection, HttpConnection):
class Socks4aHttpConnection(Socks4aConnection, HttpConnection): class Socks4aHttpConnection(Socks4aConnection, HttpConnection):
def __init__(self, host, path="/"): # pylint: disable=super-init-not-called, redefined-outer-name def __init__(self, host, path="/"): # pylint: disable=super-init-not-called
Socks4aConnection.__init__(self, address=(host, 80)) Socks4aConnection.__init__(self, address=(host, 80))
self.path = path self.path = path

View File

@ -1,3 +1,6 @@
"""
src/network/http_old.py
"""
import asyncore import asyncore
import socket import socket
import time import time

View File

@ -5,7 +5,7 @@ src/network/httpd.py
import asyncore import asyncore
import socket import socket
from tls import TLSHandshake from .tls import TLSHandshake
class HTTPRequestHandler(asyncore.dispatcher): class HTTPRequestHandler(asyncore.dispatcher):
@ -129,7 +129,7 @@ class HTTPServer(asyncore.dispatcher):
def handle_accept(self): def handle_accept(self):
pair = self.accept() pair = self.accept()
if pair is not None: if pair is not None:
sock, addr = pair sock, _ = pair
# print 'Incoming connection from %s' % repr(addr) # print 'Incoming connection from %s' % repr(addr)
self.connections += 1 self.connections += 1
# if self.connections % 1000 == 0: # if self.connections % 1000 == 0:
@ -148,7 +148,7 @@ class HTTPSServer(HTTPServer):
def handle_accept(self): def handle_accept(self):
pair = self.accept() pair = self.accept()
if pair is not None: if pair is not None:
sock, addr = pair sock, _ = pair
# print 'Incoming connection from %s' % repr(addr) # print 'Incoming connection from %s' % repr(addr)
self.connections += 1 self.connections += 1
# if self.connections % 1000 == 0: # if self.connections % 1000 == 0:

View File

@ -1,8 +1,8 @@
# pylint: disable=missing-docstring
import asyncore import asyncore
from http import HTTPClient from .http import HTTPClient
from tls import TLSHandshake from .tls import TLSHandshake
""" """
self.sslSock = ssl.wrap_socket( self.sslSock = ssl.wrap_socket(
self.sock, self.sock,
@ -17,6 +17,7 @@ self.sslSock = ssl.wrap_socket(
class HTTPSClient(HTTPClient, TLSHandshake): class HTTPSClient(HTTPClient, TLSHandshake):
def __init__(self, host, path): def __init__(self, host, path):
# pylint: disable=non-parent-init-called
if not hasattr(self, '_map'): if not hasattr(self, '_map'):
asyncore.dispatcher.__init__(self) asyncore.dispatcher.__init__(self)
self.tlsDone = False self.tlsDone = False

View File

@ -19,12 +19,12 @@ class BMNetworkThread(StoppableThread):
def stopThread(self): def stopThread(self):
super(BMNetworkThread, self).stopThread() super(BMNetworkThread, self).stopThread()
for i in [listeningSockets for listeningSockets in BMConnectionPool().listeningSockets.values()]: for i in [listeningSockets for listeningSockets in BMConnectionPool().listeningSockets.values()]:
try: try:
i.close() i.close()
except: except:
pass pass
for i in [ outboundConnections for outboundConnections in BMConnectionPool().outboundConnections.values()]: for i in [outboundConnections for outboundConnections in BMConnectionPool().outboundConnections.values()]:
try: try:
i.close() i.close()
except: except:

View File

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

View File

@ -77,7 +77,7 @@ class TCPConnection(BMProto, TLSDispatcher):
self.connect(self.destination) self.connect(self.destination)
logger.debug( logger.debug(
'Connecting to {}:{}'.format( 'Connecting to {}:{}'.format(
self.destination.host, self.destination.port)) self.destination.host, self.destination.port))
try: try:
self.local = ( self.local = (
protocol.checkIPAddress( protocol.checkIPAddress(
@ -90,7 +90,7 @@ class TCPConnection(BMProto, TLSDispatcher):
ObjectTracker.__init__(self) # pylint: disable=non-parent-init-called ObjectTracker.__init__(self) # pylint: disable=non-parent-init-called
self.bm_proto_reset() self.bm_proto_reset()
# print('--------------tcp------------------') # print('--------------tcp------------------')
from network import stats # from network import stats
self.set_state("bm_header", expectBytes=protocol.Header.size) self.set_state("bm_header", expectBytes=protocol.Header.size)
def antiIntersectionDelay(self, initial=False): def antiIntersectionDelay(self, initial=False):
@ -370,7 +370,7 @@ class TCPServer(AdvancedDispatcher):
"""TCP connection server for Bitmessage protocol""" """TCP connection server for Bitmessage protocol"""
def __init__(self, host='127.0.0.1', port=8444): def __init__(self, host='127.0.0.1', port=8444):
if '_map' not in dir(self): if '_map' not in dir(self):
AdvancedDispatcher.__init__(self) AdvancedDispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr() self.set_reuse_addr()

View File

@ -1,7 +1,6 @@
""" """
SSL/TLS negotiation. SSL/TLS negotiation.
""" """
import logging import logging
import os import os
import socket import socket
@ -23,7 +22,7 @@ if sys.version_info >= (2, 7, 13):
# in the future change to # in the future change to
# ssl.PROTOCOL_TLS1.2 # ssl.PROTOCOL_TLS1.2
# Right now I am using the python3.5.2 and I faced the ssl for protocol due to this I # Right now I am using the python3.5.2 and I faced the ssl for protocol due to this I
# have used try and catch # have used try and catch
try: try:
sslProtocolVersion = ssl.PROTOCOL_TLS # pylint: disable=no-member sslProtocolVersion = ssl.PROTOCOL_TLS # pylint: disable=no-member
except AttributeError: except AttributeError:

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
@ -277,14 +278,13 @@ def isProofOfWorkSufficient(
def CreatePacket(command, payload=''): def CreatePacket(command, payload=''):
"""Construct and return a number of bytes from a payload""" """Construct and return a number of bytes from a payload"""
payload = payload if type(payload) == bytes else payload.encode() payload = payload if type(payload) in [bytes,bytearray] else payload.encode()
payload_length = len(payload) payload_length = len(payload)
checksum = hashlib.sha512(payload).digest()[0:4] checksum = hashlib.sha512(payload).digest()[0:4]
byte = bytearray(Header.size + payload_length) byte = bytearray(Header.size + payload_length)
Header.pack_into(byte, 0, 0xE9BEB4D9, command.encode(), payload_length, checksum) Header.pack_into(byte, 0, 0xE9BEB4D9, command.encode(), payload_length, checksum)
byte[Header.size:] = payload byte[Header.size:] = payload
return byte return bytes(byte)
def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server=False, nodeid=None): def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server=False, nodeid=None):
@ -324,10 +324,8 @@ def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server=
(NODE_DANDELION if state.dandelion else 0) (NODE_DANDELION if state.dandelion else 0)
) )
# = 127.0.0.1. This will be ignored by the remote host. The actual remote connected IP will be used. # = 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('raw_unicode_escape') + pack('>L', 2130706433)
# we have a separate extPort and incoming over clearnet # we have a separate extPort and incoming over clearnet
# or outgoing through clearnet # or outgoing through clearnet
extport = BMConfigParser().safeGetInt('bitmessagesettings', 'extport') extport = BMConfigParser().safeGetInt('bitmessagesettings', 'extport')
@ -338,11 +336,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 +371,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

@ -1,43 +1,30 @@
""" """
Global runtime variables. src/state.py
=================================
""" """
import collections import collections
neededPubkeys = {} neededPubkeys = {}
streamsInWhichIAmParticipating = [] streamsInWhichIAmParticipating = []
# For UPnP
extPort = None extPort = None
"""For UPnP""" # for Tor hidden service
socksIP = None socksIP = None
"""for Tor hidden service""" # Network protocols availability, initialised below
networkProtocolAvailability = None
appdata = '' appdata = '' # holds the location of the application data storage directory
"""holds the location of the application data storage directory""" # Set to 1 by the doCleanShutdown function.
# Used to tell the proof of work worker threads to exit.
shutdown = 0 shutdown = 0
"""
Set to 1 by the `.shutdown.doCleanShutdown` function.
Used to tell the threads to exit.
"""
# Component control flags - set on startup, do not change during runtime # Component control flags - set on startup, do not change during runtime
# The defaults are for standalone GUI (default operating mode) # The defaults are for standalone GUI (default operating mode)
enableNetwork = True enableNetwork = True # enable network threads
"""enable network threads""" enableObjProc = True # enable object processing threads
enableObjProc = True enableAPI = True # enable API (if configured)
"""enable object processing thread""" enableGUI = True # enable GUI (QT or ncurses)
enableAPI = True enableSTDIO = False # enable STDIO threads
"""enable API (if configured)"""
enableGUI = True
"""enable GUI (QT or ncurses)"""
enableSTDIO = False
"""enable STDIO threads"""
curses = False curses = False
sqlReady = False # set to true by sqlTread when ready for processing
sqlReady = False
"""set to true by `.threads.sqlThread` when ready for processing"""
maximumNumberOfHalfOpenConnections = 0 maximumNumberOfHalfOpenConnections = 0
invThread = None invThread = None
addrThread = None addrThread = None
@ -68,8 +55,6 @@ def resetNetworkProtocolAvailability():
resetNetworkProtocolAvailability() resetNetworkProtocolAvailability()
discoveredPeers = {}
dandelion = 0 dandelion = 0
testmode = False testmode = False
@ -124,4 +109,4 @@ availabe_credit = 0
in_sent_method = False in_sent_method = False
in_search_mode = False in_search_mode = False

View File

@ -39,15 +39,20 @@ class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors
return True return True
def __getitem__(self, hash_): def __getitem__(self, hash_):
print('----------__getitem__------------------') if hash_ == 0:
hash_ = bytes()
with self.lock: with self.lock:
if hash_ in self._inventory: try:
return self._inventory[hash_] if hash_ in self._inventory:
rows = sqlQuery( return self._inventory[hash_]
'SELECT objecttype, streamnumber, payload, expirestime, tag FROM inventory WHERE hash=?', rows = sqlQuery(
sqlite3.Binary(hash_)) 'SELECT objecttype, streamnumber, payload, expirestime, tag FROM inventory WHERE hash=?',
if not rows: sqlite3.Binary(hash_))
raise KeyError(hash_) if not rows:
pass
# raise KeyError(hash_)
except:
pass
return InventoryItem(*rows[0]) return InventoryItem(*rows[0])
def __setitem__(self, hash_, value): def __setitem__(self, hash_, value):

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