diff --git a/.gitignore b/.gitignore index 8e9f9031..420a1bf3 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,4 @@ src/build src/dist src/.project src/.pydevproject -src/.settings/ \ No newline at end of file +src/.settings/ diff --git a/INSTALL.md b/INSTALL.md index 111db5d9..2cb4848e 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -1,4 +1,4 @@ -#PyBitmessage Installation Instructions +#PyBitmessage Installation Instructions For an up-to-date version of these instructions, please visit the [Bitmessage Wiki](https://bitmessage.org/wiki/Compiling_instructions). @@ -14,7 +14,7 @@ Here's a list of dependencies needed for PyBitmessage - python2.7 - python2-qt4 (python-qt4 on Debian/Ubuntu) - openssl -- (Fedora & Redhat only) openssl-compat-bitcoin-libs +- (Fedora & Redhat only) openssl-compat-bitcoin-libs ##Running PyBitmessage PyBitmessage can be run two ways: straight from source or via a package which diff --git a/README.md b/README.md index 73b5329c..ab5551a1 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ warrantless wiretapping programs. 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 features, it is recommended that you first solicit feedback on the DevTalk pseudo-mailing list: diff --git a/configure b/configure index 0519ecba..8b137891 100755 --- a/configure +++ b/configure @@ -1 +1 @@ - \ No newline at end of file + diff --git a/osx.sh b/osx.sh index 834a6243..fe80d5ce 100755 --- a/osx.sh +++ b/osx.sh @@ -5,7 +5,7 @@ # Requires all build dependencies for Bitmessage # 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 echo "Please supply a version number for this release as the first argument." diff --git a/src/api.py b/src/api.py index bd28d923..934c7590 100644 --- a/src/api.py +++ b/src/api.py @@ -4,7 +4,7 @@ comment= """ 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/Daemon ) then run bitmessagemain.py. +( https://bitmessage.org/wiki/Daemon ) then run bitmessagemain.py. """ if __name__ == "__main__": diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 4bcdcd1b..4459d266 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -63,7 +63,7 @@ def connectToStream(streamNumber): for row in queryData: shared.inventorySets[streamNumber].add(row[0]) - + if isOurOperatingSystemLimitedToHavingVeryFewHalfOpenConnections(): # Some XP and Vista systems can only have 10 outgoing connections at a time. maximumNumberOfHalfOpenConnections = 9 @@ -236,7 +236,7 @@ class Main: shared.doCleanShutdown() - #TODO: nice function but no one is using this + #TODO: nice function but no one is using this def getApiAddress(self): if not shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'): return None diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py index 9543503f..3c229ed0 100644 --- a/src/bitmessageqt/__init__.py +++ b/src/bitmessageqt/__init__.py @@ -62,11 +62,11 @@ def _translate(context, text): def identiconize(address): 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: # 3fd4bf901b9d4ea1394f0fb358725b28 - + try: identicon_lib = shared.config.get('bitmessagesettings', 'identiconlib') 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 # of attacks where someone creates an address to mimic someone else's identicon. identiconsuffix = shared.config.get('bitmessagesettings', 'identiconsuffix') - + if not shared.config.getboolean('bitmessagesettings', 'useidenticons'): idcon = QtGui.QIcon() return idcon - + if (identicon_lib[:len('qidenticon')] == 'qidenticon'): # print identicon_lib # originally by: @@ -115,7 +115,7 @@ def identiconize(address): idcon = QtGui.QIcon() idcon.addPixmap(pix, QtGui.QIcon.Normal, QtGui.QIcon.Off) return idcon - + def avatarize(address): """ 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.tableWidgetAddressBook.setIconSize(QtCore.QSize(identicon_size, identicon_size)) self.ui.tableWidgetBlacklist.setIconSize(QtCore.QSize(identicon_size, identicon_size)) - + self.UISignalThread = UISignaler() QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( "writeNewAddressToTable(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.writeNewAddressToTable) @@ -631,7 +631,7 @@ class MyForm(QtGui.QMainWindow): # structures were initialized. self.rerenderComboBoxSendFrom() - + # Check to see whether we can connect to namecoin. Hide the 'Fetch Namecoin ID' button if we can't. try: options = {} @@ -757,8 +757,8 @@ class MyForm(QtGui.QMainWindow): where = "toaddress || fromaddress || subject || message" sqlStatement = ''' - SELECT toaddress, fromaddress, subject, status, ackdata, lastactiontime - FROM sent WHERE folder="sent" AND %s LIKE ? + SELECT toaddress, fromaddress, subject, status, ackdata, lastactiontime + FROM sent WHERE folder="sent" AND %s LIKE ? ORDER BY lastactiontime ''' % (where,) @@ -790,7 +790,7 @@ class MyForm(QtGui.QMainWindow): if queryreturn != []: for row in queryreturn: toLabel, = row - + if toLabel == '': if shared.config.has_section(toAddress): toLabel = shared.config.get(toAddress, 'label') @@ -913,7 +913,7 @@ class MyForm(QtGui.QMainWindow): fromLabel = '' if shared.config.has_section(fromAddress): fromLabel = shared.config.get(fromAddress, 'label') - + if fromLabel == '': # If the fromAddress isn't one of our addresses and isn't a chan queryreturn = sqlQuery( '''select label from addressbook where address=?''', fromAddress) @@ -929,7 +929,7 @@ class MyForm(QtGui.QMainWindow): fromLabel, = row if fromLabel == '': fromLabel = fromAddress - + # message row self.ui.tableWidgetInbox.insertRow(0) # to @@ -1231,7 +1231,7 @@ class MyForm(QtGui.QMainWindow): soundFilename = shared.appdata + 'sounds/disconnected' # sound when the connection status becomes 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 not self.isConnectionSound(category): @@ -1251,7 +1251,7 @@ class MyForm(QtGui.QMainWindow): gst_available=False try: subprocess.call(["gst123", soundFilename], - stdin=subprocess.PIPE, + stdin=subprocess.PIPE, stdout=subprocess.PIPE) gst_available=True except: @@ -1259,7 +1259,7 @@ class MyForm(QtGui.QMainWindow): if not gst_available: try: subprocess.call(["mpg123", soundFilename], - stdin=subprocess.PIPE, + stdin=subprocess.PIPE, stdout=subprocess.PIPE) gst_available=True except: @@ -1267,7 +1267,7 @@ class MyForm(QtGui.QMainWindow): else: try: subprocess.call(["aplay", soundFilename], - stdin=subprocess.PIPE, + stdin=subprocess.PIPE, stdout=subprocess.PIPE) except: print "WARNING: aplay must be installed in order to play WAV sounds" @@ -1693,7 +1693,7 @@ class MyForm(QtGui.QMainWindow): if queryreturn != []: for row in queryreturn: fromLabel, = row - + if fromLabel == '': # It might be a broadcast message. We should check for that # label. @@ -1720,7 +1720,7 @@ class MyForm(QtGui.QMainWindow): else: self.ui.tableWidgetInbox.item( i, 1).setTextColor(QApplication.palette().text().color()) - + def rerenderInboxToLabels(self): for i in range(self.ui.tableWidgetInbox.rowCount()): @@ -1769,7 +1769,7 @@ class MyForm(QtGui.QMainWindow): if queryreturn != []: for row in queryreturn: toLabel, = row - + if toLabel == '': # Message might be to an address we own like a chan address. Let's look for that label. if shared.config.has_section(addressToLookup): @@ -1926,7 +1926,7 @@ class MyForm(QtGui.QMainWindow): '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)''', *t) toLabel = self.str_broadcast_subscribers - + self.displayNewSentMessage( toAddress, toLabel, fromAddress, subject, message, ackdata) @@ -2183,7 +2183,7 @@ class MyForm(QtGui.QMainWindow): return label = self.NewSubscriptionDialogInstance.ui.newsubscriptionlabel.text().toUtf8() 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 if self.NewSubscriptionDialogInstance.ui.checkBoxDisplayMessagesAlreadyInInventory.isChecked(): status, addressVersion, streamNumber, ripe = decodeAddress(address) @@ -2253,11 +2253,11 @@ class MyForm(QtGui.QMainWindow): self.settingsDialogInstance.ui.checkBoxUseIdenticons.isChecked())) shared.config.set('bitmessagesettings', 'replybelow', str( self.settingsDialogInstance.ui.checkBoxReplyBelow.isChecked())) - + lang_ind = int(self.settingsDialogInstance.ui.languageComboBox.currentIndex()) if not languages[lang_ind] == 'other': shared.config.set('bitmessagesettings', 'userlocale', languages[lang_ind]) - + if int(shared.config.get('bitmessagesettings', 'port')) != int(self.settingsDialogInstance.ui.lineEditTCPPort.text()): if not shared.safeConfigGetBoolean('bitmessagesettings', 'dontconnect'): QMessageBox.about(self, _translate("MainWindow", "Restart"), _translate( @@ -2583,7 +2583,7 @@ class MyForm(QtGui.QMainWindow): '''select message from inbox where msgid=?''', msgid) if queryreturn != []: for row in queryreturn: - messageAtCurrentInboxRow, = row + messageAtCurrentInboxRow, = row lines = messageAtCurrentInboxRow.split('\n') 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, 3).setFont(font) 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. # 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. @@ -2666,20 +2666,20 @@ class MyForm(QtGui.QMainWindow): self.setBroadcastEnablementDependingOnWhetherThisIsAChanAddress(toAddressAtCurrentInboxRow) 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 shared.config.has_section(toAddressAtCurrentInboxRow): if shared.safeConfigGetBoolean(toAddressAtCurrentInboxRow, 'chan'): print 'original sent to a chan. Setting the to address in the reply to the chan address.' self.ui.lineEditTo.setText(str(toAddressAtCurrentInboxRow)) - + listOfAddressesInComboBoxSendFrom = [str(self.ui.comboBoxSendFrom.itemData(i).toPyObject()) for i in range(self.ui.comboBoxSendFrom.count())] if toAddressAtCurrentInboxRow in listOfAddressesInComboBoxSendFrom: currentIndex = listOfAddressesInComboBoxSendFrom.index(toAddressAtCurrentInboxRow) self.ui.comboBoxSendFrom.setCurrentIndex(currentIndex) else: self.ui.comboBoxSendFrom.setCurrentIndex(0) - + quotedText = self.quoted_text(unicode(messageAtCurrentInboxRow, 'utf-8')) self.ui.textEditMessage.setText(quotedText) 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 def on_action_SubscriptionsNew(self): self.click_pushButtonAddSubscription() - + def on_action_SubscriptionsDelete(self): print 'clicked Delete' currentRow = self.ui.tableWidgetSubscriptions.currentRow() @@ -3044,16 +3044,16 @@ class MyForm(QtGui.QMainWindow): def on_action_YourIdentitiesSetAvatar(self): self.on_action_SetAvatar(self.ui.tableWidgetYourIdentities) - + def on_action_AddressBookSetAvatar(self): self.on_action_SetAvatar(self.ui.tableWidgetAddressBook) - + def on_action_SubscriptionsSetAvatar(self): self.on_action_SetAvatar(self.ui.tableWidgetSubscriptions) - + def on_action_BlacklistSetAvatar(self): self.on_action_SetAvatar(self.ui.tableWidgetBlacklist) - + def on_action_SetAvatar(self, thisTableWidget): # thisTableWidget = self.ui.tableWidgetYourIdentities 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) else: overwrite = QtGui.QMessageBox.No - + # copy the image file to the appdata folder if (not exists) | (overwrite == QtGui.QMessageBox.Yes): if overwrite == QtGui.QMessageBox.Yes: @@ -3121,7 +3121,7 @@ class MyForm(QtGui.QMainWindow): self.rerenderInboxToLabels() self.rerenderSentFromLabels() self.rerenderSentToLabels() - + def on_context_menuYourIdentities(self, point): self.popMenu.exec_( self.ui.tableWidgetYourIdentities.mapToGlobal(point)) @@ -3166,7 +3166,7 @@ class MyForm(QtGui.QMainWindow): font = QFont() font.setBold(False) self.ui.textEditInboxMessage.setCurrentFont(font) - + fromAddress = str(self.ui.tableWidgetInbox.item( currentRow, 1).data(Qt.UserRole).toPyObject()) msgid = str(self.ui.tableWidgetInbox.item( @@ -3296,7 +3296,7 @@ class helpDialog(QtGui.QDialog): self.parent = parent self.ui.labelHelpURI.setOpenExternalLinks(True) QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self)) - + class connectDialog(QtGui.QDialog): def __init__(self, parent): @@ -3346,8 +3346,8 @@ class settingsDialog(QtGui.QDialog): shared.safeConfigGetBoolean('bitmessagesettings', 'useidenticons')) self.ui.checkBoxReplyBelow.setChecked( 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'] user_countrycode = str(shared.config.get('bitmessagesettings', 'userlocale')) if user_countrycode in languages: @@ -3355,7 +3355,7 @@ class settingsDialog(QtGui.QDialog): else: curr_index = languages.index('other') self.ui.languageComboBox.setCurrentIndex(curr_index) - + if shared.appdata == '': self.ui.checkBoxPortableMode.setChecked(True) if 'darwin' in sys.platform: @@ -3453,8 +3453,8 @@ class settingsDialog(QtGui.QDialog): shared.config.get('bitmessagesettings', 'stopresendingafterxdays'))) self.ui.lineEditMonths.setText(str( shared.config.get('bitmessagesettings', 'stopresendingafterxmonths'))) - - + + #'System' tab removed for now. """try: maxCores = shared.config.getint('bitmessagesettings', 'maxcores') @@ -3507,7 +3507,7 @@ class settingsDialog(QtGui.QDialog): def namecoinTypeChanged(self, checked): nmctype = self.getNamecoinType() assert nmctype == "namecoind" or nmctype == "nmcontrol" - + isNamecoind = (nmctype == "namecoind") self.ui.lineEditNamecoinUser.setEnabled(isNamecoind) self.ui.labelNamecoinUser.setEnabled(isNamecoind) @@ -3601,7 +3601,7 @@ class AddAddressDialog(QtGui.QDialog): elif status == 'success': self.ui.labelAddressCheck.setText( _translate("MainWindow", "Address is valid.")) - + class NewSubscriptionDialog(QtGui.QDialog): def __init__(self, parent): @@ -3690,7 +3690,7 @@ class newChanDialog(QtGui.QDialog): self.ui.setupUi(self) self.parent = parent 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): @@ -3777,7 +3777,7 @@ class UISignaler(QThread): def run(): app = QtGui.QApplication(sys.argv) translator = QtCore.QTranslator() - + try: locale_countrycode = str(locale.getdefaultlocale()[0]) except: @@ -3790,7 +3790,7 @@ def run(): translation_path = os.path.join(sys._MEIPASS, "translations/bitmessage_") except Exception, e: translation_path = "translations/bitmessage_" - + if shared.config.get('bitmessagesettings', 'userlocale') == 'system': # try to detect the users locale otherwise fallback to English try: diff --git a/src/class_addressGenerator.py b/src/class_addressGenerator.py index c6e99a4b..29abcfa0 100644 --- a/src/class_addressGenerator.py +++ b/src/class_addressGenerator.py @@ -307,5 +307,5 @@ def pointMult(secret): OpenSSL.BN_free(priv_key) OpenSSL.EC_KEY_free(k) return mb.raw - - + + diff --git a/src/class_objectHashHolder.py b/src/class_objectHashHolder.py index c91b1c23..192da985 100644 --- a/src/class_objectHashHolder.py +++ b/src/class_objectHashHolder.py @@ -42,4 +42,4 @@ class objectHashHolder(threading.Thread): self.collectionOfPeerLists[random.randrange(0, 10)].append(peerDetails) def close(self): - self.shutdown = True \ No newline at end of file + self.shutdown = True diff --git a/src/class_objectProcessor.py b/src/class_objectProcessor.py index 20ef31ff..40843f46 100644 --- a/src/class_objectProcessor.py +++ b/src/class_objectProcessor.py @@ -31,7 +31,7 @@ class objectProcessor(threading.Thread): It may be the case that the last time Bitmessage was running, the user closed it before it finished processing everything in the 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. """ queryreturn = sqlQuery( @@ -79,7 +79,7 @@ class objectProcessor(threading.Thread): logger.debug('Saved %s objects from the objectProcessorQueue to disk. objectProcessorThread exiting.' % str(numberOfObjectsThatWereInTheObjectProcessorQueue)) shared.shutdown = 2 break - + def processgetpubkey(self, data): readPosition = 8 # bypass the nonce embeddedTime, = unpack('>I', data[readPosition:readPosition + 4]) @@ -146,9 +146,9 @@ class objectProcessor(threading.Thread): except: lastPubkeySendTime = 0 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 - 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: shared.workerQueue.put(( 'doPOWForMyV2Pubkey', requestedHash)) @@ -213,10 +213,10 @@ class objectProcessor(threading.Thread): logger.info('within recpubkey, addressVersion: %s, streamNumber: %s \n\ ripe %s\n\ publicSigningKey in hex: %s\n\ - publicEncryptionKey in hex: %s' % (addressVersion, - streamNumber, - ripe.encode('hex'), - publicSigningKey.encode('hex'), + publicEncryptionKey in hex: %s' % (addressVersion, + streamNumber, + ripe.encode('hex'), + publicSigningKey.encode('hex'), publicEncryptionKey.encode('hex') ) ) @@ -271,15 +271,15 @@ class objectProcessor(threading.Thread): ripeHasher = hashlib.new('ripemd160') ripeHasher.update(sha.digest()) ripe = ripeHasher.digest() - + logger.info('within recpubkey, addressVersion: %s, streamNumber: %s \n\ ripe %s\n\ publicSigningKey in hex: %s\n\ - publicEncryptionKey in hex: %s' % (addressVersion, - streamNumber, - ripe.encode('hex'), - publicSigningKey.encode('hex'), + publicEncryptionKey in hex: %s' % (addressVersion, + streamNumber, + ripe.encode('hex'), + publicSigningKey.encode('hex'), publicEncryptionKey.encode('hex') ) ) @@ -298,13 +298,13 @@ class objectProcessor(threading.Thread): if addressVersion == 4: """ 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 - 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 - incorrectly-tagged pubkeys, which would force us to try to decrypt them, this code - would run and handle that event quite quickly. - """ + 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 + incorrectly-tagged pubkeys, which would force us to try to decrypt them, this code + would run and handle that event quite quickly. + """ if len(data) < 350: # sanity check. logger.debug('(within processpubkey) payloadLength less than 350. Sanity check failed.') return @@ -367,14 +367,14 @@ class objectProcessor(threading.Thread): 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.') return - + logger.info('within recpubkey, addressVersion: %s, streamNumber: %s \n\ ripe %s\n\ publicSigningKey in hex: %s\n\ - publicEncryptionKey in hex: %s' % (addressVersion, - streamNumber, - ripe.encode('hex'), - publicSigningKey.encode('hex'), + publicEncryptionKey in hex: %s' % (addressVersion, + streamNumber, + ripe.encode('hex'), + publicSigningKey.encode('hex'), publicEncryptionKey.encode('hex') ) ) @@ -435,14 +435,14 @@ class objectProcessor(threading.Thread): 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. 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 except Exception as err: pass # print 'cryptorObject.decrypt Exception:', err if not initialDecryptionSuccessful: # 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 # This is a message bound for me. @@ -453,16 +453,16 @@ class objectProcessor(threading.Thread): decryptedData[readPosition:readPosition + 10]) readPosition += messageVersionLength 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 sendersAddressVersionNumber, sendersAddressVersionNumberLength = decodeVarint( decryptedData[readPosition:readPosition + 10]) readPosition += sendersAddressVersionNumberLength if sendersAddressVersionNumber == 0: - logger.info('Cannot understand sendersAddressVersionNumber = 0. Ignoring message.') + logger.info('Cannot understand sendersAddressVersionNumber = 0. Ignoring message.') return 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 if len(decryptedData) < 170: 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 subject = '' 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: body = 'Unknown encoding type.\n\n' + repr(message) subject = '' @@ -678,7 +678,7 @@ class objectProcessor(threading.Thread): sum += item logger.debug('Time to decrypt this message successfully: %s\n\ 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]) readPosition += broadcastVersionLength 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 if broadcastVersion == 1: beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table @@ -863,7 +863,7 @@ class objectProcessor(threading.Thread): sendersStream, sendersStreamLength = decodeVarint( decryptedData[readPosition:readPosition + 9]) 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 readPosition += sendersStreamLength behaviorBitfield = decryptedData[readPosition:readPosition + 4] @@ -891,7 +891,7 @@ class objectProcessor(threading.Thread): ripe.update(sha.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 messageEncodingType, messageEncodingTypeLength = decodeVarint( decryptedData[readPosition:readPosition + 9]) @@ -982,7 +982,7 @@ class objectProcessor(threading.Thread): embeddedTag = data[readPosition:readPosition+32] readPosition += 32 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 # We are interested in this broadcast because of its tag. cryptorObject = shared.MyECSubscriptionCryptorObjects[embeddedTag] @@ -990,7 +990,7 @@ class objectProcessor(threading.Thread): decryptedData = cryptorObject.decrypt(data[readPosition:]) logger.debug('EC decryption successful') except Exception as err: - logger.debug('Broadcast version 3 decryption Unsuccessful.') + logger.debug('Broadcast version 3 decryption Unsuccessful.') return signedBroadcastVersion, readPosition = decodeVarint( @@ -999,13 +999,13 @@ class objectProcessor(threading.Thread): sendersAddressVersion, sendersAddressVersionLength = decodeVarint( decryptedData[readPosition:readPosition + 9]) 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 readPosition += sendersAddressVersionLength sendersStream, sendersStreamLength = decodeVarint( decryptedData[readPosition:readPosition + 9]) 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 readPosition += sendersStreamLength behaviorBitfield = decryptedData[readPosition:readPosition + 4] @@ -1036,7 +1036,7 @@ class objectProcessor(threading.Thread): calculatedTag = hashlib.sha512(hashlib.sha512(encodeVarint( sendersAddressVersion) + encodeVarint(sendersStream) + calculatedRipe).digest()).digest()[32:] 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 messageEncodingType, messageEncodingTypeLength = decodeVarint( decryptedData[readPosition:readPosition + 9]) @@ -1210,4 +1210,4 @@ class objectProcessor(threading.Thread): # Throw away any extra lines (headers) after the subject. if subject: subject = subject.splitlines()[0] - return subject, body \ No newline at end of file + return subject, body diff --git a/src/class_outgoingSynSender.py b/src/class_outgoingSynSender.py index a1a04b51..4a2260d5 100644 --- a/src/class_outgoingSynSender.py +++ b/src/class_outgoingSynSender.py @@ -79,7 +79,7 @@ class outgoingSynSender(threading.Thread): File "C:\Python27\lib\socket.py", line 187, in __init__ _sock = _realsocket(family, type, proto) error: [Errno 10047] An address incompatible with the requested protocol was used - + So let us remove the offending address from our knownNodes file. """ shared.knownNodesLock.acquire() @@ -145,13 +145,13 @@ class outgoingSynSender(threading.Thread): rd = receiveDataThread() 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. - sendDataThreadQueue = Queue.Queue() # Used to submit information to the send data thread for this connection. - rd.setup(sock, - peer.host, - peer.port, + sendDataThreadQueue = Queue.Queue() # Used to submit information to the send data thread for this connection. + rd.setup(sock, + peer.host, + peer.port, self.streamNumber, - someObjectsOfWhichThisRemoteNodeIsAlreadyAware, - self.selfInitiatedConnections, + someObjectsOfWhichThisRemoteNodeIsAlreadyAware, + self.selfInitiatedConnections, sendDataThreadQueue) rd.start() with shared.printLock: diff --git a/src/class_receiveDataThread.py b/src/class_receiveDataThread.py index e78a7ae2..850448fb 100644 --- a/src/class_receiveDataThread.py +++ b/src/class_receiveDataThread.py @@ -43,7 +43,7 @@ class receiveDataThread(threading.Thread): someObjectsOfWhichThisRemoteNodeIsAlreadyAware, selfInitiatedConnections, sendDataThreadQueue): - + self.sock = sock self.peer = shared.Peer(HOST, port) self.streamNumber = streamNumber @@ -142,7 +142,7 @@ class receiveDataThread(threading.Thread): shared.knownNodesLock.acquire() shared.knownNodes[self.streamNumber][self.peer] = int(time.time()) shared.knownNodesLock.release() - + remoteCommand = self.data[4:16] with shared.printLock: print 'remoteCommand', repr(remoteCommand.replace('\x00', '')), ' from', self.peer @@ -306,8 +306,8 @@ class receiveDataThread(threading.Thread): self.sendinvMessageToJustThisOnePeer( numberOfObjectsInInvMessage, payload) - # Used to send a big inv message when the connection with a node is - # first fully established. Notice that there is also a broadcastinv + # Used to send a big inv message when the connection with a node is + # first fully established. Notice that there is also a broadcastinv # function for broadcasting invs to everyone in our stream. def sendinvMessageToJustThisOnePeer(self, numberOfObjects, payload): payload = encodeVarint(numberOfObjects) + payload @@ -439,7 +439,7 @@ class receiveDataThread(threading.Thread): advertisedSet.add(data[lengthOfVarint + (32 * i):32 + lengthOfVarint + (32 * i)]) 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) - for item in objectsNewToMe: + for item in objectsNewToMe: if totalNumberOfobjectsThatWeHaveYetToGetFromAllPeers > 200000 and len(self.objectsThatWeHaveYetToGetFromThisPeer) > 1000: # inv flooding attack mitigation 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.' @@ -627,8 +627,8 @@ class receiveDataThread(threading.Thread): else: hostFromAddrMessage = socket.inet_ntop(socket.AF_INET6, fullHost) if hostFromAddrMessage == "": - # This can happen on Windows systems which are not 64-bit compatible - # so let us drop the IPv6 address. + # This can happen on Windows systems which are not 64-bit compatible + # so let us drop the IPv6 address. continue if not self._checkIPv6Address(fullHost, hostFromAddrMessage): continue @@ -669,9 +669,9 @@ class receiveDataThread(threading.Thread): 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 - # when we fully establish a connection with a - # peer (with the full exchange of version and verack + # Send a huge addr message to our peer. This is only used + # when we fully establish a connection with a + # peer (with the full exchange of version and verack # messages). def sendaddr(self): addrsInMyStream = {} @@ -764,7 +764,7 @@ class receiveDataThread(threading.Thread): a new version message, like if the remote node wants to update the streams in which they are interested. But for now we'll ignore this version message - """ + """ return self.remoteProtocolVersion, = unpack('>L', data[:4]) if self.remoteProtocolVersion <= 1: @@ -806,7 +806,7 @@ class receiveDataThread(threading.Thread): with shared.printLock: print 'Closing connection to myself: ', self.peer return - + # 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. self.sendDataThreadQueue.put((0, 'setRemoteProtocolVersion', self.remoteProtocolVersion)) diff --git a/src/class_sendDataThread.py b/src/class_sendDataThread.py index 5aabaeb5..675d790e 100644 --- a/src/class_sendDataThread.py +++ b/src/class_sendDataThread.py @@ -60,7 +60,7 @@ class sendDataThread(threading.Thread): # if not 'Bad file descriptor' in err: with shared.printLock: sys.stderr.write('sock.sendall error: %s\n' % err) - + self.versionSent = 1 def run(self): @@ -82,7 +82,7 @@ class sendDataThread(threading.Thread): elif command == 'setStreamNumber': self.streamNumber = data 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': specifiedRemoteProtocolVersion = data with shared.printLock: @@ -160,7 +160,7 @@ class sendDataThread(threading.Thread): self.sock.sendall(data) self.lastTimeISentData = int(time.time()) 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 elif command == 'connectionIsOrWasFullyEstablished': self.connectionIsOrWasFullyEstablished = True diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index 4b43c22f..f75bf8bd 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -161,7 +161,7 @@ class singleWorker(threading.Thread): # 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 # send messages to "ourselves". - def sendOutOrStoreMyV3Pubkey(self, hash): + def sendOutOrStoreMyV3Pubkey(self, hash): try: myAddress = shared.myAddressesByHash[hash] except: @@ -244,7 +244,7 @@ class singleWorker(threading.Thread): pass # 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): if not shared.config.has_section(myAddress): #The address has been deleted. @@ -406,9 +406,9 @@ class singleWorker(threading.Thread): dataToEncrypt += encodeVarint(len(signature)) dataToEncrypt += signature - # 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 - # and illegal content from flowing through the Internet connections and being stored on the disk of 3rd parties. + # 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 + # and illegal content from flowing through the Internet connections and being stored on the disk of 3rd parties. if addressVersionNumber <= 3: privEncryptionKey = hashlib.sha512(encodeVarint( addressVersionNumber) + encodeVarint(streamNumber) + ripe).digest()[:32] @@ -451,7 +451,7 @@ class singleWorker(threading.Thread): 'broadcastsent', int(time.time()), ackdata) - + def sendMsg(self): # 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): with shared.printLock: print 'Not bothering to include ackdata because the receiver said that they won\'t relay it anyway.' - fullAckPayload = '' + fullAckPayload = '' else: 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. diff --git a/src/class_sqlThread.py b/src/class_sqlThread.py index 2df6c05f..aa2a64d0 100644 --- a/src/class_sqlThread.py +++ b/src/class_sqlThread.py @@ -21,7 +21,7 @@ class sqlThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) - def run(self): + def run(self): self.conn = sqlite3.connect(shared.appdata + 'messages.dat') self.conn.text_factory = str self.cur = self.conn.cursor() @@ -188,12 +188,12 @@ class sqlThread(threading.Thread): self.cur.execute( '''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') - + ensureNamecoinOptions() - + """# 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';''' parameters = '' @@ -269,7 +269,7 @@ class sqlThread(threading.Thread): item = '''update settings set value=? WHERE key='version';''' 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 @@ -285,7 +285,7 @@ class sqlThread(threading.Thread): shared.config.set( 'bitmessagesettings', 'stopresendingafterxmonths', '') #shared.config.set( - shared.config.set('bitmessagesettings', 'settingsversion', '8') + shared.config.set('bitmessagesettings', 'settingsversion', '8') with open(shared.appdata + 'keys.dat', 'wb') as 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 # Bitmessage users? Add it right above this line! - + try: testpayload = '\x00\x00' t = ('1234', 1, testpayload, '12345678', 'no') diff --git a/src/debug.py b/src/debug.py index fe7815e7..01666304 100644 --- a/src/debug.py +++ b/src/debug.py @@ -78,4 +78,4 @@ def restartLoggingInUpdatedAppdataLocation(): i.flush() i.close() configureLogging() - logger = logging.getLogger('both') \ No newline at end of file + logger = logging.getLogger('both') diff --git a/src/defaultKnownNodes.py b/src/defaultKnownNodes.py index bf98c351..8db6cb63 100644 --- a/src/defaultKnownNodes.py +++ b/src/defaultKnownNodes.py @@ -21,7 +21,7 @@ def createDefaultKnownNodes(appdata): 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('66.108.53.42', 8080)] = int(time.time()) - + ############# Stream 2 ################# stream2 = {} # None yet diff --git a/src/helper_inbox.py b/src/helper_inbox.py index 1ba0e34b..231d59a2 100644 --- a/src/helper_inbox.py +++ b/src/helper_inbox.py @@ -4,8 +4,8 @@ import shared def insert(t): sqlExecute('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''', *t) shared.UISignalQueue.put(('changedInboxUnread', None)) - + def trash(msgid): sqlExecute('''UPDATE inbox SET folder='trash' WHERE msgid=?''', msgid) shared.UISignalQueue.put(('removeInboxRowByMsgid',msgid)) - + diff --git a/src/helper_sql.py b/src/helper_sql.py index 0353f9ae..1e3c1534 100644 --- a/src/helper_sql.py +++ b/src/helper_sql.py @@ -13,7 +13,7 @@ def sqlQuery(sqlStatement, *args): sqlSubmitQueue.put('') else: sqlSubmitQueue.put(args) - + queryreturn = sqlReturnQueue.get() sqlLock.release() @@ -27,7 +27,7 @@ def sqlExecute(sqlStatement, *args): sqlSubmitQueue.put('') else: sqlSubmitQueue.put(args) - + sqlReturnQueue.get() sqlSubmitQueue.put('commit') sqlLock.release() @@ -48,7 +48,7 @@ class SqlBulkExecute: def execute(self, sqlStatement, *args): sqlSubmitQueue.put(sqlStatement) - + if args == (): sqlSubmitQueue.put('') else: diff --git a/src/helper_startup.py b/src/helper_startup.py index fd14e528..843c6e75 100644 --- a/src/helper_startup.py +++ b/src/helper_startup.py @@ -102,7 +102,7 @@ def loadConfig(): 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') - + #start:UI setting to stop trying to send messages after X days/months shared.config.set( 'bitmessagesettings', 'stopresendingafterxdays', '') diff --git a/src/namecoin.py b/src/namecoin.py index 03cd3080..9c4725e7 100644 --- a/src/namecoin.py +++ b/src/namecoin.py @@ -100,11 +100,11 @@ class namecoinConnection (object): try: val = json.loads (res) 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: 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" # command, and builds either an error message or a success message with @@ -114,7 +114,7 @@ class namecoinConnection (object): if self.nmctype == "namecoind": res = self.callRPC ("getinfo", []) vers = res["version"] - + v3 = vers % 100 vers = vers / 100 v2 = vers % 100 @@ -192,7 +192,7 @@ class namecoinConnection (object): try: s = socket.socket (socket.AF_INET, socket.SOCK_STREAM) s.setsockopt (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - s.settimeout(3) + s.settimeout(3) s.connect ((self.host, int (self.port))) s.sendall (data) result = "" @@ -266,7 +266,7 @@ def ensureNamecoinOptions (): defaultPass = val if key == "rpcport": shared.namecoinDefaultRpcPort = val - + nmc.close () except Exception as exc: diff --git a/src/pyelliptic/arithmetic.py b/src/pyelliptic/arithmetic.py index 1eec381a..f197ea81 100644 --- a/src/pyelliptic/arithmetic.py +++ b/src/pyelliptic/arithmetic.py @@ -25,7 +25,7 @@ def get_code_string(base): def encode(val,base,minlen=0): code_string = get_code_string(base) - result = "" + result = "" while val > 0: result = code_string[val % base] + result val /= base @@ -49,14 +49,14 @@ def changebase(string,frm,to,minlen=0): def base10_add(a,b): if a == None: return b[0],b[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]) else: return None m = ((b[1]-a[1]) * inv(b[0]-a[0],P)) % P x = (m*m-a[0]-b[0]) % P y = (m*(a[0]-x)-a[1]) % P return (x,y) - + def base10_double(a): if a == None: return None 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): return hashlib.sha256(hashlib.sha256(string).digest()).digest() - + def bin_to_b58check(inp): inp_fmtd = '\x00' + inp leadingzbytes = len(re.match('^\x00*',inp_fmtd).group(0)) diff --git a/src/pyelliptic/openssl.py b/src/pyelliptic/openssl.py index f83630d4..6d13933f 100644 --- a/src/pyelliptic/openssl.py +++ b/src/pyelliptic/openssl.py @@ -294,7 +294,7 @@ class _OpenSSL: except: # The above is not compatible with all versions of OSX. self.PKCS5_PBKDF2_HMAC = self._lib.PKCS5_PBKDF2_HMAC_SHA1 - + self.PKCS5_PBKDF2_HMAC.restype = ctypes.c_int self.PKCS5_PBKDF2_HMAC.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_int, @@ -394,11 +394,11 @@ class _OpenSSL: OpenSSL random function """ 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 - # 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 - # 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) while self.RAND_bytes(buffer, size) != 1: import time diff --git a/src/qidenticon.py b/src/qidenticon.py index cc3af6b3..7678a23f 100644 --- a/src/qidenticon.py +++ b/src/qidenticon.py @@ -58,7 +58,7 @@ __all__ = ['render_identicon', 'IdenticonRendererBase'] class IdenticonRendererBase(object): PATH_SET = [] - + def __init__(self, code): """ @param code code for icon @@ -66,51 +66,51 @@ class IdenticonRendererBase(object): if not isinstance(code, int): code = int(code) self.code = code - + def render(self, size, twoColor, opacity, penwidth): """ render identicon to QPicture - + @param size identicon patchsize. (image size is 3 * [size]) @return QPicture """ - + # decode the code middle, corner, side, foreColor, secondColor, swap_cross = self.decode(self.code, twoColor) # make image image = QPixmap(QSize(size * 3 +penwidth, size * 3 +penwidth)) - + # fill background backColor = QtGui.QColor(255,255,255,opacity) image.fill(backColor) - + kwds = { 'image': image, 'size': size, 'foreColor': foreColor if swap_cross else secondColor, 'penwidth': penwidth, 'backColor': backColor} - + # middle patch image = self.drawPatchQt((1, 1), middle[2], middle[1], middle[0], **kwds) - + # side patch kwds['foreColor'] = foreColor kwds['type'] = side[0] for i in xrange(4): pos = [(1, 0), (2, 1), (1, 2), (0, 1)][i] image = self.drawPatchQt(pos, side[2] + 1 + i, side[1], **kwds) - + # corner patch kwds['foreColor'] = secondColor kwds['type'] = corner[0] for i in xrange(4): pos = [(0, 0), (2, 0), (2, 2), (0, 2)][i] image = self.drawPatchQt(pos, corner[2] + 1 + i, corner[1], **kwds) - + return image - + def drawPatchQt(self, pos, turn, invert, type, image, size, foreColor, backColor, penwidth): @@ -123,28 +123,28 @@ class IdenticonRendererBase(object): invert = not invert path = [(0., 0.), (1., 0.), (1., 1.), (0., 1.), (0., 0.)] - + polygon = QPolygonF([QPointF(x*size,y*size) for x,y in path]) - + rot = turn % 4 rect = [QPointF(0.,0.), QPointF(size, 0.), QPointF(size, size), QPointF(0., size)] rotation = [0,90,180,270] - + nopen = QtGui.QPen(foreColor, Qt.NoPen) foreBrush = QtGui.QBrush(foreColor, Qt.SolidPattern) if penwidth > 0: pen_color = QtGui.QColor(255, 255, 255) pen = QtGui.QPen(pen_color, Qt.SolidPattern) pen.setWidth(penwidth) - + painter = QPainter() painter.begin(image) painter.setPen(nopen) - + painter.translate(pos[0]*size +penwidth/2, pos[1]*size +penwidth/2) painter.translate(rect[rot]) painter.rotate(rotation[rot]) - + if invert: # subtract the actual polygon from a rectangle to invert it poly_rect = QPolygonF(rect) @@ -157,21 +157,21 @@ class IdenticonRendererBase(object): # draw the fill painter.setPen(nopen) painter.drawPolygon(polygon, Qt.WindingFill) - + painter.end() - + return image ### virtual functions def decode(self, code): raise NotImplementedError - + class DonRenderer(IdenticonRendererBase): """ Don Park's implementation of identicon see : http://www.docuverse.com/blog/donpark/2007/01/19/identicon-updated-and-source-released """ - + PATH_SET = [ #[0] full square: [(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: MIDDLE_PATCH_SET = [0, 4, 8, 15] - + # modify path set for idx in xrange(len(PATH_SET)): if PATH_SET[idx]: p = map(lambda vec: (vec[0] / 4.0, vec[1] / 4.0), PATH_SET[idx]) PATH_SET[idx] = p + p[:1] - + def decode(self, code, twoColor): # decode the code shift = 0; middleType = (code >> shift) & 0x03 @@ -231,18 +231,18 @@ class DonRenderer(IdenticonRendererBase): shift += 5; second_green= (code >> shift) & 0x1F shift += 5; second_red = (code >> shift) & 0x1F shift += 1; swap_cross = (code >> shift) & 0x01 - + middleType = self.MIDDLE_PATCH_SET[middleType] - + foreColor = (red << 3, green << 3, blue << 3) foreColor = QtGui.QColor(*foreColor) - + if twoColor: secondColor = (second_blue << 3, second_green << 3, second_red << 3) secondColor = QtGui.QColor(*secondColor) else: secondColor = foreColor - + return (middleType, middleInvert, 0),\ (cornerType, cornerInvert, cornerTurn),\ (sideType, sideInvert, sideTurn),\ @@ -252,4 +252,4 @@ class DonRenderer(IdenticonRendererBase): def render_identicon(code, size, twoColor=False, opacity=255, penwidth=0, renderer=None): if not renderer: renderer = DonRenderer - return renderer(code).render(size, twoColor, opacity, penwidth) \ No newline at end of file + return renderer(code).render(size, twoColor, opacity, penwidth) diff --git a/src/shared.py b/src/shared.py index 96b9a7ce..bc82ecd0 100644 --- a/src/shared.py +++ b/src/shared.py @@ -88,7 +88,7 @@ networkDefaultPayloadLengthExtraBytes = 14000 #To make sending short messages a namecoinDefaultRpcPort = "8336" # 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. frozen = getattr(sys,'frozen', None) @@ -287,7 +287,7 @@ def reloadBroadcastSendersForWhichImWatching(): if addressVersionNumber == 2: 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. - + if addressVersionNumber <= 3: privEncryptionKey = hashlib.sha512(encodeVarint(addressVersionNumber)+encodeVarint(streamNumber)+hash).digest()[:32] MyECSubscriptionCryptorObjects[hash] = highlevelcrypto.makeCryptor(privEncryptionKey.encode('hex')) @@ -313,12 +313,12 @@ def isProofOfWorkSufficient( def doCleanShutdown(): global shutdown 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: data = 'no data' shared.objectProcessorQueueSize += len(data) objectProcessorQueue.put(('checkShutdownVariable',data)) - + knownNodesLock.acquire() UISignalQueue.put(('updateStatusBar','Saving the knownNodes list of peers to disk...')) output = open(appdata + 'knownnodes.dat', 'wb') @@ -335,21 +335,21 @@ def doCleanShutdown(): 'updateStatusBar', 'Flushing inventory in memory out to disk. This should normally only take a second...')) 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. while shutdown == 1: time.sleep(.1) - + # This one last useless query will guarantee that the previous flush committed and that the # objectProcessorThread committed before we close the program. sqlQuery('SELECT address FROM subscriptions') logger.info('Finished flushing inventory.') sqlStoredProcedure('exit') - + # 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. - time.sleep(.25) + time.sleep(.25) if safeConfigGetBoolean('bitmessagesettings','daemon'): logger.info('Clean shutdown complete.') @@ -362,7 +362,7 @@ def broadcastToSendDataQueues(data): # logger.debug('running broadcastToSendDataQueues') for q in sendDataQueues: q.put(data) - + 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. with SqlBulkExecute() as sql: @@ -432,7 +432,7 @@ def fixSensitiveFilePermissions(filename, hasEnabledKeys): except Exception, e: logger.exception('Keyfile permissions could not be fixed.') raise - + def isBitSetWithinBitfield(fourByteString, n): # Uses MSB 0 bit numbering across 4 bytes of data n = 31 - n @@ -512,7 +512,7 @@ def decryptAndCheckPubkeyPayload(payload, address): # 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.') return 'failed' - + t = (ripe, addressVersion, signedData, int(time.time()), 'yes') sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t) return 'successful' @@ -536,7 +536,7 @@ def checkAndShareMsgWithPeers(data): else: 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.') return 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) return 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 addressVersion, varintLength = decodeVarint( data[readPosition:readPosition + 10]) @@ -726,7 +726,7 @@ def checkAndShareBroadcastWithPeers(data): readPosition += 4 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 if embeddedTime < (int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept): logger.debug('The embedded time in this broadcast message is too old. Ignoring message.') diff --git a/src/singleton.py b/src/singleton.py index ee5c3077..a403e423 100644 --- a/src/singleton.py +++ b/src/singleton.py @@ -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. 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=""): import sys diff --git a/src/socks/LICENSE b/src/socks/LICENSE index 04b6b1f3..5cf2053e 100644 --- a/src/socks/LICENSE +++ b/src/socks/LICENSE @@ -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 to endorse or promote products derived from this software without specific prior written permission. - + THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO diff --git a/src/socks/README b/src/socks/README index a52f55f3..515f2db9 100644 --- a/src/socks/README +++ b/src/socks/README @@ -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 case you should run an identd server and/or configure your firewall to allow incoming 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 different userid than the one you have provided. Change your userid (through the username parameter of the setproxy method) to match and try again.