Continued daemon mode implementation

This commit is contained in:
Jonathan Warren 2013-05-02 11:53:54 -04:00
parent 08dad3e33d
commit 0bc4712063
4 changed files with 2991 additions and 2943 deletions

View File

@ -2,6 +2,8 @@ import hashlib
from struct import *
from pyelliptic import arithmetic
#There is another copy of this function in Bitmessagemain.py
def convertIntToString(n):
a = __builtins__.hex(n)

View File

@ -18,28 +18,12 @@ useVeryEasyProofOfWorkForTesting = False #If you set this to True while on the n
encryptedBroadcastSwitchoverTime = 1369735200
import sys
import ConfigParser
try:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
except Exception, err:
print 'PyBitmessage requires PyQt. You can download it from http://www.riverbankcomputing.com/software/pyqt/download or by searching Google for \'PyQt Download\' (without quotes).'
print 'Error message:', err
sys.exit()
from bitmessageui import *
import ConfigParser
from newaddressdialog import *
from newsubscriptiondialog import *
from regenerateaddresses import *
from specialaddressbehavior import *
from settings import *
from about import *
from help import *
from iconglossary import *
from addresses import *
import Queue
from addresses import *
#from shared import *
import shared
from defaultKnownNodes import *
import time
import socket
@ -49,9 +33,8 @@ from struct import *
import pickle
import random
import sqlite3
import threading #used for the locks, not for the threads
import threading
from time import strftime, localtime, gmtime
import os
import shutil #used for moving the messages.dat file
import string
import socks
@ -65,14 +48,6 @@ from SimpleXMLRPCServer import *
import json
from subprocess import call #used when the API must execute an outside program
class iconGlossaryDialog(QtGui.QDialog):
def __init__(self,parent):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_iconGlossaryDialog()
self.ui.setupUi(self)
self.parent = parent
self.ui.labelPortNumber.setText('You are using TCP port ' + str(config.getint('bitmessagesettings', 'port')) + '. (This can be changed in the settings).')
QtGui.QWidget.resize(self,QtGui.QWidget.sizeHint(self))
#For each stream to which we connect, several outgoingSynSender threads will exist and will collectively create 8 connections with peers.
class outgoingSynSender(threading.Thread):
@ -86,16 +61,16 @@ class outgoingSynSender(threading.Thread):
time.sleep(1)
global alreadyAttemptedConnectionsListResetTime
while True:
time.sleep(999999)#I sometimes use this to prevent connections for testing.
#time.sleep(999999)#I sometimes use this to prevent connections for testing.
if len(selfInitiatedConnections[self.streamNumber]) < 8: #maximum number of outgoing connections = 8
random.seed()
HOST, = random.sample(knownNodes[self.streamNumber], 1)
HOST, = random.sample(shared.knownNodes[self.streamNumber], 1)
alreadyAttemptedConnectionsListLock.acquire()
while HOST in alreadyAttemptedConnectionsList or HOST in connectedHostsList:
alreadyAttemptedConnectionsListLock.release()
#print 'choosing new sample'
random.seed()
HOST, = random.sample(knownNodes[self.streamNumber], 1)
HOST, = random.sample(shared.knownNodes[self.streamNumber], 1)
time.sleep(1)
#Clear out the alreadyAttemptedConnectionsList every half hour so that this program will again attempt a connection to any nodes, even ones it has already tried.
if (time.time() - alreadyAttemptedConnectionsListResetTime) > 1800:
@ -104,43 +79,43 @@ class outgoingSynSender(threading.Thread):
alreadyAttemptedConnectionsListLock.acquire()
alreadyAttemptedConnectionsList[HOST] = 0
alreadyAttemptedConnectionsListLock.release()
PORT, timeNodeLastSeen = knownNodes[self.streamNumber][HOST]
PORT, timeNodeLastSeen = shared.knownNodes[self.streamNumber][HOST]
sock = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM)
#This option apparently avoids the TIME_WAIT state so that we can rebind faster
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.settimeout(20)
if config.get('bitmessagesettings', 'socksproxytype') == 'none' and verbose >= 2:
printLock.acquire()
if shared.config.get('bitmessagesettings', 'socksproxytype') == 'none' and verbose >= 2:
shared.printLock.acquire()
print 'Trying an outgoing connection to', HOST, ':', PORT
printLock.release()
shared.printLock.release()
#sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
elif config.get('bitmessagesettings', 'socksproxytype') == 'SOCKS4a':
elif shared.config.get('bitmessagesettings', 'socksproxytype') == 'SOCKS4a':
if verbose >= 2:
printLock.acquire()
shared.printLock.acquire()
print '(Using SOCKS4a) Trying an outgoing connection to', HOST, ':', PORT
printLock.release()
shared.printLock.release()
proxytype = socks.PROXY_TYPE_SOCKS4
sockshostname = config.get('bitmessagesettings', 'sockshostname')
socksport = config.getint('bitmessagesettings', 'socksport')
sockshostname = shared.config.get('bitmessagesettings', 'sockshostname')
socksport = shared.config.getint('bitmessagesettings', 'socksport')
rdns = True #Do domain name lookups through the proxy; though this setting doesn't really matter since we won't be doing any domain name lookups anyway.
if config.getboolean('bitmessagesettings', 'socksauthentication'):
socksusername = config.get('bitmessagesettings', 'socksusername')
sockspassword = config.get('bitmessagesettings', 'sockspassword')
if shared.config.getboolean('bitmessagesettings', 'socksauthentication'):
socksusername = shared.config.get('bitmessagesettings', 'socksusername')
sockspassword = shared.config.get('bitmessagesettings', 'sockspassword')
sock.setproxy(proxytype, sockshostname, socksport, rdns, socksusername, sockspassword)
else:
sock.setproxy(proxytype, sockshostname, socksport, rdns)
elif config.get('bitmessagesettings', 'socksproxytype') == 'SOCKS5':
elif shared.config.get('bitmessagesettings', 'socksproxytype') == 'SOCKS5':
if verbose >= 2:
printLock.acquire()
shared.printLock.acquire()
print '(Using SOCKS5) Trying an outgoing connection to', HOST, ':', PORT
printLock.release()
shared.printLock.release()
proxytype = socks.PROXY_TYPE_SOCKS5
sockshostname = config.get('bitmessagesettings', 'sockshostname')
socksport = config.getint('bitmessagesettings', 'socksport')
sockshostname = shared.config.get('bitmessagesettings', 'sockshostname')
socksport = shared.config.getint('bitmessagesettings', 'socksport')
rdns = True #Do domain name lookups through the proxy; though this setting doesn't really matter since we won't be doing any domain name lookups anyway.
if config.getboolean('bitmessagesettings', 'socksauthentication'):
socksusername = config.get('bitmessagesettings', 'socksusername')
sockspassword = config.get('bitmessagesettings', 'sockspassword')
if shared.config.getboolean('bitmessagesettings', 'socksauthentication'):
socksusername = shared.config.get('bitmessagesettings', 'socksusername')
sockspassword = shared.config.get('bitmessagesettings', 'sockspassword')
sock.setproxy(proxytype, sockshostname, socksport, rdns, socksusername, sockspassword)
else:
sock.setproxy(proxytype, sockshostname, socksport, rdns)
@ -153,9 +128,9 @@ class outgoingSynSender(threading.Thread):
objectsOfWhichThisRemoteNodeIsAlreadyAware = {}
rd.setup(sock,HOST,PORT,self.streamNumber,objectsOfWhichThisRemoteNodeIsAlreadyAware)
rd.start()
printLock.acquire()
shared.printLock.acquire()
print self, 'connected to', HOST, 'during an outgoing attempt.'
printLock.release()
shared.printLock.release()
sd = sendDataThread()
sd.setup(sock,HOST,PORT,self.streamNumber,objectsOfWhichThisRemoteNodeIsAlreadyAware)
@ -164,18 +139,18 @@ class outgoingSynSender(threading.Thread):
except socks.GeneralProxyError, err:
if verbose >= 2:
printLock.acquire()
shared.printLock.acquire()
print 'Could NOT connect to', HOST, 'during outgoing attempt.', err
printLock.release()
PORT, timeLastSeen = knownNodes[self.streamNumber][HOST]
if (int(time.time())-timeLastSeen) > 172800 and len(knownNodes[self.streamNumber]) > 1000: # for nodes older than 48 hours old if we have more than 1000 hosts in our list, delete from the knownNodes data-structure.
knownNodesLock.acquire()
del knownNodes[self.streamNumber][HOST]
knownNodesLock.release()
print 'deleting ', HOST, 'from knownNodes because it is more than 48 hours old and we could not connect to it.'
shared.printLock.release()
PORT, timeLastSeen = shared.knownNodes[self.streamNumber][HOST]
if (int(time.time())-timeLastSeen) > 172800 and len(shared.knownNodes[self.streamNumber]) > 1000: # for nodes older than 48 hours old if we have more than 1000 hosts in our list, delete from the shared.knownNodes data-structure.
shared.knownNodesLock.acquire()
del shared.knownNodes[self.streamNumber][HOST]
shared.knownNodesLock.release()
print 'deleting ', HOST, 'from shared.knownNodes because it is more than 48 hours old and we could not connect to it.'
except socks.Socks5AuthError, err:
#self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),"SOCKS5 Authentication problem: "+str(err))
UISignalQueue.put(('updateStatusBar',"SOCKS5 Authentication problem: "+str(err)))
shared.UISignalQueue.put(('updateStatusBar',"SOCKS5 Authentication problem: "+str(err)))
except socks.Socks5Error, err:
pass
print 'SOCKS5 error. (It is possible that the server wants authentication).)' ,str(err)
@ -184,19 +159,19 @@ class outgoingSynSender(threading.Thread):
print 'Socks4Error:', err
#self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),"SOCKS4 error: "+str(err))
except socket.error, err:
if config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS':
if shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS':
print 'Bitmessage MIGHT be having trouble connecting to the SOCKS server. '+str(err)
#self.emit(SIGNAL("updateStatusBar(PyQt_PyObject)"),"Problem: Bitmessage can not connect to the SOCKS server. "+str(err))
else:
if verbose >= 1:
printLock.acquire()
shared.printLock.acquire()
print 'Could NOT connect to', HOST, 'during outgoing attempt.', err
printLock.release()
PORT, timeLastSeen = knownNodes[self.streamNumber][HOST]
if (int(time.time())-timeLastSeen) > 172800 and len(knownNodes[self.streamNumber]) > 1000: # for nodes older than 48 hours old if we have more than 1000 hosts in our list, delete from the knownNodes data-structure.
knownNodesLock.acquire()
del knownNodes[self.streamNumber][HOST]
knownNodesLock.release()
shared.printLock.release()
PORT, timeLastSeen = shared.knownNodes[self.streamNumber][HOST]
if (int(time.time())-timeLastSeen) > 172800 and len(shared.knownNodes[self.streamNumber]) > 1000: # for nodes older than 48 hours old if we have more than 1000 hosts in our list, delete from the knownNodes data-structure.
shared.knownNodesLock.acquire()
del shared.knownNodes[self.streamNumber][HOST]
shared.knownNodesLock.release()
print 'deleting ', HOST, 'from knownNodes because it is more than 48 hours old and we could not connect to it.'
except Exception, err:
sys.stderr.write('An exception has occurred in the outgoingSynSender thread that was not caught by other exception types: %s\n' % err)
@ -210,12 +185,14 @@ class singleListener(threading.Thread):
def run(self):
#We don't want to accept incoming connections if the user is using a SOCKS proxy. If they eventually select proxy 'none' then this will start listening for connections.
while config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS':
while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS':
time.sleep(300)
shared.printLock.acquire()
print 'Listening for incoming connections.'
shared.printLock.release()
HOST = '' # Symbolic name meaning all available interfaces
PORT = config.getint('bitmessagesettings', 'port')
PORT = shared.config.getint('bitmessagesettings', 'port')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#This option apparently avoids the TIME_WAIT state so that we can rebind faster
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
@ -225,7 +202,7 @@ class singleListener(threading.Thread):
while True:
#We don't want to accept incoming connections if the user is using a SOCKS proxy. If the user eventually select proxy 'none' then this will start listening for connections.
while config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS':
while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS':
time.sleep(10)
a,(HOST,PORT) = sock.accept()
#Users are finding that if they run more than one node in the same network (thus with the same public IP), they can not connect with the second node. This is because this section of code won't accept the connection from the same IP. This problem will go away when the Bitmessage network grows beyond being tiny but in the mean time I'll comment out this code section.
@ -238,9 +215,9 @@ class singleListener(threading.Thread):
#self.emit(SIGNAL("passObjectThrough(PyQt_PyObject)"),rd)
objectsOfWhichThisRemoteNodeIsAlreadyAware = {}
rd.setup(a,HOST,PORT,-1,objectsOfWhichThisRemoteNodeIsAlreadyAware)
printLock.acquire()
shared.printLock.acquire()
print self, 'connected to', HOST,'during INCOMING request.'
printLock.release()
shared.printLock.release()
rd.start()
sd = sendDataThread()
@ -276,27 +253,27 @@ class receiveDataThread(threading.Thread):
self.objectsOfWhichThisRemoteNodeIsAlreadyAware = objectsOfWhichThisRemoteNodeIsAlreadyAware
def run(self):
printLock.acquire()
shared.printLock.acquire()
print 'ID of the receiveDataThread is', str(id(self))+'. The size of the connectedHostsList is now', len(connectedHostsList)
printLock.release()
shared.printLock.release()
while True:
try:
self.data += self.sock.recv(4096)
except socket.timeout:
printLock.acquire()
shared.printLock.acquire()
print 'Timeout occurred waiting for data from', self.HOST + '. Closing receiveData thread. (ID:',str(id(self))+ ')'
printLock.release()
shared.printLock.release()
break
except Exception, err:
printLock.acquire()
shared.printLock.acquire()
print 'sock.recv error. Closing receiveData thread (HOST:', self.HOST, 'ID:',str(id(self))+ ').', err
printLock.release()
shared.printLock.release()
break
#print 'Received', repr(self.data)
if self.data == "":
printLock.acquire()
shared.printLock.acquire()
print 'Connection to', self.HOST, 'closed. Closing receiveData thread. (ID:',str(id(self))+ ')'
printLock.release()
shared.printLock.release()
break
else:
self.processData()
@ -311,43 +288,43 @@ class receiveDataThread(threading.Thread):
try:
del selfInitiatedConnections[self.streamNumber][self]
printLock.acquire()
shared.printLock.acquire()
print 'removed self (a receiveDataThread) from selfInitiatedConnections'
printLock.release()
shared.printLock.release()
except:
pass
broadcastToSendDataQueues((0, 'shutdown', self.HOST))
shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST))
if self.connectionIsOrWasFullyEstablished: #We don't want to decrement the number of connections and show the result if we never incremented it in the first place (which we only do if the connection is fully established- meaning that both nodes accepted each other's version packets.)
connectionsCountLock.acquire()
connectionsCount[self.streamNumber] -= 1
#self.emit(SIGNAL("updateNetworkStatusTab(PyQt_PyObject,PyQt_PyObject)"),self.streamNumber,connectionsCount[self.streamNumber])
UISignalQueue.put(('updateNetworkStatusTab',(self.streamNumber,connectionsCount[self.streamNumber])))
printLock.acquire()
shared.UISignalQueue.put(('updateNetworkStatusTab',(self.streamNumber,connectionsCount[self.streamNumber])))
shared.printLock.acquire()
print 'Updating network status tab with current connections count:', connectionsCount[self.streamNumber]
printLock.release()
shared.printLock.release()
connectionsCountLock.release()
try:
del connectedHostsList[self.HOST]
except Exception, err:
print 'Could not delete', self.HOST, 'from connectedHostsList.', err
printLock.acquire()
shared.printLock.acquire()
print 'The size of the connectedHostsList is now:', len(connectedHostsList)
printLock.release()
shared.printLock.release()
def processData(self):
global verbose
#if verbose >= 3:
#printLock.acquire()
#shared.printLock.acquire()
#print 'self.data is currently ', repr(self.data)
#printLock.release()
#shared.printLock.release()
if len(self.data) < 20: #if so little of the data has arrived that we can't even unpack the payload length
pass
elif self.data[0:4] != '\xe9\xbe\xb4\xd9':
if verbose >= 1:
printLock.acquire()
shared.printLock.acquire()
sys.stderr.write('The magic bytes were not correct. First 40 bytes of data: %s\n' % repr(self.data[0:40]))
print 'self.data:', self.data.encode('hex')
printLock.release()
shared.printLock.release()
self.data = ""
else:
self.payloadLength, = unpack('>L',self.data[16:20])
@ -356,14 +333,14 @@ class receiveDataThread(threading.Thread):
#print 'message checksum is correct'
#The time we've last seen this node is obviously right now since we just received valid data from it. So update the knownNodes list so that other peers can be made aware of its existance.
if self.initiatedConnection: #The remote port is only something we should share with others if it is the remote node's incoming port (rather than some random operating-system-assigned outgoing port).
knownNodesLock.acquire()
knownNodes[self.streamNumber][self.HOST] = (self.PORT,int(time.time()))
knownNodesLock.release()
shared.knownNodesLock.acquire()
shared.knownNodes[self.streamNumber][self.HOST] = (self.PORT,int(time.time()))
shared.knownNodesLock.release()
if self.payloadLength <= 180000000: #If the size of the message is greater than 180MB, ignore it. (I get memory errors when processing messages much larger than this though it is concievable that this value will have to be lowered if some systems are less tolarant of large messages.)
remoteCommand = self.data[4:16]
printLock.acquire()
shared.printLock.acquire()
print 'remoteCommand', repr(remoteCommand.replace('\x00','')), ' from', self.HOST
printLock.release()
shared.printLock.release()
if remoteCommand == 'version\x00\x00\x00\x00\x00':
self.recversion(self.data[24:self.payloadLength+24])
elif remoteCommand == 'verack\x00\x00\x00\x00\x00\x00':
@ -398,33 +375,33 @@ class receiveDataThread(threading.Thread):
while len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) > 0:
random.seed()
objectHash, = random.sample(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave, 1)
if objectHash in inventory:
printLock.acquire()
if objectHash in shared.inventory:
shared.printLock.acquire()
print 'Inventory (in memory) already has object listed in inv message.'
printLock.release()
shared.printLock.release()
del self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[objectHash]
elif isInSqlInventory(objectHash):
if verbose >= 3:
printLock.acquire()
shared.printLock.acquire()
print 'Inventory (SQL on disk) already has object listed in inv message.'
printLock.release()
shared.printLock.release()
del self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[objectHash]
else:
self.sendgetdata(objectHash)
del self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[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.
if len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) == 0:
printLock.acquire()
shared.printLock.acquire()
print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave)
printLock.release()
shared.printLock.release()
break
if len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) == 0:
printLock.acquire()
shared.printLock.acquire()
print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave)
printLock.release()
shared.printLock.release()
if len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) > 0:
printLock.acquire()
shared.printLock.acquire()
print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave)
printLock.release()
shared.printLock.release()
if len(self.ackDataThatWeHaveYetToSend) > 0:
self.data = self.ackDataThatWeHaveYetToSend.pop()
self.processData()
@ -456,30 +433,30 @@ class receiveDataThread(threading.Thread):
self.connectionIsOrWasFullyEstablished = True
if not self.initiatedConnection:
#self.emit(SIGNAL("setStatusIcon(PyQt_PyObject)"),'green')
UISignalQueue.put(('setStatusIcon','green'))
shared.UISignalQueue.put(('setStatusIcon','green'))
#Update the 'Network Status' tab
connectionsCountLock.acquire()
connectionsCount[self.streamNumber] += 1
#self.emit(SIGNAL("updateNetworkStatusTab(PyQt_PyObject,PyQt_PyObject)"),self.streamNumber,connectionsCount[self.streamNumber])
UISignalQueue.put(('updateNetworkStatusTab',(self.streamNumber,connectionsCount[self.streamNumber])))
shared.UISignalQueue.put(('updateNetworkStatusTab',(self.streamNumber,connectionsCount[self.streamNumber])))
connectionsCountLock.release()
remoteNodeIncomingPort, remoteNodeSeenTime = knownNodes[self.streamNumber][self.HOST]
printLock.acquire()
remoteNodeIncomingPort, remoteNodeSeenTime = shared.knownNodes[self.streamNumber][self.HOST]
shared.printLock.acquire()
print 'Connection fully established with', self.HOST, remoteNodeIncomingPort
print 'ConnectionsCount now:', connectionsCount[self.streamNumber]
print 'The size of the connectedHostsList is now', len(connectedHostsList)
print 'The length of sendDataQueues is now:', len(sendDataQueues)
print 'The length of sendDataQueues is now:', len(shared.sendDataQueues)
print 'broadcasting addr from within connectionFullyEstablished function.'
printLock.release()
shared.printLock.release()
self.broadcastaddr([(int(time.time()), self.streamNumber, 1, self.HOST, remoteNodeIncomingPort)]) #This lets all of our peers know about this new node.
self.sendaddr() #This is one large addr message to this one peer.
if not self.initiatedConnection and connectionsCount[self.streamNumber] > 150:
printLock.acquire()
shared.printLock.acquire()
print 'We are connected to too many people. Closing connection.'
printLock.release()
shared.printLock.release()
#self.sock.shutdown(socket.SHUT_RDWR)
#self.sock.close()
broadcastToSendDataQueues((0, 'shutdown', self.HOST))
shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST))
return
self.sendBigInv()
@ -489,32 +466,32 @@ class receiveDataThread(threading.Thread):
return
else:
self.receivedgetbiginv = True
sqlLock.acquire()
shared.sqlLock.acquire()
#Select all hashes which are younger than two days old and in this stream.
t = (int(time.time())-maximumAgeOfObjectsThatIAdvertiseToOthers,int(time.time())-lengthOfTimeToHoldOnToAllPubkeys,self.streamNumber)
sqlSubmitQueue.put('''SELECT hash FROM inventory WHERE ((receivedtime>? and objecttype<>'pubkey') or (receivedtime>? and objecttype='pubkey')) and streamnumber=?''')
sqlSubmitQueue.put(t)
queryreturn = sqlReturnQueue.get()
sqlLock.release()
shared.sqlSubmitQueue.put('''SELECT hash FROM inventory WHERE ((receivedtime>? and objecttype<>'pubkey') or (receivedtime>? and objecttype='pubkey')) and streamnumber=?''')
shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release()
bigInvList = {}
for row in queryreturn:
hash, = row
if hash not in self.objectsOfWhichThisRemoteNodeIsAlreadyAware:
bigInvList[hash] = 0
else:
printLock.acquire()
shared.printLock.acquire()
print 'Not including an object hash in a big inv message because the remote node is already aware of it.'#This line is here to check that this feature is working.
printLock.release()
shared.printLock.release()
#We also have messages in our inventory in memory (which is a python dictionary). Let's fetch those too.
for hash, storedValue in inventory.items():
for hash, storedValue in shared.inventory.items():
if hash not in self.objectsOfWhichThisRemoteNodeIsAlreadyAware:
objectType, streamNumber, payload, receivedTime = storedValue
if streamNumber == self.streamNumber and receivedTime > int(time.time())-maximumAgeOfObjectsThatIAdvertiseToOthers:
bigInvList[hash] = 0
else:
printLock.acquire()
shared.printLock.acquire()
print 'Not including an object hash in a big inv message because the remote node is already aware of it.'#This line is here to check that this feature is working.
printLock.release()
shared.printLock.release()
numberOfObjectsInInvMessage = 0
payload = ''
#Now let us start appending all of these hashes together. They will be sent out in a big inv message to our new peer.
@ -535,9 +512,9 @@ class receiveDataThread(threading.Thread):
headerData += 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00'
headerData += pack('>L',len(payload))
headerData += hashlib.sha512(payload).digest()[:4]
printLock.acquire()
shared.printLock.acquire()
print 'Sending huge inv message with', numberOfObjects, 'objects to just this one peer'
printLock.release()
shared.printLock.release()
self.sock.sendall(headerData + payload)
#We have received a broadcast message
@ -574,23 +551,23 @@ class receiveDataThread(threading.Thread):
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
inventoryLock.acquire()
shared.inventoryLock.acquire()
self.inventoryHash = calculateInventoryHash(data)
if self.inventoryHash in inventory:
if self.inventoryHash in shared.inventory:
print 'We have already received this broadcast object. Ignoring.'
inventoryLock.release()
shared.inventoryLock.release()
return
elif isInSqlInventory(self.inventoryHash):
print 'We have already received this broadcast object (it is stored on disk in the SQL inventory). Ignoring it.'
inventoryLock.release()
shared.inventoryLock.release()
return
#It is valid so far. Let's let our peers know about it.
objectType = 'broadcast'
inventory[self.inventoryHash] = (objectType, self.streamNumber, data, embeddedTime)
inventoryLock.release()
shared.inventory[self.inventoryHash] = (objectType, self.streamNumber, data, embeddedTime)
shared.inventoryLock.release()
self.broadcastinv(self.inventoryHash)
#self.emit(SIGNAL("incrementNumberOfBroadcastsProcessed()"))
UISignalQueue.put(('incrementNumberOfBroadcastsProcessed','no data'))
shared.UISignalQueue.put(('incrementNumberOfBroadcastsProcessed','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.
@ -608,13 +585,13 @@ class receiveDataThread(threading.Thread):
sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - (time.time()- self.messageProcessingStartTime)
if sleepTime > 0:
printLock.acquire()
shared.printLock.acquire()
print 'Timing attack mitigation: Sleeping for', sleepTime ,'seconds.'
printLock.release()
shared.printLock.release()
time.sleep(sleepTime)
printLock.acquire()
shared.printLock.acquire()
print 'Total message processing time:', time.time()- self.messageProcessingStartTime, 'seconds.'
printLock.release()
shared.printLock.release()
#A broadcast message has a valid time and POW and requires processing. The recbroadcast function calls this one.
def processbroadcast(self,readPosition,data):
@ -641,11 +618,11 @@ class receiveDataThread(threading.Thread):
readPosition += 64
endOfPubkeyPosition = readPosition
sendersHash = data[readPosition:readPosition+20]
if sendersHash not in broadcastSendersForWhichImWatching:
if sendersHash not in shared.broadcastSendersForWhichImWatching:
#Display timing data
printLock.acquire()
shared.printLock.acquire()
print 'Time spent deciding that we are not interested in this v1 broadcast:', time.time()- self.messageProcessingStartTime
printLock.release()
shared.printLock.release()
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
@ -680,18 +657,18 @@ class receiveDataThread(threading.Thread):
#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.)
t = (ripe.digest(),'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF'+'\xFF\xFF\xFF\xFF'+data[beginningOfPubkeyPosition:endOfPubkeyPosition],int(time.time()),'yes')
sqlLock.acquire()
sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''')
sqlSubmitQueue.put(t)
sqlReturnQueue.get()
sqlSubmitQueue.put('commit')
sqlLock.release()
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.
shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''')
shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release()
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.
fromAddress = encodeAddress(sendersAddressVersion,sendersStream,ripe.digest())
printLock.acquire()
shared.printLock.acquire()
print 'fromAddress:', fromAddress
printLock.release()
shared.printLock.release()
if messageEncodingType == 2:
bodyPositionIndex = string.find(message,'\nBody:')
if bodyPositionIndex > 1:
@ -711,34 +688,34 @@ class receiveDataThread(threading.Thread):
toAddress = '[Broadcast subscribers]'
if messageEncodingType <> 0:
sqlLock.acquire()
shared.sqlLock.acquire()
t = (self.inventoryHash,toAddress,fromAddress,subject,int(time.time()),body,'inbox',messageEncodingType,0)
sqlSubmitQueue.put('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''')
sqlSubmitQueue.put(t)
sqlReturnQueue.get()
sqlSubmitQueue.put('commit')
sqlLock.release()
shared.sqlSubmitQueue.put('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''')
shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release()
#self.emit(SIGNAL("displayNewInboxMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),self.inventoryHash,toAddress,fromAddress,subject,body)
UISignalQueue.put(('displayNewInboxMessage',(self.inventoryHash,toAddress,fromAddress,subject,body)))
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 safeConfigGetBoolean('bitmessagesettings','apienabled'):
if shared.safeConfigGetBoolean('bitmessagesettings','apienabled'):
try:
apiNotifyPath = config.get('bitmessagesettings','apinotifypath')
apiNotifyPath = shared.config.get('bitmessagesettings','apinotifypath')
except:
apiNotifyPath = ''
if apiNotifyPath != '':
call([apiNotifyPath, "newBroadcast"])
#Display timing data
printLock.acquire()
shared.printLock.acquire()
print 'Time spent processing this interesting broadcast:', time.time()- self.messageProcessingStartTime
printLock.release()
shared.printLock.release()
if broadcastVersion == 2:
cleartextStreamNumber, cleartextStreamNumberLength = decodeVarint(data[readPosition:readPosition+10])
readPosition += cleartextStreamNumberLength
initialDecryptionSuccessful = False
for key, cryptorObject in MyECSubscriptionCryptorObjects.items():
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.
@ -750,9 +727,9 @@ class receiveDataThread(threading.Thread):
#print 'cryptorObject.decrypt Exception:', err
if not initialDecryptionSuccessful:
#This is not a broadcast I am interested in.
printLock.acquire()
shared.printLock.acquire()
print 'Length of time program spent failing to decrypt this v2 broadcast:', time.time()- self.messageProcessingStartTime, 'seconds.'
printLock.release()
shared.printLock.release()
return
#At this point this is a broadcast I have decrypted and thus am interested in.
signedBroadcastVersion, readPosition = decodeVarint(decryptedData[:10])
@ -812,18 +789,18 @@ class receiveDataThread(threading.Thread):
#Let's store the public key in case we want to reply to this person.
t = (ripe.digest(),'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF'+'\xFF\xFF\xFF\xFF'+decryptedData[beginningOfPubkeyPosition:endOfPubkeyPosition],int(time.time()),'yes')
sqlLock.acquire()
sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''')
sqlSubmitQueue.put(t)
sqlReturnQueue.get()
sqlSubmitQueue.put('commit')
sqlLock.release()
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.
shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''')
shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release()
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.
fromAddress = encodeAddress(sendersAddressVersion,sendersStream,ripe.digest())
printLock.acquire()
shared.printLock.acquire()
print 'fromAddress:', fromAddress
printLock.release()
shared.printLock.release()
if messageEncodingType == 2:
bodyPositionIndex = string.find(message,'\nBody:')
if bodyPositionIndex > 1:
@ -843,29 +820,29 @@ class receiveDataThread(threading.Thread):
toAddress = '[Broadcast subscribers]'
if messageEncodingType <> 0:
sqlLock.acquire()
shared.sqlLock.acquire()
t = (self.inventoryHash,toAddress,fromAddress,subject,int(time.time()),body,'inbox',messageEncodingType,0)
sqlSubmitQueue.put('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''')
sqlSubmitQueue.put(t)
sqlReturnQueue.get()
sqlSubmitQueue.put('commit')
sqlLock.release()
shared.sqlSubmitQueue.put('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''')
shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release()
#self.emit(SIGNAL("displayNewInboxMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),self.inventoryHash,toAddress,fromAddress,subject,body)
UISignalQueue.put(('displayNewInboxMessage',(self.inventoryHash,toAddress,fromAddress,subject,body)))
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 safeConfigGetBoolean('bitmessagesettings','apienabled'):
if shared.safeConfigGetBoolean('bitmessagesettings','apienabled'):
try:
apiNotifyPath = config.get('bitmessagesettings','apinotifypath')
apiNotifyPath = shared.config.get('bitmessagesettings','apinotifypath')
except:
apiNotifyPath = ''
if apiNotifyPath != '':
call([apiNotifyPath, "newBroadcast"])
#Display timing data
printLock.acquire()
shared.printLock.acquire()
print 'Time spent processing this interesting broadcast:', time.time()- self.messageProcessingStartTime
printLock.release()
shared.printLock.release()
#We have received a msg message.
@ -898,22 +875,22 @@ class receiveDataThread(threading.Thread):
return
readPosition += streamNumberAsClaimedByMsgLength
self.inventoryHash = calculateInventoryHash(data)
inventoryLock.acquire()
if self.inventoryHash in inventory:
shared.inventoryLock.acquire()
if self.inventoryHash in shared.inventory:
print 'We have already received this msg message. Ignoring.'
inventoryLock.release()
shared.inventoryLock.release()
return
elif isInSqlInventory(self.inventoryHash):
print 'We have already received this msg message (it is stored on disk in the SQL inventory). Ignoring it.'
inventoryLock.release()
shared.inventoryLock.release()
return
#This msg message is valid. Let's let our peers know about it.
objectType = 'msg'
inventory[self.inventoryHash] = (objectType, self.streamNumber, data, embeddedTime)
inventoryLock.release()
shared.inventory[self.inventoryHash] = (objectType, self.streamNumber, data, embeddedTime)
shared.inventoryLock.release()
self.broadcastinv(self.inventoryHash)
#self.emit(SIGNAL("incrementNumberOfMessagesProcessed()"))
UISignalQueue.put(('incrementNumberOfMessagesProcessed','no data'))
shared.UISignalQueue.put(('incrementNumberOfMessagesProcessed','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.
@ -931,13 +908,13 @@ class receiveDataThread(threading.Thread):
sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - (time.time()- self.messageProcessingStartTime)
if sleepTime > 0:
printLock.acquire()
shared.printLock.acquire()
print 'Timing attack mitigation: Sleeping for', sleepTime ,'seconds.'
printLock.release()
shared.printLock.release()
time.sleep(sleepTime)
printLock.acquire()
shared.printLock.acquire()
print 'Total message processing time:', time.time()- self.messageProcessingStartTime, 'seconds.'
printLock.release()
shared.printLock.release()
#A msg message has a valid time and POW and requires processing. The recmsg function calls this one.
@ -945,28 +922,28 @@ class receiveDataThread(threading.Thread):
initialDecryptionSuccessful = False
#Let's check whether this is a message acknowledgement bound for us.
if encryptedData[readPosition:] in ackdataForWhichImWatching:
printLock.acquire()
shared.printLock.acquire()
print 'This msg IS an acknowledgement bound for me.'
printLock.release()
shared.printLock.release()
del ackdataForWhichImWatching[encryptedData[readPosition:]]
t = ('ackreceived',encryptedData[readPosition:])
sqlLock.acquire()
sqlSubmitQueue.put('UPDATE sent SET status=? WHERE ackdata=?')
sqlSubmitQueue.put(t)
sqlReturnQueue.get()
sqlSubmitQueue.put('commit')
sqlLock.release()
shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('UPDATE sent SET status=? WHERE ackdata=?')
shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release()
#self.emit(SIGNAL("updateSentItemStatusByAckdata(PyQt_PyObject,PyQt_PyObject)"),encryptedData[readPosition:],'Acknowledgement of the message received just now.')
UISignalQueue.put(('updateSentItemStatusByAckdata',(encryptedData[readPosition:],'Acknowledgement of the message received just now.')))
shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(encryptedData[readPosition:],'Acknowledgement of the message received just now.')))
return
else:
printLock.acquire()
shared.printLock.acquire()
print 'This was NOT an acknowledgement bound for me.'
#print 'ackdataForWhichImWatching', ackdataForWhichImWatching
printLock.release()
shared.printLock.release()
#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 myECCryptorObjects.items():
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.
@ -978,12 +955,12 @@ class receiveDataThread(threading.Thread):
#print 'cryptorObject.decrypt Exception:', err
if not initialDecryptionSuccessful:
#This is not a message bound for me.
printLock.acquire()
shared.printLock.acquire()
print 'Length of time program spent failing to decrypt this message:', time.time()- self.messageProcessingStartTime, 'seconds.'
printLock.release()
shared.printLock.release()
else:
#This is a message bound for me.
toAddress = myAddressesByHash[toRipe] #Look up my address based on the RIPE hash.
toAddress = shared.myAddressesByHash[toRipe] #Look up my address based on the RIPE hash.
readPosition = 0
messageVersion, messageVersionLength = decodeVarint(decryptedData[readPosition:readPosition+10])
readPosition += messageVersionLength
@ -1021,12 +998,12 @@ class receiveDataThread(threading.Thread):
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]:
printLock.acquire()
shared.printLock.acquire()
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')
printLock.release()
shared.printLock.release()
return
readPosition += 20
messageEncodingType, messageEncodingTypeLength = decodeVarint(decryptedData[readPosition:readPosition+10])
@ -1050,9 +1027,9 @@ class receiveDataThread(threading.Thread):
except Exception, err:
print 'ECDSA verify failed', err
return
printLock.acquire()
shared.printLock.acquire()
print 'As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person:', calculateBitcoinAddressFromPubkey(pubSigningKey), ' ..and here is the testnet address:',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.'
printLock.release()
shared.printLock.release()
#calculate the fromRipe.
sha = hashlib.new('sha512')
sha.update(pubSigningKey+pubEncryptionKey)
@ -1060,42 +1037,42 @@ class receiveDataThread(threading.Thread):
ripe.update(sha.digest())
#Let's store the public key in case we want to reply to this person.
t = (ripe.digest(),'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF'+'\xFF\xFF\xFF\xFF'+decryptedData[messageVersionLength:endOfThePublicKeyPosition],int(time.time()),'yes')
sqlLock.acquire()
sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''')
sqlSubmitQueue.put(t)
sqlReturnQueue.get()
sqlSubmitQueue.put('commit')
sqlLock.release()
workerQueue.put(('newpubkey',(sendersAddressVersionNumber,sendersStreamNumber,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.
shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''')
shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release()
shared.workerQueue.put(('newpubkey',(sendersAddressVersionNumber,sendersStreamNumber,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.
fromAddress = encodeAddress(sendersAddressVersionNumber,sendersStreamNumber,ripe.digest())
#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 isAddressInMyAddressBookSubscriptionsListOrWhitelist(fromAddress): #If I'm not friendly with this person:
requiredNonceTrialsPerByte = config.getint(toAddress,'noncetrialsperbyte')
requiredPayloadLengthExtraBytes = config.getint(toAddress,'payloadlengthextrabytes')
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 config.get('bitmessagesettings', 'blackwhitelist') == 'black': #If we are using a blacklist
if shared.config.get('bitmessagesettings', 'blackwhitelist') == 'black': #If we are using a blacklist
t = (fromAddress,)
sqlLock.acquire()
sqlSubmitQueue.put('''SELECT label FROM blacklist where address=? and enabled='1' ''')
sqlSubmitQueue.put(t)
queryreturn = sqlReturnQueue.get()
sqlLock.release()
shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''SELECT label FROM blacklist where address=? and enabled='1' ''')
shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release()
if queryreturn != []:
printLock.acquire()
shared.printLock.acquire()
print 'Message ignored because address is in blacklist.'
printLock.release()
shared.printLock.release()
blockMessage = True
else: #We're using a whitelist
t = (fromAddress,)
sqlLock.acquire()
sqlSubmitQueue.put('''SELECT label FROM whitelist where address=? and enabled='1' ''')
sqlSubmitQueue.put(t)
queryreturn = sqlReturnQueue.get()
sqlLock.release()
shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''SELECT label FROM whitelist where address=? and enabled='1' ''')
shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release()
if queryreturn == []:
print 'Message ignored because address not in whitelist.'
blockMessage = True
@ -1103,7 +1080,7 @@ class receiveDataThread(threading.Thread):
print 'fromAddress:', fromAddress
print 'First 150 characters of message:', repr(message[:150])
toLabel = config.get(toAddress, 'label')
toLabel = shared.config.get(toAddress, 'label')
if toLabel == '':
toLabel = addressInKeysFile
@ -1124,29 +1101,29 @@ class receiveDataThread(threading.Thread):
body = 'Unknown encoding type.\n\n' + repr(message)
subject = ''
if messageEncodingType <> 0:
sqlLock.acquire()
shared.sqlLock.acquire()
t = (self.inventoryHash,toAddress,fromAddress,subject,int(time.time()),body,'inbox',messageEncodingType,0)
sqlSubmitQueue.put('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''')
sqlSubmitQueue.put(t)
sqlReturnQueue.get()
sqlSubmitQueue.put('commit')
sqlLock.release()
shared.sqlSubmitQueue.put('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''')
shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release()
#self.emit(SIGNAL("displayNewInboxMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),self.inventoryHash,toAddress,fromAddress,subject,body)
UISignalQueue.put(('displayNewInboxMessage',(self.inventoryHash,toAddress,fromAddress,subject,body)))
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 safeConfigGetBoolean('bitmessagesettings','apienabled'):
if shared.safeConfigGetBoolean('bitmessagesettings','apienabled'):
try:
apiNotifyPath = config.get('bitmessagesettings','apinotifypath')
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 safeConfigGetBoolean(toAddress,'mailinglist'):
if shared.safeConfigGetBoolean(toAddress,'mailinglist'):
try:
mailingListName = config.get(toAddress, 'mailinglistname')
mailingListName = shared.config.get(toAddress, 'mailinglistname')
except:
mailingListName = ''
#Let us send out this message as a broadcast
@ -1157,17 +1134,17 @@ class receiveDataThread(threading.Thread):
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 = ''
sqlLock.acquire()
shared.sqlLock.acquire()
t = ('',toAddress,ripe,fromAddress,subject,message,ackdata,int(time.time()),'broadcastpending',1,1,'sent',2)
sqlSubmitQueue.put('''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)''')
sqlSubmitQueue.put(t)
sqlReturnQueue.get()
sqlSubmitQueue.put('commit')
sqlLock.release()
shared.sqlSubmitQueue.put('''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)''')
shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release()
#self.emit(SIGNAL("displayNewSentMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),toAddress,'[Broadcast subscribers]',fromAddress,subject,message,ackdata)
UISignalQueue.put(('displayNewSentMessage',(toAddress,'[Broadcast subscribers]',fromAddress,subject,message,ackdata)))
workerQueue.put(('sendbroadcast',(fromAddress,subject,message)))
shared.UISignalQueue.put(('displayNewSentMessage',(toAddress,'[Broadcast subscribers]',fromAddress,subject,message,ackdata)))
shared.workerQueue.put(('sendbroadcast',(fromAddress,subject,message)))
if self.isAckDataValid(ackData):
print 'ackData is valid. Will process it.'
@ -1178,10 +1155,10 @@ class receiveDataThread(threading.Thread):
sum = 0
for item in successfullyDecryptMessageTimings:
sum += item
printLock.acquire()
shared.printLock.acquire()
print 'Time to decrypt this message successfully:', timeRequiredToAttemptToDecryptMessage
print 'Average time for all message decryption successes since startup:', sum / len(successfullyDecryptMessageTimings)
printLock.release()
shared.printLock.release()
def isAckDataValid(self,ackData):
if len(ackData) < 24:
@ -1228,14 +1205,14 @@ class receiveDataThread(threading.Thread):
readPosition += 4
if embeddedTime < int(time.time())-lengthOfTimeToHoldOnToAllPubkeys:
printLock.acquire()
shared.printLock.acquire()
print 'The embedded time in this pubkey message is too old. Ignoring. Embedded time is:', embeddedTime
printLock.release()
shared.printLock.release()
return
if embeddedTime > int(time.time()) + 10800:
printLock.acquire()
shared.printLock.acquire()
print 'The embedded time in this pubkey message more than several hours in the future. This is irrational. Ignoring message.'
printLock.release()
shared.printLock.release()
return
addressVersion, varintLength = decodeVarint(data[readPosition:readPosition+10])
readPosition += varintLength
@ -1246,34 +1223,34 @@ class receiveDataThread(threading.Thread):
return
inventoryHash = calculateInventoryHash(data)
inventoryLock.acquire()
if inventoryHash in inventory:
shared.inventoryLock.acquire()
if inventoryHash in shared.inventory:
print 'We have already received this pubkey. Ignoring it.'
inventoryLock.release()
shared.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()
shared.inventoryLock.release()
return
objectType = 'pubkey'
inventory[inventoryHash] = (objectType, self.streamNumber, data, embeddedTime)
inventoryLock.release()
shared.inventory[inventoryHash] = (objectType, self.streamNumber, data, embeddedTime)
shared.inventoryLock.release()
self.broadcastinv(inventoryHash)
#self.emit(SIGNAL("incrementNumberOfPubkeysProcessed()"))
UISignalQueue.put(('incrementNumberOfPubkeysProcessed','no data'))
shared.UISignalQueue.put(('incrementNumberOfPubkeysProcessed','no data'))
self.processpubkey(data)
lengthOfTimeWeShouldUseToProcessThisMessage = .2
sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - (time.time()- self.pubkeyProcessingStartTime)
if sleepTime > 0:
printLock.acquire()
shared.printLock.acquire()
print 'Timing attack mitigation: Sleeping for', sleepTime ,'seconds.'
printLock.release()
shared.printLock.release()
time.sleep(sleepTime)
printLock.acquire()
shared.printLock.acquire()
print 'Total pubkey processing time:', time.time()- self.pubkeyProcessingStartTime, 'seconds.'
printLock.release()
shared.printLock.release()
def processpubkey(self,data):
readPosition = 8 #for the nonce
@ -1287,9 +1264,9 @@ class receiveDataThread(threading.Thread):
print '(Within processpubkey) addressVersion of 0 doesn\'t make sense.'
return
if addressVersion >= 4 or addressVersion == 1:
printLock.acquire()
shared.printLock.acquire()
print 'This version of Bitmessage cannot handle version', addressVersion,'addresses.'
printLock.release()
shared.printLock.release()
return
if addressVersion == 2:
if len(data) < 146: #sanity check. This is the minimum possible length.
@ -1310,39 +1287,39 @@ class receiveDataThread(threading.Thread):
ripeHasher.update(sha.digest())
ripe = ripeHasher.digest()
printLock.acquire()
shared.printLock.acquire()
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')
printLock.release()
shared.printLock.release()
t = (ripe,)
sqlLock.acquire()
sqlSubmitQueue.put('''SELECT usedpersonally FROM pubkeys WHERE hash=? AND usedpersonally='yes' ''')
sqlSubmitQueue.put(t)
queryreturn = sqlReturnQueue.get()
sqlLock.release()
shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''SELECT usedpersonally FROM pubkeys WHERE hash=? AND usedpersonally='yes' ''')
shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release()
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,data,embeddedTime,'yes')
sqlLock.acquire()
sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''')
sqlSubmitQueue.put(t)
sqlReturnQueue.get()
sqlSubmitQueue.put('commit')
sqlLock.release()
workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe)))
shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''')
shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release()
shared.workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe)))
else:
print 'We have NOT used this pubkey personally. Inserting in database.'
t = (ripe,data,embeddedTime,'no') #This will also update the embeddedTime.
sqlLock.acquire()
sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''')
sqlSubmitQueue.put(t)
sqlReturnQueue.get()
sqlSubmitQueue.put('commit')
sqlLock.release()
workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe)))
shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''')
shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release()
shared.workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe)))
if addressVersion == 3:
if len(data) < 170: #sanity check.
print '(within processpubkey) payloadLength less than 170. Sanity check failed.'
@ -1373,38 +1350,38 @@ class receiveDataThread(threading.Thread):
ripeHasher.update(sha.digest())
ripe = ripeHasher.digest()
printLock.acquire()
shared.printLock.acquire()
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')
printLock.release()
shared.printLock.release()
t = (ripe,)
sqlLock.acquire()
sqlSubmitQueue.put('''SELECT usedpersonally FROM pubkeys WHERE hash=? AND usedpersonally='yes' ''')
sqlSubmitQueue.put(t)
queryreturn = sqlReturnQueue.get()
sqlLock.release()
shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''SELECT usedpersonally FROM pubkeys WHERE hash=? AND usedpersonally='yes' ''')
shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release()
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,data,embeddedTime,'yes')
sqlLock.acquire()
sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''')
sqlSubmitQueue.put(t)
sqlReturnQueue.get()
sqlSubmitQueue.put('commit')
sqlLock.release()
shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''')
shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release()
else:
print 'We have NOT used this pubkey personally. Inserting in database.'
t = (ripe,data,embeddedTime,'no') #This will also update the embeddedTime.
sqlLock.acquire()
sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''')
sqlSubmitQueue.put(t)
sqlReturnQueue.get()
sqlSubmitQueue.put('commit')
sqlLock.release()
workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe)))
shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''')
shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release()
shared.workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe)))
#We have received a getpubkey message
@ -1440,19 +1417,19 @@ class receiveDataThread(threading.Thread):
readPosition += streamNumberLength
inventoryHash = calculateInventoryHash(data)
inventoryLock.acquire()
if inventoryHash in inventory:
shared.inventoryLock