Refactoring of config parser and shared.py

- got rid of shared config parser and made it into a singleton
- refactored safeConfigGetBoolean as a method of the config singleton
- refactored safeConfigGet as a method of the config singleton
- moved softwareVersion from shared.py into version.py
- moved some global variables from shared.py into state.py
- moved some protocol-specific functions from shared.py into protocol.py
This commit is contained in:
Peter Šurda 2017-01-11 14:27:19 +01:00
parent 2654b61bd7
commit 8bcfe80ad0
Signed by untrusted user: PeterSurda
GPG Key ID: 0C5F50C0B5F37D87
37 changed files with 1187 additions and 813 deletions

View File

@ -19,6 +19,7 @@ from binascii import hexlify
import shared
import time
from addresses import decodeAddress,addBMIfNotPresent,decodeVarint,calculateInventoryHash,varintDecodeError
from configparser import BMConfigParser
import helper_inbox
import helper_sent
import hashlib
@ -30,6 +31,7 @@ from struct import pack
from helper_sql import sqlQuery,sqlExecute,SqlBulkExecute,sqlStoredProcedure
from debug import logger
from inventory import Inventory
from version import softwareVersion
# Helper Functions
import proofofwork
@ -120,7 +122,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
# handle Basic authentication
(enctype, encstr) = self.headers.get('Authorization').split()
(emailid, password) = encstr.decode('base64').split(':')
if emailid == shared.config.get('bitmessagesettings', 'apiusername') and password == shared.config.get('bitmessagesettings', 'apipassword'):
if emailid == BMConfigParser().get('bitmessagesettings', 'apiusername') and password == BMConfigParser().get('bitmessagesettings', 'apipassword'):
return True
else:
return False
@ -163,22 +165,22 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
def HandleListAddresses(self, method):
data = '{"addresses":['
configSections = shared.config.sections()
configSections = BMConfigParser().sections()
for addressInKeysFile in configSections:
if addressInKeysFile != 'bitmessagesettings':
status, addressVersionNumber, streamNumber, hash01 = decodeAddress(
addressInKeysFile)
if len(data) > 20:
data += ','
if shared.config.has_option(addressInKeysFile, 'chan'):
chan = shared.config.getboolean(addressInKeysFile, 'chan')
if BMConfigParser().has_option(addressInKeysFile, 'chan'):
chan = BMConfigParser().getboolean(addressInKeysFile, 'chan')
else:
chan = False
label = shared.config.get(addressInKeysFile, 'label')
label = BMConfigParser().get(addressInKeysFile, 'label')
if method == 'listAddresses2':
label = label.encode('base64')
data += json.dumps({'label': label, 'address': addressInKeysFile, 'stream':
streamNumber, 'enabled': shared.config.getboolean(addressInKeysFile, 'enabled'), 'chan': chan}, indent=4, separators=(',', ': '))
streamNumber, 'enabled': BMConfigParser().getboolean(addressInKeysFile, 'enabled'), 'chan': chan}, indent=4, separators=(',', ': '))
data += ']}'
return data
@ -236,21 +238,21 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
elif len(params) == 1:
label, = params
eighteenByteRipe = False
nonceTrialsPerByte = shared.config.get(
nonceTrialsPerByte = BMConfigParser().get(
'bitmessagesettings', 'defaultnoncetrialsperbyte')
payloadLengthExtraBytes = shared.config.get(
payloadLengthExtraBytes = BMConfigParser().get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 2:
label, eighteenByteRipe = params
nonceTrialsPerByte = shared.config.get(
nonceTrialsPerByte = BMConfigParser().get(
'bitmessagesettings', 'defaultnoncetrialsperbyte')
payloadLengthExtraBytes = shared.config.get(
payloadLengthExtraBytes = BMConfigParser().get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 3:
label, eighteenByteRipe, totalDifficulty = params
nonceTrialsPerByte = int(
shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty)
payloadLengthExtraBytes = shared.config.get(
payloadLengthExtraBytes = BMConfigParser().get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 4:
label, eighteenByteRipe, totalDifficulty, smallMessageDifficulty = params
@ -280,45 +282,45 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
addressVersionNumber = 0
streamNumber = 0
eighteenByteRipe = False
nonceTrialsPerByte = shared.config.get(
nonceTrialsPerByte = BMConfigParser().get(
'bitmessagesettings', 'defaultnoncetrialsperbyte')
payloadLengthExtraBytes = shared.config.get(
payloadLengthExtraBytes = BMConfigParser().get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 2:
passphrase, numberOfAddresses = params
addressVersionNumber = 0
streamNumber = 0
eighteenByteRipe = False
nonceTrialsPerByte = shared.config.get(
nonceTrialsPerByte = BMConfigParser().get(
'bitmessagesettings', 'defaultnoncetrialsperbyte')
payloadLengthExtraBytes = shared.config.get(
payloadLengthExtraBytes = BMConfigParser().get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 3:
passphrase, numberOfAddresses, addressVersionNumber = params
streamNumber = 0
eighteenByteRipe = False
nonceTrialsPerByte = shared.config.get(
nonceTrialsPerByte = BMConfigParser().get(
'bitmessagesettings', 'defaultnoncetrialsperbyte')
payloadLengthExtraBytes = shared.config.get(
payloadLengthExtraBytes = BMConfigParser().get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 4:
passphrase, numberOfAddresses, addressVersionNumber, streamNumber = params
eighteenByteRipe = False
nonceTrialsPerByte = shared.config.get(
nonceTrialsPerByte = BMConfigParser().get(
'bitmessagesettings', 'defaultnoncetrialsperbyte')
payloadLengthExtraBytes = shared.config.get(
payloadLengthExtraBytes = BMConfigParser().get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 5:
passphrase, numberOfAddresses, addressVersionNumber, streamNumber, eighteenByteRipe = params
nonceTrialsPerByte = shared.config.get(
nonceTrialsPerByte = BMConfigParser().get(
'bitmessagesettings', 'defaultnoncetrialsperbyte')
payloadLengthExtraBytes = shared.config.get(
payloadLengthExtraBytes = BMConfigParser().get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 6:
passphrase, numberOfAddresses, addressVersionNumber, streamNumber, eighteenByteRipe, totalDifficulty = params
nonceTrialsPerByte = int(
shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty)
payloadLengthExtraBytes = shared.config.get(
payloadLengthExtraBytes = BMConfigParser().get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 7:
passphrase, numberOfAddresses, addressVersionNumber, streamNumber, eighteenByteRipe, totalDifficulty, smallMessageDifficulty = params
@ -443,13 +445,13 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
address, = params
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(address)
address = addBMIfNotPresent(address)
if not shared.config.has_section(address):
if not BMConfigParser().has_section(address):
raise APIError(13, 'Could not find this address in your keys.dat file.')
if not shared.safeConfigGetBoolean(address, 'chan'):
if not BMConfigParser().safeGetBoolean(address, 'chan'):
raise APIError(25, 'Specified address is not a chan address. Use deleteAddress API call instead.')
shared.config.remove_section(address)
BMConfigParser().remove_section(address)
with open(shared.appdata + 'keys.dat', 'wb') as configfile:
shared.config.write(configfile)
BMConfigParser().write(configfile)
return 'success'
def HandleDeleteAddress(self, params):
@ -459,11 +461,11 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
address, = params
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(address)
address = addBMIfNotPresent(address)
if not shared.config.has_section(address):
if not BMConfigParser().has_section(address):
raise APIError(13, 'Could not find this address in your keys.dat file.')
shared.config.remove_section(address)
BMConfigParser().remove_section(address)
with open(shared.appdata + 'keys.dat', 'wb') as configfile:
shared.config.write(configfile)
BMConfigParser().write(configfile)
shared.UISignalQueue.put(('rerenderMessagelistFromLabels',''))
shared.UISignalQueue.put(('rerenderMessagelistToLabels',''))
shared.reloadMyAddressHashes()
@ -659,7 +661,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(toAddress)
self._verifyAddress(fromAddress)
try:
fromAddressEnabled = shared.config.getboolean(
fromAddressEnabled = BMConfigParser().getboolean(
fromAddress, 'enabled')
except:
raise APIError(13, 'Could not find your fromAddress in the keys.dat file.')
@ -723,7 +725,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
fromAddress = addBMIfNotPresent(fromAddress)
self._verifyAddress(fromAddress)
try:
fromAddressEnabled = shared.config.getboolean(
fromAddressEnabled = BMConfigParser().getboolean(
fromAddress, 'enabled')
except:
raise APIError(13, 'could not find your fromAddress in the keys.dat file.')
@ -946,7 +948,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
networkStatus = 'connectedButHaveNotReceivedIncomingConnections'
else:
networkStatus = 'connectedAndReceivingIncomingConnections'
return json.dumps({'networkConnections':len(shared.connectedHostsList),'numberOfMessagesProcessed':shared.numberOfMessagesProcessed, 'numberOfBroadcastsProcessed':shared.numberOfBroadcastsProcessed, 'numberOfPubkeysProcessed':shared.numberOfPubkeysProcessed, 'networkStatus':networkStatus, 'softwareName':'PyBitmessage','softwareVersion':shared.softwareVersion}, indent=4, separators=(',', ': '))
return json.dumps({'networkConnections':len(shared.connectedHostsList),'numberOfMessagesProcessed':shared.numberOfMessagesProcessed, 'numberOfBroadcastsProcessed':shared.numberOfBroadcastsProcessed, 'numberOfPubkeysProcessed':shared.numberOfPubkeysProcessed, 'networkStatus':networkStatus, 'softwareName':'PyBitmessage','softwareVersion':softwareVersion}, indent=4, separators=(',', ': '))
def HandleDecodeAddress(self, params):
# Return a meaningful decoding of an address.

View File

@ -45,16 +45,6 @@ def restartBmNotify(): #Prompts the user to restart Bitmessage.
print ' WARNING: If Bitmessage is running locally, you must restart it now.'
print ' *******************************************************************\n'
def safeConfigGetBoolean(section,field):
global keysPath
config = BMConfigParser()
config.read(keysPath)
try:
return config.getboolean(section,field)
except:
return False
#Begin keys.dat interactions
def lookupAppdataFolder(): #gets the appropriate folders for the .dat files depending on the OS. Taken from bitmessagemain.py
APPNAME = "PyBitmessage"
@ -74,14 +64,13 @@ def lookupAppdataFolder(): #gets the appropriate folders for the .dat files depe
def configInit():
global keysName
config = BMConfigParser()
config.add_section('bitmessagesettings')
config.set('bitmessagesettings', 'port', '8444') #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 directory or is created locally to connect to a machine remotely.
config.set('bitmessagesettings','apienabled','true') #Sets apienabled to true in keys.dat
BMConfigParser().add_section('bitmessagesettings')
BMConfigParser().set('bitmessagesettings', 'port', '8444') #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 directory or is created locally to connect to a machine remotely.
BMConfigParser().set('bitmessagesettings','apienabled','true') #Sets apienabled to true in keys.dat
with open(keysName, 'wb') as configfile:
config.write(configfile)
BMConfigParser().write(configfile)
print '\n ' + str(keysName) + ' Initalized in the same directory as daemon.py'
print ' You will now need to configure the ' + str(keysName) + ' file.\n'
@ -89,8 +78,7 @@ def configInit():
def apiInit(apiEnabled):
global keysPath
global usrPrompt
config = BMConfigParser()
config.read(keysPath)
BMConfigParser().read(keysPath)
@ -98,9 +86,9 @@ def apiInit(apiEnabled):
uInput = userInput("The API is not enabled. Would you like to do that now, (Y)es or (N)o?").lower()
if uInput == "y": #
config.set('bitmessagesettings','apienabled','true') #Sets apienabled to true in keys.dat
BMConfigParser().set('bitmessagesettings','apienabled','true') #Sets apienabled to true in keys.dat
with open(keysPath, 'wb') as configfile:
config.write(configfile)
BMConfigParser().write(configfile)
print 'Done'
restartBmNotify()
@ -143,15 +131,15 @@ def apiInit(apiEnabled):
print ' -----------------------------------\n'
config.set('bitmessagesettings', 'port', '8444') #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 directory or is created locally to connect to a machine remotely.
config.set('bitmessagesettings','apienabled','true')
config.set('bitmessagesettings', 'apiport', apiPort)
config.set('bitmessagesettings', 'apiinterface', '127.0.0.1')
config.set('bitmessagesettings', 'apiusername', apiUsr)
config.set('bitmessagesettings', 'apipassword', apiPwd)
config.set('bitmessagesettings', 'daemon', daemon)
BMConfigParser().set('bitmessagesettings', 'port', '8444') #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 directory or is created locally to connect to a machine remotely.
BMConfigParser().set('bitmessagesettings','apienabled','true')
BMConfigParser().set('bitmessagesettings', 'apiport', apiPort)
BMConfigParser().set('bitmessagesettings', 'apiinterface', '127.0.0.1')
BMConfigParser().set('bitmessagesettings', 'apiusername', apiUsr)
BMConfigParser().set('bitmessagesettings', 'apipassword', apiPwd)
BMConfigParser().set('bitmessagesettings', 'daemon', daemon)
with open(keysPath, 'wb') as configfile:
config.write(configfile)
BMConfigParser().write(configfile)
print '\n Finished configuring the keys.dat file with API information.\n'
restartBmNotify()
@ -174,21 +162,19 @@ def apiData():
global keysPath
global usrPrompt
config = BMConfigParser()
config.read(keysPath) #First try to load the config file (the keys.dat file) from the program directory
BMConfigParser().read(keysPath) #First try to load the config file (the keys.dat file) from the program directory
try:
config.get('bitmessagesettings','port')
BMConfigParser().get('bitmessagesettings','port')
appDataFolder = ''
except:
#Could not load the keys.dat file in the program directory. Perhaps it is in the appdata directory.
appDataFolder = lookupAppdataFolder()
keysPath = appDataFolder + keysPath
config = BMConfigParser()
config.read(keysPath)
BMConfigParser().read(keysPath)
try:
config.get('bitmessagesettings','port')
BMConfigParser().get('bitmessagesettings','port')
except:
#keys.dat was not there either, something is wrong.
print '\n ******************************************************************'
@ -215,21 +201,21 @@ def apiData():
main()
try: #checks to make sure that everyting is configured correctly. Excluding apiEnabled, it is checked after
config.get('bitmessagesettings', 'apiport')
config.get('bitmessagesettings', 'apiinterface')
config.get('bitmessagesettings', 'apiusername')
config.get('bitmessagesettings', 'apipassword')
BMConfigParser().get('bitmessagesettings', 'apiport')
BMConfigParser().get('bitmessagesettings', 'apiinterface')
BMConfigParser().get('bitmessagesettings', 'apiusername')
BMConfigParser().get('bitmessagesettings', 'apipassword')
except:
apiInit("") #Initalize the keys.dat file with API information
#keys.dat file was found or appropriately configured, allow information retrieval
apiEnabled = apiInit(safeConfigGetBoolean('bitmessagesettings','apienabled')) #if false it will prompt the user, if true it will return true
apiEnabled = apiInit(BMConfigParser().safeGetBoolean('bitmessagesettings','apienabled')) #if false it will prompt the user, if true it will return true
config.read(keysPath)#read again since changes have been made
apiPort = int(config.get('bitmessagesettings', 'apiport'))
apiInterface = config.get('bitmessagesettings', 'apiinterface')
apiUsername = config.get('bitmessagesettings', 'apiusername')
apiPassword = config.get('bitmessagesettings', 'apipassword')
BMConfigParser().read(keysPath)#read again since changes have been made
apiPort = int(BMConfigParser().get('bitmessagesettings', 'apiport'))
apiInterface = BMConfigParser().get('bitmessagesettings', 'apiinterface')
apiUsername = BMConfigParser().get('bitmessagesettings', 'apiusername')
apiPassword = BMConfigParser().get('bitmessagesettings', 'apipassword')
print '\n API data successfully imported.\n'
@ -253,31 +239,30 @@ def apiTest(): #Tests the API connection to bitmessage. Returns true if it is co
def bmSettings(): #Allows the viewing and modification of keys.dat settings.
global keysPath
global usrPrompt
config = BMConfigParser()
keysPath = 'keys.dat'
config.read(keysPath)#Read the keys.dat
BMConfigParser().read(keysPath)#Read the keys.dat
try:
port = config.get('bitmessagesettings', 'port')
port = BMConfigParser().get('bitmessagesettings', 'port')
except:
print '\n File not found.\n'
usrPrompt = 0
main()
startonlogon = safeConfigGetBoolean('bitmessagesettings', 'startonlogon')
minimizetotray = safeConfigGetBoolean('bitmessagesettings', 'minimizetotray')
showtraynotifications = safeConfigGetBoolean('bitmessagesettings', 'showtraynotifications')
startintray = safeConfigGetBoolean('bitmessagesettings', 'startintray')
defaultnoncetrialsperbyte = config.get('bitmessagesettings', 'defaultnoncetrialsperbyte')
defaultpayloadlengthextrabytes = config.get('bitmessagesettings', 'defaultpayloadlengthextrabytes')
daemon = safeConfigGetBoolean('bitmessagesettings', 'daemon')
startonlogon = BMConfigParser().safeGetBoolean('bitmessagesettings', 'startonlogon')
minimizetotray = BMConfigParser().safeGetBoolean('bitmessagesettings', 'minimizetotray')
showtraynotifications = BMConfigParser().safeGetBoolean('bitmessagesettings', 'showtraynotifications')
startintray = BMConfigParser().safeGetBoolean('bitmessagesettings', 'startintray')
defaultnoncetrialsperbyte = BMConfigParser().get('bitmessagesettings', 'defaultnoncetrialsperbyte')
defaultpayloadlengthextrabytes = BMConfigParser().get('bitmessagesettings', 'defaultpayloadlengthextrabytes')
daemon = BMConfigParser().safeGetBoolean('bitmessagesettings', 'daemon')
socksproxytype = config.get('bitmessagesettings', 'socksproxytype')
sockshostname = config.get('bitmessagesettings', 'sockshostname')
socksport = config.get('bitmessagesettings', 'socksport')
socksauthentication = safeConfigGetBoolean('bitmessagesettings', 'socksauthentication')
socksusername = config.get('bitmessagesettings', 'socksusername')
sockspassword = config.get('bitmessagesettings', 'sockspassword')
socksproxytype = BMConfigParser().get('bitmessagesettings', 'socksproxytype')
sockshostname = BMConfigParser().get('bitmessagesettings', 'sockshostname')
socksport = BMConfigParser().get('bitmessagesettings', 'socksport')
socksauthentication = BMConfigParser().safeGetBoolean('bitmessagesettings', 'socksauthentication')
socksusername = BMConfigParser().get('bitmessagesettings', 'socksusername')
sockspassword = BMConfigParser().get('bitmessagesettings', 'sockspassword')
print '\n -----------------------------------'
@ -313,60 +298,60 @@ def bmSettings(): #Allows the viewing and modification of keys.dat settings.
if uInput == "port":
print ' Current port number: ' + port
uInput = userInput("Enter the new port number.")
config.set('bitmessagesettings', 'port', str(uInput))
BMConfigParser().set('bitmessagesettings', 'port', str(uInput))
elif uInput == "startonlogon":
print ' Current status: ' + str(startonlogon)
uInput = userInput("Enter the new status.")
config.set('bitmessagesettings', 'startonlogon', str(uInput))
BMConfigParser().set('bitmessagesettings', 'startonlogon', str(uInput))
elif uInput == "minimizetotray":
print ' Current status: ' + str(minimizetotray)
uInput = userInput("Enter the new status.")
config.set('bitmessagesettings', 'minimizetotray', str(uInput))
BMConfigParser().set('bitmessagesettings', 'minimizetotray', str(uInput))
elif uInput == "showtraynotifications":
print ' Current status: ' + str(showtraynotifications)
uInput = userInput("Enter the new status.")
config.set('bitmessagesettings', 'showtraynotifications', str(uInput))
BMConfigParser().set('bitmessagesettings', 'showtraynotifications', str(uInput))
elif uInput == "startintray":
print ' Current status: ' + str(startintray)
uInput = userInput("Enter the new status.")
config.set('bitmessagesettings', 'startintray', str(uInput))
BMConfigParser().set('bitmessagesettings', 'startintray', str(uInput))
elif uInput == "defaultnoncetrialsperbyte":
print ' Current default nonce trials per byte: ' + defaultnoncetrialsperbyte
uInput = userInput("Enter the new defaultnoncetrialsperbyte.")
config.set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(uInput))
BMConfigParser().set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(uInput))
elif uInput == "defaultpayloadlengthextrabytes":
print ' Current default payload length extra bytes: ' + defaultpayloadlengthextrabytes
uInput = userInput("Enter the new defaultpayloadlengthextrabytes.")
config.set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(uInput))
BMConfigParser().set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(uInput))
elif uInput == "daemon":
print ' Current status: ' + str(daemon)
uInput = userInput("Enter the new status.").lower()
config.set('bitmessagesettings', 'daemon', str(uInput))
BMConfigParser().set('bitmessagesettings', 'daemon', str(uInput))
elif uInput == "socksproxytype":
print ' Current socks proxy type: ' + socksproxytype
print "Possibilities: 'none', 'SOCKS4a', 'SOCKS5'."
uInput = userInput("Enter the new socksproxytype.")
config.set('bitmessagesettings', 'socksproxytype', str(uInput))
BMConfigParser().set('bitmessagesettings', 'socksproxytype', str(uInput))
elif uInput == "sockshostname":
print ' Current socks host name: ' + sockshostname
uInput = userInput("Enter the new sockshostname.")
config.set('bitmessagesettings', 'sockshostname', str(uInput))
BMConfigParser().set('bitmessagesettings', 'sockshostname', str(uInput))
elif uInput == "socksport":
print ' Current socks port number: ' + socksport
uInput = userInput("Enter the new socksport.")
config.set('bitmessagesettings', 'socksport', str(uInput))
BMConfigParser().set('bitmessagesettings', 'socksport', str(uInput))
elif uInput == "socksauthentication":
print ' Current status: ' + str(socksauthentication)
uInput = userInput("Enter the new status.")
config.set('bitmessagesettings', 'socksauthentication', str(uInput))
BMConfigParser().set('bitmessagesettings', 'socksauthentication', str(uInput))
elif uInput == "socksusername":
print ' Current socks username: ' + socksusername
uInput = userInput("Enter the new socksusername.")
config.set('bitmessagesettings', 'socksusername', str(uInput))
BMConfigParser().set('bitmessagesettings', 'socksusername', str(uInput))
elif uInput == "sockspassword":
print ' Current socks password: ' + sockspassword
uInput = userInput("Enter the new password.")
config.set('bitmessagesettings', 'sockspassword', str(uInput))
BMConfigParser().set('bitmessagesettings', 'sockspassword', str(uInput))
else:
print "\n Invalid input. Please try again.\n"
invalidInput = True
@ -377,7 +362,7 @@ def bmSettings(): #Allows the viewing and modification of keys.dat settings.
if uInput != "y":
print '\n Changes Made.\n'
with open(keysPath, 'wb') as configfile:
config.write(configfile)
BMConfigParser().write(configfile)
restartBmNotify()
break

View File

@ -22,7 +22,7 @@ from dialog import Dialog
from helper_sql import *
import shared
import ConfigParser
from configparser import BMConfigParser
from addresses import *
from pyelliptic.openssl import OpenSSL
import l10n
@ -482,19 +482,19 @@ def handlech(c, stdscr):
r, t = d.inputbox("New address label", init=label)
if r == d.DIALOG_OK:
label = t
shared.config.set(a, "label", label)
BMConfigParser().set(a, "label", label)
# Write config
shared.writeKeysFile()
addresses[addrcur][0] = label
elif t == "4": # Enable address
a = addresses[addrcur][2]
shared.config.set(a, "enabled", "true") # Set config
BMConfigParser().set(a, "enabled", "true") # Set config
# Write config
shared.writeKeysFile()
# Change color
if shared.safeConfigGetBoolean(a, 'chan'):
if BMConfigParser().safeGetBoolean(a, 'chan'):
addresses[addrcur][3] = 9 # orange
elif shared.safeConfigGetBoolean(a, 'mailinglist'):
elif BMConfigParser().safeGetBoolean(a, 'mailinglist'):
addresses[addrcur][3] = 5 # magenta
else:
addresses[addrcur][3] = 0 # black
@ -502,7 +502,7 @@ def handlech(c, stdscr):
shared.reloadMyAddressHashes() # Reload address hashes
elif t == "5": # Disable address
a = addresses[addrcur][2]
shared.config.set(a, "enabled", "false") # Set config
BMConfigParser().set(a, "enabled", "false") # Set config
addresses[addrcur][3] = 8 # Set color to gray
# Write config
shared.writeKeysFile()
@ -511,36 +511,36 @@ def handlech(c, stdscr):
elif t == "6": # Delete address
r, t = d.inputbox("Type in \"I want to delete this address\"", width=50)
if r == d.DIALOG_OK and t == "I want to delete this address":
shared.config.remove_section(addresses[addrcur][2])
BMConfigParser().remove_section(addresses[addrcur][2])
shared.writeKeysFile()
del addresses[addrcur]
elif t == "7": # Special address behavior
a = addresses[addrcur][2]
set_background_title(d, "Special address behavior")
if shared.safeConfigGetBoolean(a, "chan"):
if BMConfigParser().safeGetBoolean(a, "chan"):
scrollbox(d, unicode("This is a chan address. You cannot use it as a pseudo-mailing list."))
else:
m = shared.safeConfigGetBoolean(a, "mailinglist")
m = BMConfigParser().safeGetBoolean(a, "mailinglist")
r, t = d.radiolist("Select address behavior",
choices=[("1", "Behave as a normal address", not m),
("2", "Behave as a pseudo-mailing-list address", m)])
if r == d.DIALOG_OK:
if t == "1" and m == True:
shared.config.set(a, "mailinglist", "false")
BMConfigParser().set(a, "mailinglist", "false")
if addresses[addrcur][1]:
addresses[addrcur][3] = 0 # Set color to black
else:
addresses[addrcur][3] = 8 # Set color to gray
elif t == "2" and m == False:
try:
mn = shared.config.get(a, "mailinglistname")
mn = BMConfigParser().get(a, "mailinglistname")
except ConfigParser.NoOptionError:
mn = ""
r, t = d.inputbox("Mailing list name", init=mn)
if r == d.DIALOG_OK:
mn = t
shared.config.set(a, "mailinglist", "true")
shared.config.set(a, "mailinglistname", mn)
BMConfigParser().set(a, "mailinglist", "true")
BMConfigParser().set(a, "mailinglistname", mn)
addresses[addrcur][3] = 6 # Set color to magenta
# Write config
shared.writeKeysFile()
@ -793,7 +793,7 @@ def sendMessage(sender="", recv="", broadcast=None, subject="", body="", reply=F
0, # retryNumber
"sent",
2, # encodingType
shared.config.getint('bitmessagesettings', 'ttl'))
BMConfigParser().getint('bitmessagesettings', 'ttl'))
shared.workerQueue.put(("sendmessage", addr))
else: # Broadcast
if recv == "":
@ -819,7 +819,7 @@ def sendMessage(sender="", recv="", broadcast=None, subject="", body="", reply=F
0, # retryNumber
"sent", # folder
2, # encodingType
shared.config.getint('bitmessagesettings', 'ttl'))
BMConfigParser().getint('bitmessagesettings', 'ttl'))
shared.workerQueue.put(('sendbroadcast', ''))
def loadInbox():
@ -843,7 +843,7 @@ def loadInbox():
if toaddr == BROADCAST_STR:
tolabel = BROADCAST_STR
else:
tolabel = shared.config.get(toaddr, "label")
tolabel = BMConfigParser().get(toaddr, "label")
except:
tolabel = ""
if tolabel == "":
@ -852,8 +852,8 @@ def loadInbox():
# Set label for from address
fromlabel = ""
if shared.config.has_section(fromaddr):
fromlabel = shared.config.get(fromaddr, "label")
if BMConfigParser().has_section(fromaddr):
fromlabel = BMConfigParser().get(fromaddr, "label")
if fromlabel == "": # Check Address Book
qr = sqlQuery("SELECT label FROM addressbook WHERE address=?", fromaddr)
if qr != []:
@ -900,15 +900,15 @@ def loadSent():
for r in qr:
tolabel, = r
if tolabel == "":
if shared.config.has_section(toaddr):
tolabel = shared.config.get(toaddr, "label")
if BMConfigParser().has_section(toaddr):
tolabel = BMConfigParser().get(toaddr, "label")
if tolabel == "":
tolabel = toaddr
# Set label for from address
fromlabel = ""
if shared.config.has_section(fromaddr):
fromlabel = shared.config.get(fromaddr, "label")
if BMConfigParser().has_section(fromaddr):
fromlabel = BMConfigParser().get(fromaddr, "label")
if fromlabel == "":
fromlabel = fromaddr
@ -969,7 +969,7 @@ def loadSubscriptions():
subscriptions.reverse()
def loadBlackWhiteList():
global bwtype
bwtype = shared.config.get("bitmessagesettings", "blackwhitelist")
bwtype = BMConfigParser().get("bitmessagesettings", "blackwhitelist")
if bwtype == "black":
ret = sqlQuery("SELECT label, address, enabled FROM blacklist")
else:
@ -1025,17 +1025,17 @@ def run(stdscr):
curses.init_pair(9, curses.COLOR_YELLOW, curses.COLOR_BLACK) # orangish
# Init list of address in 'Your Identities' tab
configSections = shared.config.sections()
configSections = BMConfigParser().sections()
for addressInKeysFile in configSections:
if addressInKeysFile != "bitmessagesettings":
isEnabled = shared.config.getboolean(addressInKeysFile, "enabled")
addresses.append([shared.config.get(addressInKeysFile, "label"), isEnabled, addressInKeysFile])
isEnabled = BMConfigParser().getboolean(addressInKeysFile, "enabled")
addresses.append([BMConfigParser().get(addressInKeysFile, "label"), isEnabled, addressInKeysFile])
# Set address color
if not isEnabled:
addresses[len(addresses)-1].append(8) # gray
elif shared.safeConfigGetBoolean(addressInKeysFile, 'chan'):
elif BMConfigParser().safeGetBoolean(addressInKeysFile, 'chan'):
addresses[len(addresses)-1].append(9) # orange
elif shared.safeConfigGetBoolean(addressInKeysFile, 'mailinglist'):
elif BMConfigParser().safeGetBoolean(addressInKeysFile, 'mailinglist'):
addresses[len(addresses)-1].append(5) # magenta
else:
addresses[len(addresses)-1].append(0) # black

View File

@ -40,6 +40,7 @@ from class_singleWorker import singleWorker
from class_addressGenerator import addressGenerator
from class_smtpDeliver import smtpDeliver
from class_smtpServer import smtpServer
from configparser import BMConfigParser
from debug import logger
# Helper Functions
@ -58,7 +59,7 @@ def connectToStream(streamNumber):
maximumNumberOfHalfOpenConnections = 64
try:
# don't overload Tor
if shared.config.get('bitmessagesettings', 'socksproxytype') != 'none':
if BMConfigParser().get('bitmessagesettings', 'socksproxytype') != 'none':
maximumNumberOfHalfOpenConnections = 4
except:
pass
@ -128,7 +129,7 @@ class singleAPI(threading.Thread, StoppableThread):
super(singleAPI, self).stopThread()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((shared.config.get('bitmessagesettings', 'apiinterface'), shared.config.getint(
s.connect((BMConfigParser().get('bitmessagesettings', 'apiinterface'), BMConfigParser().getint(
'bitmessagesettings', 'apiport')))
s.shutdown(socket.SHUT_RDWR)
s.close()
@ -136,7 +137,7 @@ class singleAPI(threading.Thread, StoppableThread):
pass
def run(self):
se = StoppableXMLRPCServer((shared.config.get('bitmessagesettings', 'apiinterface'), shared.config.getint(
se = StoppableXMLRPCServer((BMConfigParser().get('bitmessagesettings', 'apiinterface'), BMConfigParser().getint(
'bitmessagesettings', 'apiport')), MySimpleXMLRPCRequestHandler, True, True)
se.register_introspection_functions()
se.serve_forever()
@ -188,12 +189,12 @@ class Main:
sqlLookup.start()
# SMTP delivery thread
if daemon and shared.safeConfigGet("bitmessagesettings", "smtpdeliver", '') != '':
if daemon and BMConfigParser().safeGet("bitmessagesettings", "smtpdeliver", '') != '':
smtpDeliveryThread = smtpDeliver()
smtpDeliveryThread.start()
# SMTP daemon thread
if daemon and shared.safeConfigGetBoolean("bitmessagesettings", "smtpd"):
if daemon and BMConfigParser().safeGetBoolean("bitmessagesettings", "smtpd"):
smtpServerThread = smtpServer()
smtpServerThread.start()
@ -210,9 +211,9 @@ class Main:
shared.reloadMyAddressHashes()
shared.reloadBroadcastSendersForWhichImWatching()
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
if BMConfigParser().safeGetBoolean('bitmessagesettings', 'apienabled'):
try:
apiNotifyPath = shared.config.get(
apiNotifyPath = BMConfigParser().get(
'bitmessagesettings', 'apinotifypath')
except:
apiNotifyPath = ''
@ -232,12 +233,12 @@ class Main:
singleListenerThread.daemon = True # close the main program even if there are threads left
singleListenerThread.start()
if shared.safeConfigGetBoolean('bitmessagesettings','upnp'):
if BMConfigParser().safeGetBoolean('bitmessagesettings','upnp'):
import upnp
upnpThread = upnp.uPnPThread()
upnpThread.start()
if daemon == False and shared.safeConfigGetBoolean('bitmessagesettings', 'daemon') == False:
if daemon == False and BMConfigParser().safeGetBoolean('bitmessagesettings', 'daemon') == False:
if shared.curses == False:
if not depends.check_pyqt():
print('PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API. You can download PyQt from http://www.riverbankcomputing.com/software/pyqt/download or by searching Google for \'PyQt Download\'. If you want to run in daemon mode, see https://bitmessage.org/wiki/Daemon')
@ -253,7 +254,7 @@ class Main:
import bitmessagecurses
bitmessagecurses.runwrapper()
else:
shared.config.remove_option('bitmessagesettings', 'dontconnect')
BMConfigParser().remove_option('bitmessagesettings', 'dontconnect')
while True:
time.sleep(20)
@ -290,15 +291,15 @@ class Main:
#TODO: nice function but no one is using this
def getApiAddress(self):
if not shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'apienabled'):
return None
address = shared.config.get('bitmessagesettings', 'apiinterface')
port = shared.config.getint('bitmessagesettings', 'apiport')
address = BMConfigParser().get('bitmessagesettings', 'apiinterface')
port = BMConfigParser().getint('bitmessagesettings', 'apiport')
return {'address':address,'port':port}
if __name__ == "__main__":
mainprogram = Main()
mainprogram.start(shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'))
mainprogram.start(BMConfigParser().safeGetBoolean('bitmessagesettings', 'daemon'))
# So far, the creation of and management of the Bitmessage protocol and this

View File

@ -29,6 +29,7 @@ except AttributeError:
from addresses import *
import shared
from bitmessageui import *
from configparser import BMConfigParser
from namecoin import namecoinConnection, ensureNamecoinOptions
from newaddressdialog import *
from newaddresswizard import *
@ -77,6 +78,7 @@ from class_singleWorker import singleWorker
from helper_generic import powQueueSize, invQueueSize
from proofofwork import getPowType
from statusbar import BMStatusBar
from version import softwareVersion
def _translate(context, text, disambiguation = None, encoding = None, number = None):
if number is None:
@ -490,11 +492,11 @@ class MyForm(settingsmixin.SMainWindow):
enabled = {}
for toAddress in getSortedAccounts():
isEnabled = shared.config.getboolean(
isEnabled = BMConfigParser().getboolean(
toAddress, 'enabled')
isChan = shared.safeConfigGetBoolean(
isChan = BMConfigParser().safeGetBoolean(
toAddress, 'chan')
isMaillinglist = shared.safeConfigGetBoolean(
isMaillinglist = BMConfigParser().safeGetBoolean(
toAddress, 'mailinglist')
if treeWidget == self.ui.treeWidgetYourIdentities:
@ -603,7 +605,7 @@ class MyForm(settingsmixin.SMainWindow):
reply = QtGui.QMessageBox.question(
self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
shared.config.remove_section(addressInKeysFile)
BMConfigParser().remove_section(addressInKeysFile)
shared.writeKeysFile()
# Configure Bitmessage to start on startup (or remove the
@ -614,7 +616,7 @@ class MyForm(settingsmixin.SMainWindow):
self.settings = QSettings(RUN_PATH, QSettings.NativeFormat)
self.settings.remove(
"PyBitmessage") # In case the user moves the program and the registry entry is no longer valid, this will delete the old registry entry.
if shared.config.getboolean('bitmessagesettings', 'startonlogon'):
if BMConfigParser().getboolean('bitmessagesettings', 'startonlogon'):
self.settings.setValue("PyBitmessage", sys.argv[0])
elif 'darwin' in sys.platform:
# startup for mac
@ -783,7 +785,7 @@ class MyForm(settingsmixin.SMainWindow):
self.rerenderComboBoxSendFromBroadcast()
# Put the TTL slider in the correct spot
TTL = shared.config.getint('bitmessagesettings', 'ttl')
TTL = BMConfigParser().getint('bitmessagesettings', 'ttl')
if TTL < 3600: # an hour
TTL = 3600
elif TTL > 28*24*60*60: # 28 days
@ -799,11 +801,11 @@ class MyForm(settingsmixin.SMainWindow):
# Check to see whether we can connect to namecoin. Hide the 'Fetch Namecoin ID' button if we can't.
try:
options = {}
options["type"] = shared.config.get('bitmessagesettings', 'namecoinrpctype')
options["host"] = shared.config.get('bitmessagesettings', 'namecoinrpchost')
options["port"] = shared.config.get('bitmessagesettings', 'namecoinrpcport')
options["user"] = shared.config.get('bitmessagesettings', 'namecoinrpcuser')
options["password"] = shared.config.get('bitmessagesettings', 'namecoinrpcpassword')
options["type"] = BMConfigParser().get('bitmessagesettings', 'namecoinrpctype')
options["host"] = BMConfigParser().get('bitmessagesettings', 'namecoinrpchost')
options["port"] = BMConfigParser().get('bitmessagesettings', 'namecoinrpcport')
options["user"] = BMConfigParser().get('bitmessagesettings', 'namecoinrpcuser')
options["password"] = BMConfigParser().get('bitmessagesettings', 'namecoinrpcpassword')
nc = namecoinConnection(options)
if nc.test()[0] == 'failed':
self.ui.pushButtonFetchNamecoinID.hide()
@ -814,7 +816,7 @@ class MyForm(settingsmixin.SMainWindow):
def updateTTL(self, sliderPosition):
TTL = int(sliderPosition ** 3.199 + 3600)
self.updateHumanFriendlyTTLDescription(TTL)
shared.config.set('bitmessagesettings', 'ttl', str(TTL))
BMConfigParser().set('bitmessagesettings', 'ttl', str(TTL))
shared.writeKeysFile()
def updateHumanFriendlyTTLDescription(self, TTL):
@ -1161,7 +1163,7 @@ class MyForm(settingsmixin.SMainWindow):
# show bitmessage
self.actionShow = QtGui.QAction(_translate(
"MainWindow", "Show Bitmessage"), m, checkable=True)
self.actionShow.setChecked(not shared.config.getboolean(
self.actionShow.setChecked(not BMConfigParser().getboolean(
'bitmessagesettings', 'startintray'))
self.actionShow.triggered.connect(self.appIndicatorShowOrHideWindow)
if not sys.platform[0:3] == 'win':
@ -1250,7 +1252,7 @@ class MyForm(settingsmixin.SMainWindow):
if toAddress == str_broadcast_subscribers:
toLabel = str_broadcast_subscribers
else:
toLabel = shared.config.get(toAddress, 'label')
toLabel = BMConfigParser().get(toAddress, 'label')
except:
toLabel = ''
if toLabel == '':
@ -1595,7 +1597,7 @@ class MyForm(settingsmixin.SMainWindow):
self.connectDialogInstance = connectDialog(self)
if self.connectDialogInstance.exec_():
if self.connectDialogInstance.ui.radioButtonConnectNow.isChecked():
shared.config.remove_option('bitmessagesettings', 'dontconnect')
BMConfigParser().remove_option('bitmessagesettings', 'dontconnect')
shared.writeKeysFile()
else:
self.click_actionSettings()
@ -1619,7 +1621,7 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.blackwhitelist.init_blacklist_popup_menu(False)
if event.type() == QtCore.QEvent.WindowStateChange:
if self.windowState() & QtCore.Qt.WindowMinimized:
if shared.config.getboolean('bitmessagesettings', 'minimizetotray') and not 'darwin' in sys.platform:
if BMConfigParser().getboolean('bitmessagesettings', 'minimizetotray') and not 'darwin' in sys.platform:
QTimer.singleShot(0, self.appIndicatorHide)
elif event.oldState() & QtCore.Qt.WindowMinimized:
# The window state has just been changed to
@ -1644,7 +1646,7 @@ class MyForm(settingsmixin.SMainWindow):
QIcon(":/newPrefix/images/redicon.png"))
shared.statusIconColor = 'red'
# if the connection is lost then show a notification
if self.connected and not shared.config.getboolean('bitmessagesettings', 'hidetrayconnectionnotifications'):
if self.connected and not BMConfigParser().getboolean('bitmessagesettings', 'hidetrayconnectionnotifications'):
self.notifierShow('Bitmessage', unicode(_translate(
"MainWindow", "Connection lost").toUtf8(),'utf-8'),
self.SOUND_DISCONNECTED, None)
@ -1661,7 +1663,7 @@ class MyForm(settingsmixin.SMainWindow):
":/newPrefix/images/yellowicon.png"))
shared.statusIconColor = 'yellow'
# if a new connection has been established then show a notification
if not self.connected and not shared.config.getboolean('bitmessagesettings', 'hidetrayconnectionnotifications'):
if not self.connected and not BMConfigParser().getboolean('bitmessagesettings', 'hidetrayconnectionnotifications'):
self.notifierShow('Bitmessage', unicode(_translate(
"MainWindow", "Connected").toUtf8(),'utf-8'),
self.SOUND_CONNECTED, None)
@ -1677,7 +1679,7 @@ class MyForm(settingsmixin.SMainWindow):
self.pushButtonStatusIcon.setIcon(
QIcon(":/newPrefix/images/greenicon.png"))
shared.statusIconColor = 'green'
if not self.connected and not shared.config.getboolean('bitmessagesettings', 'hidetrayconnectionnotifications'):
if not self.connected and not BMConfigParser().getboolean('bitmessagesettings', 'hidetrayconnectionnotifications'):
self.notifierShow('Bitmessage', unicode(_translate(
"MainWindow", "Connected").toUtf8(),'utf-8'),
self.SOUND_CONNECTION_GREEN, None)
@ -1856,7 +1858,7 @@ class MyForm(settingsmixin.SMainWindow):
addresses = getSortedAccounts()
for address in addresses:
account = accountClass(address)
if (account.type == AccountMixin.CHAN and shared.safeConfigGetBoolean(address, 'enabled')):
if (account.type == AccountMixin.CHAN and BMConfigParser().safeGetBoolean(address, 'enabled')):
newRows[address] = [account.getLabel(), AccountMixin.CHAN]
# normal accounts
queryreturn = sqlQuery('SELECT * FROM addressbook')
@ -1952,8 +1954,8 @@ class MyForm(settingsmixin.SMainWindow):
email = ''.join(random.SystemRandom().choice(string.ascii_lowercase) for _ in range(12)) + "@mailchuck.com"
acct = MailchuckAccount(fromAddress)
acct.register(email)
shared.config.set(fromAddress, 'label', email)
shared.config.set(fromAddress, 'gateway', 'mailchuck')
BMConfigParser().set(fromAddress, 'label', email)
BMConfigParser().set(fromAddress, 'gateway', 'mailchuck')
shared.writeKeysFile()
self.statusBar().showMessage(_translate(
"MainWindow", "Error: Your account wasn't registered at an email gateway. Sending registration now as %1, please wait for the registration to be processed before retrying sending.").arg(email), 10000)
@ -2027,7 +2029,7 @@ class MyForm(settingsmixin.SMainWindow):
0, # retryNumber
'sent', # folder
encoding, # encodingtype
shared.config.getint('bitmessagesettings', 'ttl')
BMConfigParser().getint('bitmessagesettings', 'ttl')
)
toLabel = ''
@ -2080,7 +2082,7 @@ class MyForm(settingsmixin.SMainWindow):
0, # retryNumber
'sent', # folder
encoding, # encoding type
shared.config.getint('bitmessagesettings', 'ttl')
BMConfigParser().getint('bitmessagesettings', 'ttl')
)
sqlExecute(
'''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', *t)
@ -2125,7 +2127,7 @@ class MyForm(settingsmixin.SMainWindow):
def setBroadcastEnablementDependingOnWhetherThisIsAMailingListAddress(self, address):
# If this is a chan then don't let people broadcast because no one
# should subscribe to chan addresses.
if shared.safeConfigGetBoolean(str(address), 'mailinglist'):
if BMConfigParser().safeGetBoolean(str(address), 'mailinglist'):
self.ui.tabWidgetSend.setCurrentIndex(1)
else:
self.ui.tabWidgetSend.setCurrentIndex(0)
@ -2133,11 +2135,11 @@ class MyForm(settingsmixin.SMainWindow):
def rerenderComboBoxSendFrom(self):
self.ui.comboBoxSendFrom.clear()
for addressInKeysFile in getSortedAccounts():
isEnabled = shared.config.getboolean(
isEnabled = BMConfigParser().getboolean(
addressInKeysFile, 'enabled') # I realize that this is poor programming practice but I don't care. It's easier for others to read.
isMaillinglist = shared.safeConfigGetBoolean(addressInKeysFile, 'mailinglist')
isMaillinglist = BMConfigParser().safeGetBoolean(addressInKeysFile, 'mailinglist')
if isEnabled and not isMaillinglist:
label = unicode(shared.config.get(addressInKeysFile, 'label'), 'utf-8', 'ignore').strip()
label = unicode(BMConfigParser().get(addressInKeysFile, 'label'), 'utf-8', 'ignore').strip()
if label == "":
label = addressInKeysFile
self.ui.comboBoxSendFrom.addItem(avatarize(addressInKeysFile), label, addressInKeysFile)
@ -2154,11 +2156,11 @@ class MyForm(settingsmixin.SMainWindow):
def rerenderComboBoxSendFromBroadcast(self):
self.ui.comboBoxSendFromBroadcast.clear()
for addressInKeysFile in getSortedAccounts():
isEnabled = shared.config.getboolean(
isEnabled = BMConfigParser().getboolean(
addressInKeysFile, 'enabled') # I realize that this is poor programming practice but I don't care. It's easier for others to read.
isChan = shared.safeConfigGetBoolean(addressInKeysFile, 'chan')
isChan = BMConfigParser().safeGetBoolean(addressInKeysFile, 'chan')
if isEnabled and not isChan:
label = unicode(shared.config.get(addressInKeysFile, 'label'), 'utf-8', 'ignore').strip()
label = unicode(BMConfigParser().get(addressInKeysFile, 'label'), 'utf-8', 'ignore').strip()
if label == "":
label = addressInKeysFile
self.ui.comboBoxSendFromBroadcast.addItem(avatarize(addressInKeysFile), label, addressInKeysFile)
@ -2221,7 +2223,7 @@ class MyForm(settingsmixin.SMainWindow):
else:
acct = ret
self.propagateUnreadCount(acct.address)
if shared.config.getboolean('bitmessagesettings', 'showtraynotifications'):
if BMConfigParser().getboolean('bitmessagesettings', 'showtraynotifications'):
self.notifierShow(unicode(_translate("MainWindow",'New Message').toUtf8(),'utf-8'), unicode(_translate("MainWindow",'From ').toUtf8(),'utf-8') + unicode(acct.fromLabel, 'utf-8'), self.SOUND_UNKNOWN, None)
if self.getCurrentAccount() is not None and ((self.getCurrentFolder(treeWidget) != "inbox" and self.getCurrentFolder(treeWidget) is not None) or self.getCurrentAccount(treeWidget) != acct.address):
# Ubuntu should notify of new message irespective of whether it's in current message list or not
@ -2235,8 +2237,8 @@ class MyForm(settingsmixin.SMainWindow):
email = str(self.dialog.ui.lineEditEmail.text().toUtf8())
# register resets address variables
acct.register(email)
shared.config.set(acct.fromAddress, 'label', email)
shared.config.set(acct.fromAddress, 'gateway', 'mailchuck')
BMConfigParser().set(acct.fromAddress, 'label', email)
BMConfigParser().set(acct.fromAddress, 'gateway', 'mailchuck')
shared.writeKeysFile()
self.statusBar().showMessage(_translate(
"MainWindow", "Sending email gateway registration request"), 10000)
@ -2323,113 +2325,113 @@ class MyForm(settingsmixin.SMainWindow):
def click_actionSettings(self):
self.settingsDialogInstance = settingsDialog(self)
if self.settingsDialogInstance.exec_():
shared.config.set('bitmessagesettings', 'startonlogon', str(
BMConfigParser().set('bitmessagesettings', 'startonlogon', str(
self.settingsDialogInstance.ui.checkBoxStartOnLogon.isChecked()))
shared.config.set('bitmessagesettings', 'minimizetotray', str(
BMConfigParser().set('bitmessagesettings', 'minimizetotray', str(
self.settingsDialogInstance.ui.checkBoxMinimizeToTray.isChecked()))
shared.config.set('bitmessagesettings', 'trayonclose', str(
BMConfigParser().set('bitmessagesettings', 'trayonclose', str(
self.settingsDialogInstance.ui.checkBoxTrayOnClose.isChecked()))
shared.config.set('bitmessagesettings', 'hidetrayconnectionnotifications', str(
BMConfigParser().set('bitmessagesettings', 'hidetrayconnectionnotifications', str(
self.settingsDialogInstance.ui.checkBoxHideTrayConnectionNotifications.isChecked()))
shared.config.set('bitmessagesettings', 'showtraynotifications', str(
BMConfigParser().set('bitmessagesettings', 'showtraynotifications', str(
self.settingsDialogInstance.ui.checkBoxShowTrayNotifications.isChecked()))
shared.config.set('bitmessagesettings', 'startintray', str(
BMConfigParser().set('bitmessagesettings', 'startintray', str(
self.settingsDialogInstance.ui.checkBoxStartInTray.isChecked()))
shared.config.set('bitmessagesettings', 'willinglysendtomobile', str(
BMConfigParser().set('bitmessagesettings', 'willinglysendtomobile', str(
self.settingsDialogInstance.ui.checkBoxWillinglySendToMobile.isChecked()))
shared.config.set('bitmessagesettings', 'useidenticons', str(
BMConfigParser().set('bitmessagesettings', 'useidenticons', str(
self.settingsDialogInstance.ui.checkBoxUseIdenticons.isChecked()))
shared.config.set('bitmessagesettings', 'replybelow', str(
BMConfigParser().set('bitmessagesettings', 'replybelow', str(
self.settingsDialogInstance.ui.checkBoxReplyBelow.isChecked()))
lang = str(self.settingsDialogInstance.ui.languageComboBox.itemData(self.settingsDialogInstance.ui.languageComboBox.currentIndex()).toString())
shared.config.set('bitmessagesettings', 'userlocale', lang)
BMConfigParser().set('bitmessagesettings', 'userlocale', lang)
change_translation(l10n.getTranslationLanguage())
if int(shared.config.get('bitmessagesettings', 'port')) != int(self.settingsDialogInstance.ui.lineEditTCPPort.text()):
if not shared.safeConfigGetBoolean('bitmessagesettings', 'dontconnect'):
if int(BMConfigParser().get('bitmessagesettings', 'port')) != int(self.settingsDialogInstance.ui.lineEditTCPPort.text()):
if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'dontconnect'):
QMessageBox.about(self, _translate("MainWindow", "Restart"), _translate(
"MainWindow", "You must restart Bitmessage for the port number change to take effect."))
shared.config.set('bitmessagesettings', 'port', str(
BMConfigParser().set('bitmessagesettings', 'port', str(
self.settingsDialogInstance.ui.lineEditTCPPort.text()))
if self.settingsDialogInstance.ui.checkBoxUPnP.isChecked() != shared.safeConfigGetBoolean('bitmessagesettings', 'upnp'):
shared.config.set('bitmessagesettings', 'upnp', str(self.settingsDialogInstance.ui.checkBoxUPnP.isChecked()))
if self.settingsDialogInstance.ui.checkBoxUPnP.isChecked() != BMConfigParser().safeGetBoolean('bitmessagesettings', 'upnp'):
BMConfigParser().set('bitmessagesettings', 'upnp', str(self.settingsDialogInstance.ui.checkBoxUPnP.isChecked()))
if self.settingsDialogInstance.ui.checkBoxUPnP.isChecked():
import upnp
upnpThread = upnp.uPnPThread()
upnpThread.start()
#print 'self.settingsDialogInstance.ui.comboBoxProxyType.currentText()', self.settingsDialogInstance.ui.comboBoxProxyType.currentText()
#print 'self.settingsDialogInstance.ui.comboBoxProxyType.currentText())[0:5]', self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5]
if shared.config.get('bitmessagesettings', 'socksproxytype') == 'none' and self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] == 'SOCKS':
if BMConfigParser().get('bitmessagesettings', 'socksproxytype') == 'none' and self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] == 'SOCKS':
if shared.statusIconColor != 'red':
QMessageBox.about(self, _translate("MainWindow", "Restart"), _translate(
"MainWindow", "Bitmessage will use your proxy from now on but you may want to manually restart Bitmessage now to close existing connections (if any)."))
if shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] != 'SOCKS':
if BMConfigParser().get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] != 'SOCKS':
self.statusBar().clearMessage()
if self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] == 'SOCKS':
shared.config.set('bitmessagesettings', 'socksproxytype', str(
BMConfigParser().set('bitmessagesettings', 'socksproxytype', str(
self.settingsDialogInstance.ui.comboBoxProxyType.currentText()))
else:
shared.config.set('bitmessagesettings', 'socksproxytype', 'none')
shared.config.set('bitmessagesettings', 'socksauthentication', str(
BMConfigParser().set('bitmessagesettings', 'socksproxytype', 'none')
BMConfigParser().set('bitmessagesettings', 'socksauthentication', str(
self.settingsDialogInstance.ui.checkBoxAuthentication.isChecked()))
shared.config.set('bitmessagesettings', 'sockshostname', str(
BMConfigParser().set('bitmessagesettings', 'sockshostname', str(
self.settingsDialogInstance.ui.lineEditSocksHostname.text()))
shared.config.set('bitmessagesettings', 'socksport', str(
BMConfigParser().set('bitmessagesettings', 'socksport', str(
self.settingsDialogInstance.ui.lineEditSocksPort.text()))
shared.config.set('bitmessagesettings', 'socksusername', str(
BMConfigParser().set('bitmessagesettings', 'socksusername', str(
self.settingsDialogInstance.ui.lineEditSocksUsername.text()))
shared.config.set('bitmessagesettings', 'sockspassword', str(
BMConfigParser().set('bitmessagesettings', 'sockspassword', str(
self.settingsDialogInstance.ui.lineEditSocksPassword.text()))
shared.config.set('bitmessagesettings', 'sockslisten', str(
BMConfigParser().set('bitmessagesettings', 'sockslisten', str(
self.settingsDialogInstance.ui.checkBoxSocksListen.isChecked()))
try:
# Rounding to integers just for aesthetics
shared.config.set('bitmessagesettings', 'maxdownloadrate', str(
BMConfigParser().set('bitmessagesettings', 'maxdownloadrate', str(
int(float(self.settingsDialogInstance.ui.lineEditMaxDownloadRate.text()))))
shared.config.set('bitmessagesettings', 'maxuploadrate', str(
BMConfigParser().set('bitmessagesettings', 'maxuploadrate', str(
int(float(self.settingsDialogInstance.ui.lineEditMaxUploadRate.text()))))
except:
QMessageBox.about(self, _translate("MainWindow", "Number needed"), _translate(
"MainWindow", "Your maximum download and upload rate must be numbers. Ignoring what you typed."))
shared.config.set('bitmessagesettings', 'namecoinrpctype',
BMConfigParser().set('bitmessagesettings', 'namecoinrpctype',
self.settingsDialogInstance.getNamecoinType())
shared.config.set('bitmessagesettings', 'namecoinrpchost', str(
BMConfigParser().set('bitmessagesettings', 'namecoinrpchost', str(
self.settingsDialogInstance.ui.lineEditNamecoinHost.text()))
shared.config.set('bitmessagesettings', 'namecoinrpcport', str(
BMConfigParser().set('bitmessagesettings', 'namecoinrpcport', str(
self.settingsDialogInstance.ui.lineEditNamecoinPort.text()))
shared.config.set('bitmessagesettings', 'namecoinrpcuser', str(
BMConfigParser().set('bitmessagesettings', 'namecoinrpcuser', str(
self.settingsDialogInstance.ui.lineEditNamecoinUser.text()))
shared.config.set('bitmessagesettings', 'namecoinrpcpassword', str(
BMConfigParser().set('bitmessagesettings', 'namecoinrpcpassword', str(
self.settingsDialogInstance.ui.lineEditNamecoinPassword.text()))
# Demanded difficulty tab
if float(self.settingsDialogInstance.ui.lineEditTotalDifficulty.text()) >= 1:
shared.config.set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(int(float(
BMConfigParser().set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(int(float(
self.settingsDialogInstance.ui.lineEditTotalDifficulty.text()) * shared.networkDefaultProofOfWorkNonceTrialsPerByte)))
if float(self.settingsDialogInstance.ui.lineEditSmallMessageDifficulty.text()) >= 1:
shared.config.set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(int(float(
BMConfigParser().set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(int(float(
self.settingsDialogInstance.ui.lineEditSmallMessageDifficulty.text()) * shared.networkDefaultPayloadLengthExtraBytes)))
if self.settingsDialogInstance.ui.comboBoxOpenCL.currentText().toUtf8() != shared.safeConfigGet("bitmessagesettings", "opencl"):
shared.config.set('bitmessagesettings', 'opencl', str(self.settingsDialogInstance.ui.comboBoxOpenCL.currentText()))
if self.settingsDialogInstance.ui.comboBoxOpenCL.currentText().toUtf8() != BMConfigParser().safeGet("bitmessagesettings", "opencl"):
BMConfigParser().set('bitmessagesettings', 'opencl', str(self.settingsDialogInstance.ui.comboBoxOpenCL.currentText()))
acceptableDifficultyChanged = False
if float(self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) >= 1 or float(self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) == 0:
if shared.config.get('bitmessagesettings','maxacceptablenoncetrialsperbyte') != str(int(float(
if BMConfigParser().get('bitmessagesettings','maxacceptablenoncetrialsperbyte') != str(int(float(
self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) * shared.networkDefaultProofOfWorkNonceTrialsPerByte)):
# the user changed the max acceptable total difficulty
acceptableDifficultyChanged = True
shared.config.set('bitmessagesettings', 'maxacceptablenoncetrialsperbyte', str(int(float(
BMConfigParser().set('bitmessagesettings', 'maxacceptablenoncetrialsperbyte', str(int(float(
self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) * shared.networkDefaultProofOfWorkNonceTrialsPerByte)))
if float(self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) >= 1 or float(self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) == 0:
if shared.config.get('bitmessagesettings','maxacceptablepayloadlengthextrabytes') != str(int(float(
if BMConfigParser().get('bitmessagesettings','maxacceptablepayloadlengthextrabytes') != str(int(float(
self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) * shared.networkDefaultPayloadLengthExtraBytes)):
# the user changed the max acceptable small message difficulty
acceptableDifficultyChanged = True
shared.config.set('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', str(int(float(
BMConfigParser().set('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', str(int(float(
self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) * shared.networkDefaultPayloadLengthExtraBytes)))
if acceptableDifficultyChanged:
# It might now be possible to send msgs which were previously marked as toodifficult.
@ -2442,8 +2444,8 @@ class MyForm(settingsmixin.SMainWindow):
#start:UI setting to stop trying to send messages after X days/months
# I'm open to changing this UI to something else if someone has a better idea.
if ((self.settingsDialogInstance.ui.lineEditDays.text()=='') and (self.settingsDialogInstance.ui.lineEditMonths.text()=='')):#We need to handle this special case. Bitmessage has its default behavior. The input is blank/blank
shared.config.set('bitmessagesettings', 'stopresendingafterxdays', '')
shared.config.set('bitmessagesettings', 'stopresendingafterxmonths', '')
BMConfigParser().set('bitmessagesettings', 'stopresendingafterxdays', '')
BMConfigParser().set('bitmessagesettings', 'stopresendingafterxmonths', '')
shared.maximumLengthOfTimeToBotherResendingMessages = float('inf')
try:
float(self.settingsDialogInstance.ui.lineEditDays.text())
@ -2465,13 +2467,13 @@ class MyForm(settingsmixin.SMainWindow):
if shared.maximumLengthOfTimeToBotherResendingMessages < 432000: # If the time period is less than 5 hours, we give zero values to all fields. No message will be sent again.
QMessageBox.about(self, _translate("MainWindow", "Will not resend ever"), _translate(
"MainWindow", "Note that the time limit you entered is less than the amount of time Bitmessage waits for the first resend attempt therefore your messages will never be resent."))
shared.config.set('bitmessagesettings', 'stopresendingafterxdays', '0')
shared.config.set('bitmessagesettings', 'stopresendingafterxmonths', '0')
BMConfigParser().set('bitmessagesettings', 'stopresendingafterxdays', '0')
BMConfigParser().set('bitmessagesettings', 'stopresendingafterxmonths', '0')
shared.maximumLengthOfTimeToBotherResendingMessages = 0
else:
shared.config.set('bitmessagesettings', 'stopresendingafterxdays', str(float(
BMConfigParser().set('bitmessagesettings', 'stopresendingafterxdays', str(float(
self.settingsDialogInstance.ui.lineEditDays.text())))
shared.config.set('bitmessagesettings', 'stopresendingafterxmonths', str(float(
BMConfigParser().set('bitmessagesettings', 'stopresendingafterxmonths', str(float(
self.settingsDialogInstance.ui.lineEditMonths.text())))
shared.writeKeysFile()
@ -2480,7 +2482,7 @@ class MyForm(settingsmixin.SMainWindow):
# Auto-startup for Windows
RUN_PATH = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"
self.settings = QSettings(RUN_PATH, QSettings.NativeFormat)
if shared.config.getboolean('bitmessagesettings', 'startonlogon'):
if BMConfigParser().getboolean('bitmessagesettings', 'startonlogon'):
self.settings.setValue("PyBitmessage", sys.argv[0])
else:
self.settings.remove("PyBitmessage")
@ -2495,7 +2497,7 @@ class MyForm(settingsmixin.SMainWindow):
# Write the keys.dat file to disk in the new location
sqlStoredProcedure('movemessagstoprog')
with open(shared.lookupExeFolder() + 'keys.dat', 'wb') as configfile:
shared.config.write(configfile)
BMConfigParser().write(configfile)
# Write the knownnodes.dat file to disk in the new location
shared.knownNodesLock.acquire()
output = open(shared.lookupExeFolder() + 'knownnodes.dat', 'wb')
@ -2540,21 +2542,21 @@ class MyForm(settingsmixin.SMainWindow):
# For Modal dialogs
if self.dialog.exec_():
addressAtCurrentRow = self.getCurrentAccount()
if shared.safeConfigGetBoolean(addressAtCurrentRow, 'chan'):
if BMConfigParser().safeGetBoolean(addressAtCurrentRow, 'chan'):
return
if self.dialog.ui.radioButtonBehaveNormalAddress.isChecked():
shared.config.set(str(
BMConfigParser().set(str(
addressAtCurrentRow), 'mailinglist', 'false')
# Set the color to either black or grey
if shared.config.getboolean(addressAtCurrentRow, 'enabled'):
if BMConfigParser().getboolean(addressAtCurrentRow, 'enabled'):
self.setCurrentItemColor(QApplication.palette()
.text().color())
else:
self.setCurrentItemColor(QtGui.QColor(128, 128, 128))
else:
shared.config.set(str(
BMConfigParser().set(str(
addressAtCurrentRow), 'mailinglist', 'true')
shared.config.set(str(addressAtCurrentRow), 'mailinglistname', str(
BMConfigParser().set(str(addressAtCurrentRow), 'mailinglistname', str(
self.dialog.ui.lineEditMailingListName.text().toUtf8()))
self.setCurrentItemColor(QtGui.QColor(137, 04, 177)) #magenta
self.rerenderComboBoxSendFrom()
@ -2573,7 +2575,7 @@ class MyForm(settingsmixin.SMainWindow):
return
if self.dialog.ui.radioButtonUnregister.isChecked() and isinstance(acct, GatewayAccount):
acct.unregister()
shared.config.remove_option(addressAtCurrentRow, 'gateway')
BMConfigParser().remove_option(addressAtCurrentRow, 'gateway')
shared.writeKeysFile()
self.statusBar().showMessage(_translate(
"MainWindow", "Sending email gateway unregistration request"), 10000)
@ -2599,8 +2601,8 @@ class MyForm(settingsmixin.SMainWindow):
email = str(self.dialog.ui.lineEditEmail.text().toUtf8())
acct = MailchuckAccount(addressAtCurrentRow)
acct.register(email)
shared.config.set(addressAtCurrentRow, 'label', email)
shared.config.set(addressAtCurrentRow, 'gateway', 'mailchuck')
BMConfigParser().set(addressAtCurrentRow, 'label', email)
BMConfigParser().set(addressAtCurrentRow, 'gateway', 'mailchuck')
shared.writeKeysFile()
self.statusBar().showMessage(_translate(
"MainWindow", "Sending email gateway registration request"), 10000)
@ -2818,7 +2820,7 @@ class MyForm(settingsmixin.SMainWindow):
trayonclose = False
try:
trayonclose = shared.config.getboolean(
trayonclose = BMConfigParser().getboolean(
'bitmessagesettings', 'trayonclose')
except Exception:
pass
@ -2893,7 +2895,7 @@ class MyForm(settingsmixin.SMainWindow):
# Format predefined text on message reply.
def quoted_text(self, message):
if not shared.safeConfigGetBoolean('bitmessagesettings', 'replybelow'):
if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'replybelow'):
return '\n\n------------------------------------------------------\n' + message
quoteWrapper = textwrap.TextWrapper(replace_whitespace = False,
@ -2964,10 +2966,10 @@ class MyForm(settingsmixin.SMainWindow):
if toAddressAtCurrentInboxRow == str_broadcast_subscribers:
self.ui.tabWidgetSend.setCurrentIndex(0)
# toAddressAtCurrentInboxRow = fromAddressAtCurrentInboxRow
elif not shared.config.has_section(toAddressAtCurrentInboxRow):
elif not BMConfigParser().has_section(toAddressAtCurrentInboxRow):
QtGui.QMessageBox.information(self, _translate("MainWindow", "Address is gone"), _translate(
"MainWindow", "Bitmessage cannot find your address %1. Perhaps you removed it?").arg(toAddressAtCurrentInboxRow), QMessageBox.Ok)
elif not shared.config.getboolean(toAddressAtCurrentInboxRow, 'enabled'):
elif not BMConfigParser().getboolean(toAddressAtCurrentInboxRow, 'enabled'):
QtGui.QMessageBox.information(self, _translate("MainWindow", "Address disabled"), _translate(
"MainWindow", "Error: The address from which you are trying to send is disabled. You\'ll have to enable it on the \'Your Identities\' tab before using it."), QMessageBox.Ok)
else:
@ -3041,7 +3043,7 @@ class MyForm(settingsmixin.SMainWindow):
queryreturn = sqlQuery('''select * from blacklist where address=?''',
addressAtCurrentInboxRow)
if queryreturn == []:
label = "\"" + tableWidget.item(currentInboxRow, 2).subject + "\" in " + shared.config.get(recipientAddress, "label")
label = "\"" + tableWidget.item(currentInboxRow, 2).subject + "\" in " + BMConfigParser().get(recipientAddress, "label")
sqlExecute('''INSERT INTO blacklist VALUES (?,?, ?)''',
label,
addressAtCurrentInboxRow, True)
@ -3533,7 +3535,7 @@ class MyForm(settingsmixin.SMainWindow):
return # maybe in the future
elif account.type == AccountMixin.CHAN:
if QtGui.QMessageBox.question(self, "Delete channel?", _translate("MainWindow", "If you delete the channel, messages that you already received will become inaccessible. Maybe you can consider disabling the channel instead. Disabled channels will not receive new messages, but you can still view messages you already received.\n\nAre you sure you want to delete the channel?"), QMessageBox.Yes|QMessageBox.No) == QMessageBox.Yes:
shared.config.remove_section(str(account.address))
BMConfigParser().remove_section(str(account.address))
else:
return
else:
@ -3553,7 +3555,7 @@ class MyForm(settingsmixin.SMainWindow):
account.setEnabled(True)
def enableIdentity(self, address):
shared.config.set(address, 'enabled', 'true')
BMConfigParser().set(address, 'enabled', 'true')
shared.writeKeysFile()
shared.reloadMyAddressHashes()
self.rerenderAddressBook()
@ -3565,7 +3567,7 @@ class MyForm(settingsmixin.SMainWindow):
account.setEnabled(False)
def disableIdentity(self, address):
shared.config.set(str(address), 'enabled', 'false')
BMConfigParser().set(str(address), 'enabled', 'false')
shared.writeKeysFile()
shared.reloadMyAddressHashes()
self.rerenderAddressBook()
@ -3981,7 +3983,7 @@ class aboutDialog(QtGui.QDialog):
self.ui = Ui_aboutDialog()
self.ui.setupUi(self)
self.parent = parent
self.ui.labelVersion.setText('version ' + shared.softwareVersion)
self.ui.labelVersion.setText('version ' + softwareVersion)
class regenerateAddressesDialog(QtGui.QDialog):
@ -4001,23 +4003,23 @@ class settingsDialog(QtGui.QDialog):
self.ui.setupUi(self)
self.parent = parent
self.ui.checkBoxStartOnLogon.setChecked(
shared.config.getboolean('bitmessagesettings', 'startonlogon'))
BMConfigParser().getboolean('bitmessagesettings', 'startonlogon'))
self.ui.checkBoxMinimizeToTray.setChecked(
shared.config.getboolean('bitmessagesettings', 'minimizetotray'))
BMConfigParser().getboolean('bitmessagesettings', 'minimizetotray'))
self.ui.checkBoxTrayOnClose.setChecked(
shared.safeConfigGetBoolean('bitmessagesettings', 'trayonclose'))
BMConfigParser().safeGetBoolean('bitmessagesettings', 'trayonclose'))
self.ui.checkBoxHideTrayConnectionNotifications.setChecked(
shared.config.getboolean("bitmessagesettings", "hidetrayconnectionnotifications"))
BMConfigParser().getboolean("bitmessagesettings", "hidetrayconnectionnotifications"))
self.ui.checkBoxShowTrayNotifications.setChecked(
shared.config.getboolean('bitmessagesettings', 'showtraynotifications'))
BMConfigParser().getboolean('bitmessagesettings', 'showtraynotifications'))
self.ui.checkBoxStartInTray.setChecked(
shared.config.getboolean('bitmessagesettings', 'startintray'))
BMConfigParser().getboolean('bitmessagesettings', 'startintray'))
self.ui.checkBoxWillinglySendToMobile.setChecked(
shared.safeConfigGetBoolean('bitmessagesettings', 'willinglysendtomobile'))
BMConfigParser().safeGetBoolean('bitmessagesettings', 'willinglysendtomobile'))
self.ui.checkBoxUseIdenticons.setChecked(
shared.safeConfigGetBoolean('bitmessagesettings', 'useidenticons'))
BMConfigParser().safeGetBoolean('bitmessagesettings', 'useidenticons'))
self.ui.checkBoxReplyBelow.setChecked(
shared.safeConfigGetBoolean('bitmessagesettings', 'replybelow'))
BMConfigParser().safeGetBoolean('bitmessagesettings', 'replybelow'))
if shared.appdata == shared.lookupExeFolder():
self.ui.checkBoxPortableMode.setChecked(True)
@ -4045,14 +4047,14 @@ class settingsDialog(QtGui.QDialog):
"MainWindow", "Start-on-login not yet supported on your OS."))
# On the Network settings tab:
self.ui.lineEditTCPPort.setText(str(
shared.config.get('bitmessagesettings', 'port')))
BMConfigParser().get('bitmessagesettings', 'port')))
self.ui.checkBoxUPnP.setChecked(
shared.safeConfigGetBoolean('bitmessagesettings', 'upnp'))
self.ui.checkBoxAuthentication.setChecked(shared.config.getboolean(
BMConfigParser().safeGetBoolean('bitmessagesettings', 'upnp'))
self.ui.checkBoxAuthentication.setChecked(BMConfigParser().getboolean(
'bitmessagesettings', 'socksauthentication'))
self.ui.checkBoxSocksListen.setChecked(shared.config.getboolean(
self.ui.checkBoxSocksListen.setChecked(BMConfigParser().getboolean(
'bitmessagesettings', 'sockslisten'))
if str(shared.config.get('bitmessagesettings', 'socksproxytype')) == 'none':
if str(BMConfigParser().get('bitmessagesettings', 'socksproxytype')) == 'none':
self.ui.comboBoxProxyType.setCurrentIndex(0)
self.ui.lineEditSocksHostname.setEnabled(False)
self.ui.lineEditSocksPort.setEnabled(False)
@ -4060,38 +4062,38 @@ class settingsDialog(QtGui.QDialog):
self.ui.lineEditSocksPassword.setEnabled(False)
self.ui.checkBoxAuthentication.setEnabled(False)
self.ui.checkBoxSocksListen.setEnabled(False)
elif str(shared.config.get('bitmessagesettings', 'socksproxytype')) == 'SOCKS4a':
elif str(BMConfigParser().get('bitmessagesettings', 'socksproxytype')) == 'SOCKS4a':
self.ui.comboBoxProxyType.setCurrentIndex(1)
self.ui.lineEditTCPPort.setEnabled(False)
elif str(shared.config.get('bitmessagesettings', 'socksproxytype')) == 'SOCKS5':
elif str(BMConfigParser().get('bitmessagesettings', 'socksproxytype')) == 'SOCKS5':
self.ui.comboBoxProxyType.setCurrentIndex(2)
self.ui.lineEditTCPPort.setEnabled(False)
self.ui.lineEditSocksHostname.setText(str(
shared.config.get('bitmessagesettings', 'sockshostname')))
BMConfigParser().get('bitmessagesettings', 'sockshostname')))
self.ui.lineEditSocksPort.setText(str(
shared.config.get('bitmessagesettings', 'socksport')))
BMConfigParser().get('bitmessagesettings', 'socksport')))
self.ui.lineEditSocksUsername.setText(str(
shared.config.get('bitmessagesettings', 'socksusername')))
BMConfigParser().get('bitmessagesettings', 'socksusername')))
self.ui.lineEditSocksPassword.setText(str(
shared.config.get('bitmessagesettings', 'sockspassword')))
BMConfigParser().get('bitmessagesettings', 'sockspassword')))
QtCore.QObject.connect(self.ui.comboBoxProxyType, QtCore.SIGNAL(
"currentIndexChanged(int)"), self.comboBoxProxyTypeChanged)
self.ui.lineEditMaxDownloadRate.setText(str(
shared.config.get('bitmessagesettings', 'maxdownloadrate')))
BMConfigParser().get('bitmessagesettings', 'maxdownloadrate')))
self.ui.lineEditMaxUploadRate.setText(str(
shared.config.get('bitmessagesettings', 'maxuploadrate')))
BMConfigParser().get('bitmessagesettings', 'maxuploadrate')))
# Demanded difficulty tab
self.ui.lineEditTotalDifficulty.setText(str((float(shared.config.getint(
self.ui.lineEditTotalDifficulty.setText(str((float(BMConfigParser().getint(
'bitmessagesettings', 'defaultnoncetrialsperbyte')) / shared.networkDefaultProofOfWorkNonceTrialsPerByte)))
self.ui.lineEditSmallMessageDifficulty.setText(str((float(shared.config.getint(
self.ui.lineEditSmallMessageDifficulty.setText(str((float(BMConfigParser().getint(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')) / shared.networkDefaultPayloadLengthExtraBytes)))
# Max acceptable difficulty tab
self.ui.lineEditMaxAcceptableTotalDifficulty.setText(str((float(shared.config.getint(
self.ui.lineEditMaxAcceptableTotalDifficulty.setText(str((float(BMConfigParser().getint(
'bitmessagesettings', 'maxacceptablenoncetrialsperbyte')) / shared.networkDefaultProofOfWorkNonceTrialsPerByte)))
self.ui.lineEditMaxAcceptableSmallMessageDifficulty.setText(str((float(shared.config.getint(
self.ui.lineEditMaxAcceptableSmallMessageDifficulty.setText(str((float(BMConfigParser().getint(
'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes')) / shared.networkDefaultPayloadLengthExtraBytes)))
# OpenCL
@ -4104,20 +4106,20 @@ class settingsDialog(QtGui.QDialog):
self.ui.comboBoxOpenCL.addItems(openclpow.vendors)
self.ui.comboBoxOpenCL.setCurrentIndex(0)
for i in range(self.ui.comboBoxOpenCL.count()):
if self.ui.comboBoxOpenCL.itemText(i) == shared.safeConfigGet('bitmessagesettings', 'opencl'):
if self.ui.comboBoxOpenCL.itemText(i) == BMConfigParser().safeGet('bitmessagesettings', 'opencl'):
self.ui.comboBoxOpenCL.setCurrentIndex(i)
break
# Namecoin integration tab
nmctype = shared.config.get('bitmessagesettings', 'namecoinrpctype')
nmctype = BMConfigParser().get('bitmessagesettings', 'namecoinrpctype')
self.ui.lineEditNamecoinHost.setText(str(
shared.config.get('bitmessagesettings', 'namecoinrpchost')))
BMConfigParser().get('bitmessagesettings', 'namecoinrpchost')))
self.ui.lineEditNamecoinPort.setText(str(
shared.config.get('bitmessagesettings', 'namecoinrpcport')))
BMConfigParser().get('bitmessagesettings', 'namecoinrpcport')))
self.ui.lineEditNamecoinUser.setText(str(
shared.config.get('bitmessagesettings', 'namecoinrpcuser')))
BMConfigParser().get('bitmessagesettings', 'namecoinrpcuser')))
self.ui.lineEditNamecoinPassword.setText(str(
shared.config.get('bitmessagesettings', 'namecoinrpcpassword')))
BMConfigParser().get('bitmessagesettings', 'namecoinrpcpassword')))
if nmctype == "namecoind":
self.ui.radioButtonNamecoinNamecoind.setChecked(True)
@ -4139,14 +4141,14 @@ class settingsDialog(QtGui.QDialog):
#Message Resend tab
self.ui.lineEditDays.setText(str(
shared.config.get('bitmessagesettings', 'stopresendingafterxdays')))
BMConfigParser().get('bitmessagesettings', 'stopresendingafterxdays')))
self.ui.lineEditMonths.setText(str(
shared.config.get('bitmessagesettings', 'stopresendingafterxmonths')))
BMConfigParser().get('bitmessagesettings', 'stopresendingafterxmonths')))
#'System' tab removed for now.
"""try:
maxCores = shared.config.getint('bitmessagesettings', 'maxcores')
maxCores = BMConfigParser().getint('bitmessagesettings', 'maxcores')
except:
maxCores = 99999
if maxCores <= 1:
@ -4235,13 +4237,13 @@ class SpecialAddressBehaviorDialog(QtGui.QDialog):
self.ui.setupUi(self)
self.parent = parent
addressAtCurrentRow = parent.getCurrentAccount()
if not shared.safeConfigGetBoolean(addressAtCurrentRow, 'chan'):
if shared.safeConfigGetBoolean(addressAtCurrentRow, 'mailinglist'):
if not BMConfigParser().safeGetBoolean(addressAtCurrentRow, 'chan'):
if BMConfigParser().safeGetBoolean(addressAtCurrentRow, 'mailinglist'):
self.ui.radioButtonBehaviorMailingList.click()
else:
self.ui.radioButtonBehaveNormalAddress.click()
try:
mailingListName = shared.config.get(
mailingListName = BMConfigParser().get(
addressAtCurrentRow, 'mailinglistname')
except:
mailingListName = ''
@ -4272,7 +4274,7 @@ class EmailGatewayDialog(QtGui.QDialog):
self.ui.radioButtonStatus.setEnabled(False)
self.ui.radioButtonSettings.setEnabled(False)
self.ui.radioButtonUnregister.setEnabled(False)
label = shared.config.get(addressAtCurrentRow, 'label')
label = BMConfigParser().get(addressAtCurrentRow, 'label')
if label.find("@mailchuck.com") > -1:
self.ui.lineEditEmail.setText(label)
@ -4377,7 +4379,7 @@ class iconGlossaryDialog(QtGui.QDialog):
self.ui.setupUi(self)
self.parent = parent
self.ui.labelPortNumber.setText(_translate(
"MainWindow", "You are using TCP port %1. (This can be changed in the settings).").arg(str(shared.config.getint('bitmessagesettings', 'port'))))
"MainWindow", "You are using TCP port %1. (This can be changed in the settings).").arg(str(BMConfigParser().getint('bitmessagesettings', 'port'))))
QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self))
@ -4462,17 +4464,17 @@ def run():
myapp.appIndicatorInit(app)
myapp.ubuntuMessagingMenuInit()
myapp.notifierInit()
if shared.safeConfigGetBoolean('bitmessagesettings', 'dontconnect'):
if BMConfigParser().safeGetBoolean('bitmessagesettings', 'dontconnect'):
myapp.showConnectDialog() # ask the user if we may connect
# try:
# if shared.config.get('bitmessagesettings', 'mailchuck') < 1:
# myapp.showMigrationWizard(shared.config.get('bitmessagesettings', 'mailchuck'))
# if BMConfigParser().get('bitmessagesettings', 'mailchuck') < 1:
# myapp.showMigrationWizard(BMConfigParser().get('bitmessagesettings', 'mailchuck'))
# except:
# myapp.showMigrationWizard(0)
# only show after wizards and connect dialogs have completed
if not shared.config.getboolean('bitmessagesettings', 'startintray'):
if not BMConfigParser().getboolean('bitmessagesettings', 'startintray'):
myapp.show()
sys.exit(app.exec_())

View File

@ -6,15 +6,16 @@ import sys
import inspect
from helper_sql import *
from addresses import decodeAddress
from configparser import BMConfigParser
from foldertree import AccountMixin
from pyelliptic.openssl import OpenSSL
from utils import str_broadcast_subscribers
import time
def getSortedAccounts():
configSections = filter(lambda x: x != 'bitmessagesettings', shared.config.sections())
configSections = filter(lambda x: x != 'bitmessagesettings', BMConfigParser().sections())
configSections.sort(cmp =
lambda x,y: cmp(unicode(shared.config.get(x, 'label'), 'utf-8').lower(), unicode(shared.config.get(y, 'label'), 'utf-8').lower())
lambda x,y: cmp(unicode(BMConfigParser().get(x, 'label'), 'utf-8').lower(), unicode(BMConfigParser().get(y, 'label'), 'utf-8').lower())
)
return configSections
@ -44,7 +45,7 @@ def getSortedSubscriptions(count = False):
return ret
def accountClass(address):
if not shared.config.has_section(address):
if not BMConfigParser().has_section(address):
# FIXME: This BROADCAST section makes no sense
if address == str_broadcast_subscribers:
subscription = BroadcastAccount(address)
@ -56,7 +57,7 @@ def accountClass(address):
return None
return subscription
try:
gateway = shared.config.get(address, "gateway")
gateway = BMConfigParser().get(address, "gateway")
for name, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass):
# obj = g(address)
if issubclass(cls, GatewayAccount) and cls.gatewayName == gateway:
@ -75,9 +76,9 @@ class AccountColor(AccountMixin):
if type is None:
if address is None:
self.type = AccountMixin.ALL
elif shared.safeConfigGetBoolean(self.address, 'mailinglist'):
elif BMConfigParser().safeGetBoolean(self.address, 'mailinglist'):
self.type = AccountMixin.MAILINGLIST
elif shared.safeConfigGetBoolean(self.address, 'chan'):
elif BMConfigParser().safeGetBoolean(self.address, 'chan'):
self.type = AccountMixin.CHAN
elif sqlQuery(
'''select label from subscriptions where address=?''', self.address):
@ -92,10 +93,10 @@ class BMAccount(object):
def __init__(self, address = None):
self.address = address
self.type = AccountMixin.NORMAL
if shared.config.has_section(address):
if shared.safeConfigGetBoolean(self.address, 'chan'):
if BMConfigParser().has_section(address):
if BMConfigParser().safeGetBoolean(self.address, 'chan'):
self.type = AccountMixin.CHAN
elif shared.safeConfigGetBoolean(self.address, 'mailinglist'):
elif BMConfigParser().safeGetBoolean(self.address, 'mailinglist'):
self.type = AccountMixin.MAILINGLIST
elif self.address == str_broadcast_subscribers:
self.type = AccountMixin.BROADCAST
@ -109,8 +110,8 @@ class BMAccount(object):
if address is None:
address = self.address
label = address
if shared.config.has_section(address):
label = shared.config.get(address, 'label')
if BMConfigParser().has_section(address):
label = BMConfigParser().get(address, 'label')
queryreturn = sqlQuery(
'''select label from addressbook where address=?''', address)
if queryreturn != []:
@ -168,7 +169,7 @@ class GatewayAccount(BMAccount):
0, # retryNumber
'sent', # folder
2, # encodingtype
min(shared.config.getint('bitmessagesettings', 'ttl'), 86400 * 2) # not necessary to have a TTL higher than 2 days
min(BMConfigParser().getint('bitmessagesettings', 'ttl'), 86400 * 2) # not necessary to have a TTL higher than 2 days
)
shared.workerQueue.put(('sendmessage', self.toAddress))

View File

@ -8,6 +8,7 @@
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
from configparser import BMConfigParser
from foldertree import AddressBookCompleter
from messageview import MessageView
from messagecompose import MessageCompose
@ -556,7 +557,7 @@ class Ui_MainWindow(object):
self.blackwhitelist = Blacklist()
self.tabWidget.addTab(self.blackwhitelist, QtGui.QIcon(":/newPrefix/images/blacklist.png"), "")
# Initialize the Blacklist or Whitelist
if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'white':
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'white':
self.blackwhitelist.radioButtonWhitelist.click()
self.blackwhitelist.rerenderBlackWhiteList()
@ -680,7 +681,7 @@ class Ui_MainWindow(object):
self.pushButtonTTL.setText(_translate("MainWindow", "TTL:", None))
hours = 48
try:
hours = int(shared.config.getint('bitmessagesettings', 'ttl')/60/60)
hours = int(BMConfigParser().getint('bitmessagesettings', 'ttl')/60/60)
except:
pass
self.labelHumanFriendlyTTLDescription.setText(_translate("MainWindow", "%n hour(s)", None, QtCore.QCoreApplication.CodecForTr, hours))

View File

@ -5,6 +5,7 @@ import l10n
from uisignaler import UISignaler
import widgets
from addresses import addBMIfNotPresent
from configparser import BMConfigParser
from dialogs import AddAddressDialog
from helper_sql import sqlExecute, sqlQuery
from retranslateui import RetranslateMixin
@ -39,16 +40,16 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
"rerenderBlackWhiteList()"), self.rerenderBlackWhiteList)
def click_radioButtonBlacklist(self):
if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'white':
shared.config.set('bitmessagesettings', 'blackwhitelist', 'black')
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'white':
BMConfigParser().set('bitmessagesettings', 'blackwhitelist', 'black')
shared.writeKeysFile()
# self.tableWidgetBlacklist.clearContents()
self.tableWidgetBlacklist.setRowCount(0)
self.rerenderBlackWhiteList()
def click_radioButtonWhitelist(self):
if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black':
shared.config.set('bitmessagesettings', 'blackwhitelist', 'white')
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black':
BMConfigParser().set('bitmessagesettings', 'blackwhitelist', 'white')
shared.writeKeysFile()
# self.tableWidgetBlacklist.clearContents()
self.tableWidgetBlacklist.setRowCount(0)
@ -64,7 +65,7 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
# address book. The user cannot add it again or else it will
# cause problems when updating and deleting the entry.
t = (address,)
if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black':
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black':
sql = '''select * from blacklist where address=?'''
else:
sql = '''select * from whitelist where address=?'''
@ -82,7 +83,7 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
self.tableWidgetBlacklist.setItem(0, 1, newItem)
self.tableWidgetBlacklist.setSortingEnabled(True)
t = (str(self.NewBlacklistDialogInstance.ui.newAddressLabel.text().toUtf8()), address, True)
if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black':
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black':
sql = '''INSERT INTO blacklist VALUES (?,?,?)'''
else:
sql = '''INSERT INTO whitelist VALUES (?,?,?)'''
@ -147,12 +148,12 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
def rerenderBlackWhiteList(self):
tabs = self.parent().parent()
if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black':
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black':
tabs.setTabText(tabs.indexOf(self), _translate('blacklist', 'Blacklist'))
else:
tabs.setTabText(tabs.indexOf(self), _translate('blacklist', 'Whitelist'))
self.tableWidgetBlacklist.setRowCount(0)
listType = shared.config.get('bitmessagesettings', 'blackwhitelist')
listType = BMConfigParser().get('bitmessagesettings', 'blackwhitelist')
if listType == 'black':
queryreturn = sqlQuery('''SELECT label, address, enabled FROM blacklist''')
else:
@ -184,7 +185,7 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
currentRow, 0).text().toUtf8()
addressAtCurrentRow = self.tableWidgetBlacklist.item(
currentRow, 1).text()
if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black':
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black':
sqlExecute(
'''DELETE FROM blacklist WHERE label=? AND address=?''',
str(labelAtCurrentRow), str(addressAtCurrentRow))
@ -213,7 +214,7 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
currentRow, 0).setTextColor(QtGui.QApplication.palette().text().color())
self.tableWidgetBlacklist.item(
currentRow, 1).setTextColor(QtGui.QApplication.palette().text().color())
if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black':
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black':
sqlExecute(
'''UPDATE blacklist SET enabled=1 WHERE address=?''',
str(addressAtCurrentRow))
@ -230,7 +231,7 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
currentRow, 0).setTextColor(QtGui.QColor(128, 128, 128))
self.tableWidgetBlacklist.item(
currentRow, 1).setTextColor(QtGui.QColor(128, 128, 128))
if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black':
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black':
sqlExecute(
'''UPDATE blacklist SET enabled=0 WHERE address=?''', str(addressAtCurrentRow))
else:

View File

@ -1,6 +1,7 @@
from PyQt4 import QtCore, QtGui
from string import find, rfind, rstrip, lstrip
from configparser import BMConfigParser
from helper_sql import *
from utils import *
import shared
@ -69,9 +70,9 @@ class AccountMixin (object):
if self.address is None:
self.type = self.ALL
self.setFlags(self.flags() & ~QtCore.Qt.ItemIsEditable)
elif shared.safeConfigGetBoolean(self.address, 'chan'):
elif BMConfigParser().safeGetBoolean(self.address, 'chan'):
self.type = self.CHAN
elif shared.safeConfigGetBoolean(self.address, 'mailinglist'):
elif BMConfigParser().safeGetBoolean(self.address, 'mailinglist'):
self.type = self.MAILINGLIST
elif sqlQuery(
'''select label from subscriptions where address=?''', self.address):
@ -84,7 +85,7 @@ class AccountMixin (object):
retval = None
if self.type in (AccountMixin.NORMAL, AccountMixin.CHAN, AccountMixin.MAILINGLIST):
try:
retval = unicode(shared.config.get(self.address, 'label'), 'utf-8')
retval = unicode(BMConfigParser().get(self.address, 'label'), 'utf-8')
except Exception as e:
queryreturn = sqlQuery(
'''select label from addressbook where address=?''', self.address)
@ -161,7 +162,7 @@ class Ui_AddressWidget(QtGui.QTreeWidgetItem, AccountMixin, SettingsMixin):
super(QtGui.QTreeWidgetItem, self).__init__()
parent.insertTopLevelItem(pos, self)
# only set default when creating
#super(QtGui.QTreeWidgetItem, self).setExpanded(shared.config.getboolean(self.address, 'enabled'))
#super(QtGui.QTreeWidgetItem, self).setExpanded(BMConfigParser().getboolean(self.address, 'enabled'))
self.setAddress(address)
self.setEnabled(enabled)
self.setUnreadCount(unreadCount)
@ -172,7 +173,7 @@ class Ui_AddressWidget(QtGui.QTreeWidgetItem, AccountMixin, SettingsMixin):
return unicode(QtGui.QApplication.translate("MainWindow", "All accounts").toUtf8(), 'utf-8', 'ignore')
else:
try:
return unicode(shared.config.get(self.address, 'label'), 'utf-8', 'ignore')
return unicode(BMConfigParser().get(self.address, 'label'), 'utf-8', 'ignore')
except:
return unicode(self.address, 'utf-8')
@ -211,9 +212,9 @@ class Ui_AddressWidget(QtGui.QTreeWidgetItem, AccountMixin, SettingsMixin):
def setData(self, column, role, value):
if role == QtCore.Qt.EditRole and self.type != AccountMixin.SUBSCRIPTION:
if isinstance(value, QtCore.QVariant):
shared.config.set(str(self.address), 'label', str(value.toString().toUtf8()))
BMConfigParser().set(str(self.address), 'label', str(value.toString().toUtf8()))
else:
shared.config.set(str(self.address), 'label', str(value))
BMConfigParser().set(str(self.address), 'label', str(value))
shared.writeKeysFile()
return super(Ui_AddressWidget, self).setData(column, role, value)
@ -250,7 +251,7 @@ class Ui_SubscriptionWidget(Ui_AddressWidget, AccountMixin):
super(QtGui.QTreeWidgetItem, self).__init__()
parent.insertTopLevelItem(pos, self)
# only set default when creating
#super(QtGui.QTreeWidgetItem, self).setExpanded(shared.config.getboolean(self.address, 'enabled'))
#super(QtGui.QTreeWidgetItem, self).setExpanded(BMConfigParser().getboolean(self.address, 'enabled'))
self.setAddress(address)
self.setEnabled(enabled)
self.setType()
@ -287,7 +288,7 @@ class MessageList_AddressWidget(QtGui.QTableWidgetItem, AccountMixin, SettingsMi
super(QtGui.QTableWidgetItem, self).__init__()
#parent.insertTopLevelItem(pos, self)
# only set default when creating
#super(QtGui.QTreeWidgetItem, self).setExpanded(shared.config.getboolean(self.address, 'enabled'))
#super(QtGui.QTreeWidgetItem, self).setExpanded(BMConfigParser().getboolean(self.address, 'enabled'))
self.isEnabled = True
self.setAddress(address)
self.setLabel(label)
@ -302,7 +303,7 @@ class MessageList_AddressWidget(QtGui.QTableWidgetItem, AccountMixin, SettingsMi
queryreturn = None
if self.type in (AccountMixin.NORMAL, AccountMixin.CHAN, AccountMixin.MAILINGLIST):
try:
newLabel = unicode(shared.config.get(self.address, 'label'), 'utf-8', 'ignore')
newLabel = unicode(BMConfigParser().get(self.address, 'label'), 'utf-8', 'ignore')
except:
queryreturn = sqlQuery(
'''select label from addressbook where address=?''', self.address)
@ -330,7 +331,7 @@ class MessageList_AddressWidget(QtGui.QTableWidgetItem, AccountMixin, SettingsMi
elif role == QtCore.Qt.ToolTipRole:
return self.label + " (" + self.address + ")"
elif role == QtCore.Qt.DecorationRole:
if shared.safeConfigGetBoolean('bitmessagesettings', 'useidenticons'):
if BMConfigParser().safeGetBoolean('bitmessagesettings', 'useidenticons'):
if self.address is None:
return avatarize(self.label)
else:
@ -362,7 +363,7 @@ class MessageList_SubjectWidget(QtGui.QTableWidgetItem, SettingsMixin):
super(QtGui.QTableWidgetItem, self).__init__()
#parent.insertTopLevelItem(pos, self)
# only set default when creating
#super(QtGui.QTreeWidgetItem, self).setExpanded(shared.config.getboolean(self.address, 'enabled'))
#super(QtGui.QTreeWidgetItem, self).setExpanded(BMConfigParser().getboolean(self.address, 'enabled'))
self.setSubject(subject)
self.setLabel(label)
self.setUnread(unread)
@ -418,7 +419,7 @@ class Ui_AddressBookWidgetItem(QtGui.QTableWidgetItem, AccountMixin):
elif role == QtCore.Qt.ToolTipRole:
return self.label + " (" + self.address + ")"
elif role == QtCore.Qt.DecorationRole:
if shared.safeConfigGetBoolean('bitmessagesettings', 'useidenticons'):
if BMConfigParser().safeGetBoolean('bitmessagesettings', 'useidenticons'):
if self.address is None:
return avatarize(self.label)
else:
@ -440,8 +441,8 @@ class Ui_AddressBookWidgetItem(QtGui.QTableWidgetItem, AccountMixin):
self.label = str(value)
if self.type in (AccountMixin.NORMAL, AccountMixin.MAILINGLIST, AccountMixin.CHAN):
try:
a = shared.config.get(self.address, 'label')
shared.config.set(self.address, 'label', self.label)
a = BMConfigParser().get(self.address, 'label')
BMConfigParser().set(self.address, 'label', self.label)
except:
sqlExecute('''UPDATE addressbook set label=? WHERE address=?''', self.label, self.address)
elif self.type == AccountMixin.SUBSCRIPTION:

View File

@ -2,7 +2,8 @@ import glob
import os
from PyQt4 import QtCore, QtGui
from shared import codePath, config
from configparser import BMConfigParser
from shared import codePath
class LanguageBox(QtGui.QComboBox):
languageName = {"system": "System Settings", "eo": "Esperanto", "en_pirate": "Pirate English"}
@ -16,7 +17,7 @@ class LanguageBox(QtGui.QComboBox):
localesPath = os.path.join (codePath(), 'translations')
configuredLocale = "system"
try:
configuredLocale = config.get('bitmessagesettings', 'userlocale', "system")
configuredLocale = BMConfigParser().get('bitmessagesettings', 'userlocale', "system")
except:
pass
self.addItem(QtGui.QApplication.translate("settingsDialog", "System Settings", "system"), "system")

View File

@ -5,6 +5,7 @@ import sys
import time
import account
from configparser import BMConfigParser
from debug import logger
from foldertree import AccountMixin
from helper_sql import *
@ -13,6 +14,7 @@ from openclpow import openclAvailable, openclEnabled
from proofofwork import bmpow
from pyelliptic.openssl import OpenSSL
import shared
from version import softwareVersion
# this is BM support address going to Peter Surda
SUPPORT_ADDRESS = 'BM-2cTkCtMYkrSPwFTpgcBrMrf5d8oZwvMZWK'
@ -55,7 +57,7 @@ def checkAddressBook(myapp):
def checkHasNormalAddress():
for address in account.getSortedAccounts():
acct = account.accountClass(address)
if acct.type == AccountMixin.NORMAL and shared.safeConfigGetBoolean(address, 'enabled'):
if acct.type == AccountMixin.NORMAL and BMConfigParser().safeGetBoolean(address, 'enabled'):
return address
return False
@ -80,7 +82,7 @@ def createSupportMessage(myapp):
myapp.ui.comboBoxSendFrom.setCurrentIndex(addrIndex)
myapp.ui.lineEditTo.setText(SUPPORT_ADDRESS)
version = shared.softwareVersion
version = softwareVersion
os = sys.platform
if os == "win32":
windowsversion = sys.getwindowsversion()
@ -107,15 +109,15 @@ def createSupportMessage(myapp):
portablemode = "True" if shared.appdata == shared.lookupExeFolder() else "False"
cpow = "True" if bmpow else "False"
#cpow = QtGui.QApplication.translate("Support", cpow)
openclpow = str(shared.safeConfigGet('bitmessagesettings', 'opencl')) if openclEnabled() else "None"
openclpow = str(BMConfigParser().safeGet('bitmessagesettings', 'opencl')) if openclEnabled() else "None"
#openclpow = QtGui.QApplication.translate("Support", openclpow)
locale = getTranslationLanguage()
try:
socks = shared.config.get('bitmessagesettings', 'socksproxytype')
socks = BMConfigParser().get('bitmessagesettings', 'socksproxytype')
except:
socks = "N/A"
try:
upnp = shared.config.get('bitmessagesettings', 'upnp')
upnp = BMConfigParser().get('bitmessagesettings', 'upnp')
except:
upnp = "N/A"
connectedhosts = len(shared.connectedHostsList)

View File

@ -3,6 +3,7 @@ import hashlib
import os
import shared
from addresses import addBMIfNotPresent
from configparser import BMConfigParser
str_broadcast_subscribers = '[Broadcast subscribers]'
str_chan = '[chan]'
@ -15,7 +16,7 @@ def identiconize(address):
# 3fd4bf901b9d4ea1394f0fb358725b28
try:
identicon_lib = shared.config.get('bitmessagesettings', 'identiconlib')
identicon_lib = BMConfigParser().get('bitmessagesettings', 'identiconlib')
except:
# default to qidenticon_two_x
identicon_lib = 'qidenticon_two_x'
@ -23,9 +24,9 @@ def identiconize(address):
# As an 'identiconsuffix' you could put "@bitmessge.ch" or "@bm.addr" to make it compatible with other identicon generators. (Note however, that E-Mail programs might convert the BM-address to lowercase first.)
# It can be used as a pseudo-password to salt the generation of the identicons to decrease the risk
# of attacks where someone creates an address to mimic someone else's identicon.
identiconsuffix = shared.config.get('bitmessagesettings', 'identiconsuffix')
identiconsuffix = BMConfigParser().get('bitmessagesettings', 'identiconsuffix')
if not shared.config.getboolean('bitmessagesettings', 'useidenticons'):
if not BMConfigParser().getboolean('bitmessagesettings', 'useidenticons'):
idcon = QtGui.QIcon()
return idcon

View File

@ -7,6 +7,7 @@ import ctypes
import hashlib
import highlevelcrypto
from addresses import *
from configparser import BMConfigParser
from debug import logger
from helper_threading import *
from pyelliptic import arithmetic
@ -48,7 +49,7 @@ class addressGenerator(threading.Thread, StoppableThread):
elif len(queueValue) == 7:
command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe = queueValue
try:
numberOfNullBytesDemandedOnFrontOfRipeHash = shared.config.getint(
numberOfNullBytesDemandedOnFrontOfRipeHash = BMConfigParser().getint(
'bitmessagesettings', 'numberofnullbytesonaddress')
except:
if eighteenByteRipe:
@ -58,7 +59,7 @@ class addressGenerator(threading.Thread, StoppableThread):
elif len(queueValue) == 9:
command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes = queueValue
try:
numberOfNullBytesDemandedOnFrontOfRipeHash = shared.config.getint(
numberOfNullBytesDemandedOnFrontOfRipeHash = BMConfigParser().getint(
'bitmessagesettings', 'numberofnullbytesonaddress')
except:
if eighteenByteRipe:
@ -74,12 +75,12 @@ class addressGenerator(threading.Thread, StoppableThread):
sys.stderr.write(
'Program error: For some reason the address generator queue has been given a request to create at least one version %s address which it cannot do.\n' % addressVersionNumber)
if nonceTrialsPerByte == 0:
nonceTrialsPerByte = shared.config.getint(
nonceTrialsPerByte = BMConfigParser().getint(
'bitmessagesettings', 'defaultnoncetrialsperbyte')
if nonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte:
nonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte
if payloadLengthExtraBytes == 0:
payloadLengthExtraBytes = shared.config.getint(
payloadLengthExtraBytes = BMConfigParser().getint(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
if payloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes:
payloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes
@ -128,17 +129,17 @@ class addressGenerator(threading.Thread, StoppableThread):
privEncryptionKeyWIF = arithmetic.changebase(
privEncryptionKey + checksum, 256, 58)
shared.config.add_section(address)
shared.config.set(address, 'label', label)
shared.config.set(address, 'enabled', 'true')
shared.config.set(address, 'decoy', 'false')
shared.config.set(address, 'noncetrialsperbyte', str(
BMConfigParser().add_section(address)
BMConfigParser().set(address, 'label', label)
BMConfigParser().set(address, 'enabled', 'true')
BMConfigParser().set(address, 'decoy', 'false')
BMConfigParser().set(address, 'noncetrialsperbyte', str(
nonceTrialsPerByte))
shared.config.set(address, 'payloadlengthextrabytes', str(
BMConfigParser().set(address, 'payloadlengthextrabytes', str(
payloadLengthExtraBytes))
shared.config.set(
BMConfigParser().set(
address, 'privSigningKey', privSigningKeyWIF)
shared.config.set(
BMConfigParser().set(
address, 'privEncryptionKey', privEncryptionKeyWIF)
shared.writeKeysFile()
@ -233,7 +234,7 @@ class addressGenerator(threading.Thread, StoppableThread):
try:
shared.config.add_section(address)
BMConfigParser().add_section(address)
addressAlreadyExists = False
except:
addressAlreadyExists = True
@ -244,18 +245,18 @@ class addressGenerator(threading.Thread, StoppableThread):
'updateStatusBar', tr._translate("MainWindow","%1 is already in 'Your Identities'. Not adding it again.").arg(address)))
else:
logger.debug('label: %s' % label)
shared.config.set(address, 'label', label)
shared.config.set(address, 'enabled', 'true')
shared.config.set(address, 'decoy', 'false')
BMConfigParser().set(address, 'label', label)
BMConfigParser().set(address, 'enabled', 'true')
BMConfigParser().set(address, 'decoy', 'false')
if command == 'joinChan' or command == 'createChan':
shared.config.set(address, 'chan', 'true')
shared.config.set(address, 'noncetrialsperbyte', str(
BMConfigParser().set(address, 'chan', 'true')
BMConfigParser().set(address, 'noncetrialsperbyte', str(
nonceTrialsPerByte))
shared.config.set(address, 'payloadlengthextrabytes', str(
BMConfigParser().set(address, 'payloadlengthextrabytes', str(
payloadLengthExtraBytes))
shared.config.set(
BMConfigParser().set(
address, 'privSigningKey', privSigningKeyWIF)
shared.config.set(
BMConfigParser().set(
address, 'privEncryptionKey', privEncryptionKeyWIF)
shared.writeKeysFile()
@ -278,7 +279,7 @@ class addressGenerator(threading.Thread, StoppableThread):
'sendOutOrStoreMyV4Pubkey', address))
shared.UISignalQueue.put((
'updateStatusBar', tr._translate("MainWindow", "Done generating address")))
elif saveAddressToDisk and not live and not shared.config.has_section(address):
elif saveAddressToDisk and not live and not BMConfigParser().has_section(address):
listOfNewAddressesToSendOutThroughTheAPI.append(address)
# Done generating addresses.

View File

@ -13,6 +13,7 @@ from binascii import hexlify
from pyelliptic.openssl import OpenSSL
import highlevelcrypto
from addresses import *
from configparser import BMConfigParser
import helper_generic
from helper_generic import addDataPadding
import helper_bitcoin
@ -20,6 +21,8 @@ import helper_inbox
import helper_msgcoding
import helper_sent
from helper_sql import *
import protocol
from state import neededPubkeys
import tr
from debug import logger
import l10n
@ -130,11 +133,11 @@ class objectProcessor(threading.Thread):
if decodeAddress(myAddress)[2] != streamNumber:
logger.warning('(Within the processgetpubkey function) Someone requested one of my pubkeys but the stream number on which we heard this getpubkey object doesn\'t match this address\' stream number. Ignoring.')
return
if shared.safeConfigGetBoolean(myAddress, 'chan'):
if BMConfigParser().safeGetBoolean(myAddress, 'chan'):
logger.info('Ignoring getpubkey request because it is for one of my chan addresses. The other party should already have the pubkey.')
return
try:
lastPubkeySendTime = int(shared.config.get(
lastPubkeySendTime = int(BMConfigParser().get(
myAddress, 'lastpubkeysendtime'))
except:
lastPubkeySendTime = 0
@ -283,12 +286,12 @@ class objectProcessor(threading.Thread):
return
tag = data[readPosition:readPosition + 32]
if tag not in shared.neededPubkeys:
if tag not in neededPubkeys:
logger.info('We don\'t need this v4 pubkey. We didn\'t ask for it.')
return
# Let us try to decrypt the pubkey
toAddress, cryptorObject = shared.neededPubkeys[tag]
toAddress, cryptorObject = neededPubkeys[tag]
if shared.decryptAndCheckPubkeyPayload(data, toAddress) == 'successful':
# At this point we know that we have been waiting on this pubkey.
# This function will command the workerThread to start work on
@ -458,17 +461,17 @@ class objectProcessor(threading.Thread):
# proof of work requirement. If this is bound for one of my chan
# addresses then we skip this check; the minimum network POW is
# fine.
if decodeAddress(toAddress)[1] >= 3 and not shared.safeConfigGetBoolean(toAddress, 'chan'): # If the toAddress version number is 3 or higher and not one of my chan addresses:
if decodeAddress(toAddress)[1] >= 3 and not BMConfigParser().safeGetBoolean(toAddress, 'chan'): # If the toAddress version number is 3 or higher and not one of my chan addresses:
if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(fromAddress): # If I'm not friendly with this person:
requiredNonceTrialsPerByte = shared.config.getint(
requiredNonceTrialsPerByte = BMConfigParser().getint(
toAddress, 'noncetrialsperbyte')
requiredPayloadLengthExtraBytes = shared.config.getint(
requiredPayloadLengthExtraBytes = BMConfigParser().getint(
toAddress, 'payloadlengthextrabytes')
if not shared.isProofOfWorkSufficient(data, requiredNonceTrialsPerByte, requiredPayloadLengthExtraBytes):
logger.info('Proof of work in msg is insufficient only because it does not meet our higher requirement.')
return
blockMessage = False # Gets set to True if the user shouldn't see the message according to black or white lists.
if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black': # If we are using a blacklist
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black': # If we are using a blacklist
queryreturn = sqlQuery(
'''SELECT label FROM blacklist where address=? and enabled='1' ''',
fromAddress)
@ -484,7 +487,7 @@ class objectProcessor(threading.Thread):
logger.info('Message ignored because address not in whitelist.')
blockMessage = True
toLabel = shared.config.get(toAddress, 'label')
toLabel = BMConfigParser().get(toAddress, 'label')
if toLabel == '':
toLabel = toAddress
@ -508,9 +511,9 @@ class objectProcessor(threading.Thread):
# If we are behaving as an API then we might need to run an
# outside command to let some program know that a new message
# has arrived.
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
if BMConfigParser().safeGetBoolean('bitmessagesettings', 'apienabled'):
try:
apiNotifyPath = shared.config.get(
apiNotifyPath = BMConfigParser().get(
'bitmessagesettings', 'apinotifypath')
except:
apiNotifyPath = ''
@ -519,9 +522,9 @@ class objectProcessor(threading.Thread):
# Let us now check and see whether our receiving address is
# behaving as a mailing list
if shared.safeConfigGetBoolean(toAddress, 'mailinglist') and messageEncodingType != 0:
if BMConfigParser().safeGetBoolean(toAddress, 'mailinglist') and messageEncodingType != 0:
try:
mailingListName = shared.config.get(
mailingListName = BMConfigParser().get(
toAddress, 'mailinglistname')
except:
mailingListName = ''
@ -566,8 +569,8 @@ class objectProcessor(threading.Thread):
if self.ackDataHasAValidHeader(ackData) and \
not blockMessage and \
messageEncodingType != 0 and \
not shared.safeConfigGetBoolean(toAddress, 'dontsendack') and \
not shared.safeConfigGetBoolean(toAddress, 'chan'):
not BMConfigParser().safeGetBoolean(toAddress, 'dontsendack') and \
not BMConfigParser().safeGetBoolean(toAddress, 'chan'):
shared.checkAndShareObjectWithPeers(ackData[24:])
# Display timing data
@ -756,9 +759,9 @@ class objectProcessor(threading.Thread):
# If we are behaving as an API then we might need to run an
# outside command to let some program know that a new message
# has arrived.
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
if BMConfigParser().safeGetBoolean('bitmessagesettings', 'apienabled'):
try:
apiNotifyPath = shared.config.get(
apiNotifyPath = BMConfigParser().get(
'bitmessagesettings', 'apinotifypath')
except:
apiNotifyPath = ''
@ -780,8 +783,8 @@ class objectProcessor(threading.Thread):
# stream number, and RIPE hash.
status, addressVersion, streamNumber, ripe = decodeAddress(address)
if addressVersion <=3:
if address in shared.neededPubkeys:
del shared.neededPubkeys[address]
if address in neededPubkeys:
del neededPubkeys[address]
self.sendMessages(address)
else:
logger.debug('We don\'t need this pub key. We didn\'t ask for it. For address: %s' % address)
@ -791,8 +794,8 @@ class objectProcessor(threading.Thread):
elif addressVersion >= 4:
tag = hashlib.sha512(hashlib.sha512(encodeVarint(
addressVersion) + encodeVarint(streamNumber) + ripe).digest()).digest()[32:]
if tag in shared.neededPubkeys:
del shared.neededPubkeys[tag]
if tag in neededPubkeys:
del neededPubkeys[tag]
self.sendMessages(address)
def sendMessages(self, address):
@ -808,15 +811,15 @@ class objectProcessor(threading.Thread):
shared.workerQueue.put(('sendmessage', ''))
def ackDataHasAValidHeader(self, ackData):
if len(ackData) < shared.Header.size:
if len(ackData) < protocol.Header.size:
logger.info('The length of ackData is unreasonably short. Not sending ackData.')
return False
magic,command,payloadLength,checksum = shared.Header.unpack(ackData[:shared.Header.size])
magic,command,payloadLength,checksum = protocol.Header.unpack(ackData[:protocol.Header.size])
if magic != 0xE9BEB4D9:
logger.info('Ackdata magic bytes were wrong. Not sending ackData.')
return False
payload = ackData[shared.Header.size:]
payload = ackData[protocol.Header.size:]
if len(payload) != payloadLength:
logger.info('ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.')
return False

View File

@ -10,6 +10,7 @@ import tr
from class_sendDataThread import *
from class_receiveDataThread import *
from configparser import BMConfigParser
from helper_threading import *
# For each stream to which we connect, several outgoingSynSender threads
@ -45,12 +46,12 @@ class outgoingSynSender(threading.Thread, StoppableThread):
continue
priority = (183600 - (time.time() - shared.knownNodes[self.streamNumber][peer])) / 183600 # 2 days and 3 hours
shared.knownNodesLock.release()
if shared.config.get('bitmessagesettings', 'socksproxytype') != 'none':
if BMConfigParser().get('bitmessagesettings', 'socksproxytype') != 'none':
if peer.host.find(".onion") == -1:
priority /= 10 # hidden services have 10x priority over plain net
else:
# don't connect to self
if peer.host == shared.config.get('bitmessagesettings', 'onionhostname') and peer.port == shared.config.getint("bitmessagesettings", "onionport"):
if peer.host == BMConfigParser().get('bitmessagesettings', 'onionhostname') and peer.port == BMConfigParser().getint("bitmessagesettings", "onionport"):
continue
elif peer.host.find(".onion") != -1: # onion address and so proxy
continue
@ -72,9 +73,9 @@ class outgoingSynSender(threading.Thread, StoppableThread):
pass
def run(self):
while shared.safeConfigGetBoolean('bitmessagesettings', 'dontconnect') and not self._stopped:
while BMConfigParser().safeGetBoolean('bitmessagesettings', 'dontconnect') and not self._stopped:
self.stop.wait(2)
while shared.safeConfigGetBoolean('bitmessagesettings', 'sendoutgoingconnections') and not self._stopped:
while BMConfigParser().safeGetBoolean('bitmessagesettings', 'sendoutgoingconnections') and not self._stopped:
self.name = "outgoingSynSender"
maximumConnections = 1 if shared.trustedPeer else 8 # maximum number of outgoing connections = 8
while len(self.selfInitiatedConnections[self.streamNumber]) >= maximumConnections:
@ -110,8 +111,8 @@ class outgoingSynSender(threading.Thread, StoppableThread):
self.name = "outgoingSynSender-" + peer.host.replace(":", ".") # log parser field separator
address_family = socket.AF_INET
# Proxy IP is IPv6. Unlikely but possible
if shared.config.get('bitmessagesettings', 'socksproxytype') != 'none':
if ":" in shared.config.get('bitmessagesettings', 'sockshostname'):
if BMConfigParser().get('bitmessagesettings', 'socksproxytype') != 'none':
if ":" in BMConfigParser().get('bitmessagesettings', 'sockshostname'):
address_family = socket.AF_INET6
# No proxy, and destination is IPv6
elif peer.host.find(':') >= 0 :
@ -140,44 +141,44 @@ class outgoingSynSender(threading.Thread, StoppableThread):
# can rebind faster
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.settimeout(20)
if shared.config.get('bitmessagesettings', 'socksproxytype') == 'none' and shared.verbose >= 2:
if BMConfigParser().get('bitmessagesettings', 'socksproxytype') == 'none' and shared.verbose >= 2:
logger.debug('Trying an outgoing connection to ' + str(peer))
# sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
elif shared.config.get('bitmessagesettings', 'socksproxytype') == 'SOCKS4a':
elif BMConfigParser().get('bitmessagesettings', 'socksproxytype') == 'SOCKS4a':
if shared.verbose >= 2:
logger.debug ('(Using SOCKS4a) Trying an outgoing connection to ' + str(peer))
proxytype = socks.PROXY_TYPE_SOCKS4
sockshostname = shared.config.get(
sockshostname = BMConfigParser().get(
'bitmessagesettings', 'sockshostname')
socksport = shared.config.getint(
socksport = BMConfigParser().getint(
'bitmessagesettings', 'socksport')
rdns = True # Do domain name lookups through the proxy; though this setting doesn't really matter since we won't be doing any domain name lookups anyway.
if shared.config.getboolean('bitmessagesettings', 'socksauthentication'):
socksusername = shared.config.get(
if BMConfigParser().getboolean('bitmessagesettings', 'socksauthentication'):
socksusername = BMConfigParser().get(
'bitmessagesettings', 'socksusername')
sockspassword = shared.config.get(
sockspassword = BMConfigParser().get(
'bitmessagesettings', 'sockspassword')
self.sock.setproxy(
proxytype, sockshostname, socksport, rdns, socksusername, sockspassword)
else:
self.sock.setproxy(
proxytype, sockshostname, socksport, rdns)
elif shared.config.get('bitmessagesettings', 'socksproxytype') == 'SOCKS5':
elif BMConfigParser().get('bitmessagesettings', 'socksproxytype') == 'SOCKS5':
if shared.verbose >= 2:
logger.debug ('(Using SOCKS5) Trying an outgoing connection to ' + str(peer))
proxytype = socks.PROXY_TYPE_SOCKS5
sockshostname = shared.config.get(
sockshostname = BMConfigParser().get(
'bitmessagesettings', 'sockshostname')
socksport = shared.config.getint(
socksport = BMConfigParser().getint(
'bitmessagesettings', 'socksport')
rdns = True # Do domain name lookups through the proxy; though this setting doesn't really matter since we won't be doing any domain name lookups anyway.
if shared.config.getboolean('bitmessagesettings', 'socksauthentication'):
socksusername = shared.config.get(
if BMConfigParser().getboolean('bitmessagesettings', 'socksauthentication'):
socksusername = BMConfigParser().get(
'bitmessagesettings', 'socksusername')
sockspassword = shared.config.get(
sockspassword = BMConfigParser().get(
'bitmessagesettings', 'sockspassword')
self.sock.setproxy(
proxytype, sockshostname, socksport, rdns, socksusername, sockspassword)
@ -254,7 +255,7 @@ class outgoingSynSender(threading.Thread, StoppableThread):
except socks.Socks4Error as err:
logger.error('Socks4Error: ' + str(err))
except socket.error as err:
if shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS':
if BMConfigParser().get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS':
logger.error('Bitmessage MIGHT be having trouble connecting to the SOCKS server. ' + str(err))
else:
if shared.verbose >= 1:

View File

@ -23,12 +23,15 @@ from binascii import hexlify
#import highlevelcrypto
from addresses import *
from configparser import BMConfigParser
from class_objectHashHolder import objectHashHolder
from helper_generic import addDataPadding, isHostInPrivateIPRange
from helper_sql import sqlQuery
from debug import logger
import protocol
from inventory import Inventory
import tr
from version import softwareVersion
# This thread is created either by the synSenderThread(for outgoing
# connections) or the singleListenerThread(for incoming connections).
@ -59,7 +62,7 @@ class receiveDataThread(threading.Thread):
self.objectsThatWeHaveYetToGetFromThisPeer = {}
self.selfInitiatedConnections = selfInitiatedConnections
self.sendDataThreadQueue = sendDataThreadQueue # used to send commands and data to the sendDataThread
self.hostIdent = self.peer.port if ".onion" in shared.config.get('bitmessagesettings', 'onionhostname') and shared.checkSocksIP(self.peer.host) else self.peer.host
self.hostIdent = self.peer.port if ".onion" in BMConfigParser().get('bitmessagesettings', 'onionhostname') and protocol.checkSocksIP(self.peer.host) else self.peer.host
shared.connectedHostsList[
self.hostIdent] = 0 # The very fact that this receiveData thread exists shows that we are connected to the remote host. Let's add it to this list so that an outgoingSynSender thread doesn't try to connect to it.
self.connectionIsOrWasFullyEstablished = False # set to true after the remote node and I accept each other's version messages. This is needed to allow the user interface to accurately reflect the current number of connections.
@ -77,10 +80,10 @@ class receiveDataThread(threading.Thread):
logger.debug('receiveDataThread starting. ID ' + str(id(self)) + '. The size of the shared.connectedHostsList is now ' + str(len(shared.connectedHostsList)))
while True:
if shared.config.getint('bitmessagesettings', 'maxdownloadrate') == 0:
if BMConfigParser().getint('bitmessagesettings', 'maxdownloadrate') == 0:
downloadRateLimitBytes = float("inf")
else:
downloadRateLimitBytes = shared.config.getint('bitmessagesettings', 'maxdownloadrate') * 1000
downloadRateLimitBytes = BMConfigParser().getint('bitmessagesettings', 'maxdownloadrate') * 1000
with shared.receiveDataLock:
while shared.numberOfBytesReceivedLastSecond >= downloadRateLimitBytes:
if int(time.time()) == shared.lastTimeWeResetBytesReceived:
@ -93,9 +96,9 @@ class receiveDataThread(threading.Thread):
dataLen = len(self.data)
try:
ssl = False
if ((self.services & shared.NODE_SSL == shared.NODE_SSL) and
if ((self.services & protocol.NODE_SSL == protocol.NODE_SSL) and
self.connectionIsOrWasFullyEstablished and
shared.haveSSL(not self.initiatedConnection)):
protocol.haveSSL(not self.initiatedConnection)):
ssl = True
dataRecv = self.sslSock.recv(1024)
else:
@ -106,7 +109,7 @@ class receiveDataThread(threading.Thread):
except socket.timeout:
logger.error ('Timeout occurred waiting for data from ' + str(self.peer) + '. Closing receiveData thread. (ID: ' + str(id(self)) + ')')
break
except Exception as err:
except socket.error as err:
if err.errno == 2 or (sys.platform == 'win32' and err.errno == 10035) or (sys.platform != 'win32' and err.errno == errno.EWOULDBLOCK):
if ssl:
select.select([self.sslSock], [], [])
@ -165,25 +168,25 @@ class receiveDataThread(threading.Thread):
shared.UISignalQueue.put(('updateStatusBar', tr._translate("MainWindow", "The time on your computer, %1, may be wrong. Please verify your settings.").arg(datetime.datetime.now().strftime("%H:%M:%S"))))
def processData(self):
if len(self.data) < shared.Header.size: # if so little of the data has arrived that we can't even read the checksum then wait for more data.
if len(self.data) < protocol.Header.size: # if so little of the data has arrived that we can't even read the checksum then wait for more data.
return
magic,command,payloadLength,checksum = shared.Header.unpack(self.data[:shared.Header.size])
magic,command,payloadLength,checksum = protocol.Header.unpack(self.data[:protocol.Header.size])
if magic != 0xE9BEB4D9:
self.data = ""
return
if payloadLength > 1600100: # ~1.6 MB which is the maximum possible size of an inv message.
logger.info('The incoming message, which we have not yet download, is too large. Ignoring it. (unfortunately there is no way to tell the other node to stop sending it except to disconnect.) Message size: %s' % payloadLength)
self.data = self.data[payloadLength + shared.Header.size:]
self.data = self.data[payloadLength + protocol.Header.size:]
del magic,command,payloadLength,checksum # we don't need these anymore and better to clean them now before the recursive call rather than after
self.processData()
return
if len(self.data) < payloadLength + shared.Header.size: # check if the whole message has arrived yet.
if len(self.data) < payloadLength + protocol.Header.size: # check if the whole message has arrived yet.
return
payload = self.data[shared.Header.size:payloadLength + shared.Header.size]
payload = self.data[protocol.Header.size:payloadLength + protocol.Header.size]
if checksum != hashlib.sha512(payload).digest()[0:4]: # test the checksum in the message.
logger.error('Checksum incorrect. Clearing this message.')
self.data = self.data[payloadLength + shared.Header.size:]
self.data = self.data[payloadLength + protocol.Header.size:]
del magic,command,payloadLength,checksum,payload # better to clean up before the recursive call
self.processData()
return
@ -227,7 +230,7 @@ class receiveDataThread(threading.Thread):
logger.critical("Critical error in a receiveDataThread: \n%s" % traceback.format_exc())
del payload
self.data = self.data[payloadLength + shared.Header.size:] # take this message out and then process the next message
self.data = self.data[payloadLength + protocol.Header.size:] # take this message out and then process the next message
if self.data == '': # if there are no more messages
while len(self.objectsThatWeHaveYetToGetFromThisPeer) > 0:
@ -267,7 +270,7 @@ class receiveDataThread(threading.Thread):
def sendpong(self):
logger.debug('Sending pong')
self.sendDataThreadQueue.put((0, 'sendRawData', shared.CreatePacket('pong')))
self.sendDataThreadQueue.put((0, 'sendRawData', protocol.CreatePacket('pong')))
def recverack(self):
@ -285,8 +288,8 @@ class receiveDataThread(threading.Thread):
shared.timeOffsetWrongCount = 0
self.sslSock = self.sock
if ((self.services & shared.NODE_SSL == shared.NODE_SSL) and
shared.haveSSL(not self.initiatedConnection)):
if ((self.services & protocol.NODE_SSL == protocol.NODE_SSL) and
protocol.haveSSL(not self.initiatedConnection)):
logger.debug("Initialising TLS")
self.sslSock = ssl.wrap_socket(self.sock, keyfile = os.path.join(shared.codePath(), 'sslkeys', 'key.pem'), certfile = os.path.join(shared.codePath(), 'sslkeys', 'cert.pem'), server_side = not self.initiatedConnection, ssl_version=ssl.PROTOCOL_TLSv1, do_handshake_on_connect=False, ciphers='AECDH-AES256-SHA')
if hasattr(self.sslSock, "context"):
@ -361,7 +364,7 @@ class receiveDataThread(threading.Thread):
def sendinvMessageToJustThisOnePeer(self, numberOfObjects, payload):
payload = encodeVarint(numberOfObjects) + payload
logger.debug('Sending huge inv message with ' + str(numberOfObjects) + ' objects to just this one peer')
self.sendDataThreadQueue.put((0, 'sendRawData', shared.CreatePacket('inv', payload)))
self.sendDataThreadQueue.put((0, 'sendRawData', protocol.CreatePacket('inv', payload)))
def _sleepForTimingAttackMitigation(self, sleepTime):
# We don't need to do the timing attack mitigation if we are
@ -471,7 +474,7 @@ class receiveDataThread(threading.Thread):
def sendgetdata(self, hash):
logger.debug('sending getdata to retrieve object with hash: ' + hexlify(hash))
payload = '\x01' + hash
self.sendDataThreadQueue.put((0, 'sendRawData', shared.CreatePacket('getdata', payload)))
self.sendDataThreadQueue.put((0, 'sendRawData', protocol.CreatePacket('getdata', payload)))
# We have received a getdata request from our peer
@ -499,7 +502,7 @@ class receiveDataThread(threading.Thread):
# Our peer has requested (in a getdata message) that we send an object.
def sendObject(self, payload):
logger.debug('sending an object.')
self.sendDataThreadQueue.put((0, 'sendRawData', shared.CreatePacket('object',payload)))
self.sendDataThreadQueue.put((0, 'sendRawData', protocol.CreatePacket('object',payload)))
def _checkIPAddress(self, host):
if host[0:12] == '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF':
@ -622,15 +625,15 @@ class receiveDataThread(threading.Thread):
sentOwn = False
for i in range(500):
# if current connection is over a proxy, sent our own onion address at a random position
if ownPosition == i and ".onion" in shared.config.get("bitmessagesettings", "onionhostname") and \
if ownPosition == i and ".onion" in BMConfigParser().get("bitmessagesettings", "onionhostname") and \
hasattr(self.sock, "getproxytype") and self.sock.getproxytype() != "none" and not sentOwn:
peer = shared.Peer(shared.config.get("bitmessagesettings", "onionhostname"), shared.config.getint("bitmessagesettings", "onionport"))
peer = shared.Peer(BMConfigParser().get("bitmessagesettings", "onionhostname"), BMConfigParser().getint("bitmessagesettings", "onionport"))
else:
# still may contain own onion address, but we don't change it
peer, = random.sample(shared.knownNodes[self.streamNumber], 1)
if isHostInPrivateIPRange(peer.host):
continue
if peer.host == shared.config.get("bitmessagesettings", "onionhostname") and peer.port == shared.config.getint("bitmessagesettings", "onionport") :
if peer.host == BMConfigParser().get("bitmessagesettings", "onionhostname") and peer.port == BMConfigParser().getint("bitmessagesettings", "onionport") :
sentOwn = True
addrsInMyStream[peer] = shared.knownNodes[
self.streamNumber][peer]
@ -662,7 +665,7 @@ class receiveDataThread(threading.Thread):
payload += pack('>I', self.streamNumber)
payload += pack(
'>q', 1) # service bit flags offered by this node
payload += shared.encodeHost(HOST)
payload += protocol.encodeHost(HOST)
payload += pack('>H', PORT) # remote port
for (HOST, PORT), value in addrsInChildStreamLeft.items():
timeLastReceivedMessageFromThisNode = value
@ -673,7 +676,7 @@ class receiveDataThread(threading.Thread):
payload += pack('>I', self.streamNumber * 2)
payload += pack(
'>q', 1) # service bit flags offered by this node
payload += shared.encodeHost(HOST)
payload += protocol.encodeHost(HOST)
payload += pack('>H', PORT) # remote port
for (HOST, PORT), value in addrsInChildStreamRight.items():
timeLastReceivedMessageFromThisNode = value
@ -684,11 +687,11 @@ class receiveDataThread(threading.Thread):
payload += pack('>I', (self.streamNumber * 2) + 1)
payload += pack(
'>q', 1) # service bit flags offered by this node
payload += shared.encodeHost(HOST)
payload += protocol.encodeHost(HOST)
payload += pack('>H', PORT) # remote port
payload = encodeVarint(numberOfAddressesInAddrMessage) + payload
self.sendDataThreadQueue.put((0, 'sendRawData', shared.CreatePacket('addr', payload)))
self.sendDataThreadQueue.put((0, 'sendRawData', protocol.CreatePacket('addr', payload)))
# We have received a version message
@ -714,14 +717,14 @@ class receiveDataThread(threading.Thread):
timestamp, = unpack('>Q', data[12:20])
timeOffset = timestamp - int(time.time())
if timeOffset > 3600:
self.sendDataThreadQueue.put((0, 'sendRawData', shared.assembleErrorMessage(fatal=2, errorText="Your time is too far in the future compared to mine. Closing connection.")))
self.sendDataThreadQueue.put((0, 'sendRawData', protocol.assembleErrorMessage(fatal=2, errorText="Your time is too far in the future compared to mine. Closing connection.")))
logger.info("%s's time is too far in the future (%s seconds). Closing connection to it." % (self.peer, timeOffset))
shared.timeOffsetWrongCount += 1
time.sleep(2)
self.sendDataThreadQueue.put((0, 'shutdown','no data'))
return
elif timeOffset < -3600:
self.sendDataThreadQueue.put((0, 'sendRawData', shared.assembleErrorMessage(fatal=2, errorText="Your time is too far in the past compared to mine. Closing connection.")))
self.sendDataThreadQueue.put((0, 'sendRawData', protocol.assembleErrorMessage(fatal=2, errorText="Your time is too far in the past compared to mine. Closing connection.")))
logger.info("%s's time is too far in the past (timeOffset %s seconds). Closing connection to it." % (self.peer, timeOffset))
shared.timeOffsetWrongCount += 1
time.sleep(2)
@ -747,7 +750,7 @@ class receiveDataThread(threading.Thread):
userAgentName = useragent
userAgentVersion = "0.0.0"
if userAgentName == "PyBitmessage":
myVersion = [int(n) for n in shared.softwareVersion.split(".")]
myVersion = [int(n) for n in softwareVersion.split(".")]
try:
remoteVersion = [int(n) for n in userAgentVersion.split(".")]
except:
@ -778,7 +781,7 @@ class receiveDataThread(threading.Thread):
# doesn't know the stream. We have to set it.
if not self.initiatedConnection:
self.sendDataThreadQueue.put((0, 'setStreamNumber', self.streamNumber))
if data[72:80] == shared.eightBytesOfRandomDataUsedToDetectConnectionsToSelf:
if data[72:80] == protocol.eightBytesOfRandomDataUsedToDetectConnectionsToSelf:
self.sendDataThreadQueue.put((0, 'shutdown','no data'))
logger.debug('Closing connection to myself: ' + str(self.peer))
return
@ -801,14 +804,14 @@ class receiveDataThread(threading.Thread):
# Sends a version message
def sendversion(self):
logger.debug('Sending version message')
self.sendDataThreadQueue.put((0, 'sendRawData', shared.assembleVersionMessage(
self.sendDataThreadQueue.put((0, 'sendRawData', protocol.assembleVersionMessage(
self.peer.host, self.peer.port, self.streamNumber, not self.initiatedConnection)))
# Sends a verack message
def sendverack(self):
logger.debug('Sending verack')
self.sendDataThreadQueue.put((0, 'sendRawData', shared.CreatePacket('verack')))
self.sendDataThreadQueue.put((0, 'sendRawData', protocol.CreatePacket('verack')))
self.verackSent = True
if self.verackReceived:
self.connectionFullyEstablished()

View File

@ -8,10 +8,12 @@ import random
import sys
import socket
from configparser import BMConfigParser
from helper_generic import addDataPadding
from class_objectHashHolder import *
from addresses import *
from debug import logger
import protocol
# Every connection to a peer has a sendDataThread (and also a
# receiveDataThread).
@ -53,7 +55,7 @@ class sendDataThread(threading.Thread):
def sendVersionMessage(self):
datatosend = shared.assembleVersionMessage(
datatosend = protocol.assembleVersionMessage(
self.peer.host, self.peer.port, self.streamNumber, not self.initiatedConnection) # the IP and port of the remote host, and my streamNumber.
logger.debug('Sending version packet: ' + repr(datatosend))
@ -67,10 +69,10 @@ class sendDataThread(threading.Thread):
self.versionSent = 1
def sendBytes(self, data):
if shared.config.getint('bitmessagesettings', 'maxuploadrate') == 0:
if BMConfigParser().getint('bitmessagesettings', 'maxuploadrate') == 0:
uploadRateLimitBytes = 999999999 # float("inf") doesn't work
else:
uploadRateLimitBytes = shared.config.getint('bitmessagesettings', 'maxuploadrate') * 1000
uploadRateLimitBytes = BMConfigParser().getint('bitmessagesettings', 'maxuploadrate') * 1000
with shared.sendDataLock:
while data:
while shared.numberOfBytesSentLastSecond >= uploadRateLimitBytes:
@ -83,11 +85,11 @@ class sendDataThread(threading.Thread):
# If the user raises or lowers the uploadRateLimit then we should make use of
# the new setting. If we are hitting the limit then we'll check here about
# once per second.
if shared.config.getint('bitmessagesettings', 'maxuploadrate') == 0:
if BMConfigParser().getint('bitmessagesettings', 'maxuploadrate') == 0:
uploadRateLimitBytes = 999999999 # float("inf") doesn't work
else:
uploadRateLimitBytes = shared.config.getint('bitmessagesettings', 'maxuploadrate') * 1000
if ((self.services & shared.NODE_SSL == shared.NODE_SSL) and
uploadRateLimitBytes = BMConfigParser().getint('bitmessagesettings', 'maxuploadrate') * 1000
if ((self.services & protocol.NODE_SSL == protocol.NODE_SSL) and
self.connectionIsOrWasFullyEstablished and
shared.haveSSL(not self.initiatedConnection)):
amountSent = self.sslSock.send(data[:1000])
@ -134,11 +136,11 @@ class sendDataThread(threading.Thread):
payload += pack('>I', streamNumber)
payload += pack(
'>q', services) # service bit flags offered by this node
payload += shared.encodeHost(host)
payload += protocol.encodeHost(host)
payload += pack('>H', port)
payload = encodeVarint(numberOfAddressesInAddrMessage) + payload
packet = shared.CreatePacket('addr', payload)
packet = protocol.CreatePacket('addr', payload)
try:
self.sendBytes(packet)
except:
@ -154,7 +156,7 @@ class sendDataThread(threading.Thread):
payload += hash
if payload != '':
payload = encodeVarint(len(payload)/32) + payload
packet = shared.CreatePacket('inv', payload)
packet = protocol.CreatePacket('inv', payload)
try:
self.sendBytes(packet)
except:
@ -165,7 +167,7 @@ class sendDataThread(threading.Thread):
if self.lastTimeISentData < (int(time.time()) - 298):
# Send out a pong message to keep the connection alive.
logger.debug('Sending pong to ' + str(self.peer) + ' to keep connection alive.')
packet = shared.CreatePacket('pong')
packet = protocol.CreatePacket('pong')
try:
self.sendBytes(packet)
except:

View File

@ -6,10 +6,12 @@ import os
import pickle
import tr#anslate
from configparser import BMConfigParser
from helper_sql import *
from helper_threading import *
from inventory import Inventory
from debug import logger
from state import neededPubkeys
"""
The singleCleaner class is a timer-driven thread that cleans data structures
@ -40,7 +42,7 @@ class singleCleaner(threading.Thread, StoppableThread):
def run(self):
timeWeLastClearedInventoryAndPubkeysTables = 0
try:
shared.maximumLengthOfTimeToBotherResendingMessages = (float(shared.config.get('bitmessagesettings', 'stopresendingafterxdays')) * 24 * 60 * 60) + (float(shared.config.get('bitmessagesettings', 'stopresendingafterxmonths')) * (60 * 60 * 24 *365)/12)
shared.maximumLengthOfTimeToBotherResendingMessages = (float(BMConfigParser().get('bitmessagesettings', 'stopresendingafterxdays')) * 24 * 60 * 60) + (float(BMConfigParser().get('bitmessagesettings', 'stopresendingafterxmonths')) * (60 * 60 * 24 *365)/12)
except:
# Either the user hasn't set stopresendingafterxdays and stopresendingafterxmonths yet or the options are missing from the config file.
shared.maximumLengthOfTimeToBotherResendingMessages = float('inf')
@ -56,7 +58,7 @@ class singleCleaner(threading.Thread, StoppableThread):
# If we are running as a daemon then we are going to fill up the UI
# queue which will never be handled by a UI. We should clear it to
# save memory.
if shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'):
if BMConfigParser().safeGetBoolean('bitmessagesettings', 'daemon'):
shared.UISignalQueue.queue.clear()
if timeWeLastClearedInventoryAndPubkeysTables < int(time.time()) - 7380:
timeWeLastClearedInventoryAndPubkeysTables = int(time.time())
@ -114,8 +116,8 @@ class singleCleaner(threading.Thread, StoppableThread):
def resendPubkeyRequest(address):
logger.debug('It has been a long time and we haven\'t heard a response to our getpubkey request. Sending again.')
try:
del shared.neededPubkeys[
address] # We need to take this entry out of the shared.neededPubkeys structure because the shared.workerQueue checks to see whether the entry is already present and will not do the POW and send the message because it assumes that it has already done it recently.
del neededPubkeys[
address] # We need to take this entry out of the neededPubkeys structure because the shared.workerQueue checks to see whether the entry is already present and will not do the POW and send the message because it assumes that it has already done it recently.
except:
pass

View File

@ -1,10 +1,12 @@
import threading
import shared
import socket
from configparser import BMConfigParser
from class_sendDataThread import *
from class_receiveDataThread import *
import helper_bootstrap
from helper_threading import *
import protocol
import errno
import re
@ -28,9 +30,9 @@ class singleListener(threading.Thread, StoppableThread):
def _createListenSocket(self, family):
HOST = '' # Symbolic name meaning all available interfaces
# If not sockslisten, but onionhostname defined, only listen on localhost
if not shared.safeConfigGetBoolean('bitmessagesettings', 'sockslisten') and ".onion" in shared.config.get('bitmessagesettings', 'onionhostname'):
HOST = shared.config.get('bitmessagesettings', 'onionbindip')
PORT = shared.config.getint('bitmessagesettings', 'port')
if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'sockslisten') and ".onion" in BMConfigParser().get('bitmessagesettings', 'onionhostname'):
HOST = BMConfigParser().get('bitmessagesettings', 'onionbindip')
PORT = BMConfigParser().getint('bitmessagesettings', 'port')
sock = socket.socket(family, socket.SOCK_STREAM)
if family == socket.AF_INET6:
# Make sure we can accept both IPv4 and IPv6 connections.
@ -46,9 +48,9 @@ class singleListener(threading.Thread, StoppableThread):
def stopThread(self):
super(singleListener, self).stopThread()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
for ip in ('127.0.0.1', shared.config.get('bitmessagesettings', 'onionbindip')):
for ip in ('127.0.0.1', BMConfigParser().get('bitmessagesettings', 'onionbindip')):
try:
s.connect((ip, shared.config.getint('bitmessagesettings', 'port')))
s.connect((ip, BMConfigParser().getint('bitmessagesettings', 'port')))
s.shutdown(socket.SHUT_RDWR)
s.close()
break
@ -61,7 +63,7 @@ class singleListener(threading.Thread, StoppableThread):
if shared.trustedPeer:
return
while shared.safeConfigGetBoolean('bitmessagesettings', 'dontconnect') and shared.shutdown == 0:
while BMConfigParser().safeGetBoolean('bitmessagesettings', 'dontconnect') and shared.shutdown == 0:
self.stop.wait(1)
helper_bootstrap.dns()
# We typically don't want to accept incoming connections if the user is using a
@ -69,9 +71,9 @@ class singleListener(threading.Thread, StoppableThread):
# proxy 'none' or configure SOCKS listening then this will start listening for
# connections. But if on SOCKS and have an onionhostname, listen
# (socket is then only opened for localhost)
while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and \
(not shared.config.getboolean('bitmessagesettings', 'sockslisten') and \
".onion" not in shared.config.get('bitmessagesettings', 'onionhostname')) and \
while BMConfigParser().get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and \
(not BMConfigParser().getboolean('bitmessagesettings', 'sockslisten') and \
".onion" not in BMConfigParser().get('bitmessagesettings', 'onionhostname')) and \
shared.shutdown == 0:
self.stop.wait(5)
@ -100,7 +102,7 @@ class singleListener(threading.Thread, StoppableThread):
# SOCKS proxy, unless they have configured otherwise. If they eventually select
# proxy 'none' or configure SOCKS listening then this will start listening for
# connections.
while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and not shared.config.getboolean('bitmessagesettings', 'sockslisten') and ".onion" not in shared.config.get('bitmessagesettings', 'onionhostname') and shared.shutdown == 0:
while BMConfigParser().get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and not BMConfigParser().getboolean('bitmessagesettings', 'sockslisten') and ".onion" not in BMConfigParser().get('bitmessagesettings', 'onionhostname') and shared.shutdown == 0:
self.stop.wait(10)
while len(shared.connectedHostsList) > 220 and shared.shutdown == 0:
logger.info('We are connected to too many people. Not accepting further incoming connections for ten seconds.')
@ -123,7 +125,7 @@ class singleListener(threading.Thread, StoppableThread):
# share the same external IP. This is here to prevent
# connection flooding.
# permit repeated connections from Tor
if HOST in shared.connectedHostsList and (".onion" not in shared.config.get('bitmessagesettings', 'onionhostname') or not shared.checkSocksIP(HOST)):
if HOST in shared.connectedHostsList and (".onion" not in BMConfigParser().get('bitmessagesettings', 'onionhostname') or not protocol.checkSocksIP(HOST)):
socketObject.close()
logger.info('We are already connected to ' + str(HOST) + '. Ignoring connection.')
else:

View File

@ -11,6 +11,7 @@ import highlevelcrypto
import proofofwork
import sys
import tr
from configparser import BMConfigParser
from debug import logger
from helper_sql import *
import helper_inbox
@ -19,7 +20,8 @@ import helper_msgcoding
from helper_threading import *
from inventory import Inventory
import l10n
from protocol import *
import protocol
from state import neededPubkeys
from binascii import hexlify, unhexlify
# This thread, of which there is only one, does the heavy lifting:
@ -55,13 +57,13 @@ class singleWorker(threading.Thread, StoppableThread):
toAddress, = row
toStatus, toAddressVersionNumber, toStreamNumber, toRipe = decodeAddress(toAddress)
if toAddressVersionNumber <= 3 :
shared.neededPubkeys[toAddress] = 0
neededPubkeys[toAddress] = 0
elif toAddressVersionNumber >= 4:
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(encodeVarint(
toAddressVersionNumber) + encodeVarint(toStreamNumber) + toRipe).digest()).digest()
privEncryptionKey = doubleHashOfAddressData[:32] # Note that this is the first half of the sha512 hash.
tag = doubleHashOfAddressData[32:]
shared.neededPubkeys[tag] = (toAddress, highlevelcrypto.makeCryptor(hexlify(privEncryptionKey))) # We'll need this for when we receive a pubkey reply: it will be encrypted and we'll need to decrypt it.
neededPubkeys[tag] = (toAddress, highlevelcrypto.makeCryptor(hexlify(privEncryptionKey))) # We'll need this for when we receive a pubkey reply: it will be encrypted and we'll need to decrypt it.
# Initialize the shared.ackdataForWhichImWatching data structure
queryreturn = sqlQuery(
@ -139,12 +141,12 @@ class singleWorker(threading.Thread, StoppableThread):
payload += '\x00\x00\x00\x01' # object type: pubkey
payload += encodeVarint(addressVersionNumber) # Address version number
payload += encodeVarint(streamNumber)
payload += getBitfield(myAddress) # bitfield of features supported by me (see the wiki).
payload += protocol.getBitfield(myAddress) # bitfield of features supported by me (see the wiki).
try:
privSigningKeyBase58 = shared.config.get(
privSigningKeyBase58 = BMConfigParser().get(
myAddress, 'privsigningkey')
privEncryptionKeyBase58 = shared.config.get(
privEncryptionKeyBase58 = BMConfigParser().get(
myAddress, 'privencryptionkey')
except Exception as err:
logger.error('Error within doPOWForMyV2Pubkey. Could not read the keys from the keys.dat file for a requested address. %s\n' % err)
@ -181,7 +183,7 @@ class singleWorker(threading.Thread, StoppableThread):
streamNumber, 'advertiseobject', inventoryHash))
shared.UISignalQueue.put(('updateStatusBar', ''))
try:
shared.config.set(
BMConfigParser().set(
myAddress, 'lastpubkeysendtime', str(int(time.time())))
shared.writeKeysFile()
except:
@ -199,7 +201,7 @@ class singleWorker(threading.Thread, StoppableThread):
except:
#The address has been deleted.
return
if shared.safeConfigGetBoolean(myAddress, 'chan'):
if BMConfigParser().safeGetBoolean(myAddress, 'chan'):
logger.info('This is a chan address. Not sending pubkey.')
return
status, addressVersionNumber, streamNumber, hash = decodeAddress(
@ -219,12 +221,12 @@ class singleWorker(threading.Thread, StoppableThread):
payload += '\x00\x00\x00\x01' # object type: pubkey
payload += encodeVarint(addressVersionNumber) # Address version number
payload += encodeVarint(streamNumber)
payload += getBitfield(myAddress) # bitfield of features supported by me (see the wiki).
payload += protocol.getBitfield(myAddress) # bitfield of features supported by me (see the wiki).
try:
privSigningKeyBase58 = shared.config.get(
privSigningKeyBase58 = BMConfigParser().get(
myAddress, 'privsigningkey')
privEncryptionKeyBase58 = shared.config.get(
privEncryptionKeyBase58 = BMConfigParser().get(
myAddress, 'privencryptionkey')
except Exception as err:
logger.error('Error within sendOutOrStoreMyV3Pubkey. Could not read the keys from the keys.dat file for a requested address. %s\n' % err)
@ -243,9 +245,9 @@ class singleWorker(threading.Thread, StoppableThread):
payload += pubSigningKey[1:]
payload += pubEncryptionKey[1:]
payload += encodeVarint(shared.config.getint(
payload += encodeVarint(BMConfigParser().getint(
myAddress, 'noncetrialsperbyte'))
payload += encodeVarint(shared.config.getint(
payload += encodeVarint(BMConfigParser().getint(
myAddress, 'payloadlengthextrabytes'))
signature = highlevelcrypto.sign(payload, privSigningKeyHex)
@ -271,7 +273,7 @@ class singleWorker(threading.Thread, StoppableThread):
streamNumber, 'advertiseobject', inventoryHash))
shared.UISignalQueue.put(('updateStatusBar', ''))
try:
shared.config.set(
BMConfigParser().set(
myAddress, 'lastpubkeysendtime', str(int(time.time())))
shared.writeKeysFile()
except:
@ -282,10 +284,10 @@ class singleWorker(threading.Thread, StoppableThread):
# If this isn't a chan address, this function assembles the pubkey data,
# does the necessary POW and sends it out.
def sendOutOrStoreMyV4Pubkey(self, myAddress):
if not shared.config.has_section(myAddress):
if not BMConfigParser().has_section(myAddress):
#The address has been deleted.
return
if shared.safeConfigGetBoolean(myAddress, 'chan'):
if shared.BMConfigParser().safeGetBoolean(myAddress, 'chan'):
logger.info('This is a chan address. Not sending pubkey.')
return
status, addressVersionNumber, streamNumber, hash = decodeAddress(
@ -297,12 +299,12 @@ class singleWorker(threading.Thread, StoppableThread):
payload += '\x00\x00\x00\x01' # object type: pubkey
payload += encodeVarint(addressVersionNumber) # Address version number
payload += encodeVarint(streamNumber)
dataToEncrypt = getBitfield(myAddress)
dataToEncrypt = protocol.getBitfield(myAddress)
try:
privSigningKeyBase58 = shared.config.get(
privSigningKeyBase58 = BMConfigParser().get(
myAddress, 'privsigningkey')
privEncryptionKeyBase58 = shared.config.get(
privEncryptionKeyBase58 = BMConfigParser().get(
myAddress, 'privencryptionkey')
except Exception as err:
logger.error('Error within sendOutOrStoreMyV4Pubkey. Could not read the keys from the keys.dat file for a requested address. %s\n' % err)
@ -319,9 +321,9 @@ class singleWorker(threading.Thread, StoppableThread):
dataToEncrypt += pubSigningKey[1:]
dataToEncrypt += pubEncryptionKey[1:]
dataToEncrypt += encodeVarint(shared.config.getint(
dataToEncrypt += encodeVarint(BMConfigParser().getint(
myAddress, 'noncetrialsperbyte'))
dataToEncrypt += encodeVarint(shared.config.getint(
dataToEncrypt += encodeVarint(BMConfigParser().getint(
myAddress, 'payloadlengthextrabytes'))
# When we encrypt, we'll use a hash of the data
@ -361,7 +363,7 @@ class singleWorker(threading.Thread, StoppableThread):
streamNumber, 'advertiseobject', inventoryHash))
shared.UISignalQueue.put(('updateStatusBar', ''))
try:
shared.config.set(
BMConfigParser().set(
myAddress, 'lastpubkeysendtime', str(int(time.time())))
shared.writeKeysFile()
except Exception as err:
@ -384,9 +386,9 @@ class singleWorker(threading.Thread, StoppableThread):
# We need to convert our private keys to public keys in order
# to include them.
try:
privSigningKeyBase58 = shared.config.get(
privSigningKeyBase58 = BMConfigParser().get(
fromaddress, 'privsigningkey')
privEncryptionKeyBase58 = shared.config.get(
privEncryptionKeyBase58 = BMConfigParser().get(
fromaddress, 'privencryptionkey')
except:
shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (
@ -432,12 +434,12 @@ class singleWorker(threading.Thread, StoppableThread):
dataToEncrypt = encodeVarint(addressVersionNumber)
dataToEncrypt += encodeVarint(streamNumber)
dataToEncrypt += getBitfield(fromaddress) # behavior bitfield
dataToEncrypt += protocol.getBitfield(fromaddress) # behavior bitfield
dataToEncrypt += pubSigningKey[1:]
dataToEncrypt += pubEncryptionKey[1:]
if addressVersionNumber >= 3:
dataToEncrypt += encodeVarint(shared.config.getint(fromaddress,'noncetrialsperbyte'))
dataToEncrypt += encodeVarint(shared.config.getint(fromaddress,'payloadlengthextrabytes'))
dataToEncrypt += encodeVarint(BMConfigParser().getint(fromaddress,'noncetrialsperbyte'))
dataToEncrypt += encodeVarint(BMConfigParser().getint(fromaddress,'payloadlengthextrabytes'))
dataToEncrypt += encodeVarint(encoding) # message encoding type
encodedMessage = helper_msgcoding.MsgEncode({"subject": subject, "body": body}, encoding)
dataToEncrypt += encodeVarint(encodedMessage.length)
@ -525,7 +527,7 @@ class singleWorker(threading.Thread, StoppableThread):
# so let's assume that we have it.
pass
# If we are sending a message to ourselves or a chan then we won't need an entry in the pubkeys table; we can calculate the needed pubkey using the private keys in our keys.dat file.
elif shared.config.has_section(toaddress):
elif BMConfigParser().has_section(toaddress):
sqlExecute(
'''UPDATE sent SET status='doingmsgpow' WHERE toaddress=? AND status='msgqueued' ''',
toaddress)
@ -551,7 +553,7 @@ class singleWorker(threading.Thread, StoppableThread):
toTag = ''
else:
toTag = hashlib.sha512(hashlib.sha512(encodeVarint(toAddressVersionNumber)+encodeVarint(toStreamNumber)+toRipe).digest()).digest()[32:]
if toaddress in shared.neededPubkeys or toTag in shared.neededPubkeys:
if toaddress in neededPubkeys or toTag in neededPubkeys:
# We already sent a request for the pubkey
sqlExecute(
'''UPDATE sent SET status='awaitingpubkey', sleeptill=? WHERE toaddress=? AND status='msgqueued' ''',
@ -575,7 +577,7 @@ class singleWorker(threading.Thread, StoppableThread):
toAddressVersionNumber) + encodeVarint(toStreamNumber) + toRipe).digest()).digest()
privEncryptionKey = doubleHashOfToAddressData[:32] # The first half of the sha512 hash.
tag = doubleHashOfToAddressData[32:] # The second half of the sha512 hash.
shared.neededPubkeys[tag] = (toaddress, highlevelcrypto.makeCryptor(hexlify(privEncryptionKey)))
neededPubkeys[tag] = (toaddress, highlevelcrypto.makeCryptor(hexlify(privEncryptionKey)))
for value in Inventory().by_type_and_tag(1, toTag):
if shared.decryptAndCheckPubkeyPayload(value.payload, toaddress) == 'successful': #if valid, this function also puts it in the pubkeys table.
@ -583,7 +585,7 @@ class singleWorker(threading.Thread, StoppableThread):
sqlExecute(
'''UPDATE sent SET status='doingmsgpow', retrynumber=0 WHERE toaddress=? AND (status='msgqueued' or status='awaitingpubkey' or status='doingpubkeypow')''',
toaddress)
del shared.neededPubkeys[tag]
del neededPubkeys[tag]
break
#else: # There was something wrong with this pubkey object even
# though it had the correct tag- almost certainly because
@ -609,7 +611,7 @@ class singleWorker(threading.Thread, StoppableThread):
TTL = int(TTL + random.randrange(-300, 300))# add some randomness to the TTL
embeddedTime = int(time.time() + TTL)
if not shared.config.has_section(toaddress): # if we aren't sending this to ourselves or a chan
if not BMConfigParser().has_section(toaddress): # if we aren't sending this to ourselves or a chan
shared.ackdataForWhichImWatching[ackdata] = 0
shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (
ackdata, tr._translate("MainWindow", "Looking up the receiver\'s public key"))))
@ -643,7 +645,7 @@ class singleWorker(threading.Thread, StoppableThread):
# unencrypted. Before we actually do it the sending human must check a box
# in the settings menu to allow it.
if shared.isBitSetWithinBitfield(behaviorBitfield,30): # if receiver is a mobile device who expects that their address RIPE is included unencrypted on the front of the message..
if not shared.safeConfigGetBoolean('bitmessagesettings','willinglysendtomobile'): # if we are Not willing to include the receiver's RIPE hash on the message..
if not shared.BMConfigParser().safeGetBoolean('bitmessagesettings','willinglysendtomobile'): # if we are Not willing to include the receiver's RIPE hash on the message..
logger.info('The receiver is a mobile user but the sender (you) has not selected that you are willing to send to mobiles. Aborting send.')
shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,tr._translate("MainWindow",'Problem: Destination is a mobile device who requests that the destination be included in the message but this is disallowed in your settings. %1').arg(l10n.formatTimestamp()))))
# if the human changes their setting and then sends another message or restarts their client, this one will send at that time.
@ -676,7 +678,7 @@ class singleWorker(threading.Thread, StoppableThread):
shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, tr._translate("MainWindow", "Doing work necessary to send message.\nReceiver\'s required difficulty: %1 and %2").arg(str(float(
requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte)).arg(str(float(requiredPayloadLengthExtraBytes) / shared.networkDefaultPayloadLengthExtraBytes)))))
if status != 'forcepow':
if (requiredAverageProofOfWorkNonceTrialsPerByte > shared.config.getint('bitmessagesettings', 'maxacceptablenoncetrialsperbyte') and shared.config.getint('bitmessagesettings', 'maxacceptablenoncetrialsperbyte') != 0) or (requiredPayloadLengthExtraBytes > shared.config.getint('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes') and shared.config.getint('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes') != 0):
if (requiredAverageProofOfWorkNonceTrialsPerByte > BMConfigParser().getint('bitmessagesettings', 'maxacceptablenoncetrialsperbyte') and BMConfigParser().getint('bitmessagesettings', 'maxacceptablenoncetrialsperbyte') != 0) or (requiredPayloadLengthExtraBytes > BMConfigParser().getint('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes') and BMConfigParser().getint('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes') != 0):
# The demanded difficulty is more than we are willing
# to do.
sqlExecute(
@ -688,10 +690,10 @@ class singleWorker(threading.Thread, StoppableThread):
else: # if we are sending a message to ourselves or a chan..
logger.info('Sending a message.')
logger.debug('First 150 characters of message: ' + repr(message[:150]))
behaviorBitfield = getBitfield(fromaddress)
behaviorBitfield = protocol.getBitfield(fromaddress)
try:
privEncryptionKeyBase58 = shared.config.get(
privEncryptionKeyBase58 = BMConfigParser().get(
toaddress, 'privencryptionkey')
except Exception as err:
shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,tr._translate("MainWindow",'Problem: You are trying to send a message to yourself or a chan but your encryption key could not be found in the keys.dat file. Could not encrypt message. %1').arg(l10n.formatTimestamp()))))
@ -709,14 +711,15 @@ class singleWorker(threading.Thread, StoppableThread):
# Now we can start to assemble our message.
payload = encodeVarint(fromAddressVersionNumber)
payload += encodeVarint(fromStreamNumber)
payload += getBitfield(fromaddress) # Bitfield of features and behaviors that can be expected from me. (See https://bitmessage.org/wiki/Protocol_specification#Pubkey_bitfield_features )
payload += protocol.getBitfield(fromaddress) # Bitfield of features and behaviors that can be expected from me. (See https://bitmessage.org/wiki/Protocol_specification#Pubkey_bitfield_features )
print("Going to do PoW 4")
# We need to convert our private keys to public keys in order
# to include them.
try:
privSigningKeyBase58 = shared.config.get(
privSigningKeyBase58 = BMConfigParser().get(
fromaddress, 'privsigningkey')
privEncryptionKeyBase58 = shared.config.get(
privEncryptionKeyBase58 = BMConfigParser().get(
fromaddress, 'privencryptionkey')
except:
shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (
@ -748,9 +751,9 @@ class singleWorker(threading.Thread, StoppableThread):
payload += encodeVarint(
shared.networkDefaultPayloadLengthExtraBytes)
else:
payload += encodeVarint(shared.config.getint(
payload += encodeVarint(BMConfigParser().getint(
fromaddress, 'noncetrialsperbyte'))
payload += encodeVarint(shared.config.getint(
payload += encodeVarint(BMConfigParser().getint(
fromaddress, 'payloadlengthextrabytes'))
payload += toRipe # This hash will be checked by the receiver of the message to verify that toRipe belongs to them. This prevents a Surreptitious Forwarding Attack.
@ -758,10 +761,10 @@ class singleWorker(threading.Thread, StoppableThread):
encodedMessage = helper_msgcoding.MsgEncode({"subject": subject, "body": message}, encoding)
payload += encodeVarint(encodedMessage.length)
payload += encodedMessage.data
if shared.config.has_section(toaddress):
if BMConfigParser().has_section(toaddress):
logger.info('Not bothering to include ackdata because we are sending to ourselves or a chan.')
fullAckPayload = ''
elif not checkBitfield(behaviorBitfield, shared.BITFIELD_DOESACK):
elif not protocol.checkBitfield(behaviorBitfield, protocol.BITFIELD_DOESACK):
logger.info('Not bothering to include ackdata because the receiver said that they won\'t relay it anyway.')
fullAckPayload = ''
else:
@ -811,7 +814,7 @@ class singleWorker(threading.Thread, StoppableThread):
objectType = 2
Inventory()[inventoryHash] = (
objectType, toStreamNumber, encryptedPayload, embeddedTime, '')
if shared.config.has_section(toaddress) or not checkBitfield(behaviorBitfield, shared.BITFIELD_DOESACK):
if BMConfigParser().has_section(toaddress) or not protocol.checkBitfield(behaviorBitfield, protocol.BITFIELD_DOESACK):
shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, tr._translate("MainWindow", "Message sent. Sent at %1").arg(l10n.formatTimestamp()))))
else:
# not sending to a chan or one of my addresses
@ -821,7 +824,7 @@ class singleWorker(threading.Thread, StoppableThread):
toStreamNumber, 'advertiseobject', inventoryHash))
# Update the sent message in the sent table with the necessary information.
if shared.config.has_section(toaddress) or not checkBitfield(behaviorBitfield, shared.BITFIELD_DOESACK):
if BMConfigParser().has_section(toaddress) or not protocol.checkBitfield(behaviorBitfield, protocol.BITFIELD_DOESACK):
newStatus = 'msgsentnoackexpected'
else:
newStatus = 'msgsent'
@ -839,7 +842,7 @@ class singleWorker(threading.Thread, StoppableThread):
# If we are sending to ourselves or a chan, let's put the message in
# our own inbox.
if shared.config.has_section(toaddress):
if BMConfigParser().has_section(toaddress):
sigHash = hashlib.sha512(hashlib.sha512(signature).digest()).digest()[32:] # Used to detect and ignore duplicate messages in our inbox
t = (inventoryHash, toaddress, fromaddress, subject, int(
time.time()), message, 'inbox', encoding, 0, sigHash)
@ -851,9 +854,9 @@ class singleWorker(threading.Thread, StoppableThread):
# If we are behaving as an API then we might need to run an
# outside command to let some program know that a new message
# has arrived.
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
if BMConfigParser().safeGetBoolean('bitmessagesettings', 'apienabled'):
try:
apiNotifyPath = shared.config.get(
apiNotifyPath = BMConfigParser().get(
'bitmessagesettings', 'apinotifypath')
except:
apiNotifyPath = ''
@ -877,15 +880,15 @@ class singleWorker(threading.Thread, StoppableThread):
retryNumber = queryReturn[0][0]
if addressVersionNumber <= 3:
shared.neededPubkeys[toAddress] = 0
neededPubkeys[toAddress] = 0
elif addressVersionNumber >= 4:
# If the user just clicked 'send' then the tag (and other information) will already
# be in the neededPubkeys dictionary. But if we are recovering from a restart
# of the client then we have to put it in now.
privEncryptionKey = hashlib.sha512(hashlib.sha512(encodeVarint(addressVersionNumber)+encodeVarint(streamNumber)+ripe).digest()).digest()[:32] # Note that this is the first half of the sha512 hash.
tag = hashlib.sha512(hashlib.sha512(encodeVarint(addressVersionNumber)+encodeVarint(streamNumber)+ripe).digest()).digest()[32:] # Note that this is the second half of the sha512 hash.
if tag not in shared.neededPubkeys:
shared.neededPubkeys[tag] = (toAddress, highlevelcrypto.makeCryptor(hexlify(privEncryptionKey))) # We'll need this for when we receive a pubkey reply: it will be encrypted and we'll need to decrypt it.
if tag not in neededPubkeys:
neededPubkeys[tag] = (toAddress, highlevelcrypto.makeCryptor(hexlify(privEncryptionKey))) # We'll need this for when we receive a pubkey reply: it will be encrypted and we'll need to decrypt it.
if retryNumber == 0:
TTL = 2.5*24*60*60 # 2.5 days. This was chosen fairly arbitrarily.
@ -976,4 +979,4 @@ class singleWorker(threading.Thread, StoppableThread):
pass
payload = pack('>Q', nonce) + payload
return shared.CreatePacket('object', payload)
return protocol.CreatePacket('object', payload)

View File

@ -5,6 +5,7 @@ import sys
import threading
import urlparse
from configparser import BMConfigParser
from debug import logger
from helper_threading import *
import shared
@ -47,7 +48,7 @@ class smtpDeliver(threading.Thread, StoppableThread):
pass
elif command == 'displayNewInboxMessage':
inventoryHash, toAddress, fromAddress, subject, body = data
dest = shared.safeConfigGet("bitmessagesettings", "smtpdeliver", '')
dest = BMConfigParser().safeGet("bitmessagesettings", "smtpdeliver", '')
if dest == '':
continue
try:
@ -57,7 +58,7 @@ class smtpDeliver(threading.Thread, StoppableThread):
msg = MIMEText(body, 'plain', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = fromAddress + '@' + SMTPDOMAIN
toLabel = map (lambda y: shared.safeConfigGet(y, "label"), filter(lambda x: x == toAddress, shared.config.sections()))
toLabel = map (lambda y: BMConfigParser().safeGet(y, "label"), filter(lambda x: x == toAddress, BMConfigParser().sections()))
if len(toLabel) > 0:
msg['To'] = "\"%s\" <%s>" % (Header(toLabel[0], 'utf-8'), toAddress + '@' + SMTPDOMAIN)
else:

View File

@ -10,11 +10,13 @@ import threading
import time
from addresses import decodeAddress
from configparser import BMConfigParser
from debug import logger
from helper_sql import sqlExecute
from helper_threading import StoppableThread
from pyelliptic.openssl import OpenSSL
import shared
from version import softwareVersion
SMTPDOMAIN = "bmaddr.lan"
LISTENPORT = 8425
@ -24,7 +26,7 @@ class smtpServerChannel(smtpd.SMTPChannel):
if not arg:
self.push('501 Syntax: HELO hostname')
return
self.push('250-PyBitmessage %s' % shared.softwareVersion)
self.push('250-PyBitmessage %s' % softwareVersion)
self.push('250 AUTH PLAIN')
def smtp_AUTH(self, arg):
@ -34,8 +36,8 @@ class smtpServerChannel(smtpd.SMTPChannel):
authstring = arg[6:]
try:
decoded = base64.b64decode(authstring)
correctauth = "\x00" + shared.safeConfigGet("bitmessagesettings", "smtpdusername", "") + \
"\x00" + shared.safeConfigGet("bitmessagesettings", "smtpdpassword", "")
correctauth = "\x00" + BMConfigParser().safeGet("bitmessagesettings", "smtpdusername", "") + \
"\x00" + BMConfigParser().safeGet("bitmessagesettings", "smtpdpassword", "")
logger.debug("authstring: %s / %s", correctauth, decoded)
if correctauth == decoded:
self.auth = True
@ -80,7 +82,7 @@ class smtpServerPyBitmessage(smtpd.SMTPServer):
0, # retryNumber
'sent', # folder
2, # encodingtype
min(shared.config.getint('bitmessagesettings', 'ttl'), 86400 * 2) # not necessary to have a TTL higher than 2 days
min(BMConfigParser().getint('bitmessagesettings', 'ttl'), 86400 * 2) # not necessary to have a TTL higher than 2 days
)
shared.workerQueue.put(('sendmessage', toAddress))
@ -112,7 +114,7 @@ class smtpServerPyBitmessage(smtpd.SMTPServer):
sender, domain = p.sub(r'\1', mailfrom).split("@")
if domain != SMTPDOMAIN:
raise Exception("Bad domain %s", domain)
if sender not in shared.config.sections():
if sender not in BMConfigParser().sections():
raise Exception("Nonexisting user %s", sender)
except Exception as err:
logger.debug("Bad envelope from %s: %s", mailfrom, repr(err))
@ -122,7 +124,7 @@ class smtpServerPyBitmessage(smtpd.SMTPServer):
sender, domain = msg_from.split("@")
if domain != SMTPDOMAIN:
raise Exception("Bad domain %s", domain)
if sender not in shared.config.sections():
if sender not in BMConfigParser().sections():
raise Exception("Nonexisting user %s", sender)
except Exception as err:
logger.error("Bad headers from %s: %s", msg_from, repr(err))
@ -163,7 +165,7 @@ class smtpServer(threading.Thread, StoppableThread):
self.server.close()
return
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# for ip in ('127.0.0.1', shared.config.get('bitmessagesettings', 'onionbindip')):
# for ip in ('127.0.0.1', BMConfigParser().get('bitmessagesettings', 'onionbindip')):
for ip in ('127.0.0.1'):
try:
s.connect((ip, LISTENPORT))

View File

@ -1,4 +1,5 @@
import threading
from configparser import BMConfigParser
import shared
import sqlite3
import time
@ -65,35 +66,35 @@ class sqlThread(threading.Thread):
'ERROR trying to create database file (message.dat). Error message: %s\n' % str(err))
os._exit(0)
if shared.config.getint('bitmessagesettings', 'settingsversion') == 1:
shared.config.set('bitmessagesettings', 'settingsversion', '2')
if BMConfigParser().getint('bitmessagesettings', 'settingsversion') == 1:
BMConfigParser().set('bitmessagesettings', 'settingsversion', '2')
# If the settings version is equal to 2 or 3 then the
# sqlThread will modify the pubkeys table and change
# the settings version to 4.
shared.config.set('bitmessagesettings', 'socksproxytype', 'none')
shared.config.set('bitmessagesettings', 'sockshostname', 'localhost')
shared.config.set('bitmessagesettings', 'socksport', '9050')
shared.config.set('bitmessagesettings', 'socksauthentication', 'false')
shared.config.set('bitmessagesettings', 'socksusername', '')
shared.config.set('bitmessagesettings', 'sockspassword', '')
shared.config.set('bitmessagesettings', 'sockslisten', 'false')
shared.config.set('bitmessagesettings', 'keysencrypted', 'false')
shared.config.set('bitmessagesettings', 'messagesencrypted', 'false')
BMConfigParser().set('bitmessagesettings', 'socksproxytype', 'none')
BMConfigParser().set('bitmessagesettings', 'sockshostname', 'localhost')
BMConfigParser().set('bitmessagesettings', 'socksport', '9050')
BMConfigParser().set('bitmessagesettings', 'socksauthentication', 'false')
BMConfigParser().set('bitmessagesettings', 'socksusername', '')
BMConfigParser().set('bitmessagesettings', 'sockspassword', '')
BMConfigParser().set('bitmessagesettings', 'sockslisten', 'false')
BMConfigParser().set('bitmessagesettings', 'keysencrypted', 'false')
BMConfigParser().set('bitmessagesettings', 'messagesencrypted', 'false')
# People running earlier versions of PyBitmessage do not have the
# usedpersonally field in their pubkeys table. Let's add it.
if shared.config.getint('bitmessagesettings', 'settingsversion') == 2:
if BMConfigParser().getint('bitmessagesettings', 'settingsversion') == 2:
item = '''ALTER TABLE pubkeys ADD usedpersonally text DEFAULT 'no' '''
parameters = ''
self.cur.execute(item, parameters)
self.conn.commit()
shared.config.set('bitmessagesettings', 'settingsversion', '3')
BMConfigParser().set('bitmessagesettings', 'settingsversion', '3')
# People running earlier versions of PyBitmessage do not have the
# encodingtype field in their inbox and sent tables or the read field
# in the inbox table. Let's add them.
if shared.config.getint('bitmessagesettings', 'settingsversion') == 3:
if BMConfigParser().getint('bitmessagesettings', 'settingsversion') == 3:
item = '''ALTER TABLE inbox ADD encodingtype int DEFAULT '2' '''
parameters = ''
self.cur.execute(item, parameters)
@ -107,21 +108,21 @@ class sqlThread(threading.Thread):
self.cur.execute(item, parameters)
self.conn.commit()
shared.config.set('bitmessagesettings', 'settingsversion', '4')
BMConfigParser().set('bitmessagesettings', 'settingsversion', '4')
if shared.config.getint('bitmessagesettings', 'settingsversion') == 4:
shared.config.set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(
if BMConfigParser().getint('bitmessagesettings', 'settingsversion') == 4:
BMConfigParser().set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(
shared.networkDefaultProofOfWorkNonceTrialsPerByte))
shared.config.set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(
BMConfigParser().set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(
shared.networkDefaultPayloadLengthExtraBytes))
shared.config.set('bitmessagesettings', 'settingsversion', '5')
BMConfigParser().set('bitmessagesettings', 'settingsversion', '5')
if shared.config.getint('bitmessagesettings', 'settingsversion') == 5:
shared.config.set(
if BMConfigParser().getint('bitmessagesettings', 'settingsversion') == 5:
BMConfigParser().set(
'bitmessagesettings', 'maxacceptablenoncetrialsperbyte', '0')
shared.config.set(
BMConfigParser().set(
'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', '0')
shared.config.set('bitmessagesettings', 'settingsversion', '6')
BMConfigParser().set('bitmessagesettings', 'settingsversion', '6')
# From now on, let us keep a 'version' embedded in the messages.dat
# file so that when we make changes to the database, the database
@ -174,8 +175,8 @@ class sqlThread(threading.Thread):
'''update sent set status='broadcastqueued' where status='broadcastpending' ''')
self.conn.commit()
if not shared.config.has_option('bitmessagesettings', 'sockslisten'):
shared.config.set('bitmessagesettings', 'sockslisten', 'false')
if not BMConfigParser().has_option('bitmessagesettings', 'sockslisten'):
BMConfigParser().set('bitmessagesettings', 'sockslisten', 'false')
ensureNamecoinOptions()
@ -226,18 +227,18 @@ class sqlThread(threading.Thread):
parameters = (4,)
self.cur.execute(item, parameters)
if not shared.config.has_option('bitmessagesettings', 'userlocale'):
shared.config.set('bitmessagesettings', 'userlocale', 'system')
if not shared.config.has_option('bitmessagesettings', 'sendoutgoingconnections'):
shared.config.set('bitmessagesettings', 'sendoutgoingconnections', 'True')
if not BMConfigParser().has_option('bitmessagesettings', 'userlocale'):
BMConfigParser().set('bitmessagesettings', 'userlocale', 'system')
if not BMConfigParser().has_option('bitmessagesettings', 'sendoutgoingconnections'):
BMConfigParser().set('bitmessagesettings', 'sendoutgoingconnections', 'True')
# Raise the default required difficulty from 1 to 2
# With the change to protocol v3, this is obsolete.
if shared.config.getint('bitmessagesettings', 'settingsversion') == 6:
if BMConfigParser().getint('bitmessagesettings', 'settingsversion') == 6:
"""if int(shared.config.get('bitmessagesettings','defaultnoncetrialsperbyte')) == shared.networkDefaultProofOfWorkNonceTrialsPerByte:
shared.config.set('bitmessagesettings','defaultnoncetrialsperbyte', str(shared.networkDefaultProofOfWorkNonceTrialsPerByte * 2))
"""
shared.config.set('bitmessagesettings', 'settingsversion', '7')
BMConfigParser().set('bitmessagesettings', 'settingsversion', '7')
# Add a new column to the pubkeys table to store the address version.
# We're going to trash all of our pubkeys and let them be redownloaded.
@ -255,18 +256,18 @@ class sqlThread(threading.Thread):
parameters = (5,)
self.cur.execute(item, parameters)
if not shared.config.has_option('bitmessagesettings', 'useidenticons'):
shared.config.set('bitmessagesettings', 'useidenticons', 'True')
if not shared.config.has_option('bitmessagesettings', 'identiconsuffix'): # acts as a salt
shared.config.set('bitmessagesettings', 'identiconsuffix', ''.join(random.choice("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") for x in range(12))) # a twelve character pseudo-password to salt the identicons
if not BMConfigParser().has_option('bitmessagesettings', 'useidenticons'):
BMConfigParser().set('bitmessagesettings', 'useidenticons', 'True')
if not BMConfigParser().has_option('bitmessagesettings', 'identiconsuffix'): # acts as a salt
BMConfigParser().set('bitmessagesettings', 'identiconsuffix', ''.join(random.choice("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") for x in range(12))) # a twelve character pseudo-password to salt the identicons
#Add settings to support no longer resending messages after a certain period of time even if we never get an ack
if shared.config.getint('bitmessagesettings', 'settingsversion') == 7:
shared.config.set(
if BMConfigParser().getint('bitmessagesettings', 'settingsversion') == 7:
BMConfigParser().set(
'bitmessagesettings', 'stopresendingafterxdays', '')
shared.config.set(
BMConfigParser().set(
'bitmessagesettings', 'stopresendingafterxmonths', '')
shared.config.set('bitmessagesettings', 'settingsversion', '8')
BMConfigParser().set('bitmessagesettings', 'settingsversion', '8')
# Add a new table: objectprocessorqueue with which to hold objects
# that have yet to be processed if the user shuts down Bitmessage.
@ -300,39 +301,39 @@ class sqlThread(threading.Thread):
logger.debug('Finished dropping and recreating the inventory table.')
# With the change to protocol version 3, reset the user-settable difficulties to 1
if shared.config.getint('bitmessagesettings', 'settingsversion') == 8:
shared.config.set('bitmessagesettings','defaultnoncetrialsperbyte', str(shared.networkDefaultProofOfWorkNonceTrialsPerByte))
shared.config.set('bitmessagesettings','defaultpayloadlengthextrabytes', str(shared.networkDefaultPayloadLengthExtraBytes))
previousTotalDifficulty = int(shared.config.getint('bitmessagesettings', 'maxacceptablenoncetrialsperbyte')) / 320
previousSmallMessageDifficulty = int(shared.config.getint('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes')) / 14000
shared.config.set('bitmessagesettings','maxacceptablenoncetrialsperbyte', str(previousTotalDifficulty * 1000))
shared.config.set('bitmessagesettings','maxacceptablepayloadlengthextrabytes', str(previousSmallMessageDifficulty * 1000))
shared.config.set('bitmessagesettings', 'settingsversion', '9')
if BMConfigParser().getint('bitmessagesettings', 'settingsversion') == 8:
BMConfigParser().set('bitmessagesettings','defaultnoncetrialsperbyte', str(shared.networkDefaultProofOfWorkNonceTrialsPerByte))
BMConfigParser().set('bitmessagesettings','defaultpayloadlengthextrabytes', str(shared.networkDefaultPayloadLengthExtraBytes))
previousTotalDifficulty = int(BMConfigParser().getint('bitmessagesettings', 'maxacceptablenoncetrialsperbyte')) / 320
previousSmallMessageDifficulty = int(BMConfigParser().getint('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes')) / 14000
BMConfigParser().set('bitmessagesettings','maxacceptablenoncetrialsperbyte', str(previousTotalDifficulty * 1000))
BMConfigParser().set('bitmessagesettings','maxacceptablepayloadlengthextrabytes', str(previousSmallMessageDifficulty * 1000))
BMConfigParser().set('bitmessagesettings', 'settingsversion', '9')
# Adjust the required POW values for each of this user's addresses to conform to protocol v3 norms.
if shared.config.getint('bitmessagesettings', 'settingsversion') == 9:
for addressInKeysFile in shared.config.sections():
if BMConfigParser().getint('bitmessagesettings', 'settingsversion') == 9:
for addressInKeysFile in BMConfigParser().sections():
try:
previousTotalDifficulty = float(shared.config.getint(addressInKeysFile, 'noncetrialsperbyte')) / 320
previousSmallMessageDifficulty = float(shared.config.getint(addressInKeysFile, 'payloadlengthextrabytes')) / 14000
previousTotalDifficulty = float(BMConfigParser().getint(addressInKeysFile, 'noncetrialsperbyte')) / 320
previousSmallMessageDifficulty = float(BMConfigParser().getint(addressInKeysFile, 'payloadlengthextrabytes')) / 14000
if previousTotalDifficulty <= 2:
previousTotalDifficulty = 1
if previousSmallMessageDifficulty < 1:
previousSmallMessageDifficulty = 1
shared.config.set(addressInKeysFile,'noncetrialsperbyte', str(int(previousTotalDifficulty * 1000)))
shared.config.set(addressInKeysFile,'payloadlengthextrabytes', str(int(previousSmallMessageDifficulty * 1000)))
BMConfigParser().set(addressInKeysFile,'noncetrialsperbyte', str(int(previousTotalDifficulty * 1000)))
BMConfigParser().set(addressInKeysFile,'payloadlengthextrabytes', str(int(previousSmallMessageDifficulty * 1000)))
except:
continue
shared.config.set('bitmessagesettings', 'maxdownloadrate', '0')
shared.config.set('bitmessagesettings', 'maxuploadrate', '0')
shared.config.set('bitmessagesettings', 'settingsversion', '10')
BMConfigParser().set('bitmessagesettings', 'maxdownloadrate', '0')
BMConfigParser().set('bitmessagesettings', 'maxuploadrate', '0')
BMConfigParser().set('bitmessagesettings', 'settingsversion', '10')
shared.writeKeysFile()
# sanity check
if shared.config.getint('bitmessagesettings', 'maxacceptablenoncetrialsperbyte') == 0:
shared.config.set('bitmessagesettings','maxacceptablenoncetrialsperbyte', str(shared.ridiculousDifficulty * shared.networkDefaultProofOfWorkNonceTrialsPerByte))
if shared.config.getint('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes') == 0:
shared.config.set('bitmessagesettings','maxacceptablepayloadlengthextrabytes', str(shared.ridiculousDifficulty * shared.networkDefaultPayloadLengthExtraBytes))
if BMConfigParser().getint('bitmessagesettings', 'maxacceptablenoncetrialsperbyte') == 0:
BMConfigParser().set('bitmessagesettings','maxacceptablenoncetrialsperbyte', str(shared.ridiculousDifficulty * shared.networkDefaultProofOfWorkNonceTrialsPerByte))
if BMConfigParser().getint('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes') == 0:
BMConfigParser().set('bitmessagesettings','maxacceptablepayloadlengthextrabytes', str(shared.ridiculousDifficulty * shared.networkDefaultPayloadLengthExtraBytes))
# The format of data stored in the pubkeys table has changed. Let's
# clear it, and the pubkeys from inventory, so that they'll be re-downloaded.
@ -371,8 +372,8 @@ class sqlThread(threading.Thread):
self.cur.execute(item, parameters)
# TTL is now user-specifiable. Let's add an option to save whatever the user selects.
if not shared.config.has_option('bitmessagesettings', 'ttl'):
shared.config.set('bitmessagesettings', 'ttl', '367200')
if not BMConfigParser().has_option('bitmessagesettings', 'ttl'):
BMConfigParser().set('bitmessagesettings', 'ttl', '367200')
# We'll also need a `sleeptill` field and a `ttl` field. Also we can combine
# the pubkeyretrynumber and msgretrynumber into one.
item = '''SELECT value FROM settings WHERE key='version';'''
@ -419,16 +420,16 @@ class sqlThread(threading.Thread):
logger.debug('In messages.dat database, done adding address field to the pubkeys table and removing the hash field.')
self.cur.execute('''update settings set value=10 WHERE key='version';''')
if not shared.config.has_option('bitmessagesettings', 'onionhostname'):
shared.config.set('bitmessagesettings', 'onionhostname', '')
if not shared.config.has_option('bitmessagesettings', 'onionport'):
shared.config.set('bitmessagesettings', 'onionport', '8444')
if not shared.config.has_option('bitmessagesettings', 'onionbindip'):
shared.config.set('bitmessagesettings', 'onionbindip', '127.0.0.1')
if not shared.config.has_option('bitmessagesettings', 'smtpdeliver'):
shared.config.set('bitmessagesettings', 'smtpdeliver', '')
if not shared.config.has_option('bitmessagesettings', 'hidetrayconnectionnotifications'):
shared.config.set('bitmessagesettings', 'hidetrayconnectionnotifications', 'false')
if not BMConfigParser().has_option('bitmessagesettings', 'onionhostname'):
BMConfigParser().set('bitmessagesettings', 'onionhostname', '')
if not BMConfigParser().has_option('bitmessagesettings', 'onionport'):
BMConfigParser().set('bitmessagesettings', 'onionport', '8444')
if not BMConfigParser().has_option('bitmessagesettings', 'onionbindip'):
BMConfigParser().set('bitmessagesettings', 'onionbindip', '127.0.0.1')
if not BMConfigParser().has_option('bitmessagesettings', 'smtpdeliver'):
BMConfigParser().set('bitmessagesettings', 'smtpdeliver', '')
if not BMConfigParser().has_option('bitmessagesettings', 'hidetrayconnectionnotifications'):
BMConfigParser().set('bitmessagesettings', 'hidetrayconnectionnotifications', 'false')
shared.writeKeysFile()
# Are you hoping to add a new option to the keys.dat file of existing

View File

@ -1,5 +1,9 @@
import ConfigParser
from singleton import Singleton
@Singleton
class BMConfigParser(ConfigParser.SafeConfigParser):
def set(self, section, option, value=None):
if self._optcre is self.OPTCRE or value:
@ -15,6 +19,20 @@ class BMConfigParser(ConfigParser.SafeConfigParser):
return ConfigParser.ConfigParser.get(self, section, option, True, vars)
return ConfigParser.ConfigParser.get(self, section, option, True, vars)
def safeGetBoolean(self, section, field):
if self.has_option(section, field):
try:
return self.getboolean(section, field)
except ValueError:
return False
return False
def safeGet(self, section, option, default = None):
if self.has_option(section, option):
return self.get(section, option)
else:
return default
def items(self, section, raw=False, vars=None):
return ConfigParser.ConfigParser.items(self, section, True, vars)

View File

@ -4,6 +4,7 @@ import defaultKnownNodes
import pickle
import time
from configparser import BMConfigParser
from debug import logger
import socks
@ -29,9 +30,9 @@ def knownNodes():
except:
shared.knownNodes = defaultKnownNodes.createDefaultKnownNodes(shared.appdata)
# your own onion address, if setup
if shared.config.has_option('bitmessagesettings', 'onionhostname') and ".onion" in shared.config.get('bitmessagesettings', 'onionhostname'):
shared.knownNodes[1][shared.Peer(shared.config.get('bitmessagesettings', 'onionhostname'), shared.config.getint('bitmessagesettings', 'onionport'))] = int(time.time())
if shared.config.getint('bitmessagesettings', 'settingsversion') > 10:
if BMConfigParser().has_option('bitmessagesettings', 'onionhostname') and ".onion" in BMConfigParser().get('bitmessagesettings', 'onionhostname'):
shared.knownNodes[1][shared.Peer(BMConfigParser().get('bitmessagesettings', 'onionhostname'), BMConfigParser().getint('bitmessagesettings', 'onionport'))] = int(time.time())
if BMConfigParser().getint('bitmessagesettings', 'settingsversion') > 10:
logger.error('Bitmessage cannot read future versions of the keys file (keys.dat). Run the newer version of Bitmessage.')
raise SystemExit
@ -41,7 +42,7 @@ def dns():
# defaultKnownNodes.py. Hopefully either they are up to date or the user
# has run Bitmessage recently without SOCKS turned on and received good
# bootstrap nodes using that method.
if shared.config.get('bitmessagesettings', 'socksproxytype') == 'none':
if BMConfigParser().get('bitmessagesettings', 'socksproxytype') == 'none':
try:
for item in socket.getaddrinfo('bootstrap8080.bitmessage.org', 80):
logger.info('Adding ' + item[4][0] + ' to knownNodes based on DNS bootstrap method')
@ -54,7 +55,7 @@ def dns():
shared.knownNodes[1][shared.Peer(item[4][0], 8444)] = int(time.time())
except:
logger.error('bootstrap8444.bitmessage.org DNS bootstrapping failed.')
elif shared.config.get('bitmessagesettings', 'socksproxytype') == 'SOCKS5':
elif BMConfigParser().get('bitmessagesettings', 'socksproxytype') == 'SOCKS5':
shared.knownNodes[1][shared.Peer('quzwelsuziwqgpt2.onion', 8444)] = int(time.time())
logger.debug("Adding quzwelsuziwqgpt2.onion:8444 to knownNodes.")
for port in [8080, 8444]:
@ -64,15 +65,15 @@ def dns():
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.settimeout(20)
proxytype = socks.PROXY_TYPE_SOCKS5
sockshostname = shared.config.get(
sockshostname = BMConfigParser().get(
'bitmessagesettings', 'sockshostname')
socksport = shared.config.getint(
socksport = BMConfigParser().getint(
'bitmessagesettings', 'socksport')
rdns = True # Do domain name lookups through the proxy; though this setting doesn't really matter since we won't be doing any domain name lookups anyway.
if shared.config.getboolean('bitmessagesettings', 'socksauthentication'):
socksusername = shared.config.get(
if BMConfigParser().getboolean('bitmessagesettings', 'socksauthentication'):
socksusername = BMConfigParser().get(
'bitmessagesettings', 'socksusername')
sockspassword = shared.config.get(
sockspassword = BMConfigParser().get(
'bitmessagesettings', 'sockspassword')
sock.setproxy(
proxytype, sockshostname, socksport, rdns, socksusername, sockspassword)

View File

@ -5,6 +5,7 @@ from binascii import hexlify, unhexlify
from multiprocessing import current_process
from threading import current_thread, enumerate
from configparser import BMConfigParser
from debug import logger
import shared
@ -51,7 +52,7 @@ def signal_handler(signal, frame):
if current_thread().name != "MainThread":
return
logger.error("Got signal %i", signal)
if shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'):
if BMConfigParser().safeGetBoolean('bitmessagesettings', 'daemon'):
shared.doCleanShutdown()
else:
print 'Unfortunately you cannot use Ctrl+C when running the UI because the UI captures the signal.'

View File

@ -1,5 +1,6 @@
import shared
import ConfigParser
import shared
from configparser import BMConfigParser
import sys
import os
import locale
@ -14,7 +15,7 @@ storeConfigFilesInSameDirectoryAsProgramByDefault = False # The user may de-sel
def _loadTrustedPeer():
try:
trustedPeer = shared.config.get('bitmessagesettings', 'trustedpeer')
trustedPeer = BMConfigParser().get('bitmessagesettings', 'trustedpeer')
except ConfigParser.Error:
# This probably means the trusted peer wasn't specified so we
# can just leave it as None
@ -25,19 +26,19 @@ def _loadTrustedPeer():
def loadConfig():
if shared.appdata:
shared.config.read(shared.appdata + 'keys.dat')
BMConfigParser().read(shared.appdata + 'keys.dat')
#shared.appdata must have been specified as a startup option.
try:
shared.config.get('bitmessagesettings', 'settingsversion')
BMConfigParser().get('bitmessagesettings', 'settingsversion')
print 'Loading config files from directory specified on startup: ' + shared.appdata
needToCreateKeysFile = False
except:
needToCreateKeysFile = True
else:
shared.config.read(shared.lookupExeFolder() + 'keys.dat')
BMConfigParser().read(shared.lookupExeFolder() + 'keys.dat')
try:
shared.config.get('bitmessagesettings', 'settingsversion')
BMConfigParser().get('bitmessagesettings', 'settingsversion')
print 'Loading config files from same directory as program.'
needToCreateKeysFile = False
shared.appdata = shared.lookupExeFolder()
@ -45,9 +46,9 @@ def loadConfig():
# Could not load the keys.dat file in the program directory. Perhaps it
# is in the appdata directory.
shared.appdata = shared.lookupAppdataFolder()
shared.config.read(shared.appdata + 'keys.dat')
BMConfigParser().read(shared.appdata + 'keys.dat')
try:
shared.config.get('bitmessagesettings', 'settingsversion')
BMConfigParser().get('bitmessagesettings', 'settingsversion')
print 'Loading existing config files from', shared.appdata
needToCreateKeysFile = False
except:
@ -56,62 +57,62 @@ def loadConfig():
if needToCreateKeysFile:
# This appears to be the first time running the program; there is
# no config file (or it cannot be accessed). Create config file.
shared.config.add_section('bitmessagesettings')
shared.config.set('bitmessagesettings', 'settingsversion', '10')
shared.config.set('bitmessagesettings', 'port', '8444')
shared.config.set(
BMConfigParser().add_section('bitmessagesettings')
BMConfigParser().set('bitmessagesettings', 'settingsversion', '10')
BMConfigParser().set('bitmessagesettings', 'port', '8444')
BMConfigParser().set(
'bitmessagesettings', 'timeformat', '%%c')
shared.config.set('bitmessagesettings', 'blackwhitelist', 'black')
shared.config.set('bitmessagesettings', 'startonlogon', 'false')
BMConfigParser().set('bitmessagesettings', 'blackwhitelist', 'black')
BMConfigParser().set('bitmessagesettings', 'startonlogon', 'false')
if 'linux' in sys.platform:
shared.config.set(
BMConfigParser().set(
'bitmessagesettings', 'minimizetotray', 'false')
# This isn't implimented yet and when True on
# Ubuntu causes Bitmessage to disappear while
# running when minimized.
else:
shared.config.set(
BMConfigParser().set(
'bitmessagesettings', 'minimizetotray', 'true')
shared.config.set(
BMConfigParser().set(
'bitmessagesettings', 'showtraynotifications', 'true')
shared.config.set('bitmessagesettings', 'startintray', 'false')
shared.config.set('bitmessagesettings', 'socksproxytype', 'none')
shared.config.set(
BMConfigParser().set('bitmessagesettings', 'startintray', 'false')
BMConfigParser().set('bitmessagesettings', 'socksproxytype', 'none')
BMConfigParser().set(
'bitmessagesettings', 'sockshostname', 'localhost')
shared.config.set('bitmessagesettings', 'socksport', '9050')
shared.config.set(
BMConfigParser().set('bitmessagesettings', 'socksport', '9050')
BMConfigParser().set(
'bitmessagesettings', 'socksauthentication', 'false')
shared.config.set(
BMConfigParser().set(
'bitmessagesettings', 'sockslisten', 'false')
shared.config.set('bitmessagesettings', 'socksusername', '')
shared.config.set('bitmessagesettings', 'sockspassword', '')
shared.config.set('bitmessagesettings', 'keysencrypted', 'false')
shared.config.set(
BMConfigParser().set('bitmessagesettings', 'socksusername', '')
BMConfigParser().set('bitmessagesettings', 'sockspassword', '')
BMConfigParser().set('bitmessagesettings', 'keysencrypted', 'false')
BMConfigParser().set(
'bitmessagesettings', 'messagesencrypted', 'false')
shared.config.set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(
BMConfigParser().set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(
shared.networkDefaultProofOfWorkNonceTrialsPerByte))
shared.config.set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(
BMConfigParser().set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(
shared.networkDefaultPayloadLengthExtraBytes))
shared.config.set('bitmessagesettings', 'minimizeonclose', 'false')
shared.config.set(
BMConfigParser().set('bitmessagesettings', 'minimizeonclose', 'false')
BMConfigParser().set(
'bitmessagesettings', 'maxacceptablenoncetrialsperbyte', '0')
shared.config.set(
BMConfigParser().set(
'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', '0')
shared.config.set('bitmessagesettings', 'dontconnect', 'true')
shared.config.set('bitmessagesettings', 'userlocale', 'system')
shared.config.set('bitmessagesettings', 'useidenticons', 'True')
shared.config.set('bitmessagesettings', 'identiconsuffix', ''.join(random.choice("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") for x in range(12))) # a twelve character pseudo-password to salt the identicons
shared.config.set('bitmessagesettings', 'replybelow', 'False')
shared.config.set('bitmessagesettings', 'maxdownloadrate', '0')
shared.config.set('bitmessagesettings', 'maxuploadrate', '0')
shared.config.set('bitmessagesettings', 'ttl', '367200')
BMConfigParser().set('bitmessagesettings', 'dontconnect', 'true')
BMConfigParser().set('bitmessagesettings', 'userlocale', 'system')
BMConfigParser().set('bitmessagesettings', 'useidenticons', 'True')
BMConfigParser().set('bitmessagesettings', 'identiconsuffix', ''.join(random.choice("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") for x in range(12))) # a twelve character pseudo-password to salt the identicons
BMConfigParser().set('bitmessagesettings', 'replybelow', 'False')
BMConfigParser().set('bitmessagesettings', 'maxdownloadrate', '0')
BMConfigParser().set('bitmessagesettings', 'maxuploadrate', '0')
BMConfigParser().set('bitmessagesettings', 'ttl', '367200')
#start:UI setting to stop trying to send messages after X days/months
shared.config.set(
BMConfigParser().set(
'bitmessagesettings', 'stopresendingafterxdays', '')
shared.config.set(
BMConfigParser().set(
'bitmessagesettings', 'stopresendingafterxmonths', '')
#shared.config.set(
#BMConfigParser().set(
# 'bitmessagesettings', 'timeperiod', '-1')
#end

View File

@ -3,6 +3,7 @@ import logging
import os
import time
from configparser import BMConfigParser
import shared
@ -48,8 +49,8 @@ except:
logger.exception('Could not determine language or encoding')
if shared.config.has_option('bitmessagesettings', 'timeformat'):
time_format = shared.config.get('bitmessagesettings', 'timeformat')
if BMConfigParser().has_option('bitmessagesettings', 'timeformat'):
time_format = BMConfigParser().get('bitmessagesettings', 'timeformat')
#Test the format string
try:
time.strftime(time_format)
@ -112,8 +113,8 @@ def formatTimestamp(timestamp = None, as_unicode = True):
def getTranslationLanguage():
userlocale = None
if shared.config.has_option('bitmessagesettings', 'userlocale'):
userlocale = shared.config.get('bitmessagesettings', 'userlocale')
if BMConfigParser().has_option('bitmessagesettings', 'userlocale'):
userlocale = BMConfigParser().get('bitmessagesettings', 'userlocale')
if userlocale in [None, '', 'system']:
return language

View File

@ -26,6 +26,7 @@ import socket
import sys
import os
from configparser import BMConfigParser
import shared
import tr # translate
@ -63,11 +64,11 @@ class namecoinConnection (object):
# actually changing the values (yet).
def __init__ (self, options = None):
if options is None:
self.nmctype = shared.config.get (configSection, "namecoinrpctype")
self.host = shared.config.get (configSection, "namecoinrpchost")
self.port = int(shared.config.get (configSection, "namecoinrpcport"))
self.user = shared.config.get (configSection, "namecoinrpcuser")
self.password = shared.config.get (configSection,
self.nmctype = BMConfigParser().get (configSection, "namecoinrpctype")
self.host = BMConfigParser().get (configSection, "namecoinrpchost")
self.port = int(BMConfigParser().get (configSection, "namecoinrpcport"))
self.user = BMConfigParser().get (configSection, "namecoinrpcuser")
self.password = BMConfigParser().get (configSection,
"namecoinrpcpassword")
else:
self.nmctype = options["type"]
@ -261,14 +262,14 @@ def lookupNamecoinFolder ():
# Ensure all namecoin options are set, by setting those to default values
# that aren't there.
def ensureNamecoinOptions ():
if not shared.config.has_option (configSection, "namecoinrpctype"):
shared.config.set (configSection, "namecoinrpctype", "namecoind")
if not shared.config.has_option (configSection, "namecoinrpchost"):
shared.config.set (configSection, "namecoinrpchost", "localhost")
if not BMConfigParser().has_option (configSection, "namecoinrpctype"):
BMConfigParser().set (configSection, "namecoinrpctype", "namecoind")
if not BMConfigParser().has_option (configSection, "namecoinrpchost"):
BMConfigParser().set (configSection, "namecoinrpchost", "localhost")
hasUser = shared.config.has_option (configSection, "namecoinrpcuser")
hasPass = shared.config.has_option (configSection, "namecoinrpcpassword")
hasPort = shared.config.has_option (configSection, "namecoinrpcport")
hasUser = BMConfigParser().has_option (configSection, "namecoinrpcuser")
hasPass = BMConfigParser().has_option (configSection, "namecoinrpcpassword")
hasPort = BMConfigParser().has_option (configSection, "namecoinrpcport")
# Try to read user/password from .namecoin configuration file.
defaultUser = ""
@ -302,11 +303,11 @@ def ensureNamecoinOptions ():
# If still nothing found, set empty at least.
if (not hasUser):
shared.config.set (configSection, "namecoinrpcuser", defaultUser)
BMConfigParser().set (configSection, "namecoinrpcuser", defaultUser)
if (not hasPass):
shared.config.set (configSection, "namecoinrpcpassword", defaultPass)
BMConfigParser().set (configSection, "namecoinrpcpassword", defaultPass)
# Set default port now, possibly to found value.
if (not hasPort):
shared.config.set (configSection, "namecoinrpcport",
BMConfigParser().set (configSection, "namecoinrpcport",
shared.namecoinDefaultRpcPort)

View File

@ -5,7 +5,8 @@ import hashlib
import random
import os
from shared import codePath, safeConfigGetBoolean, safeConfigGet, shutdown
from configparser import BMConfigParser
from shared import codePath, shutdown
from debug import logger
libAvailable = True
@ -30,7 +31,7 @@ def initCL():
try:
for platform in cl.get_platforms():
gpus.extend(platform.get_devices(device_type=cl.device_type.GPU))
if safeConfigGet("bitmessagesettings", "opencl") == platform.vendor:
if BMConfigParser().safeGet("bitmessagesettings", "opencl") == platform.vendor:
enabledGpus.extend(platform.get_devices(device_type=cl.device_type.GPU))
if platform.vendor not in vendors:
vendors.append(platform.vendor)

View File

@ -6,6 +6,7 @@ from struct import unpack, pack
from subprocess import call
import sys
import time
from configparser import BMConfigParser
from debug import logger
import shared
import openclpow
@ -58,7 +59,7 @@ def _doFastPoW(target, initialHash):
except:
pool_size = 4
try:
maxCores = shared.config.getint('bitmessagesettings', 'maxcores')
maxCores = BMConfigParser().getint('bitmessagesettings', 'maxcores')
except:
maxCores = 99999
if pool_size > maxCores:

View File

@ -1,14 +1,454 @@
import struct
import shared
import base64
import hashlib
import random
import socket
import ssl
from struct import pack, unpack, Struct
import sys
import time
from addresses import encodeVarint, decodeVarint
from configparser import BMConfigParser
from state import neededPubkeys, extPort, socksIP
from version import softwareVersion
#Service flags
NODE_NETWORK = 1
NODE_SSL = 2
#Bitfield flags
BITFIELD_DOESACK = 1
eightBytesOfRandomDataUsedToDetectConnectionsToSelf = pack(
'>Q', random.randrange(1, 18446744073709551615))
#Compiled struct for packing/unpacking headers
#New code should use CreatePacket instead of Header.pack
Header = Struct('!L12sL4s')
# Bitfield
def getBitfield(address):
# bitfield of features supported by me (see the wiki).
bitfield = 0
# send ack
if not shared.safeConfigGetBoolean(address, 'dontsendack'):
bitfield |= shared.BITFIELD_DOESACK
return struct.pack('>I', bitfield)
if not BMConfigParser().safeGetBoolean(address, 'dontsendack'):
bitfield |= BITFIELD_DOESACK
return pack('>I', bitfield)
def checkBitfield(bitfieldBinary, flags):
bitfield, = struct.unpack('>I', bitfieldBinary)
bitfield, = unpack('>I', bitfieldBinary)
return (bitfield & flags) == flags
def isBitSetWithinBitfield(fourByteString, n):
# Uses MSB 0 bit numbering across 4 bytes of data
n = 31 - n
x, = unpack('>L', fourByteString)
return x & 2**n != 0
# data handling
def encodeHost(host):
if host.find('.onion') > -1:
return '\xfd\x87\xd8\x7e\xeb\x43' + base64.b32decode(host.split(".")[0], True)
elif host.find(':') == -1:
return '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + \
socket.inet_aton(host)
else:
return socket.inet_pton(socket.AF_INET6, host)
# checks
def haveSSL(server = False):
# python < 2.7.9's ssl library does not support ECDSA server due to missing initialisation of available curves, but client works ok
if server == False:
return True
elif sys.version_info >= (2,7,9):
return True
return False
def sslProtocolVersion():
if sys.version_info >= (2,7,13):
# in the future once TLS is mandatory, change this to ssl.PROTOCOL_TLS1.2
return ssl.PROTOCOL_TLS
elif sys.version_info >= (2,7,9):
# once TLS is mandatory, add "ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1.1"
return ssl.PROTOCOL_SSLv23 | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3
else:
return ssl.PROTOCOL_TLS1
def checkSocksIP(host):
try:
if socksIP is None or not socksIP:
socksIP = socket.gethostbyname(BMConfigParser().get("bitmessagesettings", "sockshostname"))
except NameError:
socksIP = socket.gethostbyname(BMConfigParser().get("bitmessagesettings", "sockshostname"))
return socksIP == host
# Packet creation
def CreatePacket(command, payload=''):
payload_length = len(payload)
checksum = hashlib.sha512(payload).digest()[0:4]
b = bytearray(Header.size + payload_length)
Header.pack_into(b, 0, 0xE9BEB4D9, command, payload_length, checksum)
b[Header.size:] = payload
return bytes(b)
def assembleVersionMessage(remoteHost, remotePort, myStreamNumber, server = False):
payload = ''
payload += pack('>L', 3) # protocol version.
payload += pack('>q', NODE_NETWORK|(NODE_SSL if haveSSL(server) else 0)) # bitflags of the services I offer.
payload += pack('>q', int(time.time()))
payload += pack(
'>q', 1) # boolservices of remote connection; ignored by the remote host.
if checkSocksIP(remoteHost) and server: # prevent leaking of tor outbound IP
payload += encodeHost('127.0.0.1')
payload += pack('>H', 8444)
else:
payload += encodeHost(remoteHost)
payload += pack('>H', remotePort) # remote IPv6 and port
payload += pack('>q', 1) # bitflags of the services I offer.
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + pack(
'>L', 2130706433) # = 127.0.0.1. This will be ignored by the remote host. The actual remote connected IP will be used.
# we have a separate extPort and
# incoming over clearnet or
# outgoing through clearnet
if BMConfigParser().safeGetBoolean('bitmessagesettings', 'upnp') and extPort \
and ((server and not checkSocksIP(remoteHost)) or \
(BMConfigParser().get("bitmessagesettings", "socksproxytype") == "none" and not server)):
payload += pack('>H', extPort)
elif checkSocksIP(remoteHost) and server: # incoming connection over Tor
payload += pack('>H', BMConfigParser().getint('bitmessagesettings', 'onionport'))
else: # no extPort and not incoming over Tor
payload += pack('>H', BMConfigParser().getint('bitmessagesettings', 'port'))
random.seed()
payload += eightBytesOfRandomDataUsedToDetectConnectionsToSelf
userAgent = '/PyBitmessage:' + softwareVersion + '/'
payload += encodeVarint(len(userAgent))
payload += userAgent
payload += encodeVarint(
1) # The number of streams about which I care. PyBitmessage currently only supports 1 per connection.
payload += encodeVarint(myStreamNumber)
return CreatePacket('version', payload)
def assembleErrorMessage(fatal=0, banTime=0, inventoryVector='', errorText=''):
payload = encodeVarint(fatal)
payload += encodeVarint(banTime)
payload += encodeVarint(len(inventoryVector))
payload += inventoryVector
payload += encodeVarint(len(errorText))
payload += errorText
return CreatePacket('error', payload)
# Packet decoding
def decryptAndCheckPubkeyPayload(data, address):
"""
Version 4 pubkeys are encrypted. This function is run when we already have the
address to which we want to try to send a message. The 'data' may come either
off of the wire or we might have had it already in our inventory when we tried
to send a msg to this particular address.
"""
try:
status, addressVersion, streamNumber, ripe = decodeAddress(address)
readPosition = 20 # bypass the nonce, time, and object type
embeddedAddressVersion, varintLength = decodeVarint(data[readPosition:readPosition + 10])
readPosition += varintLength
embeddedStreamNumber, varintLength = decodeVarint(data[readPosition:readPosition + 10])
readPosition += varintLength
storedData = data[20:readPosition] # We'll store the address version and stream number (and some more) in the pubkeys table.
if addressVersion != embeddedAddressVersion:
logger.info('Pubkey decryption was UNsuccessful due to address version mismatch.')
return 'failed'
if streamNumber != embeddedStreamNumber:
logger.info('Pubkey decryption was UNsuccessful due to stream number mismatch.')
return 'failed'
tag = data[readPosition:readPosition + 32]
readPosition += 32
signedData = data[8:readPosition] # the time through the tag. More data is appended onto signedData below after the decryption.
encryptedData = data[readPosition:]
# Let us try to decrypt the pubkey
toAddress, cryptorObject = neededPubkeys[tag]
if toAddress != address:
logger.critical('decryptAndCheckPubkeyPayload failed due to toAddress mismatch. This is very peculiar. toAddress: %s, address %s' % (toAddress, address))
# the only way I can think that this could happen is if someone encodes their address data two different ways.
# That sort of address-malleability should have been caught by the UI or API and an error given to the user.
return 'failed'
try:
decryptedData = cryptorObject.decrypt(encryptedData)
except:
# Someone must have encrypted some data with a different key
# but tagged it with a tag for which we are watching.
logger.info('Pubkey decryption was unsuccessful.')
return 'failed'
readPosition = 0
bitfieldBehaviors = decryptedData[readPosition:readPosition + 4]
readPosition += 4
publicSigningKey = '\x04' + decryptedData[readPosition:readPosition + 64]
readPosition += 64
publicEncryptionKey = '\x04' + decryptedData[readPosition:readPosition + 64]
readPosition += 64
specifiedNonceTrialsPerByte, specifiedNonceTrialsPerByteLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += specifiedNonceTrialsPerByteLength
specifiedPayloadLengthExtraBytes, specifiedPayloadLengthExtraBytesLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += specifiedPayloadLengthExtraBytesLength
storedData += decryptedData[:readPosition]
signedData += decryptedData[:readPosition]
signatureLength, signatureLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += signatureLengthLength
signature = decryptedData[readPosition:readPosition + signatureLength]
if highlevelcrypto.verify(signedData, signature, hexlify(publicSigningKey)):
logger.info('ECDSA verify passed (within decryptAndCheckPubkeyPayload)')
else:
logger.info('ECDSA verify failed (within decryptAndCheckPubkeyPayload)')
return 'failed'
sha = hashlib.new('sha512')
sha.update(publicSigningKey + publicEncryptionKey)
ripeHasher = hashlib.new('ripemd160')
ripeHasher.update(sha.digest())
embeddedRipe = ripeHasher.digest()
if embeddedRipe != ripe:
# Although this pubkey object had the tag were were looking for and was
# encrypted with the correct encryption key, it doesn't contain the
# correct pubkeys. Someone is either being malicious or using buggy software.
logger.info('Pubkey decryption was UNsuccessful due to RIPE mismatch.')
return 'failed'
# Everything checked out. Insert it into the pubkeys table.
logger.info('within decryptAndCheckPubkeyPayload, addressVersion: %s, streamNumber: %s \n\
ripe %s\n\
publicSigningKey in hex: %s\n\
publicEncryptionKey in hex: %s' % (addressVersion,
streamNumber,
hexlify(ripe),
hexlify(publicSigningKey),
hexlify(publicEncryptionKey)
)
)
t = (address, addressVersion, storedData, int(time.time()), 'yes')
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
return 'successful'
except varintDecodeError as e:
logger.info('Pubkey decryption was UNsuccessful due to a malformed varint.')
return 'failed'
except Exception as e:
logger.critical('Pubkey decryption was UNsuccessful because of an unhandled exception! This is definitely a bug! \n%s' % traceback.format_exc())
return 'failed'
def checkAndShareObjectWithPeers(data):
"""
This function is called after either receiving an object off of the wire
or after receiving one as ackdata.
Returns the length of time that we should reserve to process this message
if we are receiving it off of the wire.
"""
if len(data) > 2 ** 18:
logger.info('The payload length of this object is too large (%s bytes). Ignoring it.' % len(data))
return 0
# Let us check to make sure that the proof of work is sufficient.
if not isProofOfWorkSufficient(data):
logger.info('Proof of work is insufficient.')
return 0
endOfLifeTime, = unpack('>Q', data[8:16])
if endOfLifeTime - int(time.time()) > 28 * 24 * 60 * 60 + 10800: # The TTL may not be larger than 28 days + 3 hours of wiggle room
logger.info('This object\'s End of Life time is too far in the future. Ignoring it. Time is %s' % endOfLifeTime)
return 0
if endOfLifeTime - int(time.time()) < - 3600: # The EOL time was more than an hour ago. That's too much.
logger.info('This object\'s End of Life time was more than an hour ago. Ignoring the object. Time is %s' % endOfLifeTime)
return 0
intObjectType, = unpack('>I', data[16:20])
try:
if intObjectType == 0:
_checkAndShareGetpubkeyWithPeers(data)
return 0.1
elif intObjectType == 1:
_checkAndSharePubkeyWithPeers(data)
return 0.1
elif intObjectType == 2:
_checkAndShareMsgWithPeers(data)
return 0.6
elif intObjectType == 3:
_checkAndShareBroadcastWithPeers(data)
return 0.6
else:
_checkAndShareUndefinedObjectWithPeers(data)
return 0.6
except varintDecodeError as e:
logger.debug("There was a problem with a varint while checking to see whether it was appropriate to share an object with peers. Some details: %s" % e)
except Exception as e:
logger.critical('There was a problem while checking to see whether it was appropriate to share an object with peers. This is definitely a bug! \n%s' % traceback.format_exc())
return 0
def _checkAndShareUndefinedObjectWithPeers(data):
embeddedTime, = unpack('>Q', data[8:16])
readPosition = 20 # bypass nonce, time, and object type
objectVersion, objectVersionLength = decodeVarint(
data[readPosition:readPosition + 9])
readPosition += objectVersionLength
streamNumber, streamNumberLength = decodeVarint(
data[readPosition:readPosition + 9])
if not streamNumber in streamsInWhichIAmParticipating:
logger.debug('The streamNumber %s isn\'t one we are interested in.' % streamNumber)
return
inventoryHash = calculateInventoryHash(data)
if inventoryHash in Inventory():
logger.debug('We have already received this undefined object. Ignoring.')
return
objectType, = unpack('>I', data[16:20])
Inventory()[inventoryHash] = (
objectType, streamNumber, data, embeddedTime,'')
logger.debug('advertising inv with hash: %s' % hexlify(inventoryHash))
broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
def _checkAndShareMsgWithPeers(data):
embeddedTime, = unpack('>Q', data[8:16])
readPosition = 20 # bypass nonce, time, and object type
objectVersion, objectVersionLength = decodeVarint(
data[readPosition:readPosition + 9])
readPosition += objectVersionLength
streamNumber, streamNumberLength = decodeVarint(
data[readPosition:readPosition + 9])
if not streamNumber in streamsInWhichIAmParticipating:
logger.debug('The streamNumber %s isn\'t one we are interested in.' % streamNumber)
return
readPosition += streamNumberLength
inventoryHash = calculateInventoryHash(data)
if inventoryHash in Inventory():
logger.debug('We have already received this msg message. Ignoring.')
return
# This msg message is valid. Let's let our peers know about it.
objectType = 2
Inventory()[inventoryHash] = (
objectType, streamNumber, data, embeddedTime,'')
logger.debug('advertising inv with hash: %s' % hexlify(inventoryHash))
broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
# Now let's enqueue it to be processed ourselves.
objectProcessorQueue.put((objectType,data))
def _checkAndShareGetpubkeyWithPeers(data):
if len(data) < 42:
logger.info('getpubkey message doesn\'t contain enough data. Ignoring.')
return
if len(data) > 200:
logger.info('getpubkey is abnormally long. Sanity check failed. Ignoring object.')
embeddedTime, = unpack('>Q', data[8:16])
readPosition = 20 # bypass the nonce, time, and object type
requestedAddressVersionNumber, addressVersionLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += addressVersionLength
streamNumber, streamNumberLength = decodeVarint(
data[readPosition:readPosition + 10])
if not streamNumber in streamsInWhichIAmParticipating:
logger.debug('The streamNumber %s isn\'t one we are interested in.' % streamNumber)
return
readPosition += streamNumberLength
inventoryHash = calculateInventoryHash(data)
if inventoryHash in Inventory():
logger.debug('We have already received this getpubkey request. Ignoring it.')
return
objectType = 0
Inventory()[inventoryHash] = (
objectType, streamNumber, data, embeddedTime,'')
# This getpubkey request is valid. Forward to peers.
logger.debug('advertising inv with hash: %s' % hexlify(inventoryHash))
broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
# Now let's queue it to be processed ourselves.
objectProcessorQueue.put((objectType,data))
def _checkAndSharePubkeyWithPeers(data):
if len(data) < 146 or len(data) > 440: # sanity check
return
embeddedTime, = unpack('>Q', data[8:16])
readPosition = 20 # bypass the nonce, time, and object type
addressVersion, varintLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += varintLength
streamNumber, varintLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += varintLength
if not streamNumber in streamsInWhichIAmParticipating:
logger.debug('The streamNumber %s isn\'t one we are interested in.' % streamNumber)
return
if addressVersion >= 4:
tag = data[readPosition:readPosition + 32]
logger.debug('tag in received pubkey is: %s' % hexlify(tag))
else:
tag = ''
inventoryHash = calculateInventoryHash(data)
if inventoryHash in Inventory():
logger.debug('We have already received this pubkey. Ignoring it.')
return
objectType = 1
Inventory()[inventoryHash] = (
objectType, streamNumber, data, embeddedTime, tag)
# This object is valid. Forward it to peers.
logger.debug('advertising inv with hash: %s' % hexlify(inventoryHash))
broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
# Now let's queue it to be processed ourselves.
objectProcessorQueue.put((objectType,data))
def _checkAndShareBroadcastWithPeers(data):
if len(data) < 180:
logger.debug('The payload length of this broadcast packet is unreasonably low. Someone is probably trying funny business. Ignoring message.')
return
embeddedTime, = unpack('>Q', data[8:16])
readPosition = 20 # bypass the nonce, time, and object type
broadcastVersion, broadcastVersionLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += broadcastVersionLength
if broadcastVersion >= 2:
streamNumber, streamNumberLength = decodeVarint(data[readPosition:readPosition + 10])
readPosition += streamNumberLength
if not streamNumber in streamsInWhichIAmParticipating:
logger.debug('The streamNumber %s isn\'t one we are interested in.' % streamNumber)
return
if broadcastVersion >= 3:
tag = data[readPosition:readPosition+32]
else:
tag = ''
inventoryHash = calculateInventoryHash(data)
if inventoryHash in Inventory():
logger.debug('We have already received this broadcast object. Ignoring.')
return
# It is valid. Let's let our peers know about it.
objectType = 3
Inventory()[inventoryHash] = (
objectType, streamNumber, data, embeddedTime, tag)
# This object is valid. Forward it to peers.
logger.debug('advertising inv with hash: %s' % hexlify(inventoryHash))
broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
# Now let's queue it to be processed ourselves.
objectProcessorQueue.put((objectType,data))

View File

@ -1,6 +1,5 @@
from __future__ import division
softwareVersion = '0.6.1'
verbose = 1
maximumAgeOfAnObjectThatIAmWillingToAccept = 216000 # This is obsolete with the change to protocol v3 but the singleCleaner thread still hasn't been updated so we need this a little longer.
lengthOfTimeToHoldOnToAllPubkeys = 2419200 # Equals 4 weeks. You could make this longer if you want but making it shorter would not be advisable because there is a very small possibility that it could keep you from obtaining a needed pubkey for a period of time.
@ -24,7 +23,6 @@ import time
import shutil # used for moving the data folder and copying keys.dat
import datetime
from os import path, environ
from struct import Struct
import traceback
from binascii import hexlify
@ -40,7 +38,6 @@ from helper_threading import *
from inventory import Inventory
config = BMConfigParser()
myECCryptorObjects = {}
MyECSubscriptionCryptorObjects = {}
myAddressesByHash = {} #The key in this dictionary is the RIPE hash which is encoded in an address and value is the address itself.
@ -68,9 +65,6 @@ alreadyAttemptedConnectionsListLock = threading.Lock()
alreadyAttemptedConnectionsListResetTime = int(
time.time()) # used to clear out the alreadyAttemptedConnectionsList periodically so that we will retry connecting to hosts to which we have already tried to connect.
numberOfObjectsThatWeHaveYetToGetPerPeer = {}
neededPubkeys = {}
eightBytesOfRandomDataUsedToDetectConnectionsToSelf = pack(
'>Q', random.randrange(1, 18446744073709551615))
successfullyDecryptMessageTimings = [
] # A list of the amounts of time it took to successfully decrypt msg messages
apiAddressGeneratorReturnQueue = Queue.Queue(
@ -125,109 +119,6 @@ frozen = getattr(sys,'frozen', None)
# security.
trustedPeer = None
# For UPnP
extPort = None
# for Tor hidden service
socksIP = None
#Compiled struct for packing/unpacking headers
#New code should use CreatePacket instead of Header.pack
Header = Struct('!L12sL4s')
#Service flags
NODE_NETWORK = 1
NODE_SSL = 2
#Bitfield flags
BITFIELD_DOESACK = 1
#Create a packet
def CreatePacket(command, payload=''):
payload_length = len(payload)
checksum = hashlib.sha512(payload).digest()[0:4]
b = bytearray(Header.size + payload_length)
Header.pack_into(b, 0, 0xE9BEB4D9, command, payload_length, checksum)
b[Header.size:] = payload
return bytes(b)
def encodeHost(host):
if host.find('.onion') > -1:
return '\xfd\x87\xd8\x7e\xeb\x43' + base64.b32decode(host.split(".")[0], True)
elif host.find(':') == -1:
return '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + \
socket.inet_aton(host)
else:
return socket.inet_pton(socket.AF_INET6, host)
def haveSSL(server = False):
# python < 2.7.9's ssl library does not support ECDSA server due to missing initialisation of available curves, but client works ok
if server == False:
return True
elif sys.version_info >= (2,7,9):
return True
return False
def checkSocksIP(host):
try:
if socksIP is None or not socksIP:
socksIP = socket.gethostbyname(config.get("bitmessagesettings", "sockshostname"))
except NameError:
socksIP = socket.gethostbyname(config.get("bitmessagesettings", "sockshostname"))
return socksIP == host
def assembleVersionMessage(remoteHost, remotePort, myStreamNumber, server = False):
payload = ''
payload += pack('>L', 3) # protocol version.
payload += pack('>q', NODE_NETWORK|(NODE_SSL if haveSSL(server) else 0)) # bitflags of the services I offer.
payload += pack('>q', int(time.time()))
payload += pack(
'>q', 1) # boolservices of remote connection; ignored by the remote host.
if checkSocksIP(remoteHost) and server: # prevent leaking of tor outbound IP
payload += encodeHost('127.0.0.1')
payload += pack('>H', 8444)
else:
payload += encodeHost(remoteHost)
payload += pack('>H', remotePort) # remote IPv6 and port
payload += pack('>q', 1) # bitflags of the services I offer.
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + pack(
'>L', 2130706433) # = 127.0.0.1. This will be ignored by the remote host. The actual remote connected IP will be used.
# we have a separate extPort and
# incoming over clearnet or
# outgoing through clearnet
if safeConfigGetBoolean('bitmessagesettings', 'upnp') and extPort \
and ((server and not checkSocksIP(remoteHost)) or \
(config.get("bitmessagesettings", "socksproxytype") == "none" and not server)):
payload += pack('>H', extPort)
elif checkSocksIP(remoteHost) and server: # incoming connection over Tor
payload += pack('>H', shared.config.getint('bitmessagesettings', 'onionport'))
else: # no extPort and not incoming over Tor
payload += pack('>H', shared.config.getint('bitmessagesettings', 'port'))
random.seed()
payload += eightBytesOfRandomDataUsedToDetectConnectionsToSelf
userAgent = '/PyBitmessage:' + shared.softwareVersion + '/'
payload += encodeVarint(len(userAgent))
payload += userAgent
payload += encodeVarint(
1) # The number of streams about which I care. PyBitmessage currently only supports 1 per connection.
payload += encodeVarint(myStreamNumber)
return CreatePacket('version', payload)
def assembleErrorMessage(fatal=0, banTime=0, inventoryVector='', errorText=''):
payload = encodeVarint(fatal)
payload += encodeVarint(banTime)
payload += encodeVarint(len(inventoryVector))
payload += inventoryVector
payload += encodeVarint(len(errorText))
payload += errorText
return CreatePacket('error', payload)
def lookupExeFolder():
if frozen:
if frozen == "macosx_app":
@ -318,18 +209,6 @@ def isAddressInMyAddressBookSubscriptionsListOrWhitelist(address):
return True
return False
def safeConfigGetBoolean(section,field):
try:
return config.getboolean(section,field)
except Exception, err:
return False
def safeConfigGet(section, option, default = None):
if config.has_option (section, option):
return config.get(section, option)
else:
return default
def decodeWalletImportFormat(WIFstring):
fullString = arithmetic.changebase(WIFstring,58,256)
privkey = fullString[:-4]
@ -358,11 +237,11 @@ def reloadMyAddressHashes():
#myPrivateKeys.clear()
keyfileSecure = checkSensitiveFilePermissions(appdata + 'keys.dat')
configSections = config.sections()
configSections = BMConfigParser().sections()
hasEnabledKeys = False
for addressInKeysFile in configSections:
if addressInKeysFile <> 'bitmessagesettings':
isEnabled = config.getboolean(addressInKeysFile, 'enabled')
isEnabled = BMConfigParser().getboolean(addressInKeysFile, 'enabled')
if isEnabled:
hasEnabledKeys = True
status,addressVersionNumber,streamNumber,hash = decodeAddress(addressInKeysFile)
@ -370,7 +249,7 @@ def reloadMyAddressHashes():
# Returns a simple 32 bytes of information encoded in 64 Hex characters,
# or null if there was an error.
privEncryptionKey = hexlify(decodeWalletImportFormat(
config.get(addressInKeysFile, 'privencryptionkey')))
BMConfigParser().get(addressInKeysFile, 'privencryptionkey')))
if len(privEncryptionKey) == 64:#It is 32 bytes encoded as 64 hex characters
myECCryptorObjects[hash] = highlevelcrypto.makeCryptor(privEncryptionKey)
@ -473,7 +352,7 @@ def doCleanShutdown():
logger.debug("Waiting for thread %s", thread.name)
thread.join()
if safeConfigGetBoolean('bitmessagesettings','daemon'):
if BMConfigParser().safeGetBoolean('bitmessagesettings','daemon'):
logger.info('Clean shutdown complete.')
thisapp.cleanup()
os._exit(0)
@ -881,7 +760,7 @@ def writeKeysFile():
fileNameExisted = False
# write the file
with open(fileName, 'wb') as configfile:
shared.config.write(configfile)
BMConfigParser().write(configfile)
# delete the backup
if fileNameExisted:
os.remove(fileNameBak)

7
src/state.py Normal file
View File

@ -0,0 +1,7 @@
neededPubkeys = {}
# For UPnP
extPort = None
# for Tor hidden service
socksIP = None

View File

@ -1,6 +1,8 @@
import shared
import os
from configparser import BMConfigParser
import shared
# This is used so that the translateText function can be used when we are in daemon mode and not using any QT functions.
class translateClass:
def __init__(self, context, text):
@ -16,7 +18,7 @@ def _translate(context, text, disambiguation = None, encoding = None, n = None):
return translateText(context, text, n)
def translateText(context, text, n = None):
if not shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'):
if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'daemon'):
try:
from PyQt4 import QtCore, QtGui
except Exception as err:

View File

@ -6,6 +6,7 @@ import socket
from struct import unpack, pack
import threading
import time
from configparser import BMConfigParser
from helper_threading import *
import shared
import tr
@ -175,9 +176,9 @@ class uPnPThread(threading.Thread, StoppableThread):
def __init__ (self):
threading.Thread.__init__(self, name="uPnPThread")
self.localPort = shared.config.getint('bitmessagesettings', 'port')
self.localPort = BMConfigParser().getint('bitmessagesettings', 'port')
try:
self.extPort = shared.config.getint('bitmessagesettings', 'extport')
self.extPort = BMConfigParser().getint('bitmessagesettings', 'extport')
except:
self.extPort = None
self.localIP = self.getLocalIP()
@ -195,7 +196,7 @@ class uPnPThread(threading.Thread, StoppableThread):
logger.debug("Starting UPnP thread")
logger.debug("Local IP: %s", self.localIP)
lastSent = 0
while shared.shutdown == 0 and shared.safeConfigGetBoolean('bitmessagesettings', 'upnp'):
while shared.shutdown == 0 and BMConfigParser().safeGetBoolean('bitmessagesettings', 'upnp'):
if time.time() - lastSent > self.sendSleep and len(self.routers) == 0:
try:
self.sendSearchRouter()
@ -203,7 +204,7 @@ class uPnPThread(threading.Thread, StoppableThread):
pass
lastSent = time.time()
try:
while shared.shutdown == 0 and shared.safeConfigGetBoolean('bitmessagesettings', 'upnp'):
while shared.shutdown == 0 and BMConfigParser().safeGetBoolean('bitmessagesettings', 'upnp'):
resp,(ip,port) = self.sock.recvfrom(1000)
if resp is None:
continue
@ -279,7 +280,7 @@ class uPnPThread(threading.Thread, StoppableThread):
router.AddPortMapping(extPort, self.localPort, localIP, 'TCP', 'BitMessage')
shared.extPort = extPort
self.extPort = extPort
shared.config.set('bitmessagesettings', 'extport', str(extPort))
BMConfigParser().set('bitmessagesettings', 'extport', str(extPort))
break
except UPnPError:
logger.debug("UPnP error: ", exc_info=True)

1
src/version.py Normal file
View File

@ -0,0 +1 @@
softwareVersion = '0.6.1'