Whitespace fixes

This commit is contained in:
Graham Campbell 2014-05-29 14:46:10 +01:00
parent cc21d629c9
commit 2a4acc27a3
29 changed files with 203 additions and 203 deletions

2
.gitignore vendored
View File

@ -5,4 +5,4 @@ src/build
src/dist src/dist
src/.project src/.project
src/.pydevproject src/.pydevproject
src/.settings/ src/.settings/

View File

@ -1,4 +1,4 @@
#PyBitmessage Installation Instructions #PyBitmessage Installation Instructions
For an up-to-date version of these instructions, please visit the For an up-to-date version of these instructions, please visit the
[Bitmessage Wiki](https://bitmessage.org/wiki/Compiling_instructions). [Bitmessage Wiki](https://bitmessage.org/wiki/Compiling_instructions).
@ -14,7 +14,7 @@ Here's a list of dependencies needed for PyBitmessage
- python2.7 - python2.7
- python2-qt4 (python-qt4 on Debian/Ubuntu) - python2-qt4 (python-qt4 on Debian/Ubuntu)
- openssl - openssl
- (Fedora & Redhat only) openssl-compat-bitcoin-libs - (Fedora & Redhat only) openssl-compat-bitcoin-libs
##Running PyBitmessage ##Running PyBitmessage
PyBitmessage can be run two ways: straight from source or via a package which PyBitmessage can be run two ways: straight from source or via a package which

View File

@ -12,7 +12,7 @@ warrantless wiretapping programs.
Development Development
---------- ----------
Bitmessage is a collaborative project. You are welcome to submit pull requests Bitmessage is a collaborative project. You are welcome to submit pull requests
although if you plan to put a non-trivial amount of work into coding new although if you plan to put a non-trivial amount of work into coding new
features, it is recommended that you first solicit feedback on the DevTalk features, it is recommended that you first solicit feedback on the DevTalk
pseudo-mailing list: pseudo-mailing list:

2
configure vendored
View File

@ -1 +1 @@

2
osx.sh
View File

@ -5,7 +5,7 @@
# Requires all build dependencies for Bitmessage # Requires all build dependencies for Bitmessage
# Especially important is openssl installed through brew # Especially important is openssl installed through brew
export ARCHFLAGS="-arch i386 -arch x86_64" export ARCHFLAGS="-arch i386 -arch x86_64"
if [[ -z "$1" ]]; then if [[ -z "$1" ]]; then
echo "Please supply a version number for this release as the first argument." echo "Please supply a version number for this release as the first argument."

View File

@ -4,7 +4,7 @@
comment= """ comment= """
This is not what you run to run the Bitmessage API. Instead, enable the API This is not what you run to run the Bitmessage API. Instead, enable the API
( https://bitmessage.org/wiki/API ) and optionally enable daemon mode ( https://bitmessage.org/wiki/API ) and optionally enable daemon mode
( https://bitmessage.org/wiki/Daemon ) then run bitmessagemain.py. ( https://bitmessage.org/wiki/Daemon ) then run bitmessagemain.py.
""" """
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -63,7 +63,7 @@ def connectToStream(streamNumber):
for row in queryData: for row in queryData:
shared.inventorySets[streamNumber].add(row[0]) shared.inventorySets[streamNumber].add(row[0])
if isOurOperatingSystemLimitedToHavingVeryFewHalfOpenConnections(): if isOurOperatingSystemLimitedToHavingVeryFewHalfOpenConnections():
# Some XP and Vista systems can only have 10 outgoing connections at a time. # Some XP and Vista systems can only have 10 outgoing connections at a time.
maximumNumberOfHalfOpenConnections = 9 maximumNumberOfHalfOpenConnections = 9
@ -236,7 +236,7 @@ class Main:
shared.doCleanShutdown() shared.doCleanShutdown()
#TODO: nice function but no one is using this #TODO: nice function but no one is using this
def getApiAddress(self): def getApiAddress(self):
if not shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'): if not shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
return None return None

View File

@ -62,11 +62,11 @@ def _translate(context, text):
def identiconize(address): def identiconize(address):
size = 48 size = 48
# If you include another identicon library, please generate an # If you include another identicon library, please generate an
# example identicon with the following md5 hash: # example identicon with the following md5 hash:
# 3fd4bf901b9d4ea1394f0fb358725b28 # 3fd4bf901b9d4ea1394f0fb358725b28
try: try:
identicon_lib = shared.config.get('bitmessagesettings', 'identiconlib') identicon_lib = shared.config.get('bitmessagesettings', 'identiconlib')
except: except:
@ -77,11 +77,11 @@ def identiconize(address):
# It can be used as a pseudo-password to salt the generation of the identicons to decrease the risk # 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. # of attacks where someone creates an address to mimic someone else's identicon.
identiconsuffix = shared.config.get('bitmessagesettings', 'identiconsuffix') identiconsuffix = shared.config.get('bitmessagesettings', 'identiconsuffix')
if not shared.config.getboolean('bitmessagesettings', 'useidenticons'): if not shared.config.getboolean('bitmessagesettings', 'useidenticons'):
idcon = QtGui.QIcon() idcon = QtGui.QIcon()
return idcon return idcon
if (identicon_lib[:len('qidenticon')] == 'qidenticon'): if (identicon_lib[:len('qidenticon')] == 'qidenticon'):
# print identicon_lib # print identicon_lib
# originally by: # originally by:
@ -115,7 +115,7 @@ def identiconize(address):
idcon = QtGui.QIcon() idcon = QtGui.QIcon()
idcon.addPixmap(pix, QtGui.QIcon.Normal, QtGui.QIcon.Off) idcon.addPixmap(pix, QtGui.QIcon.Normal, QtGui.QIcon.Off)
return idcon return idcon
def avatarize(address): def avatarize(address):
""" """
loads a supported image for the given address' hash form 'avatars' folder loads a supported image for the given address' hash form 'avatars' folder
@ -587,7 +587,7 @@ class MyForm(QtGui.QMainWindow):
self.ui.tableWidgetSubscriptions.setIconSize(QtCore.QSize(identicon_size, identicon_size)) self.ui.tableWidgetSubscriptions.setIconSize(QtCore.QSize(identicon_size, identicon_size))
self.ui.tableWidgetAddressBook.setIconSize(QtCore.QSize(identicon_size, identicon_size)) self.ui.tableWidgetAddressBook.setIconSize(QtCore.QSize(identicon_size, identicon_size))
self.ui.tableWidgetBlacklist.setIconSize(QtCore.QSize(identicon_size, identicon_size)) self.ui.tableWidgetBlacklist.setIconSize(QtCore.QSize(identicon_size, identicon_size))
self.UISignalThread = UISignaler() self.UISignalThread = UISignaler()
QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
"writeNewAddressToTable(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.writeNewAddressToTable) "writeNewAddressToTable(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.writeNewAddressToTable)
@ -631,7 +631,7 @@ class MyForm(QtGui.QMainWindow):
# structures were initialized. # structures were initialized.
self.rerenderComboBoxSendFrom() self.rerenderComboBoxSendFrom()
# Check to see whether we can connect to namecoin. Hide the 'Fetch Namecoin ID' button if we can't. # Check to see whether we can connect to namecoin. Hide the 'Fetch Namecoin ID' button if we can't.
try: try:
options = {} options = {}
@ -757,8 +757,8 @@ class MyForm(QtGui.QMainWindow):
where = "toaddress || fromaddress || subject || message" where = "toaddress || fromaddress || subject || message"
sqlStatement = ''' sqlStatement = '''
SELECT toaddress, fromaddress, subject, status, ackdata, lastactiontime SELECT toaddress, fromaddress, subject, status, ackdata, lastactiontime
FROM sent WHERE folder="sent" AND %s LIKE ? FROM sent WHERE folder="sent" AND %s LIKE ?
ORDER BY lastactiontime ORDER BY lastactiontime
''' % (where,) ''' % (where,)
@ -790,7 +790,7 @@ class MyForm(QtGui.QMainWindow):
if queryreturn != []: if queryreturn != []:
for row in queryreturn: for row in queryreturn:
toLabel, = row toLabel, = row
if toLabel == '': if toLabel == '':
if shared.config.has_section(toAddress): if shared.config.has_section(toAddress):
toLabel = shared.config.get(toAddress, 'label') toLabel = shared.config.get(toAddress, 'label')
@ -913,7 +913,7 @@ class MyForm(QtGui.QMainWindow):
fromLabel = '' fromLabel = ''
if shared.config.has_section(fromAddress): if shared.config.has_section(fromAddress):
fromLabel = shared.config.get(fromAddress, 'label') fromLabel = shared.config.get(fromAddress, 'label')
if fromLabel == '': # If the fromAddress isn't one of our addresses and isn't a chan if fromLabel == '': # If the fromAddress isn't one of our addresses and isn't a chan
queryreturn = sqlQuery( queryreturn = sqlQuery(
'''select label from addressbook where address=?''', fromAddress) '''select label from addressbook where address=?''', fromAddress)
@ -929,7 +929,7 @@ class MyForm(QtGui.QMainWindow):
fromLabel, = row fromLabel, = row
if fromLabel == '': if fromLabel == '':
fromLabel = fromAddress fromLabel = fromAddress
# message row # message row
self.ui.tableWidgetInbox.insertRow(0) self.ui.tableWidgetInbox.insertRow(0)
# to # to
@ -1231,7 +1231,7 @@ class MyForm(QtGui.QMainWindow):
soundFilename = shared.appdata + 'sounds/disconnected' soundFilename = shared.appdata + 'sounds/disconnected'
# sound when the connection status becomes green # sound when the connection status becomes green
elif category is self.SOUND_CONNECTION_GREEN: elif category is self.SOUND_CONNECTION_GREEN:
soundFilename = shared.appdata + 'sounds/green' soundFilename = shared.appdata + 'sounds/green'
if soundFilename is not None and play is True: if soundFilename is not None and play is True:
if not self.isConnectionSound(category): if not self.isConnectionSound(category):
@ -1251,7 +1251,7 @@ class MyForm(QtGui.QMainWindow):
gst_available=False gst_available=False
try: try:
subprocess.call(["gst123", soundFilename], subprocess.call(["gst123", soundFilename],
stdin=subprocess.PIPE, stdin=subprocess.PIPE,
stdout=subprocess.PIPE) stdout=subprocess.PIPE)
gst_available=True gst_available=True
except: except:
@ -1259,7 +1259,7 @@ class MyForm(QtGui.QMainWindow):
if not gst_available: if not gst_available:
try: try:
subprocess.call(["mpg123", soundFilename], subprocess.call(["mpg123", soundFilename],
stdin=subprocess.PIPE, stdin=subprocess.PIPE,
stdout=subprocess.PIPE) stdout=subprocess.PIPE)
gst_available=True gst_available=True
except: except:
@ -1267,7 +1267,7 @@ class MyForm(QtGui.QMainWindow):
else: else:
try: try:
subprocess.call(["aplay", soundFilename], subprocess.call(["aplay", soundFilename],
stdin=subprocess.PIPE, stdin=subprocess.PIPE,
stdout=subprocess.PIPE) stdout=subprocess.PIPE)
except: except:
print "WARNING: aplay must be installed in order to play WAV sounds" print "WARNING: aplay must be installed in order to play WAV sounds"
@ -1693,7 +1693,7 @@ class MyForm(QtGui.QMainWindow):
if queryreturn != []: if queryreturn != []:
for row in queryreturn: for row in queryreturn:
fromLabel, = row fromLabel, = row
if fromLabel == '': if fromLabel == '':
# It might be a broadcast message. We should check for that # It might be a broadcast message. We should check for that
# label. # label.
@ -1720,7 +1720,7 @@ class MyForm(QtGui.QMainWindow):
else: else:
self.ui.tableWidgetInbox.item( self.ui.tableWidgetInbox.item(
i, 1).setTextColor(QApplication.palette().text().color()) i, 1).setTextColor(QApplication.palette().text().color())
def rerenderInboxToLabels(self): def rerenderInboxToLabels(self):
for i in range(self.ui.tableWidgetInbox.rowCount()): for i in range(self.ui.tableWidgetInbox.rowCount()):
@ -1769,7 +1769,7 @@ class MyForm(QtGui.QMainWindow):
if queryreturn != []: if queryreturn != []:
for row in queryreturn: for row in queryreturn:
toLabel, = row toLabel, = row
if toLabel == '': if toLabel == '':
# Message might be to an address we own like a chan address. Let's look for that label. # Message might be to an address we own like a chan address. Let's look for that label.
if shared.config.has_section(addressToLookup): if shared.config.has_section(addressToLookup):
@ -1926,7 +1926,7 @@ class MyForm(QtGui.QMainWindow):
'''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)''', *t) '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)''', *t)
toLabel = self.str_broadcast_subscribers toLabel = self.str_broadcast_subscribers
self.displayNewSentMessage( self.displayNewSentMessage(
toAddress, toLabel, fromAddress, subject, message, ackdata) toAddress, toLabel, fromAddress, subject, message, ackdata)
@ -2183,7 +2183,7 @@ class MyForm(QtGui.QMainWindow):
return return
label = self.NewSubscriptionDialogInstance.ui.newsubscriptionlabel.text().toUtf8() label = self.NewSubscriptionDialogInstance.ui.newsubscriptionlabel.text().toUtf8()
self.addSubscription(address, label) self.addSubscription(address, label)
# Now, if the user wants to display old broadcasts, let's get them out of the inventory and put them # Now, if the user wants to display old broadcasts, let's get them out of the inventory and put them
# in the objectProcessorQueue to be processed # in the objectProcessorQueue to be processed
if self.NewSubscriptionDialogInstance.ui.checkBoxDisplayMessagesAlreadyInInventory.isChecked(): if self.NewSubscriptionDialogInstance.ui.checkBoxDisplayMessagesAlreadyInInventory.isChecked():
status, addressVersion, streamNumber, ripe = decodeAddress(address) status, addressVersion, streamNumber, ripe = decodeAddress(address)
@ -2253,11 +2253,11 @@ class MyForm(QtGui.QMainWindow):
self.settingsDialogInstance.ui.checkBoxUseIdenticons.isChecked())) self.settingsDialogInstance.ui.checkBoxUseIdenticons.isChecked()))
shared.config.set('bitmessagesettings', 'replybelow', str( shared.config.set('bitmessagesettings', 'replybelow', str(
self.settingsDialogInstance.ui.checkBoxReplyBelow.isChecked())) self.settingsDialogInstance.ui.checkBoxReplyBelow.isChecked()))
lang_ind = int(self.settingsDialogInstance.ui.languageComboBox.currentIndex()) lang_ind = int(self.settingsDialogInstance.ui.languageComboBox.currentIndex())
if not languages[lang_ind] == 'other': if not languages[lang_ind] == 'other':
shared.config.set('bitmessagesettings', 'userlocale', languages[lang_ind]) shared.config.set('bitmessagesettings', 'userlocale', languages[lang_ind])
if int(shared.config.get('bitmessagesettings', 'port')) != int(self.settingsDialogInstance.ui.lineEditTCPPort.text()): if int(shared.config.get('bitmessagesettings', 'port')) != int(self.settingsDialogInstance.ui.lineEditTCPPort.text()):
if not shared.safeConfigGetBoolean('bitmessagesettings', 'dontconnect'): if not shared.safeConfigGetBoolean('bitmessagesettings', 'dontconnect'):
QMessageBox.about(self, _translate("MainWindow", "Restart"), _translate( QMessageBox.about(self, _translate("MainWindow", "Restart"), _translate(
@ -2583,7 +2583,7 @@ class MyForm(QtGui.QMainWindow):
'''select message from inbox where msgid=?''', msgid) '''select message from inbox where msgid=?''', msgid)
if queryreturn != []: if queryreturn != []:
for row in queryreturn: for row in queryreturn:
messageAtCurrentInboxRow, = row messageAtCurrentInboxRow, = row
lines = messageAtCurrentInboxRow.split('\n') lines = messageAtCurrentInboxRow.split('\n')
for i in xrange(len(lines)): for i in xrange(len(lines)):
@ -2611,7 +2611,7 @@ class MyForm(QtGui.QMainWindow):
self.ui.tableWidgetInbox.item(currentRow, 2).setFont(font) self.ui.tableWidgetInbox.item(currentRow, 2).setFont(font)
self.ui.tableWidgetInbox.item(currentRow, 3).setFont(font) self.ui.tableWidgetInbox.item(currentRow, 3).setFont(font)
self.changedInboxUnread() self.changedInboxUnread()
# self.ui.tableWidgetInbox.selectRow(currentRow + 1) # self.ui.tableWidgetInbox.selectRow(currentRow + 1)
# This doesn't de-select the last message if you try to mark it unread, but that doesn't interfere. Might not be necessary. # This doesn't de-select the last message if you try to mark it unread, but that doesn't interfere. Might not be necessary.
# We could also select upwards, but then our problem would be with the topmost message. # We could also select upwards, but then our problem would be with the topmost message.
# self.ui.tableWidgetInbox.clearSelection() manages to mark the message as read again. # self.ui.tableWidgetInbox.clearSelection() manages to mark the message as read again.
@ -2666,20 +2666,20 @@ class MyForm(QtGui.QMainWindow):
self.setBroadcastEnablementDependingOnWhetherThisIsAChanAddress(toAddressAtCurrentInboxRow) self.setBroadcastEnablementDependingOnWhetherThisIsAChanAddress(toAddressAtCurrentInboxRow)
self.ui.lineEditTo.setText(str(fromAddressAtCurrentInboxRow)) self.ui.lineEditTo.setText(str(fromAddressAtCurrentInboxRow))
# If the previous message was to a chan then we should send our reply to the chan rather than to the particular person who sent the message. # If the previous message was to a chan then we should send our reply to the chan rather than to the particular person who sent the message.
if shared.config.has_section(toAddressAtCurrentInboxRow): if shared.config.has_section(toAddressAtCurrentInboxRow):
if shared.safeConfigGetBoolean(toAddressAtCurrentInboxRow, 'chan'): if shared.safeConfigGetBoolean(toAddressAtCurrentInboxRow, 'chan'):
print 'original sent to a chan. Setting the to address in the reply to the chan address.' print 'original sent to a chan. Setting the to address in the reply to the chan address.'
self.ui.lineEditTo.setText(str(toAddressAtCurrentInboxRow)) self.ui.lineEditTo.setText(str(toAddressAtCurrentInboxRow))
listOfAddressesInComboBoxSendFrom = [str(self.ui.comboBoxSendFrom.itemData(i).toPyObject()) for i in range(self.ui.comboBoxSendFrom.count())] listOfAddressesInComboBoxSendFrom = [str(self.ui.comboBoxSendFrom.itemData(i).toPyObject()) for i in range(self.ui.comboBoxSendFrom.count())]
if toAddressAtCurrentInboxRow in listOfAddressesInComboBoxSendFrom: if toAddressAtCurrentInboxRow in listOfAddressesInComboBoxSendFrom:
currentIndex = listOfAddressesInComboBoxSendFrom.index(toAddressAtCurrentInboxRow) currentIndex = listOfAddressesInComboBoxSendFrom.index(toAddressAtCurrentInboxRow)
self.ui.comboBoxSendFrom.setCurrentIndex(currentIndex) self.ui.comboBoxSendFrom.setCurrentIndex(currentIndex)
else: else:
self.ui.comboBoxSendFrom.setCurrentIndex(0) self.ui.comboBoxSendFrom.setCurrentIndex(0)
quotedText = self.quoted_text(unicode(messageAtCurrentInboxRow, 'utf-8')) quotedText = self.quoted_text(unicode(messageAtCurrentInboxRow, 'utf-8'))
self.ui.textEditMessage.setText(quotedText) self.ui.textEditMessage.setText(quotedText)
if self.ui.tableWidgetInbox.item(currentInboxRow, 2).text()[0:3] in ['Re:', 'RE:']: if self.ui.tableWidgetInbox.item(currentInboxRow, 2).text()[0:3] in ['Re:', 'RE:']:
@ -2877,7 +2877,7 @@ class MyForm(QtGui.QMainWindow):
# Group of functions for the Subscriptions dialog box # Group of functions for the Subscriptions dialog box
def on_action_SubscriptionsNew(self): def on_action_SubscriptionsNew(self):
self.click_pushButtonAddSubscription() self.click_pushButtonAddSubscription()
def on_action_SubscriptionsDelete(self): def on_action_SubscriptionsDelete(self):
print 'clicked Delete' print 'clicked Delete'
currentRow = self.ui.tableWidgetSubscriptions.currentRow() currentRow = self.ui.tableWidgetSubscriptions.currentRow()
@ -3044,16 +3044,16 @@ class MyForm(QtGui.QMainWindow):
def on_action_YourIdentitiesSetAvatar(self): def on_action_YourIdentitiesSetAvatar(self):
self.on_action_SetAvatar(self.ui.tableWidgetYourIdentities) self.on_action_SetAvatar(self.ui.tableWidgetYourIdentities)
def on_action_AddressBookSetAvatar(self): def on_action_AddressBookSetAvatar(self):
self.on_action_SetAvatar(self.ui.tableWidgetAddressBook) self.on_action_SetAvatar(self.ui.tableWidgetAddressBook)
def on_action_SubscriptionsSetAvatar(self): def on_action_SubscriptionsSetAvatar(self):
self.on_action_SetAvatar(self.ui.tableWidgetSubscriptions) self.on_action_SetAvatar(self.ui.tableWidgetSubscriptions)
def on_action_BlacklistSetAvatar(self): def on_action_BlacklistSetAvatar(self):
self.on_action_SetAvatar(self.ui.tableWidgetBlacklist) self.on_action_SetAvatar(self.ui.tableWidgetBlacklist)
def on_action_SetAvatar(self, thisTableWidget): def on_action_SetAvatar(self, thisTableWidget):
# thisTableWidget = self.ui.tableWidgetYourIdentities # thisTableWidget = self.ui.tableWidgetYourIdentities
if not os.path.exists(shared.appdata + 'avatars/'): if not os.path.exists(shared.appdata + 'avatars/'):
@ -3099,7 +3099,7 @@ class MyForm(QtGui.QMainWindow):
self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
else: else:
overwrite = QtGui.QMessageBox.No overwrite = QtGui.QMessageBox.No
# copy the image file to the appdata folder # copy the image file to the appdata folder
if (not exists) | (overwrite == QtGui.QMessageBox.Yes): if (not exists) | (overwrite == QtGui.QMessageBox.Yes):
if overwrite == QtGui.QMessageBox.Yes: if overwrite == QtGui.QMessageBox.Yes:
@ -3121,7 +3121,7 @@ class MyForm(QtGui.QMainWindow):
self.rerenderInboxToLabels() self.rerenderInboxToLabels()
self.rerenderSentFromLabels() self.rerenderSentFromLabels()
self.rerenderSentToLabels() self.rerenderSentToLabels()
def on_context_menuYourIdentities(self, point): def on_context_menuYourIdentities(self, point):
self.popMenu.exec_( self.popMenu.exec_(
self.ui.tableWidgetYourIdentities.mapToGlobal(point)) self.ui.tableWidgetYourIdentities.mapToGlobal(point))
@ -3166,7 +3166,7 @@ class MyForm(QtGui.QMainWindow):
font = QFont() font = QFont()
font.setBold(False) font.setBold(False)
self.ui.textEditInboxMessage.setCurrentFont(font) self.ui.textEditInboxMessage.setCurrentFont(font)
fromAddress = str(self.ui.tableWidgetInbox.item( fromAddress = str(self.ui.tableWidgetInbox.item(
currentRow, 1).data(Qt.UserRole).toPyObject()) currentRow, 1).data(Qt.UserRole).toPyObject())
msgid = str(self.ui.tableWidgetInbox.item( msgid = str(self.ui.tableWidgetInbox.item(
@ -3296,7 +3296,7 @@ class helpDialog(QtGui.QDialog):
self.parent = parent self.parent = parent
self.ui.labelHelpURI.setOpenExternalLinks(True) self.ui.labelHelpURI.setOpenExternalLinks(True)
QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self)) QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self))
class connectDialog(QtGui.QDialog): class connectDialog(QtGui.QDialog):
def __init__(self, parent): def __init__(self, parent):
@ -3346,8 +3346,8 @@ class settingsDialog(QtGui.QDialog):
shared.safeConfigGetBoolean('bitmessagesettings', 'useidenticons')) shared.safeConfigGetBoolean('bitmessagesettings', 'useidenticons'))
self.ui.checkBoxReplyBelow.setChecked( self.ui.checkBoxReplyBelow.setChecked(
shared.safeConfigGetBoolean('bitmessagesettings', 'replybelow')) shared.safeConfigGetBoolean('bitmessagesettings', 'replybelow'))
global languages global languages
languages = ['system','en','eo','fr','de','es','ru','no','ar','zh_cn','ja','nl','en_pirate','other'] languages = ['system','en','eo','fr','de','es','ru','no','ar','zh_cn','ja','nl','en_pirate','other']
user_countrycode = str(shared.config.get('bitmessagesettings', 'userlocale')) user_countrycode = str(shared.config.get('bitmessagesettings', 'userlocale'))
if user_countrycode in languages: if user_countrycode in languages:
@ -3355,7 +3355,7 @@ class settingsDialog(QtGui.QDialog):
else: else:
curr_index = languages.index('other') curr_index = languages.index('other')
self.ui.languageComboBox.setCurrentIndex(curr_index) self.ui.languageComboBox.setCurrentIndex(curr_index)
if shared.appdata == '': if shared.appdata == '':
self.ui.checkBoxPortableMode.setChecked(True) self.ui.checkBoxPortableMode.setChecked(True)
if 'darwin' in sys.platform: if 'darwin' in sys.platform:
@ -3453,8 +3453,8 @@ class settingsDialog(QtGui.QDialog):
shared.config.get('bitmessagesettings', 'stopresendingafterxdays'))) shared.config.get('bitmessagesettings', 'stopresendingafterxdays')))
self.ui.lineEditMonths.setText(str( self.ui.lineEditMonths.setText(str(
shared.config.get('bitmessagesettings', 'stopresendingafterxmonths'))) shared.config.get('bitmessagesettings', 'stopresendingafterxmonths')))
#'System' tab removed for now. #'System' tab removed for now.
"""try: """try:
maxCores = shared.config.getint('bitmessagesettings', 'maxcores') maxCores = shared.config.getint('bitmessagesettings', 'maxcores')
@ -3507,7 +3507,7 @@ class settingsDialog(QtGui.QDialog):
def namecoinTypeChanged(self, checked): def namecoinTypeChanged(self, checked):
nmctype = self.getNamecoinType() nmctype = self.getNamecoinType()
assert nmctype == "namecoind" or nmctype == "nmcontrol" assert nmctype == "namecoind" or nmctype == "nmcontrol"
isNamecoind = (nmctype == "namecoind") isNamecoind = (nmctype == "namecoind")
self.ui.lineEditNamecoinUser.setEnabled(isNamecoind) self.ui.lineEditNamecoinUser.setEnabled(isNamecoind)
self.ui.labelNamecoinUser.setEnabled(isNamecoind) self.ui.labelNamecoinUser.setEnabled(isNamecoind)
@ -3601,7 +3601,7 @@ class AddAddressDialog(QtGui.QDialog):
elif status == 'success': elif status == 'success':
self.ui.labelAddressCheck.setText( self.ui.labelAddressCheck.setText(
_translate("MainWindow", "Address is valid.")) _translate("MainWindow", "Address is valid."))
class NewSubscriptionDialog(QtGui.QDialog): class NewSubscriptionDialog(QtGui.QDialog):
def __init__(self, parent): def __init__(self, parent):
@ -3690,7 +3690,7 @@ class newChanDialog(QtGui.QDialog):
self.ui.setupUi(self) self.ui.setupUi(self)
self.parent = parent self.parent = parent
self.ui.groupBoxCreateChan.setHidden(True) self.ui.groupBoxCreateChan.setHidden(True)
QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self)) QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self))
class iconGlossaryDialog(QtGui.QDialog): class iconGlossaryDialog(QtGui.QDialog):
@ -3777,7 +3777,7 @@ class UISignaler(QThread):
def run(): def run():
app = QtGui.QApplication(sys.argv) app = QtGui.QApplication(sys.argv)
translator = QtCore.QTranslator() translator = QtCore.QTranslator()
try: try:
locale_countrycode = str(locale.getdefaultlocale()[0]) locale_countrycode = str(locale.getdefaultlocale()[0])
except: except:
@ -3790,7 +3790,7 @@ def run():
translation_path = os.path.join(sys._MEIPASS, "translations/bitmessage_") translation_path = os.path.join(sys._MEIPASS, "translations/bitmessage_")
except Exception, e: except Exception, e:
translation_path = "translations/bitmessage_" translation_path = "translations/bitmessage_"
if shared.config.get('bitmessagesettings', 'userlocale') == 'system': if shared.config.get('bitmessagesettings', 'userlocale') == 'system':
# try to detect the users locale otherwise fallback to English # try to detect the users locale otherwise fallback to English
try: try:

View File

@ -307,5 +307,5 @@ def pointMult(secret):
OpenSSL.BN_free(priv_key) OpenSSL.BN_free(priv_key)
OpenSSL.EC_KEY_free(k) OpenSSL.EC_KEY_free(k)
return mb.raw return mb.raw

View File

@ -42,4 +42,4 @@ class objectHashHolder(threading.Thread):
self.collectionOfPeerLists[random.randrange(0, 10)].append(peerDetails) self.collectionOfPeerLists[random.randrange(0, 10)].append(peerDetails)
def close(self): def close(self):
self.shutdown = True self.shutdown = True

View File

@ -31,7 +31,7 @@ class objectProcessor(threading.Thread):
It may be the case that the last time Bitmessage was running, the user It may be the case that the last time Bitmessage was running, the user
closed it before it finished processing everything in the closed it before it finished processing everything in the
objectProcessorQueue. Assuming that Bitmessage wasn't closed forcefully, objectProcessorQueue. Assuming that Bitmessage wasn't closed forcefully,
it should have saved the data in the queue into the objectprocessorqueue it should have saved the data in the queue into the objectprocessorqueue
table. Let's pull it out. table. Let's pull it out.
""" """
queryreturn = sqlQuery( queryreturn = sqlQuery(
@ -79,7 +79,7 @@ class objectProcessor(threading.Thread):
logger.debug('Saved %s objects from the objectProcessorQueue to disk. objectProcessorThread exiting.' % str(numberOfObjectsThatWereInTheObjectProcessorQueue)) logger.debug('Saved %s objects from the objectProcessorQueue to disk. objectProcessorThread exiting.' % str(numberOfObjectsThatWereInTheObjectProcessorQueue))
shared.shutdown = 2 shared.shutdown = 2
break break
def processgetpubkey(self, data): def processgetpubkey(self, data):
readPosition = 8 # bypass the nonce readPosition = 8 # bypass the nonce
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4]) embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
@ -146,9 +146,9 @@ class objectProcessor(threading.Thread):
except: except:
lastPubkeySendTime = 0 lastPubkeySendTime = 0
if lastPubkeySendTime > time.time() - shared.lengthOfTimeToHoldOnToAllPubkeys: # If the last time we sent our pubkey was more recent than 28 days ago... if lastPubkeySendTime > time.time() - shared.lengthOfTimeToHoldOnToAllPubkeys: # If the last time we sent our pubkey was more recent than 28 days ago...
logger.info('Found getpubkey-requested-item in my list of EC hashes BUT we already sent it recently. Ignoring request. The lastPubkeySendTime is: %s' % lastPubkeySendTime) logger.info('Found getpubkey-requested-item in my list of EC hashes BUT we already sent it recently. Ignoring request. The lastPubkeySendTime is: %s' % lastPubkeySendTime)
return return
logger.info('Found getpubkey-requested-hash in my list of EC hashes. Telling Worker thread to do the POW for a pubkey message and send it out.') logger.info('Found getpubkey-requested-hash in my list of EC hashes. Telling Worker thread to do the POW for a pubkey message and send it out.')
if requestedAddressVersionNumber == 2: if requestedAddressVersionNumber == 2:
shared.workerQueue.put(( shared.workerQueue.put((
'doPOWForMyV2Pubkey', requestedHash)) 'doPOWForMyV2Pubkey', requestedHash))
@ -213,10 +213,10 @@ class objectProcessor(threading.Thread):
logger.info('within recpubkey, addressVersion: %s, streamNumber: %s \n\ logger.info('within recpubkey, addressVersion: %s, streamNumber: %s \n\
ripe %s\n\ ripe %s\n\
publicSigningKey in hex: %s\n\ publicSigningKey in hex: %s\n\
publicEncryptionKey in hex: %s' % (addressVersion, publicEncryptionKey in hex: %s' % (addressVersion,
streamNumber, streamNumber,
ripe.encode('hex'), ripe.encode('hex'),
publicSigningKey.encode('hex'), publicSigningKey.encode('hex'),
publicEncryptionKey.encode('hex') publicEncryptionKey.encode('hex')
) )
) )
@ -271,15 +271,15 @@ class objectProcessor(threading.Thread):
ripeHasher = hashlib.new('ripemd160') ripeHasher = hashlib.new('ripemd160')
ripeHasher.update(sha.digest()) ripeHasher.update(sha.digest())
ripe = ripeHasher.digest() ripe = ripeHasher.digest()
logger.info('within recpubkey, addressVersion: %s, streamNumber: %s \n\ logger.info('within recpubkey, addressVersion: %s, streamNumber: %s \n\
ripe %s\n\ ripe %s\n\
publicSigningKey in hex: %s\n\ publicSigningKey in hex: %s\n\
publicEncryptionKey in hex: %s' % (addressVersion, publicEncryptionKey in hex: %s' % (addressVersion,
streamNumber, streamNumber,
ripe.encode('hex'), ripe.encode('hex'),
publicSigningKey.encode('hex'), publicSigningKey.encode('hex'),
publicEncryptionKey.encode('hex') publicEncryptionKey.encode('hex')
) )
) )
@ -298,13 +298,13 @@ class objectProcessor(threading.Thread):
if addressVersion == 4: if addressVersion == 4:
""" """
There exist a function: shared.decryptAndCheckPubkeyPayload which does something almost There exist a function: shared.decryptAndCheckPubkeyPayload which does something almost
the same as this section of code. There are differences, however; one being that the same as this section of code. There are differences, however; one being that
decryptAndCheckPubkeyPayload requires that a cryptor object be created each time it is decryptAndCheckPubkeyPayload requires that a cryptor object be created each time it is
run which is an expensive operation. This, on the other hand, keeps them saved in run which is an expensive operation. This, on the other hand, keeps them saved in
the shared.neededPubkeys dictionary so that if an attacker sends us many the shared.neededPubkeys dictionary so that if an attacker sends us many
incorrectly-tagged pubkeys, which would force us to try to decrypt them, this code incorrectly-tagged pubkeys, which would force us to try to decrypt them, this code
would run and handle that event quite quickly. would run and handle that event quite quickly.
""" """
if len(data) < 350: # sanity check. if len(data) < 350: # sanity check.
logger.debug('(within processpubkey) payloadLength less than 350. Sanity check failed.') logger.debug('(within processpubkey) payloadLength less than 350. Sanity check failed.')
return return
@ -367,14 +367,14 @@ class objectProcessor(threading.Thread):
if tag != hashlib.sha512(hashlib.sha512(encodeVarint(addressVersion) + encodeVarint(streamNumber) + ripe).digest()).digest()[32:]: if tag != hashlib.sha512(hashlib.sha512(encodeVarint(addressVersion) + encodeVarint(streamNumber) + ripe).digest()).digest()[32:]:
logger.info('Someone was trying to act malicious: tag doesn\'t match the keys in this pubkey message. Ignoring it.') logger.info('Someone was trying to act malicious: tag doesn\'t match the keys in this pubkey message. Ignoring it.')
return return
logger.info('within recpubkey, addressVersion: %s, streamNumber: %s \n\ logger.info('within recpubkey, addressVersion: %s, streamNumber: %s \n\
ripe %s\n\ ripe %s\n\
publicSigningKey in hex: %s\n\ publicSigningKey in hex: %s\n\
publicEncryptionKey in hex: %s' % (addressVersion, publicEncryptionKey in hex: %s' % (addressVersion,
streamNumber, streamNumber,
ripe.encode('hex'), ripe.encode('hex'),
publicSigningKey.encode('hex'), publicSigningKey.encode('hex'),
publicEncryptionKey.encode('hex') publicEncryptionKey.encode('hex')
) )
) )
@ -435,14 +435,14 @@ class objectProcessor(threading.Thread):
data[readPosition:]) data[readPosition:])
toRipe = key # This is the RIPE hash of my pubkeys. We need this below to compare to the destination_ripe included in the encrypted data. toRipe = key # This is the RIPE hash of my pubkeys. We need this below to compare to the destination_ripe included in the encrypted data.
initialDecryptionSuccessful = True initialDecryptionSuccessful = True
logger.info('EC decryption successful using key associated with ripe hash: %s' % key.encode('hex')) logger.info('EC decryption successful using key associated with ripe hash: %s' % key.encode('hex'))
break break
except Exception as err: except Exception as err:
pass pass
# print 'cryptorObject.decrypt Exception:', err # print 'cryptorObject.decrypt Exception:', err
if not initialDecryptionSuccessful: if not initialDecryptionSuccessful:
# This is not a message bound for me. # This is not a message bound for me.
logger.info('Length of time program spent failing to decrypt this message: %s seconds.' % (time.time() - messageProcessingStartTime,)) logger.info('Length of time program spent failing to decrypt this message: %s seconds.' % (time.time() - messageProcessingStartTime,))
return return
# This is a message bound for me. # This is a message bound for me.
@ -453,16 +453,16 @@ class objectProcessor(threading.Thread):
decryptedData[readPosition:readPosition + 10]) decryptedData[readPosition:readPosition + 10])
readPosition += messageVersionLength readPosition += messageVersionLength
if messageVersion != 1: if messageVersion != 1:
logger.info('Cannot understand message versions other than one. Ignoring message.') logger.info('Cannot understand message versions other than one. Ignoring message.')
return return
sendersAddressVersionNumber, sendersAddressVersionNumberLength = decodeVarint( sendersAddressVersionNumber, sendersAddressVersionNumberLength = decodeVarint(
decryptedData[readPosition:readPosition + 10]) decryptedData[readPosition:readPosition + 10])
readPosition += sendersAddressVersionNumberLength readPosition += sendersAddressVersionNumberLength
if sendersAddressVersionNumber == 0: if sendersAddressVersionNumber == 0:
logger.info('Cannot understand sendersAddressVersionNumber = 0. Ignoring message.') logger.info('Cannot understand sendersAddressVersionNumber = 0. Ignoring message.')
return return
if sendersAddressVersionNumber > 4: if sendersAddressVersionNumber > 4:
logger.info('Sender\'s address version number %s not yet supported. Ignoring message.' % sendersAddressVersionNumber) logger.info('Sender\'s address version number %s not yet supported. Ignoring message.' % sendersAddressVersionNumber)
return return
if len(decryptedData) < 170: if len(decryptedData) < 170:
logger.info('Length of the unencrypted data is unreasonably short. Sanity check failed. Ignoring message.') logger.info('Length of the unencrypted data is unreasonably short. Sanity check failed. Ignoring message.')
@ -606,7 +606,7 @@ class objectProcessor(threading.Thread):
body = message body = message
subject = '' subject = ''
elif messageEncodingType == 0: elif messageEncodingType == 0:
logger.info('messageEncodingType == 0. Doing nothing with the message. They probably just sent it so that we would store their public key or send their ack data for them.') logger.info('messageEncodingType == 0. Doing nothing with the message. They probably just sent it so that we would store their public key or send their ack data for them.')
else: else:
body = 'Unknown encoding type.\n\n' + repr(message) body = 'Unknown encoding type.\n\n' + repr(message)
subject = '' subject = ''
@ -678,7 +678,7 @@ class objectProcessor(threading.Thread):
sum += item sum += item
logger.debug('Time to decrypt this message successfully: %s\n\ logger.debug('Time to decrypt this message successfully: %s\n\
Average time for all message decryption successes since startup: %s.' % Average time for all message decryption successes since startup: %s.' %
(timeRequiredToAttemptToDecryptMessage, sum / len(shared.successfullyDecryptMessageTimings)) (timeRequiredToAttemptToDecryptMessage, sum / len(shared.successfullyDecryptMessageTimings))
) )
@ -703,7 +703,7 @@ class objectProcessor(threading.Thread):
data[readPosition:readPosition + 9]) data[readPosition:readPosition + 9])
readPosition += broadcastVersionLength readPosition += broadcastVersionLength
if broadcastVersion < 1 or broadcastVersion > 3: if broadcastVersion < 1 or broadcastVersion > 3:
logger.debug('Cannot decode incoming broadcast versions higher than 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.') logger.debug('Cannot decode incoming broadcast versions higher than 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.')
return return
if broadcastVersion == 1: if broadcastVersion == 1:
beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table
@ -863,7 +863,7 @@ class objectProcessor(threading.Thread):
sendersStream, sendersStreamLength = decodeVarint( sendersStream, sendersStreamLength = decodeVarint(
decryptedData[readPosition:readPosition + 9]) decryptedData[readPosition:readPosition + 9])
if sendersStream != cleartextStreamNumber: if sendersStream != cleartextStreamNumber:
logger.info('The stream number outside of the encryption on which the POW was completed doesn\'t match the stream number inside the encryption. Ignoring broadcast.') logger.info('The stream number outside of the encryption on which the POW was completed doesn\'t match the stream number inside the encryption. Ignoring broadcast.')
return return
readPosition += sendersStreamLength readPosition += sendersStreamLength
behaviorBitfield = decryptedData[readPosition:readPosition + 4] behaviorBitfield = decryptedData[readPosition:readPosition + 4]
@ -891,7 +891,7 @@ class objectProcessor(threading.Thread):
ripe.update(sha.digest()) ripe.update(sha.digest())
if toRipe != ripe.digest(): if toRipe != ripe.digest():
logger.info('The encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.') logger.info('The encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.')
return return
messageEncodingType, messageEncodingTypeLength = decodeVarint( messageEncodingType, messageEncodingTypeLength = decodeVarint(
decryptedData[readPosition:readPosition + 9]) decryptedData[readPosition:readPosition + 9])
@ -982,7 +982,7 @@ class objectProcessor(threading.Thread):
embeddedTag = data[readPosition:readPosition+32] embeddedTag = data[readPosition:readPosition+32]
readPosition += 32 readPosition += 32
if embeddedTag not in shared.MyECSubscriptionCryptorObjects: if embeddedTag not in shared.MyECSubscriptionCryptorObjects:
logger.debug('We\'re not interested in this broadcast.') logger.debug('We\'re not interested in this broadcast.')
return return
# We are interested in this broadcast because of its tag. # We are interested in this broadcast because of its tag.
cryptorObject = shared.MyECSubscriptionCryptorObjects[embeddedTag] cryptorObject = shared.MyECSubscriptionCryptorObjects[embeddedTag]
@ -990,7 +990,7 @@ class objectProcessor(threading.Thread):
decryptedData = cryptorObject.decrypt(data[readPosition:]) decryptedData = cryptorObject.decrypt(data[readPosition:])
logger.debug('EC decryption successful') logger.debug('EC decryption successful')
except Exception as err: except Exception as err:
logger.debug('Broadcast version 3 decryption Unsuccessful.') logger.debug('Broadcast version 3 decryption Unsuccessful.')
return return
signedBroadcastVersion, readPosition = decodeVarint( signedBroadcastVersion, readPosition = decodeVarint(
@ -999,13 +999,13 @@ class objectProcessor(threading.Thread):
sendersAddressVersion, sendersAddressVersionLength = decodeVarint( sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
decryptedData[readPosition:readPosition + 9]) decryptedData[readPosition:readPosition + 9])
if sendersAddressVersion < 4: if sendersAddressVersion < 4:
logger.info('Cannot decode senderAddressVersion less than 4 for broadcast version number 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.') logger.info('Cannot decode senderAddressVersion less than 4 for broadcast version number 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.')
return return
readPosition += sendersAddressVersionLength readPosition += sendersAddressVersionLength
sendersStream, sendersStreamLength = decodeVarint( sendersStream, sendersStreamLength = decodeVarint(
decryptedData[readPosition:readPosition + 9]) decryptedData[readPosition:readPosition + 9])
if sendersStream != cleartextStreamNumber: if sendersStream != cleartextStreamNumber:
logger.info('The stream number outside of the encryption on which the POW was completed doesn\'t match the stream number inside the encryption. Ignoring broadcast.') logger.info('The stream number outside of the encryption on which the POW was completed doesn\'t match the stream number inside the encryption. Ignoring broadcast.')
return return
readPosition += sendersStreamLength readPosition += sendersStreamLength
behaviorBitfield = decryptedData[readPosition:readPosition + 4] behaviorBitfield = decryptedData[readPosition:readPosition + 4]
@ -1036,7 +1036,7 @@ class objectProcessor(threading.Thread):
calculatedTag = hashlib.sha512(hashlib.sha512(encodeVarint( calculatedTag = hashlib.sha512(hashlib.sha512(encodeVarint(
sendersAddressVersion) + encodeVarint(sendersStream) + calculatedRipe).digest()).digest()[32:] sendersAddressVersion) + encodeVarint(sendersStream) + calculatedRipe).digest()).digest()[32:]
if calculatedTag != embeddedTag: if calculatedTag != embeddedTag:
logger.debug('The tag and encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.') logger.debug('The tag and encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.')
return return
messageEncodingType, messageEncodingTypeLength = decodeVarint( messageEncodingType, messageEncodingTypeLength = decodeVarint(
decryptedData[readPosition:readPosition + 9]) decryptedData[readPosition:readPosition + 9])
@ -1210,4 +1210,4 @@ class objectProcessor(threading.Thread):
# Throw away any extra lines (headers) after the subject. # Throw away any extra lines (headers) after the subject.
if subject: if subject:
subject = subject.splitlines()[0] subject = subject.splitlines()[0]
return subject, body return subject, body

View File

@ -79,7 +79,7 @@ class outgoingSynSender(threading.Thread):
File "C:\Python27\lib\socket.py", line 187, in __init__ File "C:\Python27\lib\socket.py", line 187, in __init__
_sock = _realsocket(family, type, proto) _sock = _realsocket(family, type, proto)
error: [Errno 10047] An address incompatible with the requested protocol was used error: [Errno 10047] An address incompatible with the requested protocol was used
So let us remove the offending address from our knownNodes file. So let us remove the offending address from our knownNodes file.
""" """
shared.knownNodesLock.acquire() shared.knownNodesLock.acquire()
@ -145,13 +145,13 @@ class outgoingSynSender(threading.Thread):
rd = receiveDataThread() rd = receiveDataThread()
rd.daemon = True # close the main program even if there are threads left rd.daemon = True # close the main program even if there are threads left
someObjectsOfWhichThisRemoteNodeIsAlreadyAware = {} # This is not necessairly a complete list; we clear it from time to time to save memory. someObjectsOfWhichThisRemoteNodeIsAlreadyAware = {} # This is not necessairly a complete list; we clear it from time to time to save memory.
sendDataThreadQueue = Queue.Queue() # Used to submit information to the send data thread for this connection. sendDataThreadQueue = Queue.Queue() # Used to submit information to the send data thread for this connection.
rd.setup(sock, rd.setup(sock,
peer.host, peer.host,
peer.port, peer.port,
self.streamNumber, self.streamNumber,
someObjectsOfWhichThisRemoteNodeIsAlreadyAware, someObjectsOfWhichThisRemoteNodeIsAlreadyAware,
self.selfInitiatedConnections, self.selfInitiatedConnections,
sendDataThreadQueue) sendDataThreadQueue)
rd.start() rd.start()
with shared.printLock: with shared.printLock:

View File

@ -43,7 +43,7 @@ class receiveDataThread(threading.Thread):
someObjectsOfWhichThisRemoteNodeIsAlreadyAware, someObjectsOfWhichThisRemoteNodeIsAlreadyAware,
selfInitiatedConnections, selfInitiatedConnections,
sendDataThreadQueue): sendDataThreadQueue):
self.sock = sock self.sock = sock
self.peer = shared.Peer(HOST, port) self.peer = shared.Peer(HOST, port)
self.streamNumber = streamNumber self.streamNumber = streamNumber
@ -142,7 +142,7 @@ class receiveDataThread(threading.Thread):
shared.knownNodesLock.acquire() shared.knownNodesLock.acquire()
shared.knownNodes[self.streamNumber][self.peer] = int(time.time()) shared.knownNodes[self.streamNumber][self.peer] = int(time.time())
shared.knownNodesLock.release() shared.knownNodesLock.release()
remoteCommand = self.data[4:16] remoteCommand = self.data[4:16]
with shared.printLock: with shared.printLock:
print 'remoteCommand', repr(remoteCommand.replace('\x00', '')), ' from', self.peer print 'remoteCommand', repr(remoteCommand.replace('\x00', '')), ' from', self.peer
@ -306,8 +306,8 @@ class receiveDataThread(threading.Thread):
self.sendinvMessageToJustThisOnePeer( self.sendinvMessageToJustThisOnePeer(
numberOfObjectsInInvMessage, payload) numberOfObjectsInInvMessage, payload)
# Used to send a big inv message when the connection with a node is # Used to send a big inv message when the connection with a node is
# first fully established. Notice that there is also a broadcastinv # first fully established. Notice that there is also a broadcastinv
# function for broadcasting invs to everyone in our stream. # function for broadcasting invs to everyone in our stream.
def sendinvMessageToJustThisOnePeer(self, numberOfObjects, payload): def sendinvMessageToJustThisOnePeer(self, numberOfObjects, payload):
payload = encodeVarint(numberOfObjects) + payload payload = encodeVarint(numberOfObjects) + payload
@ -439,7 +439,7 @@ class receiveDataThread(threading.Thread):
advertisedSet.add(data[lengthOfVarint + (32 * i):32 + lengthOfVarint + (32 * i)]) advertisedSet.add(data[lengthOfVarint + (32 * i):32 + lengthOfVarint + (32 * i)])
objectsNewToMe = advertisedSet - shared.inventorySets[self.streamNumber] objectsNewToMe = advertisedSet - shared.inventorySets[self.streamNumber]
logger.info('inv message lists %s objects. Of those %s are new to me. It took %s seconds to figure that out.', numberOfItemsInInv, len(objectsNewToMe), time.time()-startTime) logger.info('inv message lists %s objects. Of those %s are new to me. It took %s seconds to figure that out.', numberOfItemsInInv, len(objectsNewToMe), time.time()-startTime)
for item in objectsNewToMe: for item in objectsNewToMe:
if totalNumberOfobjectsThatWeHaveYetToGetFromAllPeers > 200000 and len(self.objectsThatWeHaveYetToGetFromThisPeer) > 1000: # inv flooding attack mitigation if totalNumberOfobjectsThatWeHaveYetToGetFromAllPeers > 200000 and len(self.objectsThatWeHaveYetToGetFromThisPeer) > 1000: # inv flooding attack mitigation
with shared.printLock: with shared.printLock:
print 'We already have', totalNumberOfobjectsThatWeHaveYetToGetFromAllPeers, 'items yet to retrieve from peers and over', len(self.objectsThatWeHaveYetToGetFromThisPeer), 'from this node in particular. Ignoring the rest of this inv message.' print 'We already have', totalNumberOfobjectsThatWeHaveYetToGetFromAllPeers, 'items yet to retrieve from peers and over', len(self.objectsThatWeHaveYetToGetFromThisPeer), 'from this node in particular. Ignoring the rest of this inv message.'
@ -627,8 +627,8 @@ class receiveDataThread(threading.Thread):
else: else:
hostFromAddrMessage = socket.inet_ntop(socket.AF_INET6, fullHost) hostFromAddrMessage = socket.inet_ntop(socket.AF_INET6, fullHost)
if hostFromAddrMessage == "": if hostFromAddrMessage == "":
# This can happen on Windows systems which are not 64-bit compatible # This can happen on Windows systems which are not 64-bit compatible
# so let us drop the IPv6 address. # so let us drop the IPv6 address.
continue continue
if not self._checkIPv6Address(fullHost, hostFromAddrMessage): if not self._checkIPv6Address(fullHost, hostFromAddrMessage):
continue continue
@ -669,9 +669,9 @@ class receiveDataThread(threading.Thread):
print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.' print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.'
# Send a huge addr message to our peer. This is only used # Send a huge addr message to our peer. This is only used
# when we fully establish a connection with a # when we fully establish a connection with a
# peer (with the full exchange of version and verack # peer (with the full exchange of version and verack
# messages). # messages).
def sendaddr(self): def sendaddr(self):
addrsInMyStream = {} addrsInMyStream = {}
@ -764,7 +764,7 @@ class receiveDataThread(threading.Thread):
a new version message, like if the remote node wants to update a new version message, like if the remote node wants to update
the streams in which they are interested. But for now we'll the streams in which they are interested. But for now we'll
ignore this version message ignore this version message
""" """
return return
self.remoteProtocolVersion, = unpack('>L', data[:4]) self.remoteProtocolVersion, = unpack('>L', data[:4])
if self.remoteProtocolVersion <= 1: if self.remoteProtocolVersion <= 1:
@ -806,7 +806,7 @@ class receiveDataThread(threading.Thread):
with shared.printLock: with shared.printLock:
print 'Closing connection to myself: ', self.peer print 'Closing connection to myself: ', self.peer
return return
# The other peer's protocol version is of interest to the sendDataThread but we learn of it # The other peer's protocol version is of interest to the sendDataThread but we learn of it
# in this version message. Let us inform the sendDataThread. # in this version message. Let us inform the sendDataThread.
self.sendDataThreadQueue.put((0, 'setRemoteProtocolVersion', self.remoteProtocolVersion)) self.sendDataThreadQueue.put((0, 'setRemoteProtocolVersion', self.remoteProtocolVersion))

View File

@ -60,7 +60,7 @@ class sendDataThread(threading.Thread):
# if not 'Bad file descriptor' in err: # if not 'Bad file descriptor' in err:
with shared.printLock: with shared.printLock:
sys.stderr.write('sock.sendall error: %s\n' % err) sys.stderr.write('sock.sendall error: %s\n' % err)
self.versionSent = 1 self.versionSent = 1
def run(self): def run(self):
@ -82,7 +82,7 @@ class sendDataThread(threading.Thread):
elif command == 'setStreamNumber': elif command == 'setStreamNumber':
self.streamNumber = data self.streamNumber = data
with shared.printLock: with shared.printLock:
print 'setting the stream number in the sendData thread (ID:', id(self), ') to', self.streamNumber print 'setting the stream number in the sendData thread (ID:', id(self), ') to', self.streamNumber
elif command == 'setRemoteProtocolVersion': elif command == 'setRemoteProtocolVersion':
specifiedRemoteProtocolVersion = data specifiedRemoteProtocolVersion = data
with shared.printLock: with shared.printLock:
@ -160,7 +160,7 @@ class sendDataThread(threading.Thread):
self.sock.sendall(data) self.sock.sendall(data)
self.lastTimeISentData = int(time.time()) self.lastTimeISentData = int(time.time())
except: except:
print 'Sending of data to', self.peer, 'failed. sendDataThread thread', self, 'ending now.' print 'Sending of data to', self.peer, 'failed. sendDataThread thread', self, 'ending now.'
break break
elif command == 'connectionIsOrWasFullyEstablished': elif command == 'connectionIsOrWasFullyEstablished':
self.connectionIsOrWasFullyEstablished = True self.connectionIsOrWasFullyEstablished = True

View File

@ -161,7 +161,7 @@ class singleWorker(threading.Thread):
# does the necessary POW and sends it out. If it *is* a chan then it # does the necessary POW and sends it out. If it *is* a chan then it
# assembles the pubkey and stores is in the pubkey table so that we can # assembles the pubkey and stores is in the pubkey table so that we can
# send messages to "ourselves". # send messages to "ourselves".
def sendOutOrStoreMyV3Pubkey(self, hash): def sendOutOrStoreMyV3Pubkey(self, hash):
try: try:
myAddress = shared.myAddressesByHash[hash] myAddress = shared.myAddressesByHash[hash]
except: except:
@ -244,7 +244,7 @@ class singleWorker(threading.Thread):
pass pass
# If this isn't a chan address, this function assembles the pubkey data, # If this isn't a chan address, this function assembles the pubkey data,
# does the necessary POW and sends it out. # does the necessary POW and sends it out.
def sendOutOrStoreMyV4Pubkey(self, myAddress): def sendOutOrStoreMyV4Pubkey(self, myAddress):
if not shared.config.has_section(myAddress): if not shared.config.has_section(myAddress):
#The address has been deleted. #The address has been deleted.
@ -406,9 +406,9 @@ class singleWorker(threading.Thread):
dataToEncrypt += encodeVarint(len(signature)) dataToEncrypt += encodeVarint(len(signature))
dataToEncrypt += signature dataToEncrypt += signature
# Encrypt the broadcast with the information contained in the broadcaster's address. Anyone who knows the address can generate # Encrypt the broadcast with the information contained in the broadcaster's address. Anyone who knows the address can generate
# the private encryption key to decrypt the broadcast. This provides virtually no privacy; its purpose is to keep questionable # the private encryption key to decrypt the broadcast. This provides virtually no privacy; its purpose is to keep questionable
# and illegal content from flowing through the Internet connections and being stored on the disk of 3rd parties. # and illegal content from flowing through the Internet connections and being stored on the disk of 3rd parties.
if addressVersionNumber <= 3: if addressVersionNumber <= 3:
privEncryptionKey = hashlib.sha512(encodeVarint( privEncryptionKey = hashlib.sha512(encodeVarint(
addressVersionNumber) + encodeVarint(streamNumber) + ripe).digest()[:32] addressVersionNumber) + encodeVarint(streamNumber) + ripe).digest()[:32]
@ -451,7 +451,7 @@ class singleWorker(threading.Thread):
'broadcastsent', 'broadcastsent',
int(time.time()), int(time.time()),
ackdata) ackdata)
def sendMsg(self): def sendMsg(self):
# Check to see if there are any messages queued to be sent # Check to see if there are any messages queued to be sent
@ -787,7 +787,7 @@ class singleWorker(threading.Thread):
elif not shared.isBitSetWithinBitfield(behaviorBitfield,31): elif not shared.isBitSetWithinBitfield(behaviorBitfield,31):
with shared.printLock: with shared.printLock:
print 'Not bothering to include ackdata because the receiver said that they won\'t relay it anyway.' print 'Not bothering to include ackdata because the receiver said that they won\'t relay it anyway.'
fullAckPayload = '' fullAckPayload = ''
else: else:
fullAckPayload = self.generateFullAckMessage( fullAckPayload = self.generateFullAckMessage(
ackdata, toStreamNumber) # The fullAckPayload is a normal msg protocol message with the proof of work already completed that the receiver of this message can easily send out. ackdata, toStreamNumber) # The fullAckPayload is a normal msg protocol message with the proof of work already completed that the receiver of this message can easily send out.

View File

@ -21,7 +21,7 @@ class sqlThread(threading.Thread):
def __init__(self): def __init__(self):
threading.Thread.__init__(self) threading.Thread.__init__(self)
def run(self): def run(self):
self.conn = sqlite3.connect(shared.appdata + 'messages.dat') self.conn = sqlite3.connect(shared.appdata + 'messages.dat')
self.conn.text_factory = str self.conn.text_factory = str
self.cur = self.conn.cursor() self.cur = self.conn.cursor()
@ -188,12 +188,12 @@ class sqlThread(threading.Thread):
self.cur.execute( self.cur.execute(
'''update sent set status='broadcastqueued' where status='broadcastpending' ''') '''update sent set status='broadcastqueued' where status='broadcastpending' ''')
self.conn.commit() self.conn.commit()
if not shared.config.has_option('bitmessagesettings', 'sockslisten'): if not shared.config.has_option('bitmessagesettings', 'sockslisten'):
shared.config.set('bitmessagesettings', 'sockslisten', 'false') shared.config.set('bitmessagesettings', 'sockslisten', 'false')
ensureNamecoinOptions() ensureNamecoinOptions()
"""# Add a new column to the inventory table to store the first 20 bytes of encrypted messages to support Android app """# Add a new column to the inventory table to store the first 20 bytes of encrypted messages to support Android app
item = '''SELECT value FROM settings WHERE key='version';''' item = '''SELECT value FROM settings WHERE key='version';'''
parameters = '' parameters = ''
@ -269,7 +269,7 @@ class sqlThread(threading.Thread):
item = '''update settings set value=? WHERE key='version';''' item = '''update settings set value=? WHERE key='version';'''
parameters = (5,) parameters = (5,)
self.cur.execute(item, parameters) self.cur.execute(item, parameters)
if not shared.config.has_option('bitmessagesettings', 'useidenticons'): if not shared.config.has_option('bitmessagesettings', 'useidenticons'):
shared.config.set('bitmessagesettings', 'useidenticons', 'True') shared.config.set('bitmessagesettings', 'useidenticons', 'True')
if not shared.config.has_option('bitmessagesettings', 'identiconsuffix'): # acts as a salt if not shared.config.has_option('bitmessagesettings', 'identiconsuffix'): # acts as a salt
@ -285,7 +285,7 @@ class sqlThread(threading.Thread):
shared.config.set( shared.config.set(
'bitmessagesettings', 'stopresendingafterxmonths', '') 'bitmessagesettings', 'stopresendingafterxmonths', '')
#shared.config.set( #shared.config.set(
shared.config.set('bitmessagesettings', 'settingsversion', '8') shared.config.set('bitmessagesettings', 'settingsversion', '8')
with open(shared.appdata + 'keys.dat', 'wb') as configfile: with open(shared.appdata + 'keys.dat', 'wb') as configfile:
shared.config.write(configfile) shared.config.write(configfile)
@ -305,7 +305,7 @@ class sqlThread(threading.Thread):
# Are you hoping to add a new option to the keys.dat file of existing # Are you hoping to add a new option to the keys.dat file of existing
# Bitmessage users? Add it right above this line! # Bitmessage users? Add it right above this line!
try: try:
testpayload = '\x00\x00' testpayload = '\x00\x00'
t = ('1234', 1, testpayload, '12345678', 'no') t = ('1234', 1, testpayload, '12345678', 'no')

View File

@ -78,4 +78,4 @@ def restartLoggingInUpdatedAppdataLocation():
i.flush() i.flush()
i.close() i.close()
configureLogging() configureLogging()
logger = logging.getLogger('both') logger = logging.getLogger('both')

View File

@ -21,7 +21,7 @@ def createDefaultKnownNodes(appdata):
stream1[shared.Peer('75.95.134.9', 8444)] = int(time.time()) stream1[shared.Peer('75.95.134.9', 8444)] = int(time.time())
stream1[shared.Peer('46.236.100.108', 48444)] = int(time.time()) stream1[shared.Peer('46.236.100.108', 48444)] = int(time.time())
stream1[shared.Peer('66.108.53.42', 8080)] = int(time.time()) stream1[shared.Peer('66.108.53.42', 8080)] = int(time.time())
############# Stream 2 ################# ############# Stream 2 #################
stream2 = {} stream2 = {}
# None yet # None yet

View File

@ -4,8 +4,8 @@ import shared
def insert(t): def insert(t):
sqlExecute('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''', *t) sqlExecute('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''', *t)
shared.UISignalQueue.put(('changedInboxUnread', None)) shared.UISignalQueue.put(('changedInboxUnread', None))
def trash(msgid): def trash(msgid):
sqlExecute('''UPDATE inbox SET folder='trash' WHERE msgid=?''', msgid) sqlExecute('''UPDATE inbox SET folder='trash' WHERE msgid=?''', msgid)
shared.UISignalQueue.put(('removeInboxRowByMsgid',msgid)) shared.UISignalQueue.put(('removeInboxRowByMsgid',msgid))

View File

@ -13,7 +13,7 @@ def sqlQuery(sqlStatement, *args):
sqlSubmitQueue.put('') sqlSubmitQueue.put('')
else: else:
sqlSubmitQueue.put(args) sqlSubmitQueue.put(args)
queryreturn = sqlReturnQueue.get() queryreturn = sqlReturnQueue.get()
sqlLock.release() sqlLock.release()
@ -27,7 +27,7 @@ def sqlExecute(sqlStatement, *args):
sqlSubmitQueue.put('') sqlSubmitQueue.put('')
else: else:
sqlSubmitQueue.put(args) sqlSubmitQueue.put(args)
sqlReturnQueue.get() sqlReturnQueue.get()
sqlSubmitQueue.put('commit') sqlSubmitQueue.put('commit')
sqlLock.release() sqlLock.release()
@ -48,7 +48,7 @@ class SqlBulkExecute:
def execute(self, sqlStatement, *args): def execute(self, sqlStatement, *args):
sqlSubmitQueue.put(sqlStatement) sqlSubmitQueue.put(sqlStatement)
if args == (): if args == ():
sqlSubmitQueue.put('') sqlSubmitQueue.put('')
else: else:

View File

@ -102,7 +102,7 @@ def loadConfig():
shared.config.set('bitmessagesettings', 'useidenticons', 'True') 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', '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', 'replybelow', 'False')
#start:UI setting to stop trying to send messages after X days/months #start:UI setting to stop trying to send messages after X days/months
shared.config.set( shared.config.set(
'bitmessagesettings', 'stopresendingafterxdays', '') 'bitmessagesettings', 'stopresendingafterxdays', '')

View File

@ -100,11 +100,11 @@ class namecoinConnection (object):
try: try:
val = json.loads (res) val = json.loads (res)
except: except:
return (tr.translateText("MainWindow",'The name %1 has no valid JSON data.').arg(unicode(string)), None) return (tr.translateText("MainWindow",'The name %1 has no valid JSON data.').arg(unicode(string)), None)
if "bitmessage" in val: if "bitmessage" in val:
return (None, val["bitmessage"]) return (None, val["bitmessage"])
return (tr.translateText("MainWindow",'The name %1 has no associated Bitmessage address.').arg(unicode(string)), None) return (tr.translateText("MainWindow",'The name %1 has no associated Bitmessage address.').arg(unicode(string)), None)
# Test the connection settings. This routine tries to query a "getinfo" # Test the connection settings. This routine tries to query a "getinfo"
# command, and builds either an error message or a success message with # command, and builds either an error message or a success message with
@ -114,7 +114,7 @@ class namecoinConnection (object):
if self.nmctype == "namecoind": if self.nmctype == "namecoind":
res = self.callRPC ("getinfo", []) res = self.callRPC ("getinfo", [])
vers = res["version"] vers = res["version"]
v3 = vers % 100 v3 = vers % 100
vers = vers / 100 vers = vers / 100
v2 = vers % 100 v2 = vers % 100
@ -192,7 +192,7 @@ class namecoinConnection (object):
try: try:
s = socket.socket (socket.AF_INET, socket.SOCK_STREAM) s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.settimeout(3) s.settimeout(3)
s.connect ((self.host, int (self.port))) s.connect ((self.host, int (self.port)))
s.sendall (data) s.sendall (data)
result = "" result = ""
@ -266,7 +266,7 @@ def ensureNamecoinOptions ():
defaultPass = val defaultPass = val
if key == "rpcport": if key == "rpcport":
shared.namecoinDefaultRpcPort = val shared.namecoinDefaultRpcPort = val
nmc.close () nmc.close ()
except Exception as exc: except Exception as exc:

View File

@ -25,7 +25,7 @@ def get_code_string(base):
def encode(val,base,minlen=0): def encode(val,base,minlen=0):
code_string = get_code_string(base) code_string = get_code_string(base)
result = "" result = ""
while val > 0: while val > 0:
result = code_string[val % base] + result result = code_string[val % base] + result
val /= base val /= base
@ -49,14 +49,14 @@ def changebase(string,frm,to,minlen=0):
def base10_add(a,b): def base10_add(a,b):
if a == None: return b[0],b[1] if a == None: return b[0],b[1]
if b == None: return a[0],a[1] if b == None: return a[0],a[1]
if a[0] == b[0]: if a[0] == b[0]:
if a[1] == b[1]: return base10_double(a[0],a[1]) if a[1] == b[1]: return base10_double(a[0],a[1])
else: return None else: return None
m = ((b[1]-a[1]) * inv(b[0]-a[0],P)) % P m = ((b[1]-a[1]) * inv(b[0]-a[0],P)) % P
x = (m*m-a[0]-b[0]) % P x = (m*m-a[0]-b[0]) % P
y = (m*(a[0]-x)-a[1]) % P y = (m*(a[0]-x)-a[1]) % P
return (x,y) return (x,y)
def base10_double(a): def base10_double(a):
if a == None: return None if a == None: return None
m = ((3*a[0]*a[0]+A)*inv(2*a[1],P)) % P m = ((3*a[0]*a[0]+A)*inv(2*a[1],P)) % P
@ -94,7 +94,7 @@ def hash_160(string):
def dbl_sha256(string): def dbl_sha256(string):
return hashlib.sha256(hashlib.sha256(string).digest()).digest() return hashlib.sha256(hashlib.sha256(string).digest()).digest()
def bin_to_b58check(inp): def bin_to_b58check(inp):
inp_fmtd = '\x00' + inp inp_fmtd = '\x00' + inp
leadingzbytes = len(re.match('^\x00*',inp_fmtd).group(0)) leadingzbytes = len(re.match('^\x00*',inp_fmtd).group(0))

View File

@ -294,7 +294,7 @@ class _OpenSSL:
except: except:
# The above is not compatible with all versions of OSX. # The above is not compatible with all versions of OSX.
self.PKCS5_PBKDF2_HMAC = self._lib.PKCS5_PBKDF2_HMAC_SHA1 self.PKCS5_PBKDF2_HMAC = self._lib.PKCS5_PBKDF2_HMAC_SHA1
self.PKCS5_PBKDF2_HMAC.restype = ctypes.c_int self.PKCS5_PBKDF2_HMAC.restype = ctypes.c_int
self.PKCS5_PBKDF2_HMAC.argtypes = [ctypes.c_void_p, ctypes.c_int, self.PKCS5_PBKDF2_HMAC.argtypes = [ctypes.c_void_p, ctypes.c_int,
ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_int,
@ -394,11 +394,11 @@ class _OpenSSL:
OpenSSL random function OpenSSL random function
""" """
buffer = self.malloc(0, size) buffer = self.malloc(0, size)
# This pyelliptic library, by default, didn't check the return value of RAND_bytes. It is # This pyelliptic library, by default, didn't check the return value of RAND_bytes. It is
# evidently possible that it returned an error and not-actually-random data. However, in # evidently possible that it returned an error and not-actually-random data. However, in
# tests on various operating systems, while generating hundreds of gigabytes of random # tests on various operating systems, while generating hundreds of gigabytes of random
# strings of various sizes I could not get an error to occur. Also Bitcoin doesn't check # strings of various sizes I could not get an error to occur. Also Bitcoin doesn't check
# the return value of RAND_bytes either. # the return value of RAND_bytes either.
# Fixed in Bitmessage version 0.4.2 (in source code on 2013-10-13) # Fixed in Bitmessage version 0.4.2 (in source code on 2013-10-13)
while self.RAND_bytes(buffer, size) != 1: while self.RAND_bytes(buffer, size) != 1:
import time import time

View File

@ -58,7 +58,7 @@ __all__ = ['render_identicon', 'IdenticonRendererBase']
class IdenticonRendererBase(object): class IdenticonRendererBase(object):
PATH_SET = [] PATH_SET = []
def __init__(self, code): def __init__(self, code):
""" """
@param code code for icon @param code code for icon
@ -66,51 +66,51 @@ class IdenticonRendererBase(object):
if not isinstance(code, int): if not isinstance(code, int):
code = int(code) code = int(code)
self.code = code self.code = code
def render(self, size, twoColor, opacity, penwidth): def render(self, size, twoColor, opacity, penwidth):
""" """
render identicon to QPicture render identicon to QPicture
@param size identicon patchsize. (image size is 3 * [size]) @param size identicon patchsize. (image size is 3 * [size])
@return QPicture @return QPicture
""" """
# decode the code # decode the code
middle, corner, side, foreColor, secondColor, swap_cross = self.decode(self.code, twoColor) middle, corner, side, foreColor, secondColor, swap_cross = self.decode(self.code, twoColor)
# make image # make image
image = QPixmap(QSize(size * 3 +penwidth, size * 3 +penwidth)) image = QPixmap(QSize(size * 3 +penwidth, size * 3 +penwidth))
# fill background # fill background
backColor = QtGui.QColor(255,255,255,opacity) backColor = QtGui.QColor(255,255,255,opacity)
image.fill(backColor) image.fill(backColor)
kwds = { kwds = {
'image': image, 'image': image,
'size': size, 'size': size,
'foreColor': foreColor if swap_cross else secondColor, 'foreColor': foreColor if swap_cross else secondColor,
'penwidth': penwidth, 'penwidth': penwidth,
'backColor': backColor} 'backColor': backColor}
# middle patch # middle patch
image = self.drawPatchQt((1, 1), middle[2], middle[1], middle[0], **kwds) image = self.drawPatchQt((1, 1), middle[2], middle[1], middle[0], **kwds)
# side patch # side patch
kwds['foreColor'] = foreColor kwds['foreColor'] = foreColor
kwds['type'] = side[0] kwds['type'] = side[0]
for i in xrange(4): for i in xrange(4):
pos = [(1, 0), (2, 1), (1, 2), (0, 1)][i] pos = [(1, 0), (2, 1), (1, 2), (0, 1)][i]
image = self.drawPatchQt(pos, side[2] + 1 + i, side[1], **kwds) image = self.drawPatchQt(pos, side[2] + 1 + i, side[1], **kwds)
# corner patch # corner patch
kwds['foreColor'] = secondColor kwds['foreColor'] = secondColor
kwds['type'] = corner[0] kwds['type'] = corner[0]
for i in xrange(4): for i in xrange(4):
pos = [(0, 0), (2, 0), (2, 2), (0, 2)][i] pos = [(0, 0), (2, 0), (2, 2), (0, 2)][i]
image = self.drawPatchQt(pos, corner[2] + 1 + i, corner[1], **kwds) image = self.drawPatchQt(pos, corner[2] + 1 + i, corner[1], **kwds)
return image return image
def drawPatchQt(self, pos, turn, invert, type, image, size, foreColor, def drawPatchQt(self, pos, turn, invert, type, image, size, foreColor,
backColor, penwidth): backColor, penwidth):
@ -123,28 +123,28 @@ class IdenticonRendererBase(object):
invert = not invert invert = not invert
path = [(0., 0.), (1., 0.), (1., 1.), (0., 1.), (0., 0.)] path = [(0., 0.), (1., 0.), (1., 1.), (0., 1.), (0., 0.)]
polygon = QPolygonF([QPointF(x*size,y*size) for x,y in path]) polygon = QPolygonF([QPointF(x*size,y*size) for x,y in path])
rot = turn % 4 rot = turn % 4
rect = [QPointF(0.,0.), QPointF(size, 0.), QPointF(size, size), QPointF(0., size)] rect = [QPointF(0.,0.), QPointF(size, 0.), QPointF(size, size), QPointF(0., size)]
rotation = [0,90,180,270] rotation = [0,90,180,270]
nopen = QtGui.QPen(foreColor, Qt.NoPen) nopen = QtGui.QPen(foreColor, Qt.NoPen)
foreBrush = QtGui.QBrush(foreColor, Qt.SolidPattern) foreBrush = QtGui.QBrush(foreColor, Qt.SolidPattern)
if penwidth > 0: if penwidth > 0:
pen_color = QtGui.QColor(255, 255, 255) pen_color = QtGui.QColor(255, 255, 255)
pen = QtGui.QPen(pen_color, Qt.SolidPattern) pen = QtGui.QPen(pen_color, Qt.SolidPattern)
pen.setWidth(penwidth) pen.setWidth(penwidth)
painter = QPainter() painter = QPainter()
painter.begin(image) painter.begin(image)
painter.setPen(nopen) painter.setPen(nopen)
painter.translate(pos[0]*size +penwidth/2, pos[1]*size +penwidth/2) painter.translate(pos[0]*size +penwidth/2, pos[1]*size +penwidth/2)
painter.translate(rect[rot]) painter.translate(rect[rot])
painter.rotate(rotation[rot]) painter.rotate(rotation[rot])
if invert: if invert:
# subtract the actual polygon from a rectangle to invert it # subtract the actual polygon from a rectangle to invert it
poly_rect = QPolygonF(rect) poly_rect = QPolygonF(rect)
@ -157,21 +157,21 @@ class IdenticonRendererBase(object):
# draw the fill # draw the fill
painter.setPen(nopen) painter.setPen(nopen)
painter.drawPolygon(polygon, Qt.WindingFill) painter.drawPolygon(polygon, Qt.WindingFill)
painter.end() painter.end()
return image return image
### virtual functions ### virtual functions
def decode(self, code): def decode(self, code):
raise NotImplementedError raise NotImplementedError
class DonRenderer(IdenticonRendererBase): class DonRenderer(IdenticonRendererBase):
""" """
Don Park's implementation of identicon Don Park's implementation of identicon
see : http://www.docuverse.com/blog/donpark/2007/01/19/identicon-updated-and-source-released see : http://www.docuverse.com/blog/donpark/2007/01/19/identicon-updated-and-source-released
""" """
PATH_SET = [ PATH_SET = [
#[0] full square: #[0] full square:
[(0, 0), (4, 0), (4, 4), (0, 4)], [(0, 0), (4, 0), (4, 4), (0, 4)],
@ -207,13 +207,13 @@ class DonRenderer(IdenticonRendererBase):
[]] []]
# get the [0] full square, [4] square standing on diagonale, [8] small centered square, or [15] empty tile: # get the [0] full square, [4] square standing on diagonale, [8] small centered square, or [15] empty tile:
MIDDLE_PATCH_SET = [0, 4, 8, 15] MIDDLE_PATCH_SET = [0, 4, 8, 15]
# modify path set # modify path set
for idx in xrange(len(PATH_SET)): for idx in xrange(len(PATH_SET)):
if PATH_SET[idx]: if PATH_SET[idx]:
p = map(lambda vec: (vec[0] / 4.0, vec[1] / 4.0), PATH_SET[idx]) p = map(lambda vec: (vec[0] / 4.0, vec[1] / 4.0), PATH_SET[idx])
PATH_SET[idx] = p + p[:1] PATH_SET[idx] = p + p[:1]
def decode(self, code, twoColor): def decode(self, code, twoColor):
# decode the code # decode the code
shift = 0; middleType = (code >> shift) & 0x03 shift = 0; middleType = (code >> shift) & 0x03
@ -231,18 +231,18 @@ class DonRenderer(IdenticonRendererBase):
shift += 5; second_green= (code >> shift) & 0x1F shift += 5; second_green= (code >> shift) & 0x1F
shift += 5; second_red = (code >> shift) & 0x1F shift += 5; second_red = (code >> shift) & 0x1F
shift += 1; swap_cross = (code >> shift) & 0x01 shift += 1; swap_cross = (code >> shift) & 0x01
middleType = self.MIDDLE_PATCH_SET[middleType] middleType = self.MIDDLE_PATCH_SET[middleType]
foreColor = (red << 3, green << 3, blue << 3) foreColor = (red << 3, green << 3, blue << 3)
foreColor = QtGui.QColor(*foreColor) foreColor = QtGui.QColor(*foreColor)
if twoColor: if twoColor:
secondColor = (second_blue << 3, second_green << 3, second_red << 3) secondColor = (second_blue << 3, second_green << 3, second_red << 3)
secondColor = QtGui.QColor(*secondColor) secondColor = QtGui.QColor(*secondColor)
else: else:
secondColor = foreColor secondColor = foreColor
return (middleType, middleInvert, 0),\ return (middleType, middleInvert, 0),\
(cornerType, cornerInvert, cornerTurn),\ (cornerType, cornerInvert, cornerTurn),\
(sideType, sideInvert, sideTurn),\ (sideType, sideInvert, sideTurn),\
@ -252,4 +252,4 @@ class DonRenderer(IdenticonRendererBase):
def render_identicon(code, size, twoColor=False, opacity=255, penwidth=0, renderer=None): def render_identicon(code, size, twoColor=False, opacity=255, penwidth=0, renderer=None):
if not renderer: if not renderer:
renderer = DonRenderer renderer = DonRenderer
return renderer(code).render(size, twoColor, opacity, penwidth) return renderer(code).render(size, twoColor, opacity, penwidth)

View File

@ -88,7 +88,7 @@ networkDefaultPayloadLengthExtraBytes = 14000 #To make sending short messages a
namecoinDefaultRpcPort = "8336" namecoinDefaultRpcPort = "8336"
# When using py2exe or py2app, the variable frozen is added to the sys # When using py2exe or py2app, the variable frozen is added to the sys
# namespace. This can be used to setup a different code path for # namespace. This can be used to setup a different code path for
# binary distributions vs source distributions. # binary distributions vs source distributions.
frozen = getattr(sys,'frozen', None) frozen = getattr(sys,'frozen', None)
@ -287,7 +287,7 @@ def reloadBroadcastSendersForWhichImWatching():
if addressVersionNumber == 2: if addressVersionNumber == 2:
broadcastSendersForWhichImWatching[hash] = 0 broadcastSendersForWhichImWatching[hash] = 0
#Now, for all addresses, even version 2 addresses, we should create Cryptor objects in a dictionary which we will use to attempt to decrypt encrypted broadcast messages. #Now, for all addresses, even version 2 addresses, we should create Cryptor objects in a dictionary which we will use to attempt to decrypt encrypted broadcast messages.
if addressVersionNumber <= 3: if addressVersionNumber <= 3:
privEncryptionKey = hashlib.sha512(encodeVarint(addressVersionNumber)+encodeVarint(streamNumber)+hash).digest()[:32] privEncryptionKey = hashlib.sha512(encodeVarint(addressVersionNumber)+encodeVarint(streamNumber)+hash).digest()[:32]
MyECSubscriptionCryptorObjects[hash] = highlevelcrypto.makeCryptor(privEncryptionKey.encode('hex')) MyECSubscriptionCryptorObjects[hash] = highlevelcrypto.makeCryptor(privEncryptionKey.encode('hex'))
@ -313,12 +313,12 @@ def isProofOfWorkSufficient(
def doCleanShutdown(): def doCleanShutdown():
global shutdown global shutdown
shutdown = 1 #Used to tell proof of work worker threads and the objectProcessorThread to exit. shutdown = 1 #Used to tell proof of work worker threads and the objectProcessorThread to exit.
broadcastToSendDataQueues((0, 'shutdown', 'all')) broadcastToSendDataQueues((0, 'shutdown', 'all'))
with shared.objectProcessorQueueSizeLock: with shared.objectProcessorQueueSizeLock:
data = 'no data' data = 'no data'
shared.objectProcessorQueueSize += len(data) shared.objectProcessorQueueSize += len(data)
objectProcessorQueue.put(('checkShutdownVariable',data)) objectProcessorQueue.put(('checkShutdownVariable',data))
knownNodesLock.acquire() knownNodesLock.acquire()
UISignalQueue.put(('updateStatusBar','Saving the knownNodes list of peers to disk...')) UISignalQueue.put(('updateStatusBar','Saving the knownNodes list of peers to disk...'))
output = open(appdata + 'knownnodes.dat', 'wb') output = open(appdata + 'knownnodes.dat', 'wb')
@ -335,21 +335,21 @@ def doCleanShutdown():
'updateStatusBar', 'updateStatusBar',
'Flushing inventory in memory out to disk. This should normally only take a second...')) 'Flushing inventory in memory out to disk. This should normally only take a second...'))
flushInventory() flushInventory()
# Verify that the objectProcessor has finished exiting. It should have incremented the # Verify that the objectProcessor has finished exiting. It should have incremented the
# shutdown variable from 1 to 2. This must finish before we command the sqlThread to exit. # shutdown variable from 1 to 2. This must finish before we command the sqlThread to exit.
while shutdown == 1: while shutdown == 1:
time.sleep(.1) time.sleep(.1)
# This one last useless query will guarantee that the previous flush committed and that the # This one last useless query will guarantee that the previous flush committed and that the
# objectProcessorThread committed before we close the program. # objectProcessorThread committed before we close the program.
sqlQuery('SELECT address FROM subscriptions') sqlQuery('SELECT address FROM subscriptions')
logger.info('Finished flushing inventory.') logger.info('Finished flushing inventory.')
sqlStoredProcedure('exit') sqlStoredProcedure('exit')
# Wait long enough to guarantee that any running proof of work worker threads will check the # Wait long enough to guarantee that any running proof of work worker threads will check the
# shutdown variable and exit. If the main thread closes before they do then they won't stop. # shutdown variable and exit. If the main thread closes before they do then they won't stop.
time.sleep(.25) time.sleep(.25)
if safeConfigGetBoolean('bitmessagesettings','daemon'): if safeConfigGetBoolean('bitmessagesettings','daemon'):
logger.info('Clean shutdown complete.') logger.info('Clean shutdown complete.')
@ -362,7 +362,7 @@ def broadcastToSendDataQueues(data):
# logger.debug('running broadcastToSendDataQueues') # logger.debug('running broadcastToSendDataQueues')
for q in sendDataQueues: for q in sendDataQueues:
q.put(data) q.put(data)
def flushInventory(): def flushInventory():
#Note that the singleCleanerThread clears out the inventory dictionary from time to time, although it only clears things that have been in the dictionary for a long time. This clears the inventory dictionary Now. #Note that the singleCleanerThread clears out the inventory dictionary from time to time, although it only clears things that have been in the dictionary for a long time. This clears the inventory dictionary Now.
with SqlBulkExecute() as sql: with SqlBulkExecute() as sql:
@ -432,7 +432,7 @@ def fixSensitiveFilePermissions(filename, hasEnabledKeys):
except Exception, e: except Exception, e:
logger.exception('Keyfile permissions could not be fixed.') logger.exception('Keyfile permissions could not be fixed.')
raise raise
def isBitSetWithinBitfield(fourByteString, n): def isBitSetWithinBitfield(fourByteString, n):
# Uses MSB 0 bit numbering across 4 bytes of data # Uses MSB 0 bit numbering across 4 bytes of data
n = 31 - n n = 31 - n
@ -512,7 +512,7 @@ def decryptAndCheckPubkeyPayload(payload, address):
# correct keys. Someone is either being malicious or using buggy software. # correct keys. Someone is either being malicious or using buggy software.
logger.info('Pubkey decryption was UNsuccessful due to RIPE mismatch. This shouldn\'t have happened.') logger.info('Pubkey decryption was UNsuccessful due to RIPE mismatch. This shouldn\'t have happened.')
return 'failed' return 'failed'
t = (ripe, addressVersion, signedData, int(time.time()), 'yes') t = (ripe, addressVersion, signedData, int(time.time()), 'yes')
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t) sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
return 'successful' return 'successful'
@ -536,7 +536,7 @@ def checkAndShareMsgWithPeers(data):
else: else:
readPosition += 4 readPosition += 4
if embeddedTime > (int(time.time()) + 10800): if embeddedTime > (int(time.time()) + 10800):
logger.debug('The embedded time in this msg message is more than three hours in the future. That doesn\'t make sense. Ignoring message.') logger.debug('The embedded time in this msg message is more than three hours in the future. That doesn\'t make sense. Ignoring message.')
return return
if embeddedTime < (int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept): if embeddedTime < (int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept):
@ -662,7 +662,7 @@ def checkAndSharePubkeyWithPeers(data):
logger.debug('The embedded time in this pubkey message is too old. Ignoring. Embedded time is: %s' % embeddedTime) logger.debug('The embedded time in this pubkey message is too old. Ignoring. Embedded time is: %s' % embeddedTime)
return return
if embeddedTime > int(time.time()) + 10800: if embeddedTime > int(time.time()) + 10800:
logger.debug('The embedded time in this pubkey message more than several hours in the future. This is irrational. Ignoring message.') logger.debug('The embedded time in this pubkey message more than several hours in the future. This is irrational. Ignoring message.')
return return
addressVersion, varintLength = decodeVarint( addressVersion, varintLength = decodeVarint(
data[readPosition:readPosition + 10]) data[readPosition:readPosition + 10])
@ -726,7 +726,7 @@ def checkAndShareBroadcastWithPeers(data):
readPosition += 4 readPosition += 4
if embeddedTime > (int(time.time()) + 10800): # prevent funny business if embeddedTime > (int(time.time()) + 10800): # prevent funny business
logger.debug('The embedded time in this broadcast message is more than three hours in the future. That doesn\'t make sense. Ignoring message.') logger.debug('The embedded time in this broadcast message is more than three hours in the future. That doesn\'t make sense. Ignoring message.')
return return
if embeddedTime < (int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept): if embeddedTime < (int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept):
logger.debug('The embedded time in this broadcast message is too old. Ignoring message.') logger.debug('The embedded time in this broadcast message is too old. Ignoring message.')

View File

@ -12,7 +12,7 @@ class singleinstance:
Implements a single instance application by creating a lock file based on the full path to the script file. Implements a single instance application by creating a lock file based on the full path to the script file.
This is based upon the singleton class from tendo https://github.com/pycontribs/tendo This is based upon the singleton class from tendo https://github.com/pycontribs/tendo
which is under the Python Software Foundation License version 2 which is under the Python Software Foundation License version 2
""" """
def __init__(self, flavor_id=""): def __init__(self, flavor_id=""):
import sys import sys

View File

@ -10,7 +10,7 @@ are permitted provided that the following conditions are met:
3. Neither the name of Dan Haim nor the names of his contributors may be used 3. Neither the name of Dan Haim nor the names of his contributors may be used
to endorse or promote products derived from this software without specific to endorse or promote products derived from this software without specific
prior written permission. prior written permission.
THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO

View File

@ -160,7 +160,7 @@ reason other then the two mentioned next.
The Socks server had tried an ident lookup on your computer and has failed. In this The Socks server had tried an ident lookup on your computer and has failed. In this
case you should run an identd server and/or configure your firewall to allow incoming case you should run an identd server and/or configure your firewall to allow incoming
connections to local port 113 from the remote server. connections to local port 113 from the remote server.
3 - request rejected because the client program and identd report different user-ids - 3 - request rejected because the client program and identd report different user-ids -
The Socks server had performed an ident lookup on your computer and has received a The Socks server had performed an ident lookup on your computer and has received a
different userid than the one you have provided. Change your userid (through the different userid than the one you have provided. Change your userid (through the
username parameter of the setproxy method) to match and try again. username parameter of the setproxy method) to match and try again.