Merge pull request #582 from Atheros1/master

objectProcessorThread
This commit is contained in:
Jonathan Warren 2013-12-07 12:47:52 -08:00
commit e423343e9a
12 changed files with 1928 additions and 1507 deletions

View File

@ -29,6 +29,7 @@ from helper_sql import *
from class_sqlThread import *
from class_singleCleaner import *
from class_singleWorker import *
from class_objectProcessor import *
from class_outgoingSynSender import *
from class_singleListener import *
from class_addressGenerator import *
@ -47,6 +48,7 @@ if sys.platform == 'darwin':
sys.exit(0)
def connectToStream(streamNumber):
shared.streamsInWhichIAmParticipating[streamNumber] = 'no data'
selfInitiatedConnections[streamNumber] = {}
shared.inventorySets[streamNumber] = set()
queryData = sqlQuery('''SELECT hash FROM inventory WHERE streamnumber=?''', streamNumber)
@ -985,6 +987,11 @@ class Main:
sqlLookup.daemon = False # DON'T close the main program even if there are threads left. The closeEvent should command this thread to exit gracefully.
sqlLookup.start()
# Start the thread that calculates POWs
objectProcessorThread = objectProcessor()
objectProcessorThread.daemon = False # DON'T close the main program even the thread remains. This thread checks the shutdown variable after processing each object.
objectProcessorThread.start()
# Start the cleanerThread
singleCleanerThread = singleCleaner()
singleCleanerThread.daemon = True # close the main program even if there are threads left

View File

@ -16,6 +16,7 @@ import shared
from bitmessageui import *
from namecoin import namecoinConnection, ensureNamecoinOptions
from newaddressdialog import *
from addaddressdialog import *
from newsubscriptiondialog import *
from regenerateaddresses import *
from newchandialog import *
@ -2063,15 +2064,15 @@ class MyForm(QtGui.QMainWindow):
self.ubuntuMessagingMenuUpdate(True, newItem, toLabel)
def click_pushButtonAddAddressBook(self):
self.NewSubscriptionDialogInstance = NewSubscriptionDialog(self)
if self.NewSubscriptionDialogInstance.exec_():
if self.NewSubscriptionDialogInstance.ui.labelSubscriptionAddressCheck.text() == _translate("MainWindow", "Address is valid."):
self.AddAddressDialogInstance = AddAddressDialog(self)
if self.AddAddressDialogInstance.exec_():
if self.AddAddressDialogInstance.ui.labelAddressCheck.text() == _translate("MainWindow", "Address is valid."):
# First we must check to see if the address is already in the
# address book. The user cannot add it again or else it will
# cause problems when updating and deleting the entry.
address = addBMIfNotPresent(str(
self.NewSubscriptionDialogInstance.ui.lineEditSubscriptionAddress.text()))
label = self.NewSubscriptionDialogInstance.ui.newsubscriptionlabel.text().toUtf8()
self.AddAddressDialogInstance.ui.lineEditAddress.text()))
label = self.AddAddressDialogInstance.ui.newAddressLabel.text().toUtf8()
self.addEntryToAddressBook(address,label)
else:
self.statusBar().showMessage(_translate(
@ -2120,7 +2121,7 @@ class MyForm(QtGui.QMainWindow):
def click_pushButtonAddSubscription(self):
self.NewSubscriptionDialogInstance = NewSubscriptionDialog(self)
if self.NewSubscriptionDialogInstance.exec_():
if self.NewSubscriptionDialogInstance.ui.labelSubscriptionAddressCheck.text() != _translate("MainWindow", "Address is valid."):
if self.NewSubscriptionDialogInstance.ui.labelAddressCheck.text() != _translate("MainWindow", "Address is valid."):
self.statusBar().showMessage(_translate("MainWindow", "The address you entered was invalid. Ignoring it."))
return
address = addBMIfNotPresent(str(self.NewSubscriptionDialogInstance.ui.lineEditSubscriptionAddress.text()))
@ -2130,6 +2131,22 @@ 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
# in the objectProcessorQueue to be processed
if self.NewSubscriptionDialogInstance.ui.checkBoxDisplayMessagesAlreadyInInventory.isChecked():
status, addressVersion, streamNumber, ripe = decodeAddress(address)
shared.flushInventory()
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(encodeVarint(
addressVersion) + encodeVarint(streamNumber) + ripe).digest()).digest()
tag = doubleHashOfAddressData[32:]
queryreturn = sqlQuery(
'''select payload from inventory where objecttype='broadcast' and tag=?''', tag)
for row in queryreturn:
payload, = row
objectType = 'broadcast'
with shared.objectProcessorQueueSizeLock:
shared.objectProcessorQueueSize += len(payload)
shared.objectProcessorQueue.put((objectType,payload))
def loadBlackWhiteList(self):
# Initialize the Blacklist or Whitelist table
@ -2368,11 +2385,11 @@ class MyForm(QtGui.QMainWindow):
self.ui.tabWidget.setTabText(6, 'Whitelist')
def click_pushButtonAddBlacklist(self):
self.NewBlacklistDialogInstance = NewSubscriptionDialog(self)
self.NewBlacklistDialogInstance = AddAddressDialog(self)
if self.NewBlacklistDialogInstance.exec_():
if self.NewBlacklistDialogInstance.ui.labelSubscriptionAddressCheck.text() == _translate("MainWindow", "Address is valid."):
if self.NewBlacklistDialogInstance.ui.labelAddressCheck.text() == _translate("MainWindow", "Address is valid."):
address = addBMIfNotPresent(str(
self.NewBlacklistDialogInstance.ui.lineEditSubscriptionAddress.text()))
self.NewBlacklistDialogInstance.ui.lineEditAddress.text()))
# First we must check to see if the address is already in the
# address book. The user cannot add it again or else it will
# cause problems when updating and deleting the entry.
@ -2386,7 +2403,7 @@ class MyForm(QtGui.QMainWindow):
self.ui.tableWidgetBlacklist.setSortingEnabled(False)
self.ui.tableWidgetBlacklist.insertRow(0)
newItem = QtGui.QTableWidgetItem(unicode(
self.NewBlacklistDialogInstance.ui.newsubscriptionlabel.text().toUtf8(), 'utf-8'))
self.NewBlacklistDialogInstance.ui.newAddressLabel.text().toUtf8(), 'utf-8'))
newItem.setIcon(avatarize(address))
self.ui.tableWidgetBlacklist.setItem(0, 0, newItem)
newItem = QtGui.QTableWidgetItem(address)
@ -2394,7 +2411,7 @@ class MyForm(QtGui.QMainWindow):
QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
self.ui.tableWidgetBlacklist.setItem(0, 1, newItem)
self.ui.tableWidgetBlacklist.setSortingEnabled(True)
t = (str(self.NewBlacklistDialogInstance.ui.newsubscriptionlabel.text().toUtf8()), address, True)
t = (str(self.NewBlacklistDialogInstance.ui.newAddressLabel.text().toUtf8()), address, True)
if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black':
sql = '''INSERT INTO blacklist VALUES (?,?,?)'''
else:
@ -3465,6 +3482,40 @@ class SpecialAddressBehaviorDialog(QtGui.QDialog):
QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self))
class AddAddressDialog(QtGui.QDialog):
def __init__(self, parent):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_AddAddressDialog()
self.ui.setupUi(self)
self.parent = parent
QtCore.QObject.connect(self.ui.lineEditAddress, QtCore.SIGNAL(
"textChanged(QString)"), self.addressChanged)
def addressChanged(self, QString):
status, a, b, c = decodeAddress(str(QString))
if status == 'missingbm':
self.ui.labelAddressCheck.setText(_translate(
"MainWindow", "The address should start with ''BM-''"))
elif status == 'checksumfailed':
self.ui.labelAddressCheck.setText(_translate(
"MainWindow", "The address is not typed or copied correctly (the checksum failed)."))
elif status == 'versiontoohigh':
self.ui.labelAddressCheck.setText(_translate(
"MainWindow", "The version number of this address is higher than this software can support. Please upgrade Bitmessage."))
elif status == 'invalidcharacters':
self.ui.labelAddressCheck.setText(_translate(
"MainWindow", "The address contains invalid characters."))
elif status == 'ripetooshort':
self.ui.labelAddressCheck.setText(_translate(
"MainWindow", "Some data encoded in the address is too short."))
elif status == 'ripetoolong':
self.ui.labelAddressCheck.setText(_translate(
"MainWindow", "Some data encoded in the address is too long."))
elif status == 'success':
self.ui.labelAddressCheck.setText(
_translate("MainWindow", "Address is valid."))
class NewSubscriptionDialog(QtGui.QDialog):
def __init__(self, parent):
@ -3473,31 +3524,56 @@ class NewSubscriptionDialog(QtGui.QDialog):
self.ui.setupUi(self)
self.parent = parent
QtCore.QObject.connect(self.ui.lineEditSubscriptionAddress, QtCore.SIGNAL(
"textChanged(QString)"), self.subscriptionAddressChanged)
"textChanged(QString)"), self.addressChanged)
self.ui.checkBoxDisplayMessagesAlreadyInInventory.setText(
_translate("MainWindow", "Enter an address above."))
def subscriptionAddressChanged(self, QString):
status, a, b, c = decodeAddress(str(QString))
def addressChanged(self, QString):
self.ui.checkBoxDisplayMessagesAlreadyInInventory.setEnabled(False)
self.ui.checkBoxDisplayMessagesAlreadyInInventory.setChecked(False)
status, addressVersion, streamNumber, ripe = decodeAddress(str(QString))
if status == 'missingbm':
self.ui.labelSubscriptionAddressCheck.setText(_translate(
self.ui.labelAddressCheck.setText(_translate(
"MainWindow", "The address should start with ''BM-''"))
elif status == 'checksumfailed':
self.ui.labelSubscriptionAddressCheck.setText(_translate(
self.ui.labelAddressCheck.setText(_translate(
"MainWindow", "The address is not typed or copied correctly (the checksum failed)."))
elif status == 'versiontoohigh':
self.ui.labelSubscriptionAddressCheck.setText(_translate(
self.ui.labelAddressCheck.setText(_translate(
"MainWindow", "The version number of this address is higher than this software can support. Please upgrade Bitmessage."))
elif status == 'invalidcharacters':
self.ui.labelSubscriptionAddressCheck.setText(_translate(
self.ui.labelAddressCheck.setText(_translate(
"MainWindow", "The address contains invalid characters."))
elif status == 'ripetooshort':
self.ui.labelSubscriptionAddressCheck.setText(_translate(
self.ui.labelAddressCheck.setText(_translate(
"MainWindow", "Some data encoded in the address is too short."))
elif status == 'ripetoolong':
self.ui.labelSubscriptionAddressCheck.setText(_translate(
self.ui.labelAddressCheck.setText(_translate(
"MainWindow", "Some data encoded in the address is too long."))
elif status == 'success':
self.ui.labelSubscriptionAddressCheck.setText(
self.ui.labelAddressCheck.setText(
_translate("MainWindow", "Address is valid."))
if addressVersion <= 3:
self.ui.checkBoxDisplayMessagesAlreadyInInventory.setText(
_translate("MainWindow", "Address is an old type. We cannot display its past broadcasts."))
else:
shared.flushInventory()
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(encodeVarint(
addressVersion) + encodeVarint(streamNumber) + ripe).digest()).digest()
tag = doubleHashOfAddressData[32:]
queryreturn = sqlQuery(
'''select hash from inventory where objecttype='broadcast' and tag=?''', tag)
if len(queryreturn) == 0:
self.ui.checkBoxDisplayMessagesAlreadyInInventory.setText(
_translate("MainWindow", "There are no recent broadcasts from this address to display."))
elif len(queryreturn) == 1:
self.ui.checkBoxDisplayMessagesAlreadyInInventory.setEnabled(True)
self.ui.checkBoxDisplayMessagesAlreadyInInventory.setText(
_translate("MainWindow", "Display the %1 recent broadcast from this address.").arg(str(len(queryreturn))))
else:
self.ui.checkBoxDisplayMessagesAlreadyInInventory.setEnabled(True)
self.ui.checkBoxDisplayMessagesAlreadyInInventory.setText(
_translate("MainWindow", "Display the %1 recent broadcasts from this address.").arg(str(len(queryreturn))))
class NewAddressDialog(QtGui.QDialog):

View File

@ -0,0 +1,65 @@
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'addaddressdialog.ui'
#
# Created: Sat Nov 30 20:35:38 2013
# by: PyQt4 UI code generator 4.10.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_AddAddressDialog(object):
def setupUi(self, AddAddressDialog):
AddAddressDialog.setObjectName(_fromUtf8("AddAddressDialog"))
AddAddressDialog.resize(368, 162)
self.formLayout = QtGui.QFormLayout(AddAddressDialog)
self.formLayout.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow)
self.formLayout.setObjectName(_fromUtf8("formLayout"))
self.label_2 = QtGui.QLabel(AddAddressDialog)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.formLayout.setWidget(0, QtGui.QFormLayout.SpanningRole, self.label_2)
self.newAddressLabel = QtGui.QLineEdit(AddAddressDialog)
self.newAddressLabel.setObjectName(_fromUtf8("newAddressLabel"))
self.formLayout.setWidget(2, QtGui.QFormLayout.SpanningRole, self.newAddressLabel)
self.label = QtGui.QLabel(AddAddressDialog)
self.label.setObjectName(_fromUtf8("label"))
self.formLayout.setWidget(4, QtGui.QFormLayout.LabelRole, self.label)
self.lineEditAddress = QtGui.QLineEdit(AddAddressDialog)
self.lineEditAddress.setObjectName(_fromUtf8("lineEditAddress"))
self.formLayout.setWidget(5, QtGui.QFormLayout.SpanningRole, self.lineEditAddress)
self.labelAddressCheck = QtGui.QLabel(AddAddressDialog)
self.labelAddressCheck.setText(_fromUtf8(""))
self.labelAddressCheck.setWordWrap(True)
self.labelAddressCheck.setObjectName(_fromUtf8("labelAddressCheck"))
self.formLayout.setWidget(6, QtGui.QFormLayout.SpanningRole, self.labelAddressCheck)
self.buttonBox = QtGui.QDialogButtonBox(AddAddressDialog)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
self.formLayout.setWidget(7, QtGui.QFormLayout.FieldRole, self.buttonBox)
self.retranslateUi(AddAddressDialog)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), AddAddressDialog.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), AddAddressDialog.reject)
QtCore.QMetaObject.connectSlotsByName(AddAddressDialog)
def retranslateUi(self, AddAddressDialog):
AddAddressDialog.setWindowTitle(_translate("AddAddressDialog", "Add new entry", None))
self.label_2.setText(_translate("AddAddressDialog", "Label", None))
self.label.setText(_translate("AddAddressDialog", "Address", None))

View File

@ -0,0 +1,97 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>AddAddressDialog</class>
<widget class="QDialog" name="AddAddressDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>368</width>
<height>162</height>
</rect>
</property>
<property name="windowTitle">
<string>Add new entry</string>
</property>
<layout class="QFormLayout" name="formLayout">
<property name="fieldGrowthPolicy">
<enum>QFormLayout::AllNonFixedFieldsGrow</enum>
</property>
<item row="0" column="0" colspan="2">
<widget class="QLabel" name="label_2">
<property name="text">
<string>Label</string>
</property>
</widget>
</item>
<item row="2" column="0" colspan="2">
<widget class="QLineEdit" name="newAddressLabel"/>
</item>
<item row="4" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>Address</string>
</property>
</widget>
</item>
<item row="5" column="0" colspan="2">
<widget class="QLineEdit" name="lineEditAddress"/>
</item>
<item row="6" column="0" colspan="2">
<widget class="QLabel" name="labelAddressCheck">
<property name="text">
<string/>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item row="7" column="1">
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>AddAddressDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>360</x>
<y>234</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>256</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>AddAddressDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>360</x>
<y>240</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>256</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View File

@ -2,8 +2,8 @@
# Form implementation generated from reading ui file 'newsubscriptiondialog.ui'
#
# Created: Fri Oct 19 15:30:41 2012
# by: PyQt4 UI code generator 4.9.4
# Created: Sat Nov 30 21:53:38 2013
# by: PyQt4 UI code generator 4.10.3
#
# WARNING! All changes made in this file will be lost!
@ -12,41 +12,49 @@ from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_NewSubscriptionDialog(object):
def setupUi(self, NewSubscriptionDialog):
NewSubscriptionDialog.setObjectName(_fromUtf8("NewSubscriptionDialog"))
NewSubscriptionDialog.resize(368, 192)
NewSubscriptionDialog.resize(368, 173)
self.formLayout = QtGui.QFormLayout(NewSubscriptionDialog)
self.formLayout.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow)
self.formLayout.setObjectName(_fromUtf8("formLayout"))
self.label_2 = QtGui.QLabel(NewSubscriptionDialog)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.formLayout.setWidget(0, QtGui.QFormLayout.SpanningRole, self.label_2)
self.formLayout.setWidget(0, QtGui.QFormLayout.LabelRole, self.label_2)
self.newsubscriptionlabel = QtGui.QLineEdit(NewSubscriptionDialog)
self.newsubscriptionlabel.setObjectName(_fromUtf8("newsubscriptionlabel"))
self.formLayout.setWidget(2, QtGui.QFormLayout.SpanningRole, self.newsubscriptionlabel)
self.formLayout.setWidget(1, QtGui.QFormLayout.SpanningRole, self.newsubscriptionlabel)
self.label = QtGui.QLabel(NewSubscriptionDialog)
self.label.setObjectName(_fromUtf8("label"))
self.formLayout.setWidget(4, QtGui.QFormLayout.LabelRole, self.label)
spacerItem = QtGui.QSpacerItem(302, 10, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.formLayout.setItem(4, QtGui.QFormLayout.FieldRole, spacerItem)
self.formLayout.setWidget(2, QtGui.QFormLayout.LabelRole, self.label)
self.lineEditSubscriptionAddress = QtGui.QLineEdit(NewSubscriptionDialog)
self.lineEditSubscriptionAddress.setObjectName(_fromUtf8("lineEditSubscriptionAddress"))
self.formLayout.setWidget(5, QtGui.QFormLayout.SpanningRole, self.lineEditSubscriptionAddress)
self.formLayout.setWidget(3, QtGui.QFormLayout.SpanningRole, self.lineEditSubscriptionAddress)
self.labelAddressCheck = QtGui.QLabel(NewSubscriptionDialog)
self.labelAddressCheck.setText(_fromUtf8(""))
self.labelAddressCheck.setWordWrap(True)
self.labelAddressCheck.setObjectName(_fromUtf8("labelAddressCheck"))
self.formLayout.setWidget(4, QtGui.QFormLayout.SpanningRole, self.labelAddressCheck)
self.checkBoxDisplayMessagesAlreadyInInventory = QtGui.QCheckBox(NewSubscriptionDialog)
self.checkBoxDisplayMessagesAlreadyInInventory.setEnabled(False)
self.checkBoxDisplayMessagesAlreadyInInventory.setObjectName(_fromUtf8("checkBoxDisplayMessagesAlreadyInInventory"))
self.formLayout.setWidget(5, QtGui.QFormLayout.SpanningRole, self.checkBoxDisplayMessagesAlreadyInInventory)
self.buttonBox = QtGui.QDialogButtonBox(NewSubscriptionDialog)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
self.formLayout.setWidget(8, QtGui.QFormLayout.FieldRole, self.buttonBox)
spacerItem1 = QtGui.QSpacerItem(20, 10, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.formLayout.setItem(7, QtGui.QFormLayout.FieldRole, spacerItem1)
self.labelSubscriptionAddressCheck = QtGui.QLabel(NewSubscriptionDialog)
self.labelSubscriptionAddressCheck.setText(_fromUtf8(""))
self.labelSubscriptionAddressCheck.setWordWrap(True)
self.labelSubscriptionAddressCheck.setObjectName(_fromUtf8("labelSubscriptionAddressCheck"))
self.formLayout.setWidget(6, QtGui.QFormLayout.SpanningRole, self.labelSubscriptionAddressCheck)
self.formLayout.setWidget(6, QtGui.QFormLayout.FieldRole, self.buttonBox)
self.retranslateUi(NewSubscriptionDialog)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), NewSubscriptionDialog.accept)
@ -54,7 +62,8 @@ class Ui_NewSubscriptionDialog(object):
QtCore.QMetaObject.connectSlotsByName(NewSubscriptionDialog)
def retranslateUi(self, NewSubscriptionDialog):
NewSubscriptionDialog.setWindowTitle(QtGui.QApplication.translate("NewSubscriptionDialog", "Add new entry", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("NewSubscriptionDialog", "Label", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("NewSubscriptionDialog", "Address", None, QtGui.QApplication.UnicodeUTF8))
NewSubscriptionDialog.setWindowTitle(_translate("NewSubscriptionDialog", "Add new entry", None))
self.label_2.setText(_translate("NewSubscriptionDialog", "Label", None))
self.label.setText(_translate("NewSubscriptionDialog", "Address", None))
self.checkBoxDisplayMessagesAlreadyInInventory.setText(_translate("NewSubscriptionDialog", "CheckBox", None))

View File

@ -7,50 +7,54 @@
<x>0</x>
<y>0</y>
<width>368</width>
<height>192</height>
<height>173</height>
</rect>
</property>
<property name="windowTitle">
<string>Add new entry</string>
</property>
<layout class="QFormLayout" name="formLayout">
<property name="fieldGrowthPolicy">
<enum>QFormLayout::AllNonFixedFieldsGrow</enum>
</property>
<item row="0" column="0" colspan="2">
<item row="0" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>Label</string>
</property>
</widget>
</item>
<item row="2" column="0" colspan="2">
<item row="1" column="0" colspan="2">
<widget class="QLineEdit" name="newsubscriptionlabel"/>
</item>
<item row="4" column="0">
<item row="2" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>Address</string>
</property>
</widget>
</item>
<item row="4" column="1">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>302</width>
<height>10</height>
</size>
</property>
</spacer>
</item>
<item row="5" column="0" colspan="2">
<item row="3" column="0" colspan="2">
<widget class="QLineEdit" name="lineEditSubscriptionAddress"/>
</item>
<item row="8" column="1">
<item row="4" column="0" colspan="2">
<widget class="QLabel" name="labelAddressCheck">
<property name="text">
<string/>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item row="5" column="0" colspan="2">
<widget class="QCheckBox" name="checkBoxDisplayMessagesAlreadyInInventory">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>CheckBox</string>
</property>
</widget>
</item>
<item row="6" column="1">
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
@ -60,29 +64,6 @@
</property>
</widget>
</item>
<item row="7" column="1">
<spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>10</height>
</size>
</property>
</spacer>
</item>
<item row="6" column="0" colspan="2">
<widget class="QLabel" name="labelSubscriptionAddressCheck">
<property name="text">
<string/>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>

1228
src/class_objectProcessor.py Normal file
View File

@ -0,0 +1,1228 @@
import time
import threading
import shared
import hashlib
import random
from struct import unpack, pack
import sys
import string
from subprocess import call # used when the API must execute an outside program
from pyelliptic.openssl import OpenSSL
import highlevelcrypto
from addresses import *
import helper_generic
import helper_bitcoin
import helper_inbox
import helper_sent
from helper_sql import *
import tr
from debug import logger
class objectProcessor(threading.Thread):
"""
The objectProcessor thread, of which there is only one, receives network
objecs (msg, broadcast, pubkey, getpubkey) from the receiveDataThreads.
"""
def __init__(self):
threading.Thread.__init__(self)
"""
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
table. Let's pull it out.
"""
queryreturn = sqlQuery(
'''SELECT objecttype, data FROM objectprocessorqueue''')
with shared.objectProcessorQueueSizeLock:
for row in queryreturn:
objectType, data = row
shared.objectProcessorQueueSize += len(data)
shared.objectProcessorQueue.put((objectType,data))
sqlExecute('''DELETE FROM objectprocessorqueue''')
logger.debug('Loaded %s objects from disk into the objectProcessorQueue.' % str(len(queryreturn)))
def run(self):
while True:
objectType, data = shared.objectProcessorQueue.get()
if objectType == 'getpubkey':
self.processgetpubkey(data)
elif objectType == 'pubkey':
self.processpubkey(data)
elif objectType == 'msg':
self.processmsg(data)
elif objectType == 'broadcast':
self.processbroadcast(data)
elif objectType == 'checkShutdownVariable': # is more of a command, not an object type. Is used to get this thread past the queue.get() so that it will check the shutdown variable.
pass
else:
logger.critical('Error! Bug! The class_objectProcessor was passed an object type it doesn\'t recognize: %s' % str(objectType))
with shared.objectProcessorQueueSizeLock:
shared.objectProcessorQueueSize -= len(data) # We maintain objectProcessorQueueSize so that we will slow down requesting objects if too much data accumulates in the queue.
if shared.shutdown:
time.sleep(.5) # Wait just a moment for most of the connections to close
numberOfObjectsThatWereInTheObjectProcessorQueue = 0
with SqlBulkExecute() as sql:
while shared.objectProcessorQueueSize > 1:
objectType, data = shared.objectProcessorQueue.get()
sql.execute('''INSERT INTO objectprocessorqueue VALUES (?,?)''',
objectType,data)
with shared.objectProcessorQueueSizeLock:
shared.objectProcessorQueueSize -= len(data) # We maintain objectProcessorQueueSize so that we will slow down requesting objects if too much data accumulates in the queue.
numberOfObjectsThatWereInTheObjectProcessorQueue += 1
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])
# This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0:
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
readPosition += 8
else:
readPosition += 4
requestedAddressVersionNumber, addressVersionLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += addressVersionLength
streamNumber, streamNumberLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += streamNumberLength
if requestedAddressVersionNumber == 0:
print 'The requestedAddressVersionNumber of the pubkey request is zero. That doesn\'t make any sense. Ignoring it.'
return
elif requestedAddressVersionNumber == 1:
print 'The requestedAddressVersionNumber of the pubkey request is 1 which isn\'t supported anymore. Ignoring it.'
return
elif requestedAddressVersionNumber > 4:
print 'The requestedAddressVersionNumber of the pubkey request is too high. Can\'t understand. Ignoring it.'
return
myAddress = ''
if requestedAddressVersionNumber <= 3 :
requestedHash = data[readPosition:readPosition + 20]
if len(requestedHash) != 20:
print 'The length of the requested hash is not 20 bytes. Something is wrong. Ignoring.'
return
with shared.printLock:
print 'the hash requested in this getpubkey request is:', requestedHash.encode('hex')
if requestedHash in shared.myAddressesByHash: # if this address hash is one of mine
myAddress = shared.myAddressesByHash[requestedHash]
elif requestedAddressVersionNumber >= 4:
requestedTag = data[readPosition:readPosition + 32]
if len(requestedTag) != 32:
print 'The length of the requested tag is not 32 bytes. Something is wrong. Ignoring.'
return
with shared.printLock:
print 'the tag requested in this getpubkey request is:', requestedTag.encode('hex')
if requestedTag in shared.myAddressesByTag:
myAddress = shared.myAddressesByTag[requestedTag]
if myAddress == '':
with shared.printLock:
print 'This getpubkey request is not for any of my keys.'
return
if decodeAddress(myAddress)[1] != requestedAddressVersionNumber:
with shared.printLock:
sys.stderr.write(
'(Within the recgetpubkey function) Someone requested one of my pubkeys but the requestedAddressVersionNumber doesn\'t match my actual address version number. Ignoring.\n')
return
if decodeAddress(myAddress)[2] != streamNumber:
with shared.printLock:
sys.stderr.write(
'(Within the recgetpubkey function) Someone requested one of my pubkeys but the stream number on which we heard this getpubkey object doesn\'t match this address\' stream number. Ignoring.\n')
return
if shared.safeConfigGetBoolean(myAddress, 'chan'):
with shared.printLock:
print 'Ignoring getpubkey request because it is for one of my chan addresses. The other party should already have the pubkey.'
return
try:
lastPubkeySendTime = int(shared.config.get(
myAddress, 'lastpubkeysendtime'))
except:
lastPubkeySendTime = 0
if lastPubkeySendTime > time.time() - shared.lengthOfTimeToHoldOnToAllPubkeys: # If the last time we sent our pubkey was more recent than 28 days ago...
with shared.printLock:
print 'Found getpubkey-requested-item in my list of EC hashes BUT we already sent it recently. Ignoring request. The lastPubkeySendTime is:', lastPubkeySendTime
return
with shared.printLock:
print '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))
elif requestedAddressVersionNumber == 3:
shared.workerQueue.put((
'sendOutOrStoreMyV3Pubkey', requestedHash))
elif requestedAddressVersionNumber == 4:
shared.workerQueue.put((
'sendOutOrStoreMyV4Pubkey', myAddress))
def processpubkey(self, data):
pubkeyProcessingStartTime = time.time()
shared.numberOfPubkeysProcessed += 1
shared.UISignalQueue.put((
'updateNumberOfPubkeysProcessed', 'no data'))
readPosition = 8 # bypass the nonce
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
# This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0:
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
readPosition += 8
else:
readPosition += 4
addressVersion, varintLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += varintLength
streamNumber, varintLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += varintLength
if addressVersion == 0:
print '(Within processpubkey) addressVersion of 0 doesn\'t make sense.'
return
if addressVersion > 4 or addressVersion == 1:
with shared.printLock:
print 'This version of Bitmessage cannot handle version', addressVersion, 'addresses.'
return
if addressVersion == 2:
if len(data) < 146: # sanity check. This is the minimum possible length.
print '(within processpubkey) payloadLength less than 146. Sanity check failed.'
return
bitfieldBehaviors = data[readPosition:readPosition + 4]
readPosition += 4
publicSigningKey = data[readPosition:readPosition + 64]
# Is it possible for a public key to be invalid such that trying to
# encrypt or sign with it will cause an error? If it is, we should
# probably test these keys here.
readPosition += 64
publicEncryptionKey = data[readPosition:readPosition + 64]
if len(publicEncryptionKey) < 64:
print 'publicEncryptionKey length less than 64. Sanity check failed.'
return
sha = hashlib.new('sha512')
sha.update(
'\x04' + publicSigningKey + '\x04' + publicEncryptionKey)
ripeHasher = hashlib.new('ripemd160')
ripeHasher.update(sha.digest())
ripe = ripeHasher.digest()
with shared.printLock:
print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber
print 'ripe', ripe.encode('hex')
print 'publicSigningKey in hex:', publicSigningKey.encode('hex')
print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex')
queryreturn = sqlQuery(
'''SELECT usedpersonally FROM pubkeys WHERE hash=? AND addressversion=? AND usedpersonally='yes' ''', ripe, addressVersion)
if queryreturn != []: # if this pubkey is already in our database and if we have used it personally:
print 'We HAVE used this pubkey personally. Updating time.'
t = (ripe, addressVersion, data, embeddedTime, 'yes')
else:
print 'We have NOT used this pubkey personally. Inserting in database.'
t = (ripe, addressVersion, data, embeddedTime, 'no')
# This will also update the embeddedTime.
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
# shared.workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe)))
self.possibleNewPubkey(ripe = ripe)
if addressVersion == 3:
if len(data) < 170: # sanity check.
print '(within processpubkey) payloadLength less than 170. Sanity check failed.'
return
bitfieldBehaviors = data[readPosition:readPosition + 4]
readPosition += 4
publicSigningKey = '\x04' + data[readPosition:readPosition + 64]
# Is it possible for a public key to be invalid such that trying to
# encrypt or sign with it will cause an error? If it is, we should
# probably test these keys here.
readPosition += 64
publicEncryptionKey = '\x04' + data[readPosition:readPosition + 64]
readPosition += 64
specifiedNonceTrialsPerByte, specifiedNonceTrialsPerByteLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += specifiedNonceTrialsPerByteLength
specifiedPayloadLengthExtraBytes, specifiedPayloadLengthExtraBytesLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += specifiedPayloadLengthExtraBytesLength
endOfSignedDataPosition = readPosition
signatureLength, signatureLengthLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += signatureLengthLength
signature = data[readPosition:readPosition + signatureLength]
try:
if not highlevelcrypto.verify(data[8:endOfSignedDataPosition], signature, publicSigningKey.encode('hex')):
print 'ECDSA verify failed (within processpubkey)'
return
print 'ECDSA verify passed (within processpubkey)'
except Exception as err:
print 'ECDSA verify failed (within processpubkey)', err
return
sha = hashlib.new('sha512')
sha.update(publicSigningKey + publicEncryptionKey)
ripeHasher = hashlib.new('ripemd160')
ripeHasher.update(sha.digest())
ripe = ripeHasher.digest()
with shared.printLock:
print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber
print 'ripe', ripe.encode('hex')
print 'publicSigningKey in hex:', publicSigningKey.encode('hex')
print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex')
queryreturn = sqlQuery('''SELECT usedpersonally FROM pubkeys WHERE hash=? AND addressversion=? AND usedpersonally='yes' ''', ripe, addressVersion)
if queryreturn != []: # if this pubkey is already in our database and if we have used it personally:
print 'We HAVE used this pubkey personally. Updating time.'
t = (ripe, addressVersion, data, embeddedTime, 'yes')
else:
print 'We have NOT used this pubkey personally. Inserting in database.'
t = (ripe, addressVersion, data, embeddedTime, 'no')
# This will also update the embeddedTime.
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
self.possibleNewPubkey(ripe = ripe)
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
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.
"""
if len(data) < 350: # sanity check.
print '(within processpubkey) payloadLength less than 350. Sanity check failed.'
return
signedData = data[8:readPosition] # Some of the signed data is not encrypted so let's keep it for now.
tag = data[readPosition:readPosition + 32]
readPosition += 32
encryptedData = data[readPosition:]
if tag not in shared.neededPubkeys:
with shared.printLock:
print 'We don\'t need this v4 pubkey. We didn\'t ask for it.'
return
# Let us try to decrypt the pubkey
cryptorObject = shared.neededPubkeys[tag]
try:
decryptedData = cryptorObject.decrypt(encryptedData)
except:
# Someone must have encrypted some data with a different key
# but tagged it with a tag for which we are watching.
with shared.printLock:
print 'Pubkey decryption was unsuccessful.'
return
readPosition = 0
bitfieldBehaviors = decryptedData[readPosition:readPosition + 4]
readPosition += 4
publicSigningKey = '\x04' + decryptedData[readPosition:readPosition + 64]
# Is it possible for a public key to be invalid such that trying to
# encrypt or check a sig with it will cause an error? If it is, we
# should probably test these keys here.
readPosition += 64
publicEncryptionKey = '\x04' + decryptedData[readPosition:readPosition + 64]
readPosition += 64
specifiedNonceTrialsPerByte, specifiedNonceTrialsPerByteLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += specifiedNonceTrialsPerByteLength
specifiedPayloadLengthExtraBytes, specifiedPayloadLengthExtraBytesLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += specifiedPayloadLengthExtraBytesLength
signedData += decryptedData[:readPosition]
signatureLength, signatureLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += signatureLengthLength
signature = decryptedData[readPosition:readPosition + signatureLength]
try:
if not highlevelcrypto.verify(signedData, signature, publicSigningKey.encode('hex')):
print 'ECDSA verify failed (within processpubkey)'
return
print 'ECDSA verify passed (within processpubkey)'
except Exception as err:
print 'ECDSA verify failed (within processpubkey)', err
return
sha = hashlib.new('sha512')
sha.update(publicSigningKey + publicEncryptionKey)
ripeHasher = hashlib.new('ripemd160')
ripeHasher.update(sha.digest())
ripe = ripeHasher.digest()
# We need to make sure that the tag on the outside of the encryption
# is the one generated from hashing these particular keys.
if tag != hashlib.sha512(hashlib.sha512(encodeVarint(addressVersion) + encodeVarint(streamNumber) + ripe).digest()).digest()[32:]:
with shared.printLock:
print 'Someone was trying to act malicious: tag doesn\'t match the keys in this pubkey message. Ignoring it.'
return
else:
print 'Tag successfully matches keys in pubkey message' # testing. Will remove soon.
with shared.printLock:
print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber
print 'ripe', ripe.encode('hex')
print 'publicSigningKey in hex:', publicSigningKey.encode('hex')
print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex')
t = (ripe, addressVersion, signedData, embeddedTime, 'yes')
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
fromAddress = encodeAddress(addressVersion, streamNumber, ripe)
# That this point we know that we have been waiting on this pubkey.
# This function will command the workerThread to start work on
# the messages that require it.
self.possibleNewPubkey(address = fromAddress)
# Display timing data
timeRequiredToProcessPubkey = time.time(
) - pubkeyProcessingStartTime
with shared.printLock:
print 'Time required to process this pubkey:', timeRequiredToProcessPubkey
def processmsg(self, data):
messageProcessingStartTime = time.time()
shared.numberOfMessagesProcessed += 1
shared.UISignalQueue.put((
'updateNumberOfMessagesProcessed', 'no data'))
readPosition = 8 # bypass the nonce
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
# This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0:
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
readPosition += 8
else:
readPosition += 4
streamNumberAsClaimedByMsg, streamNumberAsClaimedByMsgLength = decodeVarint(
data[readPosition:readPosition + 9])
readPosition += streamNumberAsClaimedByMsgLength
inventoryHash = calculateInventoryHash(data)
initialDecryptionSuccessful = False
# Let's check whether this is a message acknowledgement bound for us.
if data[readPosition:] in shared.ackdataForWhichImWatching:
with shared.printLock:
print 'This msg IS an acknowledgement bound for me.'
del shared.ackdataForWhichImWatching[data[readPosition:]]
sqlExecute('UPDATE sent SET status=? WHERE ackdata=?',
'ackreceived', data[readPosition:])
shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (data[readPosition:], tr.translateText("MainWindow",'Acknowledgement of the message received. %1').arg(unicode(
time.strftime(shared.config.get('bitmessagesettings', 'timeformat'), time.localtime(int(time.time()))), 'utf-8')))))
return
else:
with shared.printLock:
print 'This was NOT an acknowledgement bound for me.'
# print 'shared.ackdataForWhichImWatching', shared.ackdataForWhichImWatching
# This is not an acknowledgement bound for me. See if it is a message
# bound for me by trying to decrypt it with my private keys.
for key, cryptorObject in shared.myECCryptorObjects.items():
try:
decryptedData = cryptorObject.decrypt(
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
with shared.printLock:
print 'EC decryption successful using key associated with ripe hash:', 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.
with shared.printLock:
print 'Length of time program spent failing to decrypt this message:', time.time() - messageProcessingStartTime, 'seconds.'
return
# This is a message bound for me.
toAddress = shared.myAddressesByHash[
toRipe] # Look up my address based on the RIPE hash.
readPosition = 0
messageVersion, messageVersionLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += messageVersionLength
if messageVersion != 1:
print 'Cannot understand message versions other than one. Ignoring message.'
return
sendersAddressVersionNumber, sendersAddressVersionNumberLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += sendersAddressVersionNumberLength
if sendersAddressVersionNumber == 0:
print 'Cannot understand sendersAddressVersionNumber = 0. Ignoring message.'
return
if sendersAddressVersionNumber > 4:
print 'Sender\'s address version number', sendersAddressVersionNumber, 'not yet supported. Ignoring message.'
return
if len(decryptedData) < 170:
print 'Length of the unencrypted data is unreasonably short. Sanity check failed. Ignoring message.'
return
sendersStreamNumber, sendersStreamNumberLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
if sendersStreamNumber == 0:
print 'sender\'s stream number is 0. Ignoring message.'
return
readPosition += sendersStreamNumberLength
behaviorBitfield = decryptedData[readPosition:readPosition + 4]
readPosition += 4
pubSigningKey = '\x04' + decryptedData[
readPosition:readPosition + 64]
readPosition += 64
pubEncryptionKey = '\x04' + decryptedData[
readPosition:readPosition + 64]
readPosition += 64
if sendersAddressVersionNumber >= 3:
requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += varintLength
print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte
requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += varintLength
print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes
endOfThePublicKeyPosition = readPosition # needed for when we store the pubkey in our database of pubkeys for later use.
if toRipe != decryptedData[readPosition:readPosition + 20]:
with shared.printLock:
print 'The original sender of this message did not send it to you. Someone is attempting a Surreptitious Forwarding Attack.'
print 'See: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html'
print 'your toRipe:', toRipe.encode('hex')
print 'embedded destination toRipe:', decryptedData[readPosition:readPosition + 20].encode('hex')
return
readPosition += 20
messageEncodingType, messageEncodingTypeLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += messageEncodingTypeLength
messageLength, messageLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += messageLengthLength
message = decryptedData[readPosition:readPosition + messageLength]
# print 'First 150 characters of message:', repr(message[:150])
readPosition += messageLength
ackLength, ackLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += ackLengthLength
ackData = decryptedData[readPosition:readPosition + ackLength]
readPosition += ackLength
positionOfBottomOfAckData = readPosition # needed to mark the end of what is covered by the signature
signatureLength, signatureLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += signatureLengthLength
signature = decryptedData[
readPosition:readPosition + signatureLength]
try:
if not highlevelcrypto.verify(decryptedData[:positionOfBottomOfAckData], signature, pubSigningKey.encode('hex')):
print 'ECDSA verify failed'
return
print 'ECDSA verify passed'
except Exception as err:
print 'ECDSA verify failed', err
return
with shared.printLock:
print 'As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person:', helper_bitcoin.calculateBitcoinAddressFromPubkey(pubSigningKey), ' ..and here is the testnet address:', helper_bitcoin.calculateTestnetAddressFromPubkey(pubSigningKey), '. The other person must take their private signing key from Bitmessage and import it into Bitcoin (or a service like Blockchain.info) for it to be of any use. Do not use this unless you know what you are doing.'
# calculate the fromRipe.
sha = hashlib.new('sha512')
sha.update(pubSigningKey + pubEncryptionKey)
ripe = hashlib.new('ripemd160')
ripe.update(sha.digest())
fromAddress = encodeAddress(
sendersAddressVersionNumber, sendersStreamNumber, ripe.digest())
# Let's store the public key in case we want to reply to this
# person.
if sendersAddressVersionNumber <= 3:
sqlExecute(
'''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
ripe.digest(),
sendersAddressVersionNumber,
'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + decryptedData[messageVersionLength:endOfThePublicKeyPosition],
int(time.time()),
'yes')
# This will check to see whether we happen to be awaiting this
# pubkey in order to send a message. If we are, it will do the POW
# and send it.
self.possibleNewPubkey(ripe=ripe.digest())
elif sendersAddressVersionNumber >= 4:
sqlExecute(
'''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
ripe.digest(),
sendersAddressVersionNumber,
'\x00\x00\x00\x00\x00\x00\x00\x01' + decryptedData[messageVersionLength:endOfThePublicKeyPosition],
int(time.time()),
'yes')
# This will check to see whether we happen to be awaiting this
# pubkey in order to send a message. If we are, it will do the POW
# and send it.
self.possibleNewPubkey(address = fromAddress)
# If this message is bound for one of my version 3 addresses (or
# higher), then we must check to make sure it meets our demanded
# proof of work requirement.
if decodeAddress(toAddress)[1] >= 3: # If the toAddress version number is 3 or higher:
if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(fromAddress): # If I'm not friendly with this person:
requiredNonceTrialsPerByte = shared.config.getint(
toAddress, 'noncetrialsperbyte')
requiredPayloadLengthExtraBytes = shared.config.getint(
toAddress, 'payloadlengthextrabytes')
if not shared.isProofOfWorkSufficient(data, requiredNonceTrialsPerByte, requiredPayloadLengthExtraBytes):
print 'Proof of work in msg message insufficient only because it does not meet our higher requirement.'
return
blockMessage = False # Gets set to True if the user shouldn't see the message according to black or white lists.
if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black': # If we are using a blacklist
queryreturn = sqlQuery(
'''SELECT label FROM blacklist where address=? and enabled='1' ''',
fromAddress)
if queryreturn != []:
with shared.printLock:
print 'Message ignored because address is in blacklist.'
blockMessage = True
else: # We're using a whitelist
queryreturn = sqlQuery(
'''SELECT label FROM whitelist where address=? and enabled='1' ''',
fromAddress)
if queryreturn == []:
print 'Message ignored because address not in whitelist.'
blockMessage = True
if not blockMessage:
toLabel = shared.config.get(toAddress, 'label')
if toLabel == '':
toLabel = toAddress
if messageEncodingType == 2:
subject, body = self.decodeType2Message(message)
elif messageEncodingType == 1:
body = message
subject = ''
elif messageEncodingType == 0:
print '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 = ''
if messageEncodingType != 0:
t = (inventoryHash, toAddress, fromAddress, subject, int(
time.time()), body, 'inbox', messageEncodingType, 0)
helper_inbox.insert(t)
shared.UISignalQueue.put(('displayNewInboxMessage', (
inventoryHash, toAddress, fromAddress, subject, body)))
# If we are behaving as an API then we might need to run an
# outside command to let some program know that a new message
# has arrived.
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
try:
apiNotifyPath = shared.config.get(
'bitmessagesettings', 'apinotifypath')
except:
apiNotifyPath = ''
if apiNotifyPath != '':
call([apiNotifyPath, "newMessage"])
# Let us now check and see whether our receiving address is
# behaving as a mailing list
if shared.safeConfigGetBoolean(toAddress, 'mailinglist'):
try:
mailingListName = shared.config.get(
toAddress, 'mailinglistname')
except:
mailingListName = ''
# Let us send out this message as a broadcast
subject = self.addMailingListNameToSubject(
subject, mailingListName)
# Let us now send this message out as a broadcast
message = time.strftime("%a, %Y-%m-%d %H:%M:%S UTC", time.gmtime(
)) + ' Message ostensibly from ' + fromAddress + ':\n\n' + body
fromAddress = toAddress # The fromAddress for the broadcast that we are about to send is the toAddress (my address) for the msg message we are currently processing.
ackdataForBroadcast = OpenSSL.rand(
32) # We don't actually need the ackdataForBroadcast for acknowledgement since this is a broadcast message but we can use it to update the user interface when the POW is done generating.
toAddress = '[Broadcast subscribers]'
ripe = ''
t = ('', toAddress, ripe, fromAddress, subject, message, ackdataForBroadcast, int(
time.time()), 'broadcastqueued', 1, 1, 'sent', 2)
helper_sent.insert(t)
shared.UISignalQueue.put(('displayNewSentMessage', (
toAddress, '[Broadcast subscribers]', fromAddress, subject, message, ackdataForBroadcast)))
shared.workerQueue.put(('sendbroadcast', ''))
if self.ackDataHasAVaildHeader(ackData):
if ackData[4:16] == 'getpubkey\x00\x00\x00':
shared.checkAndSharegetpubkeyWithPeers(ackData[24:])
elif ackData[4:16] == 'pubkey\x00\x00\x00\x00\x00\x00':
shared.checkAndSharePubkeyWithPeers(ackData[24:])
elif ackData[4:16] == 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00':
shared.checkAndShareMsgWithPeers(ackData[24:])
elif ackData[4:16] == 'broadcast\x00\x00\x00':
shared.checkAndShareBroadcastWithPeers(ackData[24:])
# Display timing data
timeRequiredToAttemptToDecryptMessage = time.time(
) - messageProcessingStartTime
shared.successfullyDecryptMessageTimings.append(
timeRequiredToAttemptToDecryptMessage)
sum = 0
for item in shared.successfullyDecryptMessageTimings:
sum += item
with shared.printLock:
print 'Time to decrypt this message successfully:', timeRequiredToAttemptToDecryptMessage
print 'Average time for all message decryption successes since startup:', sum / len(shared.successfullyDecryptMessageTimings)
def processbroadcast(self, data):
messageProcessingStartTime = time.time()
shared.numberOfBroadcastsProcessed += 1
shared.UISignalQueue.put((
'updateNumberOfBroadcastsProcessed', 'no data'))
inventoryHash = calculateInventoryHash(data)
readPosition = 8 # bypass the nonce
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
# This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0:
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
readPosition += 8
else:
readPosition += 4
broadcastVersion, broadcastVersionLength = decodeVarint(
data[readPosition:readPosition + 9])
readPosition += broadcastVersionLength
if broadcastVersion < 1 or broadcastVersion > 3:
print '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
sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
data[readPosition:readPosition + 9])
if sendersAddressVersion <= 1 or sendersAddressVersion >= 3:
# Cannot decode senderAddressVersion higher than 2. Assuming
# the sender isn\'t being silly, you should upgrade Bitmessage
# because this message shall be ignored.
return
readPosition += sendersAddressVersionLength
if sendersAddressVersion == 2:
sendersStream, sendersStreamLength = decodeVarint(
data[readPosition:readPosition + 9])
readPosition += sendersStreamLength
behaviorBitfield = data[readPosition:readPosition + 4]
readPosition += 4
sendersPubSigningKey = '\x04' + \
data[readPosition:readPosition + 64]
readPosition += 64
sendersPubEncryptionKey = '\x04' + \
data[readPosition:readPosition + 64]
readPosition += 64
endOfPubkeyPosition = readPosition
sendersHash = data[readPosition:readPosition + 20]
if sendersHash not in shared.broadcastSendersForWhichImWatching:
# Display timing data
with shared.printLock:
print 'Time spent deciding that we are not interested in this v1 broadcast:', time.time() - messageProcessingStartTime
return
# At this point, this message claims to be from sendersHash and
# we are interested in it. We still have to hash the public key
# to make sure it is truly the key that matches the hash, and
# also check the signiture.
readPosition += 20
sha = hashlib.new('sha512')
sha.update(sendersPubSigningKey + sendersPubEncryptionKey)
ripe = hashlib.new('ripemd160')
ripe.update(sha.digest())
if ripe.digest() != sendersHash:
# The sender of this message lied.
return
messageEncodingType, messageEncodingTypeLength = decodeVarint(
data[readPosition:readPosition + 9])
if messageEncodingType == 0:
return
readPosition += messageEncodingTypeLength
messageLength, messageLengthLength = decodeVarint(
data[readPosition:readPosition + 9])
readPosition += messageLengthLength
message = data[readPosition:readPosition + messageLength]
readPosition += messageLength
readPositionAtBottomOfMessage = readPosition
signatureLength, signatureLengthLength = decodeVarint(
data[readPosition:readPosition + 9])
readPosition += signatureLengthLength
signature = data[readPosition:readPosition + signatureLength]
try:
if not highlevelcrypto.verify(data[12:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')):
print 'ECDSA verify failed'
return
print 'ECDSA verify passed'
except Exception as err:
print 'ECDSA verify failed', err
return
# verify passed
fromAddress = encodeAddress(
sendersAddressVersion, sendersStream, ripe.digest())
with shared.printLock:
print 'fromAddress:', fromAddress
# Let's store the public key in case we want to reply to this person.
# We don't have the correct nonce or time (which would let us
# send out a pubkey message) so we'll just fill it with 1's. We
# won't be able to send this pubkey to others (without doing
# the proof of work ourselves, which this program is programmed
# to not do.)
sqlExecute(
'''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
ripe.digest(),
sendersAddressVersion,
'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + data[beginningOfPubkeyPosition:endOfPubkeyPosition],
int(time.time()),
'yes')
# This will check to see whether we happen to be awaiting this
# pubkey in order to send a message. If we are, it will do the
# POW and send it.
self.possibleNewPubkey(ripe=ripe.digest())
if messageEncodingType == 2:
subject, body = decodeType2Message(message)
elif messageEncodingType == 1:
body = message
subject = ''
elif messageEncodingType == 0:
print 'messageEncodingType == 0. Doing nothing with the message.'
else:
body = 'Unknown encoding type.\n\n' + repr(message)
subject = ''
toAddress = '[Broadcast subscribers]'
if messageEncodingType != 0:
t = (inventoryHash, toAddress, fromAddress, subject, int(
time.time()), body, 'inbox', messageEncodingType, 0)
helper_inbox.insert(t)
shared.UISignalQueue.put(('displayNewInboxMessage', (
inventoryHash, toAddress, fromAddress, subject, body)))
# If we are behaving as an API then we might need to run an
# outside command to let some program know that a new
# message has arrived.
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
try:
apiNotifyPath = shared.config.get(
'bitmessagesettings', 'apinotifypath')
except:
apiNotifyPath = ''
if apiNotifyPath != '':
call([apiNotifyPath, "newBroadcast"])
# Display timing data
with shared.printLock:
print 'Time spent processing this interesting broadcast:', time.time() - messageProcessingStartTime
if broadcastVersion == 2:
cleartextStreamNumber, cleartextStreamNumberLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += cleartextStreamNumberLength
initialDecryptionSuccessful = False
for key, cryptorObject in shared.MyECSubscriptionCryptorObjects.items():
try:
decryptedData = cryptorObject.decrypt(data[readPosition:])
toRipe = key # This is the RIPE hash of the sender's pubkey. We need this below to compare to the RIPE hash of the sender's address to verify that it was encrypted by with their key rather than some other key.
initialDecryptionSuccessful = True
print 'EC decryption successful using key associated with ripe hash:', key.encode('hex')
break
except Exception as err:
pass
# print 'cryptorObject.decrypt Exception:', err
if not initialDecryptionSuccessful:
# This is not a broadcast I am interested in.
with shared.printLock:
print 'Length of time program spent failing to decrypt this v2 broadcast:', time.time() - messageProcessingStartTime, 'seconds.'
return
# At this point this is a broadcast I have decrypted and thus am
# interested in.
signedBroadcastVersion, readPosition = decodeVarint(
decryptedData[:10])
beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table
sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
decryptedData[readPosition:readPosition + 9])
if sendersAddressVersion < 2 or sendersAddressVersion > 3:
print 'Cannot decode senderAddressVersion other than 2 or 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:
print '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]
readPosition += 4
sendersPubSigningKey = '\x04' + \
decryptedData[readPosition:readPosition + 64]
readPosition += 64
sendersPubEncryptionKey = '\x04' + \
decryptedData[readPosition:readPosition + 64]
readPosition += 64
if sendersAddressVersion >= 3:
requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += varintLength
print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte
requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += varintLength
print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes
endOfPubkeyPosition = readPosition
sha = hashlib.new('sha512')
sha.update(sendersPubSigningKey + sendersPubEncryptionKey)
ripe = hashlib.new('ripemd160')
ripe.update(sha.digest())
if toRipe != ripe.digest():
print '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])
if messageEncodingType == 0:
return
readPosition += messageEncodingTypeLength
messageLength, messageLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 9])
readPosition += messageLengthLength
message = decryptedData[readPosition:readPosition + messageLength]
readPosition += messageLength
readPositionAtBottomOfMessage = readPosition
signatureLength, signatureLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 9])
readPosition += signatureLengthLength
signature = decryptedData[
readPosition:readPosition + signatureLength]
try:
if not highlevelcrypto.verify(decryptedData[:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')):
print 'ECDSA verify failed'
return
print 'ECDSA verify passed'
except Exception as err:
print 'ECDSA verify failed', err
return
# verify passed
# Let's store the public key in case we want to reply to this
# person.
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
ripe.digest(),
sendersAddressVersion,
'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + decryptedData[beginningOfPubkeyPosition:endOfPubkeyPosition],
int(time.time()),
'yes')
# shared.workerQueue.put(('newpubkey',(sendersAddressVersion,sendersStream,ripe.digest())))
# This will check to see whether we happen to be awaiting this
# pubkey in order to send a message. If we are, it will do the POW
# and send it.
self.possibleNewPubkey(ripe=ripe.digest())
fromAddress = encodeAddress(
sendersAddressVersion, sendersStream, ripe.digest())
with shared.printLock:
print 'fromAddress:', fromAddress
if messageEncodingType == 2:
subject, body = self.decodeType2Message(message)
elif messageEncodingType == 1:
body = message
subject = ''
elif messageEncodingType == 0:
print 'messageEncodingType == 0. Doing nothing with the message.'
else:
body = 'Unknown encoding type.\n\n' + repr(message)
subject = ''
toAddress = '[Broadcast subscribers]'
if messageEncodingType != 0:
t = (inventoryHash, toAddress, fromAddress, subject, int(
time.time()), body, 'inbox', messageEncodingType, 0)
helper_inbox.insert(t)
shared.UISignalQueue.put(('displayNewInboxMessage', (
inventoryHash, toAddress, fromAddress, subject, body)))
# If we are behaving as an API then we might need to run an
# outside command to let some program know that a new message
# has arrived.
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
try:
apiNotifyPath = shared.config.get(
'bitmessagesettings', 'apinotifypath')
except:
apiNotifyPath = ''
if apiNotifyPath != '':
call([apiNotifyPath, "newBroadcast"])
# Display timing data
with shared.printLock:
print 'Time spent processing this interesting broadcast:', time.time() - messageProcessingStartTime
if broadcastVersion == 3:
cleartextStreamNumber, cleartextStreamNumberLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += cleartextStreamNumberLength
embeddedTag = data[readPosition:readPosition+32]
readPosition += 32
if embeddedTag not in shared.MyECSubscriptionCryptorObjects:
with shared.printLock:
print 'We\'re not interested in this broadcast.'
return
# We are interested in this broadcast because of its tag.
cryptorObject = shared.MyECSubscriptionCryptorObjects[embeddedTag]
try:
decryptedData = cryptorObject.decrypt(data[readPosition:])
print 'EC decryption successful'
except Exception as err:
with shared.printLock:
print 'Broadcast version 3 decryption Unsuccessful.'
return
signedBroadcastVersion, readPosition = decodeVarint(
decryptedData[:10])
beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table
sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
decryptedData[readPosition:readPosition + 9])
if sendersAddressVersion < 4:
print '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:
print '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]
readPosition += 4
sendersPubSigningKey = '\x04' + \
decryptedData[readPosition:readPosition + 64]
readPosition += 64
sendersPubEncryptionKey = '\x04' + \
decryptedData[readPosition:readPosition + 64]
readPosition += 64
if sendersAddressVersion >= 3:
requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += varintLength
print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte
requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += varintLength
print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes
endOfPubkeyPosition = readPosition
sha = hashlib.new('sha512')
sha.update(sendersPubSigningKey + sendersPubEncryptionKey)
ripeHasher = hashlib.new('ripemd160')
ripeHasher.update(sha.digest())
calculatedRipe = ripeHasher.digest()
calculatedTag = hashlib.sha512(hashlib.sha512(encodeVarint(
sendersAddressVersion) + encodeVarint(sendersStream) + calculatedRipe).digest()).digest()[32:]
if calculatedTag != embeddedTag:
print '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])
if messageEncodingType == 0:
return
readPosition += messageEncodingTypeLength
messageLength, messageLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 9])
readPosition += messageLengthLength
message = decryptedData[readPosition:readPosition + messageLength]
readPosition += messageLength
readPositionAtBottomOfMessage = readPosition
signatureLength, signatureLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 9])
readPosition += signatureLengthLength
signature = decryptedData[
readPosition:readPosition + signatureLength]
try:
if not highlevelcrypto.verify(decryptedData[:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')):
print 'ECDSA verify failed'
return
print 'ECDSA verify passed'
except Exception as err:
print 'ECDSA verify failed', err
return
# verify passed
fromAddress = encodeAddress(
sendersAddressVersion, sendersStream, calculatedRipe)
with shared.printLock:
print 'fromAddress:', fromAddress
# Let's store the public key in case we want to reply to this person.
sqlExecute(
'''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
calculatedRipe,
sendersAddressVersion,
'\x00\x00\x00\x00\x00\x00\x00\x01' + decryptedData[beginningOfPubkeyPosition:endOfPubkeyPosition],
int(time.time()),
'yes')
# This will check to see whether we happen to be awaiting this
# pubkey in order to send a message. If we are, it will do the
# POW and send it.
self.possibleNewPubkey(address = fromAddress)
if messageEncodingType == 2:
subject, body = self.decodeType2Message(message)
elif messageEncodingType == 1:
body = message
subject = ''
elif messageEncodingType == 0:
print 'messageEncodingType == 0. Doing nothing with the message.'
else:
body = 'Unknown encoding type.\n\n' + repr(message)
subject = ''
toAddress = '[Broadcast subscribers]'
if messageEncodingType != 0:
t = (inventoryHash, toAddress, fromAddress, subject, int(
time.time()), body, 'inbox', messageEncodingType, 0)
helper_inbox.insert(t)
shared.UISignalQueue.put(('displayNewInboxMessage', (
inventoryHash, toAddress, fromAddress, subject, body)))
# If we are behaving as an API then we might need to run an
# outside command to let some program know that a new message
# has arrived.
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
try:
apiNotifyPath = shared.config.get(
'bitmessagesettings', 'apinotifypath')
except:
apiNotifyPath = ''
if apiNotifyPath != '':
call([apiNotifyPath, "newBroadcast"])
# Display timing data
with shared.printLock:
print 'Time spent processing this interesting broadcast:', time.time() - messageProcessingStartTime
# We have inserted a pubkey into our pubkey table which we received from a
# pubkey, msg, or broadcast message. It might be one that we have been
# waiting for. Let's check.
def possibleNewPubkey(self, ripe=None, address=None):
# For address versions <= 3, we wait on a key with the correct ripe hash
if ripe != None:
if ripe in shared.neededPubkeys:
print 'We have been awaiting the arrival of this pubkey.'
del shared.neededPubkeys[ripe]
sqlExecute(
'''UPDATE sent SET status='doingmsgpow' WHERE toripe=? AND (status='awaitingpubkey' or status='doingpubkeypow') and folder='sent' ''',
ripe)
shared.workerQueue.put(('sendmessage', ''))
else:
with shared.printLock:
print 'We don\'t need this pub key. We didn\'t ask for it. Pubkey hash:', ripe.encode('hex')
# For address versions >= 4, we wait on a pubkey with the correct tag.
# Let us create the tag from the address and see if we were waiting
# for it.
elif address != None:
status, addressVersion, streamNumber, ripe = decodeAddress(address)
tag = hashlib.sha512(hashlib.sha512(encodeVarint(
addressVersion) + encodeVarint(streamNumber) + ripe).digest()).digest()[32:]
if tag in shared.neededPubkeys:
print 'We have been awaiting the arrival of this pubkey.'
del shared.neededPubkeys[tag]
sqlExecute(
'''UPDATE sent SET status='doingmsgpow' WHERE toripe=? AND (status='awaitingpubkey' or status='doingpubkeypow') and folder='sent' ''',
ripe)
shared.workerQueue.put(('sendmessage', ''))
def ackDataHasAVaildHeader(self, ackData):
if len(ackData) < 24:
print 'The length of ackData is unreasonably short. Not sending ackData.'
return False
if ackData[0:4] != '\xe9\xbe\xb4\xd9':
print 'Ackdata magic bytes were wrong. Not sending ackData.'
return False
ackDataPayloadLength, = unpack('>L', ackData[16:20])
if len(ackData) - 24 != ackDataPayloadLength:
print 'ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.'
return False
if ackData[20:24] != hashlib.sha512(ackData[24:]).digest()[0:4]: # test the checksum in the message.
print 'ackdata checksum wrong. Not sending ackdata.'
return False
if ackDataPayloadLength > 180000000: # If the size of the message is greater than 180MB, ignore it.
return False
if (ackData[4:16] != 'getpubkey\x00\x00\x00' and
ackData[4:16] != 'pubkey\x00\x00\x00\x00\x00\x00' and
ackData[4:16] != 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' and
ackData[4:16] != 'broadcast\x00\x00\x00'):
return False
return True
def decodeType2Message(self, message):
bodyPositionIndex = string.find(message, '\nBody:')
if bodyPositionIndex > 1:
subject = message[8:bodyPositionIndex]
# Only save and show the first 500 characters of the subject.
# Any more is probably an attack.
subject = subject[:500]
body = message[bodyPositionIndex + 6:]
else:
subject = ''
body = message
# Throw away any extra lines (headers) after the subject.
if subject:
subject = subject.splitlines()[0]
return subject, body
def addMailingListNameToSubject(self, subject, mailingListName):
subject = subject.strip()
if subject[:3] == 'Re:' or subject[:3] == 'RE:':
subject = subject[3:].strip()
if '[' + mailingListName + ']' in subject:
return subject
else:
return '[' + mailingListName + '] ' + subject
def decodeType2Message(self, message):
bodyPositionIndex = string.find(message, '\nBody:')
if bodyPositionIndex > 1:
subject = message[8:bodyPositionIndex]
# Only save and show the first 500 characters of the subject.
# Any more is probably an attack.
subject = subject[:500]
body = message[bodyPositionIndex + 6:]
else:
subject = ''
body = message
# Throw away any extra lines (headers) after the subject.
if subject:
subject = subject.splitlines()[0]
return subject, body

View File

@ -8,23 +8,23 @@ import socket
import random
from struct import unpack, pack
import sys
import string
from subprocess import call # used when the API must execute an outside program
from pyelliptic.openssl import OpenSSL
#import string
#from subprocess import call # used when the API must execute an outside program
#from pyelliptic.openssl import OpenSSL
import highlevelcrypto
#import highlevelcrypto
from addresses import *
import helper_generic
import helper_bitcoin
import helper_inbox
import helper_sent
#import helper_bitcoin
#import helper_inbox
#import helper_sent
from helper_sql import *
import tr
#import tr
from debug import logger
#from bitmessagemain import shared.lengthOfTimeToLeaveObjectsInInventory, shared.lengthOfTimeToHoldOnToAllPubkeys, shared.maximumAgeOfAnObjectThatIAmWillingToAccept, shared.maximumAgeOfObjectsThatIAdvertiseToOthers, shared.maximumAgeOfNodesThatIAdvertiseToOthers, shared.numberOfObjectsThatWeHaveYetToGetPerPeer, shared.neededPubkeys
# This thread is created either by the synSenderThread(for outgoing
# connections) or the singleListenerThread(for incoming connectiosn).
# connections) or the singleListenerThread(for incoming connections).
class receiveDataThread(threading.Thread):
@ -56,8 +56,6 @@ class receiveDataThread(threading.Thread):
else:
self.initiatedConnection = True
self.selfInitiatedConnections[streamNumber][self] = 0
self.ackDataThatWeHaveYetToSend = [
] # When we receive a message bound for us, we store the acknowledgement that we need to send (the ackdata) here until we are done processing all other data received from this peer.
self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware = someObjectsOfWhichThisRemoteNodeIsAlreadyAware
def run(self):
@ -71,12 +69,10 @@ class receiveDataThread(threading.Thread):
except socket.timeout:
with shared.printLock:
print 'Timeout occurred waiting for data from', self.peer, '. Closing receiveData thread. (ID:', str(id(self)) + ')'
break
except Exception as err:
with shared.printLock:
print 'sock.recv error. Closing receiveData thread (HOST:', self.peer, 'ID:', str(id(self)) + ').', err
break
# print 'Received', repr(self.data)
if len(self.data) == dataLen: # If self.sock.recv returned no data:
@ -92,7 +88,7 @@ class receiveDataThread(threading.Thread):
print 'removed self (a receiveDataThread) from selfInitiatedConnections'
except:
pass
shared.broadcastToSendDataQueues((0, 'shutdown', self.peer))
shared.broadcastToSendDataQueues((0, 'shutdown', self.peer)) # commands the corresponding sendDataThread to shut itself down.
try:
del shared.connectedHostsList[self.peer.host]
except Exception as err:
@ -114,7 +110,7 @@ class receiveDataThread(threading.Thread):
# with shared.printLock:
# print 'self.data is currently ', repr(self.data)
#
if len(self.data) < 20: # if so little of the data has arrived that we can't even unpack the payload length
if len(self.data) < 24: # if so little of the data has arrived that we can't even read the checksum then wait for more data.
return
if self.data[0:4] != '\xe9\xbe\xb4\xd9':
if shared.verbose >= 1:
@ -150,7 +146,7 @@ class receiveDataThread(threading.Thread):
elif remoteCommand == 'addr\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
self.recaddr(self.data[24:self.payloadLength + 24])
elif remoteCommand == 'getpubkey\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
self.recgetpubkey(self.data[24:self.payloadLength + 24])
shared.checkAndSharegetpubkeyWithPeers(self.data[24:self.payloadLength + 24])
elif remoteCommand == 'pubkey\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
self.recpubkey(self.data[24:self.payloadLength + 24])
elif remoteCommand == 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
@ -191,7 +187,7 @@ class receiveDataThread(threading.Thread):
else:
self.sendgetdata(objectHash)
del self.objectsThatWeHaveYetToGetFromThisPeer[
objectHash] # It is possible that the remote node doesn't respond with the object. In that case, we'll very likely get it from someone else anyway.
objectHash] # It is possible that the remote node might not respond with the object. In that case, we'll very likely get it from someone else anyway.
if len(self.objectsThatWeHaveYetToGetFromThisPeer) == 0:
with shared.printLock:
print '(concerning', str(self.peer) + ')', 'number of objectsThatWeHaveYetToGetFromThisPeer is now', len(self.objectsThatWeHaveYetToGetFromThisPeer)
@ -217,23 +213,8 @@ class receiveDataThread(threading.Thread):
shared.numberOfObjectsThatWeHaveYetToGetPerPeer[self.peer] = len(
self.objectsThatWeHaveYetToGetFromThisPeer) # this data structure is maintained so that we can keep track of how many total objects, across all connections, are currently outstanding. If it goes too high it can indicate that we are under attack by multiple nodes working together.
if len(self.ackDataThatWeHaveYetToSend) > 0:
self.data = self.ackDataThatWeHaveYetToSend.pop()
self.processData()
def isProofOfWorkSufficient(
self,
data,
nonceTrialsPerByte=0,
payloadLengthExtraBytes=0):
if nonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte:
nonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte
if payloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes:
payloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes
POW, = unpack('>Q', hashlib.sha512(hashlib.sha512(data[
:8] + hashlib.sha512(data[8:]).digest()).digest()).digest()[0:8])
# print 'POW:', POW
return POW <= 2 ** 64 / ((len(data) + payloadLengthExtraBytes) * (nonceTrialsPerByte))
def sendpong(self):
print 'Sending pong'
@ -267,8 +248,7 @@ class receiveDataThread(threading.Thread):
print 'The length of sendDataQueues is now:', len(shared.sendDataQueues)
print 'broadcasting addr from within connectionFullyEstablished function.'
#self.broadcastaddr([(int(time.time()), self.streamNumber, 1, self.peer.host,
# self.remoteNodeIncomingPort)]) # This lets all of our peers know about this new node.
# Let all of our peers know about this new node.
dataToSend = (int(time.time()), self.streamNumber, 1, self.peer.host, self.remoteNodeIncomingPort)
shared.broadcastToSendDataQueues((
self.streamNumber, 'advertisepeer', dataToSend))
@ -341,71 +321,19 @@ class receiveDataThread(threading.Thread):
# We have received a broadcast message
def recbroadcast(self, data):
self.messageProcessingStartTime = time.time()
# First we must check to make sure the proof of work is sufficient.
if not self.isProofOfWorkSufficient(data):
print 'Proof of work in broadcast message insufficient.'
return
readPosition = 8 # bypass the nonce
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
# This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0:
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
readPosition += 8
else:
readPosition += 4
shared.checkAndShareBroadcastWithPeers(data)
if embeddedTime > (int(time.time()) + 10800): # prevent funny business
print '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()) - shared.maximumAgeOfAnObjectThatIAmWillingToAccept):
print 'The embedded time in this broadcast message is too old. Ignoring message.'
return
if len(data) < 180:
print 'The payload length of this broadcast packet is unreasonably low. Someone is probably trying funny business. Ignoring message.'
return
# Let us check to make sure the stream number is correct (thus
# preventing an individual from sending broadcasts out on the wrong
# streams or all streams).
broadcastVersion, broadcastVersionLength = decodeVarint(
data[readPosition:readPosition + 10])
if broadcastVersion >= 2:
streamNumber, streamNumberLength = decodeVarint(data[
readPosition + broadcastVersionLength:readPosition + broadcastVersionLength + 10])
if streamNumber != self.streamNumber:
print 'The stream number encoded in this broadcast message (' + str(streamNumber) + ') does not match the stream number on which it was received. Ignoring it.'
return
shared.numberOfInventoryLookupsPerformed += 1
shared.inventoryLock.acquire()
self.inventoryHash = calculateInventoryHash(data)
if self.inventoryHash in shared.inventory:
print 'We have already received this broadcast object. Ignoring.'
shared.inventoryLock.release()
return
elif shared.isInSqlInventory(self.inventoryHash):
print 'We have already received this broadcast object (it is stored on disk in the SQL inventory). Ignoring it.'
shared.inventoryLock.release()
return
# It is valid so far. Let's let our peers know about it.
objectType = 'broadcast'
shared.inventory[self.inventoryHash] = (
objectType, self.streamNumber, data, embeddedTime,'')
shared.inventorySets[self.streamNumber].add(self.inventoryHash)
shared.inventoryLock.release()
self.broadcastinv(self.inventoryHash)
shared.numberOfBroadcastsProcessed += 1
shared.UISignalQueue.put((
'updateNumberOfBroadcastsProcessed', 'no data'))
self.processbroadcast(
readPosition, data) # When this function returns, we will have either successfully processed this broadcast because we are interested in it, ignored it because we aren't interested in it, or found problem with the broadcast that warranted ignoring it.
# Let us now set lengthOfTimeWeShouldUseToProcessThisMessage. If we
# haven't used the specified amount of time, we shall sleep. These
# values are mostly the same values used for msg messages although
# broadcast messages are processed faster.
"""
Let us now set lengthOfTimeWeShouldUseToProcessThisMessage. Sleeping
will help guarantee that we can process messages faster than a remote
node can send them. If we fall behind, the attacker could observe that
we are are slowing down the rate at which we request objects from the
network which would indicate that we own a particular address (whichever
one to which they are sending all of their attack messages). Note
that if an attacker connects to a target with many connections, this
mitigation mechanism might not be sufficient.
"""
if len(data) > 100000000: # Size is greater than 100 megabytes
lengthOfTimeWeShouldUseToProcessThisMessage = 100 # seconds.
elif len(data) > 10000000: # Between 100 and 10 megabytes
@ -420,501 +348,24 @@ class receiveDataThread(threading.Thread):
if sleepTime > 0 and doTimingAttackMitigation:
with shared.printLock:
print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.'
time.sleep(sleepTime)
with shared.printLock:
print 'Total message processing time:', time.time() - self.messageProcessingStartTime, 'seconds.'
# A broadcast message has a valid time and POW and requires processing.
# The recbroadcast function calls this one.
def processbroadcast(self, readPosition, data):
broadcastVersion, broadcastVersionLength = decodeVarint(
data[readPosition:readPosition + 9])
readPosition += broadcastVersionLength
if broadcastVersion < 1 or broadcastVersion > 3:
print '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
sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
data[readPosition:readPosition + 9])
if sendersAddressVersion <= 1 or sendersAddressVersion >= 3:
# Cannot decode senderAddressVersion higher than 2. Assuming
# the sender isn\'t being silly, you should upgrade Bitmessage
# because this message shall be ignored.
return
readPosition += sendersAddressVersionLength
if sendersAddressVersion == 2:
sendersStream, sendersStreamLength = decodeVarint(
data[readPosition:readPosition + 9])
readPosition += sendersStreamLength
behaviorBitfield = data[readPosition:readPosition + 4]
readPosition += 4
sendersPubSigningKey = '\x04' + \
data[readPosition:readPosition + 64]
readPosition += 64
sendersPubEncryptionKey = '\x04' + \
data[readPosition:readPosition + 64]
readPosition += 64
endOfPubkeyPosition = readPosition
sendersHash = data[readPosition:readPosition + 20]
if sendersHash not in shared.broadcastSendersForWhichImWatching:
# Display timing data
with shared.printLock:
print 'Time spent deciding that we are not interested in this v1 broadcast:', time.time() - self.messageProcessingStartTime
return
# At this point, this message claims to be from sendersHash and
# we are interested in it. We still have to hash the public key
# to make sure it is truly the key that matches the hash, and
# also check the signiture.
readPosition += 20
sha = hashlib.new('sha512')
sha.update(sendersPubSigningKey + sendersPubEncryptionKey)
ripe = hashlib.new('ripemd160')
ripe.update(sha.digest())
if ripe.digest() != sendersHash:
# The sender of this message lied.
return
messageEncodingType, messageEncodingTypeLength = decodeVarint(
data[readPosition:readPosition + 9])
if messageEncodingType == 0:
return
readPosition += messageEncodingTypeLength
messageLength, messageLengthLength = decodeVarint(
data[readPosition:readPosition + 9])
readPosition += messageLengthLength
message = data[readPosition:readPosition + messageLength]
readPosition += messageLength
readPositionAtBottomOfMessage = readPosition
signatureLength, signatureLengthLength = decodeVarint(
data[readPosition:readPosition + 9])
readPosition += signatureLengthLength
signature = data[readPosition:readPosition + signatureLength]
try:
if not highlevelcrypto.verify(data[12:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')):
print 'ECDSA verify failed'
return
print 'ECDSA verify passed'
except Exception as err:
print 'ECDSA verify failed', err
return
# verify passed
fromAddress = encodeAddress(
sendersAddressVersion, sendersStream, ripe.digest())
with shared.printLock:
print 'fromAddress:', fromAddress
# Let's store the public key in case we want to reply to this person.
# We don't have the correct nonce or time (which would let us
# send out a pubkey message) so we'll just fill it with 1's. We
# won't be able to send this pubkey to others (without doing
# the proof of work ourselves, which this program is programmed
# to not do.)
sqlExecute(
'''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
ripe.digest(),
sendersAddressVersion,
'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + data[beginningOfPubkeyPosition:endOfPubkeyPosition],
int(time.time()),
'yes')
# This will check to see whether we happen to be awaiting this
# pubkey in order to send a message. If we are, it will do the
# POW and send it.
self.possibleNewPubkey(ripe=ripe.digest())
if messageEncodingType == 2:
subject, body = self.decodeType2Message(message)
elif messageEncodingType == 1:
body = message
subject = ''
elif messageEncodingType == 0:
print 'messageEncodingType == 0. Doing nothing with the message.'
else:
body = 'Unknown encoding type.\n\n' + repr(message)
subject = ''
toAddress = '[Broadcast subscribers]'
if messageEncodingType != 0:
t = (self.inventoryHash, toAddress, fromAddress, subject, int(
time.time()), body, 'inbox', messageEncodingType, 0)
helper_inbox.insert(t)
shared.UISignalQueue.put(('displayNewInboxMessage', (
self.inventoryHash, toAddress, fromAddress, subject, body)))
# If we are behaving as an API then we might need to run an
# outside command to let some program know that a new
# message has arrived.
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
try:
apiNotifyPath = shared.config.get(
'bitmessagesettings', 'apinotifypath')
except:
apiNotifyPath = ''
if apiNotifyPath != '':
call([apiNotifyPath, "newBroadcast"])
# Display timing data
with shared.printLock:
print 'Time spent processing this interesting broadcast:', time.time() - self.messageProcessingStartTime
if broadcastVersion == 2:
cleartextStreamNumber, cleartextStreamNumberLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += cleartextStreamNumberLength
initialDecryptionSuccessful = False
for key, cryptorObject in shared.MyECSubscriptionCryptorObjects.items():
try:
decryptedData = cryptorObject.decrypt(data[readPosition:])
toRipe = key # This is the RIPE hash of the sender's pubkey. We need this below to compare to the RIPE hash of the sender's address to verify that it was encrypted by with their key rather than some other key.
initialDecryptionSuccessful = True
print 'EC decryption successful using key associated with ripe hash:', key.encode('hex')
break
except Exception as err:
pass
# print 'cryptorObject.decrypt Exception:', err
if not initialDecryptionSuccessful:
# This is not a broadcast I am interested in.
with shared.printLock:
print 'Length of time program spent failing to decrypt this v2 broadcast:', time.time() - self.messageProcessingStartTime, 'seconds.'
return
# At this point this is a broadcast I have decrypted and thus am
# interested in.
signedBroadcastVersion, readPosition = decodeVarint(
decryptedData[:10])
beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table
sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
decryptedData[readPosition:readPosition + 9])
if sendersAddressVersion < 2 or sendersAddressVersion > 3:
print 'Cannot decode senderAddressVersion other than 2 or 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:
print '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]
readPosition += 4
sendersPubSigningKey = '\x04' + \
decryptedData[readPosition:readPosition + 64]
readPosition += 64
sendersPubEncryptionKey = '\x04' + \
decryptedData[readPosition:readPosition + 64]
readPosition += 64
if sendersAddressVersion >= 3:
requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += varintLength
print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte
requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += varintLength
print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes
endOfPubkeyPosition = readPosition
sha = hashlib.new('sha512')
sha.update(sendersPubSigningKey + sendersPubEncryptionKey)
ripe = hashlib.new('ripemd160')
ripe.update(sha.digest())
if toRipe != ripe.digest():
print '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])
if messageEncodingType == 0:
return
readPosition += messageEncodingTypeLength
messageLength, messageLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 9])
readPosition += messageLengthLength
message = decryptedData[readPosition:readPosition + messageLength]
readPosition += messageLength
readPositionAtBottomOfMessage = readPosition
signatureLength, signatureLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 9])
readPosition += signatureLengthLength
signature = decryptedData[
readPosition:readPosition + signatureLength]
try:
if not highlevelcrypto.verify(decryptedData[:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')):
print 'ECDSA verify failed'
return
print 'ECDSA verify passed'
except Exception as err:
print 'ECDSA verify failed', err
return
# verify passed
# Let's store the public key in case we want to reply to this
# person.
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
ripe.digest(),
sendersAddressVersion,
'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + decryptedData[beginningOfPubkeyPosition:endOfPubkeyPosition],
int(time.time()),
'yes')
# shared.workerQueue.put(('newpubkey',(sendersAddressVersion,sendersStream,ripe.digest())))
# This will check to see whether we happen to be awaiting this
# pubkey in order to send a message. If we are, it will do the POW
# and send it.
self.possibleNewPubkey(ripe=ripe.digest())
fromAddress = encodeAddress(
sendersAddressVersion, sendersStream, ripe.digest())
with shared.printLock:
print 'fromAddress:', fromAddress
if messageEncodingType == 2:
subject, body = self.decodeType2Message(message)
elif messageEncodingType == 1:
body = message
subject = ''
elif messageEncodingType == 0:
print 'messageEncodingType == 0. Doing nothing with the message.'
else:
body = 'Unknown encoding type.\n\n' + repr(message)
subject = ''
toAddress = '[Broadcast subscribers]'
if messageEncodingType != 0:
t = (self.inventoryHash, toAddress, fromAddress, subject, int(
time.time()), body, 'inbox', messageEncodingType, 0)
helper_inbox.insert(t)
shared.UISignalQueue.put(('displayNewInboxMessage', (
self.inventoryHash, toAddress, fromAddress, subject, body)))
# If we are behaving as an API then we might need to run an
# outside command to let some program know that a new message
# has arrived.
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
try:
apiNotifyPath = shared.config.get(
'bitmessagesettings', 'apinotifypath')
except:
apiNotifyPath = ''
if apiNotifyPath != '':
call([apiNotifyPath, "newBroadcast"])
# Display timing data
with shared.printLock:
print 'Time spent processing this interesting broadcast:', time.time() - self.messageProcessingStartTime
if broadcastVersion == 3:
cleartextStreamNumber, cleartextStreamNumberLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += cleartextStreamNumberLength
embeddedTag = data[readPosition:readPosition+32]
readPosition += 32
if embeddedTag not in shared.MyECSubscriptionCryptorObjects:
with shared.printLock:
print 'We\'re not interested in this broadcast.'
return
# We are interested in this broadcast because of its tag.
cryptorObject = shared.MyECSubscriptionCryptorObjects[embeddedTag]
try:
decryptedData = cryptorObject.decrypt(data[readPosition:])
print 'EC decryption successful'
except Exception as err:
with shared.printLock:
print 'Broadcast version 3 decryption Unsuccessful.'
return
signedBroadcastVersion, readPosition = decodeVarint(
decryptedData[:10])
beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table
sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
decryptedData[readPosition:readPosition + 9])
if sendersAddressVersion < 4:
print '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:
print '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]
readPosition += 4
sendersPubSigningKey = '\x04' + \
decryptedData[readPosition:readPosition + 64]
readPosition += 64
sendersPubEncryptionKey = '\x04' + \
decryptedData[readPosition:readPosition + 64]
readPosition += 64
if sendersAddressVersion >= 3:
requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += varintLength
print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte
requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += varintLength
print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes
endOfPubkeyPosition = readPosition
sha = hashlib.new('sha512')
sha.update(sendersPubSigningKey + sendersPubEncryptionKey)
ripeHasher = hashlib.new('ripemd160')
ripeHasher.update(sha.digest())
calculatedRipe = ripeHasher.digest()
calculatedTag = hashlib.sha512(hashlib.sha512(encodeVarint(
sendersAddressVersion) + encodeVarint(sendersStream) + calculatedRipe).digest()).digest()[32:]
if calculatedTag != embeddedTag:
print '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])
if messageEncodingType == 0:
return
readPosition += messageEncodingTypeLength
messageLength, messageLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 9])
readPosition += messageLengthLength
message = decryptedData[readPosition:readPosition + messageLength]
readPosition += messageLength
readPositionAtBottomOfMessage = readPosition
signatureLength, signatureLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 9])
readPosition += signatureLengthLength
signature = decryptedData[
readPosition:readPosition + signatureLength]
try:
if not highlevelcrypto.verify(decryptedData[:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')):
print 'ECDSA verify failed'
return
print 'ECDSA verify passed'
except Exception as err:
print 'ECDSA verify failed', err
return
# verify passed
fromAddress = encodeAddress(
sendersAddressVersion, sendersStream, calculatedRipe)
with shared.printLock:
print 'fromAddress:', fromAddress
# Let's store the public key in case we want to reply to this person.
sqlExecute(
'''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
calculatedRipe,
sendersAddressVersion,
'\x00\x00\x00\x00\x00\x00\x00\x01' + decryptedData[beginningOfPubkeyPosition:endOfPubkeyPosition],
int(time.time()),
'yes')
# This will check to see whether we happen to be awaiting this
# pubkey in order to send a message. If we are, it will do the
# POW and send it.
self.possibleNewPubkey(address = fromAddress)
if messageEncodingType == 2:
subject, body = self.decodeType2Message(message)
elif messageEncodingType == 1:
body = message
subject = ''
elif messageEncodingType == 0:
print 'messageEncodingType == 0. Doing nothing with the message.'
else:
body = 'Unknown encoding type.\n\n' + repr(message)
subject = ''
toAddress = '[Broadcast subscribers]'
if messageEncodingType != 0:
t = (self.inventoryHash, toAddress, fromAddress, subject, int(
time.time()), body, 'inbox', messageEncodingType, 0)
helper_inbox.insert(t)
shared.UISignalQueue.put(('displayNewInboxMessage', (
self.inventoryHash, toAddress, fromAddress, subject, body)))
# If we are behaving as an API then we might need to run an
# outside command to let some program know that a new message
# has arrived.
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
try:
apiNotifyPath = shared.config.get(
'bitmessagesettings', 'apinotifypath')
except:
apiNotifyPath = ''
if apiNotifyPath != '':
call([apiNotifyPath, "newBroadcast"])
# Display timing data
with shared.printLock:
print 'Time spent processing this interesting broadcast:', time.time() - self.messageProcessingStartTime
# We have received a msg message.
def recmsg(self, data):
self.messageProcessingStartTime = time.time()
# First we must check to make sure the proof of work is sufficient.
if not self.isProofOfWorkSufficient(data):
print 'Proof of work in msg message insufficient.'
return
readPosition = 8
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
shared.checkAndShareMsgWithPeers(data)
# This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0:
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
readPosition += 8
else:
readPosition += 4
if embeddedTime > int(time.time()) + 10800:
print 'The time in the msg message is too new. Ignoring it. Time:', embeddedTime
return
if embeddedTime < int(time.time()) - shared.maximumAgeOfAnObjectThatIAmWillingToAccept:
print 'The time in the msg message is too old. Ignoring it. Time:', embeddedTime
return
streamNumberAsClaimedByMsg, streamNumberAsClaimedByMsgLength = decodeVarint(
data[readPosition:readPosition + 9])
if streamNumberAsClaimedByMsg != self.streamNumber:
print 'The stream number encoded in this msg (' + str(streamNumberAsClaimedByMsg) + ') message does not match the stream number on which it was received. Ignoring it.'
return
readPosition += streamNumberAsClaimedByMsgLength
self.inventoryHash = calculateInventoryHash(data)
shared.numberOfInventoryLookupsPerformed += 1
shared.inventoryLock.acquire()
if self.inventoryHash in shared.inventory:
print 'We have already received this msg message. Ignoring.'
shared.inventoryLock.release()
return
elif shared.isInSqlInventory(self.inventoryHash):
print 'We have already received this msg message (it is stored on disk in the SQL inventory). Ignoring it.'
shared.inventoryLock.release()
return
# This msg message is valid. Let's let our peers know about it.
objectType = 'msg'
shared.inventory[self.inventoryHash] = (
objectType, self.streamNumber, data, embeddedTime,'')
shared.inventorySets[self.streamNumber].add(self.inventoryHash)
shared.inventoryLock.release()
self.broadcastinv(self.inventoryHash)
shared.numberOfMessagesProcessed += 1
shared.UISignalQueue.put((
'updateNumberOfMessagesProcessed', 'no data'))
self.processmsg(
readPosition, data) # When this function returns, we will have either successfully processed the message bound for us, ignored it because it isn't bound for us, or found problem with the message that warranted ignoring it.
# Let us now set lengthOfTimeWeShouldUseToProcessThisMessage. If we
# haven't used the specified amount of time, we shall sleep. These
# values are based on test timings and you may change them at-will.
"""
Let us now set lengthOfTimeWeShouldUseToProcessThisMessage. Sleeping
will help guarantee that we can process messages faster than a remote
node can send them. If we fall behind, the attacker could observe that
we are are slowing down the rate at which we request objects from the
network which would indicate that we own a particular address (whichever
one to which they are sending all of their attack messages). Note
that if an attacker connects to a target with many connections, this
mitigation mechanism might not be sufficient.
"""
if len(data) > 100000000: # Size is greater than 100 megabytes
lengthOfTimeWeShouldUseToProcessThisMessage = 100 # seconds. Actual length of time it took my computer to decrypt and verify the signature of a 100 MB message: 3.7 seconds.
elif len(data) > 10000000: # Between 100 and 10 megabytes
@ -929,422 +380,13 @@ class receiveDataThread(threading.Thread):
if sleepTime > 0 and doTimingAttackMitigation:
with shared.printLock:
print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.'
time.sleep(sleepTime)
with shared.printLock:
print 'Total message processing time:', time.time() - self.messageProcessingStartTime, 'seconds.'
# A msg message has a valid time and POW and requires processing. The
# recmsg function calls this one.
def processmsg(self, readPosition, encryptedData):
initialDecryptionSuccessful = False
# Let's check whether this is a message acknowledgement bound for us.
if encryptedData[readPosition:] in shared.ackdataForWhichImWatching:
with shared.printLock:
print 'This msg IS an acknowledgement bound for me.'
del shared.ackdataForWhichImWatching[encryptedData[readPosition:]]
sqlExecute('UPDATE sent SET status=? WHERE ackdata=?',
'ackreceived', encryptedData[readPosition:])
shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (encryptedData[readPosition:], tr.translateText("MainWindow",'Acknowledgement of the message received. %1').arg(unicode(
time.strftime(shared.config.get('bitmessagesettings', 'timeformat'), time.localtime(int(time.time()))), 'utf-8')))))
return
else:
with shared.printLock:
print 'This was NOT an acknowledgement bound for me.'
# print 'shared.ackdataForWhichImWatching', shared.ackdataForWhichImWatching
# This is not an acknowledgement bound for me. See if it is a message
# bound for me by trying to decrypt it with my private keys.
for key, cryptorObject in shared.myECCryptorObjects.items():
try:
decryptedData = cryptorObject.decrypt(
encryptedData[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
with shared.printLock:
print 'EC decryption successful using key associated with ripe hash:', 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.
with shared.printLock:
print 'Length of time program spent failing to decrypt this message:', time.time() - self.messageProcessingStartTime, 'seconds.'
else:
# This is a message bound for me.
toAddress = shared.myAddressesByHash[
toRipe] # Look up my address based on the RIPE hash.
readPosition = 0
messageVersion, messageVersionLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += messageVersionLength
if messageVersion != 1:
print 'Cannot understand message versions other than one. Ignoring message.'
return
sendersAddressVersionNumber, sendersAddressVersionNumberLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += sendersAddressVersionNumberLength
if sendersAddressVersionNumber == 0:
print 'Cannot understand sendersAddressVersionNumber = 0. Ignoring message.'
return
if sendersAddressVersionNumber > 4:
print 'Sender\'s address version number', sendersAddressVersionNumber, 'not yet supported. Ignoring message.'
return
if len(decryptedData) < 170:
print 'Length of the unencrypted data is unreasonably short. Sanity check failed. Ignoring message.'
return
sendersStreamNumber, sendersStreamNumberLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
if sendersStreamNumber == 0:
print 'sender\'s stream number is 0. Ignoring message.'
return
readPosition += sendersStreamNumberLength
behaviorBitfield = decryptedData[readPosition:readPosition + 4]
readPosition += 4
pubSigningKey = '\x04' + decryptedData[
readPosition:readPosition + 64]
readPosition += 64
pubEncryptionKey = '\x04' + decryptedData[
readPosition:readPosition + 64]
readPosition += 64
if sendersAddressVersionNumber >= 3:
requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += varintLength
print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte
requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += varintLength
print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes
endOfThePublicKeyPosition = readPosition # needed for when we store the pubkey in our database of pubkeys for later use.
if toRipe != decryptedData[readPosition:readPosition + 20]:
with shared.printLock:
print 'The original sender of this message did not send it to you. Someone is attempting a Surreptitious Forwarding Attack.'
print 'See: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html'
print 'your toRipe:', toRipe.encode('hex')
print 'embedded destination toRipe:', decryptedData[readPosition:readPosition + 20].encode('hex')
return
readPosition += 20
messageEncodingType, messageEncodingTypeLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += messageEncodingTypeLength
messageLength, messageLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += messageLengthLength
message = decryptedData[readPosition:readPosition + messageLength]
# print 'First 150 characters of message:', repr(message[:150])
readPosition += messageLength
ackLength, ackLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += ackLengthLength
ackData = decryptedData[readPosition:readPosition + ackLength]
readPosition += ackLength
positionOfBottomOfAckData = readPosition # needed to mark the end of what is covered by the signature
signatureLength, signatureLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += signatureLengthLength
signature = decryptedData[
readPosition:readPosition + signatureLength]
try:
if not highlevelcrypto.verify(decryptedData[:positionOfBottomOfAckData], signature, pubSigningKey.encode('hex')):
print 'ECDSA verify failed'
return
print 'ECDSA verify passed'
except Exception as err:
print 'ECDSA verify failed', err
return
with shared.printLock:
print 'As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person:', helper_bitcoin.calculateBitcoinAddressFromPubkey(pubSigningKey), ' ..and here is the testnet address:', helper_bitcoin.calculateTestnetAddressFromPubkey(pubSigningKey), '. The other person must take their private signing key from Bitmessage and import it into Bitcoin (or a service like Blockchain.info) for it to be of any use. Do not use this unless you know what you are doing.'
# calculate the fromRipe.
sha = hashlib.new('sha512')
sha.update(pubSigningKey + pubEncryptionKey)
ripe = hashlib.new('ripemd160')
ripe.update(sha.digest())
fromAddress = encodeAddress(
sendersAddressVersionNumber, sendersStreamNumber, ripe.digest())
# Let's store the public key in case we want to reply to this
# person.
if sendersAddressVersionNumber <= 3:
sqlExecute(
'''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
ripe.digest(),
sendersAddressVersionNumber,
'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + decryptedData[messageVersionLength:endOfThePublicKeyPosition],
int(time.time()),
'yes')
# This will check to see whether we happen to be awaiting this
# pubkey in order to send a message. If we are, it will do the POW
# and send it.
self.possibleNewPubkey(ripe=ripe.digest())
elif sendersAddressVersionNumber >= 4:
sqlExecute(
'''INSERT INTO pubkeys VALUES (?,?,?,?,?)''',
ripe.digest(),
sendersAddressVersionNumber,
'\x00\x00\x00\x00\x00\x00\x00\x01' + decryptedData[messageVersionLength:endOfThePublicKeyPosition],
int(time.time()),
'yes')
# This will check to see whether we happen to be awaiting this
# pubkey in order to send a message. If we are, it will do the POW
# and send it.
self.possibleNewPubkey(address = fromAddress)
# If this message is bound for one of my version 3 addresses (or
# higher), then we must check to make sure it meets our demanded
# proof of work requirement.
if decodeAddress(toAddress)[1] >= 3: # If the toAddress version number is 3 or higher:
if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(fromAddress): # If I'm not friendly with this person:
requiredNonceTrialsPerByte = shared.config.getint(
toAddress, 'noncetrialsperbyte')
requiredPayloadLengthExtraBytes = shared.config.getint(
toAddress, 'payloadlengthextrabytes')
if not self.isProofOfWorkSufficient(encryptedData, requiredNonceTrialsPerByte, requiredPayloadLengthExtraBytes):
print 'Proof of work in msg message insufficient only because it does not meet our higher requirement.'
return
blockMessage = False # Gets set to True if the user shouldn't see the message according to black or white lists.
if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black': # If we are using a blacklist
queryreturn = sqlQuery(
'''SELECT label FROM blacklist where address=? and enabled='1' ''',
fromAddress)
if queryreturn != []:
with shared.printLock:
print 'Message ignored because address is in blacklist.'
blockMessage = True
else: # We're using a whitelist
queryreturn = sqlQuery(
'''SELECT label FROM whitelist where address=? and enabled='1' ''',
fromAddress)
if queryreturn == []:
print 'Message ignored because address not in whitelist.'
blockMessage = True
if not blockMessage:
print 'fromAddress:', fromAddress
print 'First 150 characters of message:', repr(message[:150])
toLabel = shared.config.get(toAddress, 'label')
if toLabel == '':
toLabel = toAddress
if messageEncodingType == 2:
subject, body = self.decodeType2Message(message)
elif messageEncodingType == 1:
body = message
subject = ''
elif messageEncodingType == 0:
print '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 = ''
if messageEncodingType != 0:
t = (self.inventoryHash, toAddress, fromAddress, subject, int(
time.time()), body, 'inbox', messageEncodingType, 0)
helper_inbox.insert(t)
shared.UISignalQueue.put(('displayNewInboxMessage', (
self.inventoryHash, toAddress, fromAddress, subject, body)))
# If we are behaving as an API then we might need to run an
# outside command to let some program know that a new message
# has arrived.
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
try:
apiNotifyPath = shared.config.get(
'bitmessagesettings', 'apinotifypath')
except:
apiNotifyPath = ''
if apiNotifyPath != '':
call([apiNotifyPath, "newMessage"])
# Let us now check and see whether our receiving address is
# behaving as a mailing list
if shared.safeConfigGetBoolean(toAddress, 'mailinglist'):
try:
mailingListName = shared.config.get(
toAddress, 'mailinglistname')
except:
mailingListName = ''
# Let us send out this message as a broadcast
subject = self.addMailingListNameToSubject(
subject, mailingListName)
# Let us now send this message out as a broadcast
message = time.strftime("%a, %Y-%m-%d %H:%M:%S UTC", time.gmtime(
)) + ' Message ostensibly from ' + fromAddress + ':\n\n' + body
fromAddress = toAddress # The fromAddress for the broadcast that we are about to send is the toAddress (my address) for the msg message we are currently processing.
ackdata = OpenSSL.rand(
32) # We don't actually need the ackdata for acknowledgement since this is a broadcast message but we can use it to update the user interface when the POW is done generating.
toAddress = '[Broadcast subscribers]'
ripe = ''
t = ('', toAddress, ripe, fromAddress, subject, message, ackdata, int(
time.time()), 'broadcastqueued', 1, 1, 'sent', 2)
helper_sent.insert(t)
shared.UISignalQueue.put(('displayNewSentMessage', (
toAddress, '[Broadcast subscribers]', fromAddress, subject, message, ackdata)))
shared.workerQueue.put(('sendbroadcast', ''))
if self.isAckDataValid(ackData):
print 'ackData is valid. Will process it.'
self.ackDataThatWeHaveYetToSend.append(
ackData) # When we have processed all data, the processData function will pop the ackData out and process it as if it is a message received from our peer.
# Display timing data
timeRequiredToAttemptToDecryptMessage = time.time(
) - self.messageProcessingStartTime
shared.successfullyDecryptMessageTimings.append(
timeRequiredToAttemptToDecryptMessage)
sum = 0
for item in shared.successfullyDecryptMessageTimings:
sum += item
with shared.printLock:
print 'Time to decrypt this message successfully:', timeRequiredToAttemptToDecryptMessage
print 'Average time for all message decryption successes since startup:', sum / len(shared.successfullyDecryptMessageTimings)
def decodeType2Message(self, message):
bodyPositionIndex = string.find(message, '\nBody:')
if bodyPositionIndex > 1:
subject = message[8:bodyPositionIndex]
# Only save and show the first 500 characters of the subject.
# Any more is probably an attack.
subject = subject[:500]
body = message[bodyPositionIndex + 6:]
else:
subject = ''
body = message
# Throw away any extra lines (headers) after the subject.
if subject:
subject = subject.splitlines()[0]
return subject, body
def isAckDataValid(self, ackData):
if len(ackData) < 24:
print 'The length of ackData is unreasonably short. Not sending ackData.'
return False
if ackData[0:4] != '\xe9\xbe\xb4\xd9':
print 'Ackdata magic bytes were wrong. Not sending ackData.'
return False
ackDataPayloadLength, = unpack('>L', ackData[16:20])
if len(ackData) - 24 != ackDataPayloadLength:
print 'ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.'
return False
if ackData[4:16] != 'getpubkey\x00\x00\x00' and ackData[4:16] != 'pubkey\x00\x00\x00\x00\x00\x00' and ackData[4:16] != 'msg\x00\x00\x00\x00\x00\x00\x00\x00\x00' and ackData[4:16] != 'broadcast\x00\x00\x00':
return False
return True
def addMailingListNameToSubject(self, subject, mailingListName):
subject = subject.strip()
if subject[:3] == 'Re:' or subject[:3] == 'RE:':
subject = subject[3:].strip()
if '[' + mailingListName + ']' in subject:
return subject
else:
return '[' + mailingListName + '] ' + subject
# We have inserted a pubkey into our pubkey table which we received from a
# pubkey, msg, or broadcast message. It might be one that we have been
# waiting for. Let's check.
def possibleNewPubkey(self, ripe=None, address=None):
# For address versions <= 3, we wait on a key with the correct ripe hash
if ripe != None:
if ripe in shared.neededPubkeys:
print 'We have been awaiting the arrival of this pubkey.'
del shared.neededPubkeys[ripe]
sqlExecute(
'''UPDATE sent SET status='doingmsgpow' WHERE toripe=? AND (status='awaitingpubkey' or status='doingpubkeypow') and folder='sent' ''',
ripe)
shared.workerQueue.put(('sendmessage', ''))
else:
with shared.printLock:
print 'We don\'t need this pub key. We didn\'t ask for it. Pubkey hash:', ripe.encode('hex')
# For address versions >= 4, we wait on a pubkey with the correct tag.
# Let us create the tag from the address and see if we were waiting
# for it.
elif address != None:
status, addressVersion, streamNumber, ripe = decodeAddress(address)
tag = hashlib.sha512(hashlib.sha512(encodeVarint(
addressVersion) + encodeVarint(streamNumber) + ripe).digest()).digest()[32:]
if tag in shared.neededPubkeys:
print 'We have been awaiting the arrival of this pubkey.'
del shared.neededPubkeys[tag]
sqlExecute(
'''UPDATE sent SET status='doingmsgpow' WHERE toripe=? AND (status='awaitingpubkey' or status='doingpubkeypow') and folder='sent' ''',
ripe)
shared.workerQueue.put(('sendmessage', ''))
# We have received a pubkey
def recpubkey(self, data):
self.pubkeyProcessingStartTime = time.time()
if len(data) < 146 or len(data) > 420: # sanity check
return
# We must check to make sure the proof of work is sufficient.
if not self.isProofOfWorkSufficient(data):
print 'Proof of work in pubkey message insufficient.'
return
readPosition = 8 # for the nonce
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
# This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0:
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
readPosition += 8
else:
readPosition += 4
if embeddedTime < int(time.time()) - shared.lengthOfTimeToHoldOnToAllPubkeys:
with shared.printLock:
print 'The embedded time in this pubkey message is too old. Ignoring. Embedded time is:', embeddedTime
return
if embeddedTime > int(time.time()) + 10800:
with shared.printLock:
print '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])
readPosition += varintLength
streamNumber, varintLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += varintLength
if self.streamNumber != streamNumber:
print 'stream number embedded in this pubkey doesn\'t match our stream number. Ignoring.'
return
if addressVersion >= 4:
tag = data[readPosition:readPosition + 32]
print 'tag in received pubkey is:', tag.encode('hex')
else:
tag = ''
shared.numberOfInventoryLookupsPerformed += 1
inventoryHash = calculateInventoryHash(data)
shared.inventoryLock.acquire()
if inventoryHash in shared.inventory:
print 'We have already received this pubkey. Ignoring it.'
shared.inventoryLock.release()
return
elif shared.isInSqlInventory(inventoryHash):
print 'We have already received this pubkey (it is stored on disk in the SQL inventory). Ignoring it.'
shared.inventoryLock.release()
return
objectType = 'pubkey'
shared.inventory[inventoryHash] = (
objectType, self.streamNumber, data, embeddedTime, tag)
shared.inventorySets[self.streamNumber].add(inventoryHash)
shared.inventoryLock.release()
self.broadcastinv(inventoryHash)
shared.numberOfPubkeysProcessed += 1
shared.UISignalQueue.put((
'updateNumberOfPubkeysProcessed', 'no data'))
self.processpubkey(data)
shared.checkAndSharePubkeyWithPeers(data)
lengthOfTimeWeShouldUseToProcessThisMessage = .1
sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \
@ -1352,343 +394,7 @@ class receiveDataThread(threading.Thread):
if sleepTime > 0 and doTimingAttackMitigation:
with shared.printLock:
print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.'
time.sleep(sleepTime)
with shared.printLock:
print 'Total pubkey processing time:', time.time() - self.pubkeyProcessingStartTime, 'seconds.'
def processpubkey(self, data):
readPosition = 8 # for the nonce
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
# This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0:
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
readPosition += 8
else:
readPosition += 4
addressVersion, varintLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += varintLength
streamNumber, varintLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += varintLength
if addressVersion == 0:
print '(Within processpubkey) addressVersion of 0 doesn\'t make sense.'
return
if addressVersion > 4 or addressVersion == 1:
with shared.printLock:
print 'This version of Bitmessage cannot handle version', addressVersion, 'addresses.'
return
if addressVersion == 2:
if len(data) < 146: # sanity check. This is the minimum possible length.
print '(within processpubkey) payloadLength less than 146. Sanity check failed.'
return
bitfieldBehaviors = data[readPosition:readPosition + 4]
readPosition += 4
publicSigningKey = data[readPosition:readPosition + 64]
# Is it possible for a public key to be invalid such that trying to
# encrypt or sign with it will cause an error? If it is, we should
# probably test these keys here.
readPosition += 64
publicEncryptionKey = data[readPosition:readPosition + 64]
if len(publicEncryptionKey) < 64:
print 'publicEncryptionKey length less than 64. Sanity check failed.'
return
sha = hashlib.new('sha512')
sha.update(
'\x04' + publicSigningKey + '\x04' + publicEncryptionKey)
ripeHasher = hashlib.new('ripemd160')
ripeHasher.update(sha.digest())
ripe = ripeHasher.digest()
with shared.printLock:
print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber
print 'ripe', ripe.encode('hex')
print 'publicSigningKey in hex:', publicSigningKey.encode('hex')
print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex')
queryreturn = sqlQuery(
'''SELECT usedpersonally FROM pubkeys WHERE hash=? AND addressversion=? AND usedpersonally='yes' ''', ripe, addressVersion)
if queryreturn != []: # if this pubkey is already in our database and if we have used it personally:
print 'We HAVE used this pubkey personally. Updating time.'
t = (ripe, addressVersion, data, embeddedTime, 'yes')
else:
print 'We have NOT used this pubkey personally. Inserting in database.'
t = (ripe, addressVersion, data, embeddedTime, 'no')
# This will also update the embeddedTime.
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
# shared.workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe)))
self.possibleNewPubkey(ripe = ripe)
if addressVersion == 3:
if len(data) < 170: # sanity check.
print '(within processpubkey) payloadLength less than 170. Sanity check failed.'
return
bitfieldBehaviors = data[readPosition:readPosition + 4]
readPosition += 4
publicSigningKey = '\x04' + data[readPosition:readPosition + 64]
# Is it possible for a public key to be invalid such that trying to
# encrypt or sign with it will cause an error? If it is, we should
# probably test these keys here.
readPosition += 64
publicEncryptionKey = '\x04' + data[readPosition:readPosition + 64]
readPosition += 64
specifiedNonceTrialsPerByte, specifiedNonceTrialsPerByteLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += specifiedNonceTrialsPerByteLength
specifiedPayloadLengthExtraBytes, specifiedPayloadLengthExtraBytesLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += specifiedPayloadLengthExtraBytesLength
endOfSignedDataPosition = readPosition
signatureLength, signatureLengthLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += signatureLengthLength
signature = data[readPosition:readPosition + signatureLength]
try:
if not highlevelcrypto.verify(data[8:endOfSignedDataPosition], signature, publicSigningKey.encode('hex')):
print 'ECDSA verify failed (within processpubkey)'
return
print 'ECDSA verify passed (within processpubkey)'
except Exception as err:
print 'ECDSA verify failed (within processpubkey)', err
return
sha = hashlib.new('sha512')
sha.update(publicSigningKey + publicEncryptionKey)
ripeHasher = hashlib.new('ripemd160')
ripeHasher.update(sha.digest())
ripe = ripeHasher.digest()
with shared.printLock:
print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber
print 'ripe', ripe.encode('hex')
print 'publicSigningKey in hex:', publicSigningKey.encode('hex')
print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex')
queryreturn = sqlQuery('''SELECT usedpersonally FROM pubkeys WHERE hash=? AND addressversion=? AND usedpersonally='yes' ''', ripe, addressVersion)
if queryreturn != []: # if this pubkey is already in our database and if we have used it personally:
print 'We HAVE used this pubkey personally. Updating time.'
t = (ripe, addressVersion, data, embeddedTime, 'yes')
else:
print 'We have NOT used this pubkey personally. Inserting in database.'
t = (ripe, addressVersion, data, embeddedTime, 'no')
# This will also update the embeddedTime.
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
self.possibleNewPubkey(ripe = ripe)
if addressVersion == 4:
if len(data) < 350: # sanity check.
print '(within processpubkey) payloadLength less than 350. Sanity check failed.'
return
signedData = data[8:readPosition] # Used only for v4 or higher pubkeys
tag = data[readPosition:readPosition + 32]
readPosition += 32
encryptedData = data[readPosition:]
if tag not in shared.neededPubkeys:
with shared.printLock:
print 'We don\'t need this v4 pubkey. We didn\'t ask for it.'
return
# Let us try to decrypt the pubkey
cryptorObject = shared.neededPubkeys[tag]
try:
decryptedData = cryptorObject.decrypt(encryptedData)
except:
# Someone must have encrypted some data with a different key
# but tagged it with a tag for which we are watching.
with shared.printLock:
print 'Pubkey decryption was unsuccessful.'
return
readPosition = 0
bitfieldBehaviors = decryptedData[readPosition:readPosition + 4]
readPosition += 4
publicSigningKey = '\x04' + decryptedData[readPosition:readPosition + 64]
# Is it possible for a public key to be invalid such that trying to
# encrypt or sign with it will cause an error? If it is, we should
# probably test these keys here.
readPosition += 64
publicEncryptionKey = '\x04' + decryptedData[readPosition:readPosition + 64]
readPosition += 64
specifiedNonceTrialsPerByte, specifiedNonceTrialsPerByteLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += specifiedNonceTrialsPerByteLength
specifiedPayloadLengthExtraBytes, specifiedPayloadLengthExtraBytesLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += specifiedPayloadLengthExtraBytesLength
signedData += decryptedData[:readPosition]
signatureLength, signatureLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += signatureLengthLength
signature = decryptedData[readPosition:readPosition + signatureLength]
try:
if not highlevelcrypto.verify(signedData, signature, publicSigningKey.encode('hex')):
print 'ECDSA verify failed (within processpubkey)'
return
print 'ECDSA verify passed (within processpubkey)'
except Exception as err:
print 'ECDSA verify failed (within processpubkey)', err
return
sha = hashlib.new('sha512')
sha.update(publicSigningKey + publicEncryptionKey)
ripeHasher = hashlib.new('ripemd160')
ripeHasher.update(sha.digest())
ripe = ripeHasher.digest()
# We need to make sure that the tag on the outside of the encryption
# is the one generated from hashing these particular keys.
if tag != hashlib.sha512(hashlib.sha512(encodeVarint(addressVersion) + encodeVarint(streamNumber) + ripe).digest()).digest()[32:]:
with shared.printLock:
print 'Someone was trying to act malicious: tag doesn\'t match the keys in this pubkey message. Ignoring it.'
return
else:
print 'Tag successfully matches keys in pubkey message' # testing. Will remove soon.
with shared.printLock:
print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber
print 'ripe', ripe.encode('hex')
print 'publicSigningKey in hex:', publicSigningKey.encode('hex')
print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex')
t = (ripe, addressVersion, signedData, embeddedTime, 'yes')
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
fromAddress = encodeAddress(addressVersion, streamNumber, ripe)
# That this point we know that we have been waiting on this pubkey.
# This function will command the workerThread to start work on
# the messages that require it.
self.possibleNewPubkey(address = fromAddress)
# We have received a getpubkey message
def recgetpubkey(self, data):
if not self.isProofOfWorkSufficient(data):
print 'Proof of work in getpubkey message insufficient.'
return
if len(data) < 34:
print 'getpubkey message doesn\'t contain enough data. Ignoring.'
return
readPosition = 8 # bypass the nonce
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
# This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0:
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
readPosition += 8
else:
readPosition += 4
if embeddedTime > int(time.time()) + 10800:
print 'The time in this getpubkey message is too new. Ignoring it. Time:', embeddedTime
return
if embeddedTime < int(time.time()) - shared.maximumAgeOfAnObjectThatIAmWillingToAccept:
print 'The time in this getpubkey message is too old. Ignoring it. Time:', embeddedTime
return
requestedAddressVersionNumber, addressVersionLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += addressVersionLength
streamNumber, streamNumberLength = decodeVarint(
data[readPosition:readPosition + 10])
if streamNumber != self.streamNumber:
print 'The streamNumber', streamNumber, 'doesn\'t match our stream number:', self.streamNumber
return
readPosition += streamNumberLength
shared.numberOfInventoryLookupsPerformed += 1
inventoryHash = calculateInventoryHash(data)
shared.inventoryLock.acquire()
if inventoryHash in shared.inventory:
print 'We have already received this getpubkey request. Ignoring it.'
shared.inventoryLock.release()
return
elif shared.isInSqlInventory(inventoryHash):
print 'We have already received this getpubkey request (it is stored on disk in the SQL inventory). Ignoring it.'
shared.inventoryLock.release()
return
objectType = 'getpubkey'
shared.inventory[inventoryHash] = (
objectType, self.streamNumber, data, embeddedTime,'')
shared.inventorySets[self.streamNumber].add(inventoryHash)
shared.inventoryLock.release()
# This getpubkey request is valid so far. Forward to peers.
self.broadcastinv(inventoryHash)
if requestedAddressVersionNumber == 0:
print 'The requestedAddressVersionNumber of the pubkey request is zero. That doesn\'t make any sense. Ignoring it.'
return
elif requestedAddressVersionNumber == 1:
print 'The requestedAddressVersionNumber of the pubkey request is 1 which isn\'t supported anymore. Ignoring it.'
return
elif requestedAddressVersionNumber > 4:
print 'The requestedAddressVersionNumber of the pubkey request is too high. Can\'t understand. Ignoring it.'
return
myAddress = ''
if requestedAddressVersionNumber <= 3 :
requestedHash = data[readPosition:readPosition + 20]
if len(requestedHash) != 20:
print 'The length of the requested hash is not 20 bytes. Something is wrong. Ignoring.'
return
with shared.printLock:
print 'the hash requested in this getpubkey request is:', requestedHash.encode('hex')
if requestedHash in shared.myAddressesByHash: # if this address hash is one of mine
myAddress = shared.myAddressesByHash[requestedHash]
elif requestedAddressVersionNumber >= 4:
requestedTag = data[readPosition:readPosition + 32]
if len(requestedTag) != 32:
print 'The length of the requested tag is not 32 bytes. Something is wrong. Ignoring.'
return
with shared.printLock:
print 'the tag requested in this getpubkey request is:', requestedTag.encode('hex')
if requestedTag in shared.myAddressesByTag:
myAddress = shared.myAddressesByTag[requestedTag]
if myAddress == '':
with shared.printLock:
print 'This getpubkey request is not for any of my keys.'
return
if decodeAddress(myAddress)[1] != requestedAddressVersionNumber:
with shared.printLock:
sys.stderr.write(
'(Within the recgetpubkey function) Someone requested one of my pubkeys but the requestedAddressVersionNumber doesn\'t match my actual address version number. They shouldn\'t have done that. Ignoring.\n')
return
if shared.safeConfigGetBoolean(myAddress, 'chan'):
with shared.printLock:
print 'Ignoring getpubkey request because it is for one of my chan addresses. The other party should already have the pubkey.'
return
try:
lastPubkeySendTime = int(shared.config.get(
myAddress, 'lastpubkeysendtime'))
except:
lastPubkeySendTime = 0
if lastPubkeySendTime > time.time() - shared.lengthOfTimeToHoldOnToAllPubkeys: # If the last time we sent our pubkey was more recent than 28 days ago...
with shared.printLock:
print 'Found getpubkey-requested-item in my list of EC hashes BUT we already sent it recently. Ignoring request. The lastPubkeySendTime is:', lastPubkeySendTime
return
with shared.printLock:
print '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))
elif requestedAddressVersionNumber == 3:
shared.workerQueue.put((
'sendOutOrStoreMyV3Pubkey', requestedHash))
elif requestedAddressVersionNumber == 4:
shared.workerQueue.put((
'sendOutOrStoreMyV4Pubkey', myAddress))
# We have received an inv message
@ -1712,7 +418,6 @@ class receiveDataThread(threading.Thread):
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 1000 from this node in particular. Ignoring this inv message.'
return
self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware[
data[lengthOfVarint:32 + lengthOfVarint]] = 0
@ -1835,12 +540,12 @@ class receiveDataThread(threading.Thread):
# Advertise this object to all of our peers
def broadcastinv(self, hash):
"""def broadcastinv(self, hash):
with shared.printLock:
print 'broadcasting inv with hash:', hash.encode('hex')
shared.broadcastToSendDataQueues((self.streamNumber, 'advertiseobject', hash))
"""
# We have received an addr message.
def recaddr(self, data):
#listOfAddressDetailsToBroadcastToPeers = []
@ -1863,13 +568,11 @@ class receiveDataThread(threading.Thread):
if data[20 + lengthOfNumberOfAddresses + (38 * i):32 + lengthOfNumberOfAddresses + (38 * i)] != '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF':
with shared.printLock:
print 'Skipping IPv6 address.', repr(data[20 + lengthOfNumberOfAddresses + (38 * i):32 + lengthOfNumberOfAddresses + (38 * i)])
continue
except Exception as err:
with shared.printLock:
sys.stderr.write(
'ERROR TRYING TO UNPACK recaddr (to test for an IPv6 address). Message: %s\n' % str(err))
break # giving up on unpacking any more. We should still be connected however.
try:
@ -1879,7 +582,6 @@ class receiveDataThread(threading.Thread):
with shared.printLock:
sys.stderr.write(
'ERROR TRYING TO UNPACK recaddr (recaddrStream). Message: %s\n' % str(err))
break # giving up on unpacking any more. We should still be connected however.
if recaddrStream == 0:
continue
@ -1892,7 +594,6 @@ class receiveDataThread(threading.Thread):
with shared.printLock:
sys.stderr.write(
'ERROR TRYING TO UNPACK recaddr (recaddrServices). Message: %s\n' % str(err))
break # giving up on unpacking any more. We should still be connected however.
try:
@ -1902,7 +603,6 @@ class receiveDataThread(threading.Thread):
with shared.printLock:
sys.stderr.write(
'ERROR TRYING TO UNPACK recaddr (recaddrPort). Message: %s\n' % str(err))
break # giving up on unpacking any more. We should still be connected however.
# print 'Within recaddr(): IP', recaddrIP, ', Port',
# recaddrPort, ', i', i
@ -1955,37 +655,6 @@ class receiveDataThread(threading.Thread):
print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.'
# Function runs when we want to broadcast an addr message to all of our
# peers. Runs when we learn of nodes that we didn't previously know about
# and want to share them with our peers.
"""def broadcastaddr(self, listOfAddressDetailsToBroadcastToPeers):
numberOfAddressesInAddrMessage = len(
listOfAddressDetailsToBroadcastToPeers)
payload = ''
for hostDetails in listOfAddressDetailsToBroadcastToPeers:
timeLastReceivedMessageFromThisNode, streamNumber, services, host, port = hostDetails
payload += pack(
'>Q', timeLastReceivedMessageFromThisNode) # now uses 64-bit time
payload += pack('>I', streamNumber)
payload += pack(
'>q', services) # service bit flags offered by this node
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + \
socket.inet_aton(host)
payload += pack('>H', port) # remote port
payload = encodeVarint(numberOfAddressesInAddrMessage) + payload
datatosend = '\xE9\xBE\xB4\xD9addr\x00\x00\x00\x00\x00\x00\x00\x00'
datatosend = datatosend + pack('>L', len(payload)) # payload length
datatosend = datatosend + hashlib.sha512(payload).digest()[0:4]
datatosend = datatosend + payload
if shared.verbose >= 1:
with shared.printLock:
print 'Broadcasting addr with', numberOfAddressesInAddrMessage, 'entries.'
shared.broadcastToSendDataQueues((
self.streamNumber, 'sendaddr', datatosend))"""
# Send a big addr message to our peer
def sendaddr(self):
addrsInMyStream = {}
@ -2089,7 +758,6 @@ class receiveDataThread(threading.Thread):
shared.broadcastToSendDataQueues((0, 'shutdown', self.peer))
with shared.printLock:
print 'Closing connection to old protocol version 1 node: ', self.peer
return
# print 'remoteProtocolVersion', self.remoteProtocolVersion
self.myExternalIP = socket.inet_ntoa(data[40:44])
@ -2113,7 +781,6 @@ class receiveDataThread(threading.Thread):
shared.broadcastToSendDataQueues((0, 'shutdown', self.peer))
with shared.printLock:
print 'Closed connection to', self.peer, 'because they are interested in stream', self.streamNumber, '.'
return
shared.connectedHostsList[
self.peer.host] = 1 # We use this data structure to not only keep track of what hosts we are connected to so that we don't try to connect to them again, but also to list the connections count on the Network Status tab.
@ -2126,7 +793,6 @@ class receiveDataThread(threading.Thread):
shared.broadcastToSendDataQueues((0, 'shutdown', self.peer))
with shared.printLock:
print 'Closing connection to myself: ', self.peer
return
shared.broadcastToSendDataQueues((0, 'setRemoteProtocolVersion', (
self.peer, self.remoteProtocolVersion)))
@ -2158,7 +824,6 @@ class receiveDataThread(threading.Thread):
def sendverack(self):
with shared.printLock:
print 'Sending verack'
try:
self.sock.sendall(
'\xE9\xBE\xB4\xD9\x76\x65\x72\x61\x63\x6B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xcf\x83\xe1\x35')
@ -2166,11 +831,6 @@ class receiveDataThread(threading.Thread):
# if not 'Bad file descriptor' in err:
with shared.printLock:
print 'sock.sendall error:', err
# cf
# 83
# e1
# 35
self.verackSent = True
if self.verackReceived:
self.connectionFullyEstablished()

View File

@ -260,7 +260,6 @@ class singleWorker(threading.Thread):
payload = pack('>Q', (embeddedTime))
payload += encodeVarint(addressVersionNumber) # Address version number
payload += encodeVarint(streamNumber)
dataToStoreInOurPubkeysTable = payload # used if this is a chan. We'll add more data further down.
dataToEncrypt = '\x00\x00\x00\x01' # bitfield of features supported by me (see the wiki).
@ -291,8 +290,6 @@ class singleWorker(threading.Thread):
dataToEncrypt += encodeVarint(shared.config.getint(
myAddress, 'payloadlengthextrabytes'))
dataToStoreInOurPubkeysTable += dataToEncrypt # dataToStoreInOurPubkeysTable is used if this is a chan
signature = highlevelcrypto.sign(payload + dataToEncrypt, privSigningKeyHex)
dataToEncrypt += encodeVarint(len(signature))
dataToEncrypt += signature
@ -337,10 +334,8 @@ class singleWorker(threading.Thread):
myAddress, 'lastpubkeysendtime', str(int(time.time())))
with open(shared.appdata + 'keys.dat', 'wb') as configfile:
shared.config.write(configfile)
except:
# The user deleted the address out of the keys.dat file before this
# finished.
pass
except Exception as err:
logger.error('Error: Couldn\'t add the lastpubkeysendtime to the keys.dat file. Error message: %s' % err)
def sendBroadcast(self):
queryreturn = sqlQuery(
@ -386,7 +381,10 @@ class singleWorker(threading.Thread):
if addressVersionNumber >= 4:
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(encodeVarint(
addressVersionNumber) + encodeVarint(streamNumber) + ripe).digest()).digest()
payload += doubleHashOfAddressData[32:] # the tag
tag = doubleHashOfAddressData[32:]
payload += tag
else:
tag = ''
if addressVersionNumber <= 3:
dataToEncrypt = encodeVarint(2) # broadcast version
@ -416,6 +414,7 @@ class singleWorker(threading.Thread):
addressVersionNumber) + encodeVarint(streamNumber) + ripe).digest()[:32]
else:
privEncryptionKey = doubleHashOfAddressData[:32]
pubEncryptionKey = pointMult(privEncryptionKey)
payload += highlevelcrypto.encrypt(
dataToEncrypt, pubEncryptionKey.encode('hex'))
@ -434,7 +433,7 @@ class singleWorker(threading.Thread):
inventoryHash = calculateInventoryHash(payload)
objectType = 'broadcast'
shared.inventory[inventoryHash] = (
objectType, streamNumber, payload, int(time.time()),'')
objectType, streamNumber, payload, int(time.time()),tag)
shared.inventorySets[streamNumber].add(inventoryHash)
with shared.printLock:
print 'sending inv (within sendBroadcast function) for object:', inventoryHash.encode('hex')
@ -494,7 +493,7 @@ class singleWorker(threading.Thread):
if queryreturn != []: # if there was a pubkey in our inventory with the correct tag, we need to try to decrypt it.
for row in queryreturn:
data, = row
if shared.decryptAndCheckPubkeyPayload(data[8:], toaddress) == 'successful':
if shared.decryptAndCheckPubkeyPayload(data, toaddress) == 'successful':
needToRequestPubkey = False
print 'debug. successfully decrypted and checked pubkey from sql inventory.' #testing
sqlExecute(
@ -508,7 +507,7 @@ class singleWorker(threading.Thread):
for hash, storedValue in shared.inventory.items():
objectType, streamNumber, payload, receivedTime, tag = storedValue
if objectType == 'pubkey' and tag == toTag:
result = shared.decryptAndCheckPubkeyPayload(payload[8:], toaddress) #if valid, this function also puts it in the pubkeys table.
result = shared.decryptAndCheckPubkeyPayload(payload, toaddress) #if valid, this function also puts it in the pubkeys table.
if result == 'successful':
print 'debug. successfully decrypted and checked pubkey from memory inventory.'
needToRequestPubkey = False
@ -682,7 +681,7 @@ class singleWorker(threading.Thread):
ackdata, tr.translateText("MainWindow", "Doing work necessary to send message."))))
embeddedTime = pack('>Q', (int(time.time()) + random.randrange(
-300, 300))) # the current time plus or minus five minutes. We will use this time both for our message and for the ackdata packed within our message.
-300, 300))) # the current time plus or minus five minutes.
if fromAddressVersionNumber == 2:
payload = '\x01' # Message version.
payload += encodeVarint(fromAddressVersionNumber)
@ -722,7 +721,7 @@ class singleWorker(threading.Thread):
payload += encodeVarint(len(messageToTransmit))
payload += messageToTransmit
fullAckPayload = self.generateFullAckMessage(
ackdata, toStreamNumber, embeddedTime) # 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.
payload += encodeVarint(len(fullAckPayload))
payload += fullAckPayload
signature = highlevelcrypto.sign(payload, privSigningKeyHex)
@ -791,7 +790,7 @@ class singleWorker(threading.Thread):
fullAckPayload = ''
else:
fullAckPayload = self.generateFullAckMessage(
ackdata, toStreamNumber, embeddedTime) # 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.
payload += encodeVarint(len(fullAckPayload))
payload += fullAckPayload
signature = highlevelcrypto.sign(payload, privSigningKeyHex)
@ -930,7 +929,9 @@ class singleWorker(threading.Thread):
shared.UISignalQueue.put(('updateSentItemStatusByHash', (ripe, tr.translateText("MainWindow",'Sending public key request. Waiting for reply. Requested at %1').arg(unicode(
strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8')))))
def generateFullAckMessage(self, ackdata, toStreamNumber, embeddedTime):
def generateFullAckMessage(self, ackdata, toStreamNumber):
embeddedTime = pack('>Q', (int(time.time()) + random.randrange(
-300, 300))) # the current time plus or minus five minutes.
payload = embeddedTime + encodeVarint(toStreamNumber) + ackdata
target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes +
8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte)

View File

@ -25,6 +25,7 @@ class sqlThread(threading.Thread):
self.conn = sqlite3.connect(shared.appdata + 'messages.dat')
self.conn.text_factory = str
self.cur = self.conn.cursor()
try:
self.cur.execute(
'''CREATE TABLE inbox (msgid blob, toaddress text, fromaddress text, subject text, received text, message text, folder text, encodingtype int, read bool, UNIQUE(msgid) ON CONFLICT REPLACE)''' )
@ -51,17 +52,15 @@ class sqlThread(threading.Thread):
'''CREATE TABLE pubkeys (hash blob, addressversion int, transmitdata blob, time int, usedpersonally text, UNIQUE(hash, addressversion) ON CONFLICT REPLACE)''' )
self.cur.execute(
'''CREATE TABLE inventory (hash blob, objecttype text, streamnumber int, payload blob, receivedtime integer, tag blob, UNIQUE(hash) ON CONFLICT REPLACE)''' )
self.cur.execute(
'''CREATE TABLE knownnodes (timelastseen int, stream int, services blob, host blob, port blob, UNIQUE(host, stream, port) ON CONFLICT REPLACE)''' )
# This table isn't used in the program yet but I
# have a feeling that we'll need it.
self.cur.execute(
'''INSERT INTO subscriptions VALUES('Bitmessage new releases/announcements','BM-GtovgYdgs7qXPkoYaRgrLFuFKz1SFpsw',1)''')
self.cur.execute(
'''CREATE TABLE settings (key blob, value blob, UNIQUE(key) ON CONFLICT REPLACE)''' )
self.cur.execute( '''INSERT INTO settings VALUES('version','5')''')
self.cur.execute( '''INSERT INTO settings VALUES('version','6')''')
self.cur.execute( '''INSERT INTO settings VALUES('lastvacuumtime',?)''', (
int(time.time()),))
self.cur.execute(
'''CREATE TABLE objectprocessorqueue (objecttype text, data blob, UNIQUE(objecttype, data) ON CONFLICT REPLACE)''' )
self.conn.commit()
logger.info('Created messages database file')
except Exception as err:
@ -290,6 +289,20 @@ class sqlThread(threading.Thread):
with open(shared.appdata + 'keys.dat', 'wb') as configfile:
shared.config.write(configfile)
# Add a new table: objectprocessorqueue with which to hold objects
# that have yet to be processed if the user shuts down Bitmessage.
item = '''SELECT value FROM settings WHERE key='version';'''
parameters = ''
self.cur.execute(item, parameters)
currentVersion = int(self.cur.fetchall()[0][0])
if currentVersion == 5:
self.cur.execute( '''DROP TABLE knownnodes''')
self.cur.execute(
'''CREATE TABLE objectprocessorqueue (objecttype text, data blob, UNIQUE(objecttype, data) ON CONFLICT REPLACE)''' )
item = '''update settings set value=? WHERE key='version';'''
parameters = (6,)
self.cur.execute(item, parameters)
# Are you hoping to add a new option to the keys.dat file of existing
# Bitmessage users? Add it right above this line!

View File

@ -57,7 +57,7 @@ def _doFastPoW(target, initialHash):
for i in range(pool_size):
result.append(pool.apply_async(_pool_worker, args = (i, initialHash, target, pool_size)))
while True:
if shared.shutdown:
if shared.shutdown >= 1:
pool.terminate()
while True:
time.sleep(10) # Don't let this thread return here; it will return nothing and cause an exception in bitmessagemain.py

View File

@ -45,6 +45,8 @@ sendDataQueues = [] #each sendData thread puts its queue in this list.
inventory = {} #of objects (like msg payloads and pubkey payloads) Does not include protocol headers (the first 24 bytes of each packet).
inventoryLock = threading.Lock() #Guarantees that two receiveDataThreads don't receive and process the same message concurrently (probably sent by a malicious individual)
printLock = threading.Lock()
objectProcessorQueueSizeLock = threading.Lock()
objectProcessorQueueSize = 0 # in Bytes. We maintain this to prevent nodes from flooing us with objects which take up too much memory. If this gets too big we'll sleep before asking for further objects.
appdata = '' #holds the location of the application data storage directory
statusIconColor = 'red'
connectedHostsList = {} #List of hosts to which we are connected. Used to guarantee that the outgoingSynSender threads won't connect to the same remote node twice.
@ -72,6 +74,9 @@ daemon = False
inventorySets = {} # key = streamNumer, value = a set which holds the inventory object hashes that we are aware of. This is used whenever we receive an inv message from a peer to check to see what items are new to us. We don't delete things out of it; instead, the singleCleaner thread clears and refills it every couple hours.
needToWriteKnownNodesToDisk = False # If True, the singleCleaner will write it to disk eventually.
maximumLengthOfTimeToBotherResendingMessages = 0
objectProcessorQueue = Queue.Queue(
) # receiveDataThreads dump objects they hear on the network into this queue to be processed.
streamsInWhichIAmParticipating = {}
#If changed, these values will cause particularly unexpected behavior: You won't be able to either send or receive messages because the proof of work you do (or demand) won't match that done or demanded by others. Don't change them!
networkDefaultProofOfWorkNonceTrialsPerByte = 320 #The amount of work that should be performed (and demanded) per byte of the payload. Double this number to double the work.
@ -89,10 +94,7 @@ frozen = getattr(sys,'frozen', None)
def isInSqlInventory(hash):
queryreturn = sqlQuery('''select hash from inventory where hash=?''', hash)
if queryreturn == []:
return False
else:
return True
return queryreturn != []
def assembleVersionMessage(remoteHost, remotePort, myStreamNumber):
payload = ''
@ -101,7 +103,7 @@ def assembleVersionMessage(remoteHost, remotePort, myStreamNumber):
payload += pack('>q', int(time.time()))
payload += pack(
'>q', 1) # boolservices of remote connection. How can I even know this for sure? This is probably ignored by the remote host.
'>q', 1) # boolservices of remote connection; ignored by the remote host.
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + \
socket.inet_aton(remoteHost)
payload += pack('>H', remotePort) # remote IPv6 and port
@ -110,7 +112,7 @@ def assembleVersionMessage(remoteHost, remotePort, myStreamNumber):
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + pack(
'>L', 2130706433) # = 127.0.0.1. This will be ignored by the remote host. The actual remote connected IP will be used.
payload += pack('>H', shared.config.getint(
'bitmessagesettings', 'port')) # my external IPv6 and port
'bitmessagesettings', 'port'))
random.seed()
payload += eightBytesOfRandomDataUsedToDetectConnectionsToSelf
@ -129,7 +131,6 @@ def assembleVersionMessage(remoteHost, remotePort, myStreamNumber):
def lookupAppdataFolder():
APPNAME = "PyBitmessage"
from os import path, environ
if "BITMESSAGE_HOME" in environ:
dataFolder = environ["BITMESSAGE_HOME"]
if dataFolder[-1] not in [os.path.sep, os.path.altsep]:
@ -207,7 +208,8 @@ def decodeWalletImportFormat(WIFstring):
privkey = fullString[:-4]
if fullString[-4:] != hashlib.sha256(hashlib.sha256(privkey).digest()).digest()[:4]:
logger.critical('Major problem! When trying to decode one of your private keys, the checksum '
'failed. Here is the PRIVATE key: %s' % str(WIFstring))
'failed. Here are the first 6 characters of the PRIVATE key: %s' % str(WIFstring)[:6])
os._exit(0)
return ""
else:
#checksum passed
@ -217,6 +219,7 @@ def decodeWalletImportFormat(WIFstring):
logger.critical('Major problem! When trying to decode one of your private keys, the '
'checksum passed but the key doesn\'t begin with hex 80. Here is the '
'PRIVATE key: %s' % str(WIFstring))
os._exit(0)
return ""
@ -277,10 +280,27 @@ def reloadBroadcastSendersForWhichImWatching():
privEncryptionKey = doubleHashOfAddressData[:32]
MyECSubscriptionCryptorObjects[tag] = highlevelcrypto.makeCryptor(privEncryptionKey.encode('hex'))
def isProofOfWorkSufficient(
data,
nonceTrialsPerByte=0,
payloadLengthExtraBytes=0):
if nonceTrialsPerByte < networkDefaultProofOfWorkNonceTrialsPerByte:
nonceTrialsPerByte = networkDefaultProofOfWorkNonceTrialsPerByte
if payloadLengthExtraBytes < networkDefaultPayloadLengthExtraBytes:
payloadLengthExtraBytes = networkDefaultPayloadLengthExtraBytes
POW, = unpack('>Q', hashlib.sha512(hashlib.sha512(data[
:8] + hashlib.sha512(data[8:]).digest()).digest()).digest()[0:8])
# print 'POW:', POW
return POW <= 2 ** 64 / ((len(data) + payloadLengthExtraBytes) * (nonceTrialsPerByte))
def doCleanShutdown():
global shutdown
shutdown = 1 #Used to tell proof of work worker threads to exit.
shutdown = 1 #Used to tell proof of work worker threads and the objectProcessorThread to exit.
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...'))
@ -299,11 +319,16 @@ def doCleanShutdown():
'Flushing inventory in memory out to disk. This should normally only take a second...'))
flushInventory()
# This one last useless query will guarantee that the previous flush committed before we close
# the program.
# 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')
sqlStoredProcedure('exit')
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.
@ -396,8 +421,8 @@ def decryptAndCheckPubkeyPayload(payload, address):
status, addressVersion, streamNumber, ripe = decodeAddress(address)
doubleHashOfAddressData = hashlib.sha512(hashlib.sha512(encodeVarint(
addressVersion) + encodeVarint(streamNumber) + ripe).digest()).digest()
# this function expects that the nonce is Not included in payload.
readPosition = 8 # for the time
readPosition = 8 # bypass the nonce
readPosition += 8 # bypass the time
embeddedVersionNumber, varintLength = decodeVarint(
payload[readPosition:readPosition + 10])
if embeddedVersionNumber != addressVersion:
@ -412,7 +437,7 @@ def decryptAndCheckPubkeyPayload(payload, address):
print 'Pubkey decryption was UNsuccessful due to stream number mismatch. This shouldn\'t have happened.'
return 'failed'
readPosition += varintLength
signedData = payload[:readPosition] # Some of the signed data is not encrypted so let's keep it for now.
signedData = payload[8:readPosition] # Some of the signed data is not encrypted so let's keep it for now.
toTag = payload[readPosition:readPosition+32]
readPosition += 32 #for the tag
encryptedData = payload[readPosition:]
@ -431,7 +456,7 @@ def decryptAndCheckPubkeyPayload(payload, address):
readPosition = 4 # bypass the behavior bitfield
publicSigningKey = '\x04' + decryptedData[readPosition:readPosition + 64]
# Is it possible for a public key to be invalid such that trying to
# encrypt or sign with it will cause an error? If it is, we should
# encrypt or check a sig with it will cause an error? If it is, we should
# probably test these keys here.
readPosition += 64
publicEncryptionKey = '\x04' + decryptedData[readPosition:readPosition + 64]
@ -476,5 +501,264 @@ def decryptAndCheckPubkeyPayload(payload, address):
Peer = collections.namedtuple('Peer', ['host', 'port'])
def checkAndShareMsgWithPeers(data):
# Let us check to make sure that the proof of work is sufficient.
if not isProofOfWorkSufficient(data):
print 'Proof of work in msg message insufficient.'
return
readPosition = 8
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
# This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0:
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
readPosition += 8
else:
readPosition += 4
streamNumberAsClaimedByMsg, streamNumberAsClaimedByMsgLength = decodeVarint(
data[readPosition:readPosition + 9])
if not streamNumberAsClaimedByMsg in streamsInWhichIAmParticipating:
print 'The streamNumber', streamNumberAsClaimedByMsg, 'isn\'t one we are interested in.'
return
readPosition += streamNumberAsClaimedByMsgLength
inventoryHash = calculateInventoryHash(data)
shared.numberOfInventoryLookupsPerformed += 1
inventoryLock.acquire()
if inventoryHash in inventory:
print 'We have already received this msg message. Ignoring.'
inventoryLock.release()
return
elif isInSqlInventory(inventoryHash):
print 'We have already received this msg message (it is stored on disk in the SQL inventory). Ignoring it.'
inventoryLock.release()
return
# This msg message is valid. Let's let our peers know about it.
objectType = 'msg'
inventory[inventoryHash] = (
objectType, streamNumberAsClaimedByMsg, data, embeddedTime,'')
inventorySets[streamNumberAsClaimedByMsg].add(inventoryHash)
inventoryLock.release()
with printLock:
print 'advertising inv with hash:', inventoryHash.encode('hex')
broadcastToSendDataQueues((streamNumberAsClaimedByMsg, 'advertiseobject', inventoryHash))
# Now let's enqueue it to be processed ourselves.
# If we already have too much data in the queue to be processed, just sleep for now.
while shared.objectProcessorQueueSize > 120000000:
time.sleep(2)
with shared.objectProcessorQueueSizeLock:
shared.objectProcessorQueueSize += len(data)
objectProcessorQueue.put((objectType,data))
def checkAndSharegetpubkeyWithPeers(data):
if not isProofOfWorkSufficient(data):
print 'Proof of work in getpubkey message insufficient.'
return
if len(data) < 34:
print 'getpubkey message doesn\'t contain enough data. Ignoring.'
return
readPosition = 8 # bypass the nonce
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
# This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0:
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
readPosition += 8
else:
readPosition += 4
if embeddedTime > int(time.time()) + 10800:
print 'The time in this getpubkey message is too new. Ignoring it. Time:', embeddedTime
return
if embeddedTime < int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept:
print 'The time in this getpubkey message is too old. Ignoring it. Time:', embeddedTime
return
requestedAddressVersionNumber, addressVersionLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += addressVersionLength
streamNumber, streamNumberLength = decodeVarint(
data[readPosition:readPosition + 10])
if not streamNumber in streamsInWhichIAmParticipating:
print 'The streamNumber', streamNumber, 'isn\'t one we are interested in.'
return
readPosition += streamNumberLength
shared.numberOfInventoryLookupsPerformed += 1
inventoryHash = calculateInventoryHash(data)
inventoryLock.acquire()
if inventoryHash in inventory:
print 'We have already received this getpubkey request. Ignoring it.'
inventoryLock.release()
return
elif isInSqlInventory(inventoryHash):
print 'We have already received this getpubkey request (it is stored on disk in the SQL inventory). Ignoring it.'
inventoryLock.release()
return
objectType = 'getpubkey'
inventory[inventoryHash] = (
objectType, streamNumber, data, embeddedTime,'')
inventorySets[streamNumber].add(inventoryHash)
inventoryLock.release()
# This getpubkey request is valid. Forward to peers.
with printLock:
print 'advertising inv with hash:', inventoryHash.encode('hex')
broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
# Now let's queue it to be processed ourselves.
# If we already have too much data in the queue to be processed, just sleep for now.
while shared.objectProcessorQueueSize > 120000000:
time.sleep(2)
with shared.objectProcessorQueueSizeLock:
shared.objectProcessorQueueSize += len(data)
objectProcessorQueue.put((objectType,data))
def checkAndSharePubkeyWithPeers(data):
if len(data) < 146 or len(data) > 420: # sanity check
return
# Let us make sure that the proof of work is sufficient.
if not isProofOfWorkSufficient(data):
print 'Proof of work in pubkey message insufficient.'
return
readPosition = 8 # for the nonce
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
# This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0:
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
readPosition += 8
else:
readPosition += 4
if embeddedTime < int(time.time()) - lengthOfTimeToHoldOnToAllPubkeys:
with printLock:
print 'The embedded time in this pubkey message is too old. Ignoring. Embedded time is:', embeddedTime
return
if embeddedTime > int(time.time()) + 10800:
with printLock:
print '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])
readPosition += varintLength
streamNumber, varintLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += varintLength
if not streamNumber in streamsInWhichIAmParticipating:
print 'The streamNumber', streamNumber, 'isn\'t one we are interested in.'
return
if addressVersion >= 4:
tag = data[readPosition:readPosition + 32]
print 'tag in received pubkey is:', tag.encode('hex')
else:
tag = ''
shared.numberOfInventoryLookupsPerformed += 1
inventoryHash = calculateInventoryHash(data)
inventoryLock.acquire()
if inventoryHash in inventory:
print 'We have already received this pubkey. Ignoring it.'
inventoryLock.release()
return
elif isInSqlInventory(inventoryHash):
print 'We have already received this pubkey (it is stored on disk in the SQL inventory). Ignoring it.'
inventoryLock.release()
return
objectType = 'pubkey'
inventory[inventoryHash] = (
objectType, streamNumber, data, embeddedTime, tag)
inventorySets[streamNumber].add(inventoryHash)
inventoryLock.release()
# This object is valid. Forward it to peers.
with printLock:
print 'advertising inv with hash:', inventoryHash.encode('hex')
broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
# Now let's queue it to be processed ourselves.
# If we already have too much data in the queue to be processed, just sleep for now.
while shared.objectProcessorQueueSize > 120000000:
time.sleep(2)
with shared.objectProcessorQueueSizeLock:
shared.objectProcessorQueueSize += len(data)
objectProcessorQueue.put((objectType,data))
def checkAndShareBroadcastWithPeers(data):
# Let us verify that the proof of work is sufficient.
if not isProofOfWorkSufficient(data):
print 'Proof of work in broadcast message insufficient.'
return
readPosition = 8 # bypass the nonce
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
# This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0:
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
readPosition += 8
else:
readPosition += 4
if embeddedTime > (int(time.time()) + 10800): # prevent funny business
print '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):
print 'The embedded time in this broadcast message is too old. Ignoring message.'
return
if len(data) < 180:
print 'The payload length of this broadcast packet is unreasonably low. Someone is probably trying funny business. Ignoring message.'
return
broadcastVersion, broadcastVersionLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += broadcastVersionLength
if broadcastVersion >= 2:
streamNumber, streamNumberLength = decodeVarint(data[readPosition:readPosition + 10])
readPosition += streamNumberLength
if not streamNumber in streamsInWhichIAmParticipating:
print 'The streamNumber', streamNumber, 'isn\'t one we are interested in.'
return
if broadcastVersion >= 3:
tag = data[readPosition:readPosition+32]
print 'debugging. in broadcast, tag is:', tag.encode('hex')
else:
tag = ''
shared.numberOfInventoryLookupsPerformed += 1
inventoryLock.acquire()
inventoryHash = calculateInventoryHash(data)
if inventoryHash in inventory:
print 'We have already received this broadcast object. Ignoring.'
inventoryLock.release()
return
elif isInSqlInventory(inventoryHash):
print 'We have already received this broadcast object (it is stored on disk in the SQL inventory). Ignoring it.'
inventoryLock.release()
return
# It is valid. Let's let our peers know about it.
objectType = 'broadcast'
inventory[inventoryHash] = (
objectType, streamNumber, data, embeddedTime, tag)
inventorySets[streamNumber].add(inventoryHash)
inventoryLock.release()
# This object is valid. Forward it to peers.
with printLock:
print 'advertising inv with hash:', inventoryHash.encode('hex')
broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
# Now let's queue it to be processed ourselves.
# If we already have too much data in the queue to be processed, just sleep for now.
while shared.objectProcessorQueueSize > 120000000:
time.sleep(2)
with shared.objectProcessorQueueSizeLock:
shared.objectProcessorQueueSize += len(data)
objectProcessorQueue.put((objectType,data))
helper_startup.loadConfig()
from debug import logger