autopep8 bitmessagemain.py file + fixed typo

This commit is contained in:
Gatien Bovyn 2013-06-13 20:00:56 +02:00
parent 04c3857c68
commit 63744bfb27

View File

@ -4,7 +4,8 @@
# Distributed under the MIT/X11 software license. See the accompanying # Distributed under the MIT/X11 software license. See the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
#Right now, PyBitmessage only support connecting to stream 1. It doesn't yet contain logic to expand into further streams. # Right now, PyBitmessage only support connecting to stream 1. It doesn't
# yet contain logic to expand into further streams.
# The software version variable is now held in shared.py # The software version variable is now held in shared.py
verbose = 1 verbose = 1
@ -48,8 +49,12 @@ from subprocess import call #used when the API must execute an outside program
import singleton import singleton
import proofofwork import proofofwork
#For each stream to which we connect, several outgoingSynSender threads will exist and will collectively create 8 connections with peers. # For each stream to which we connect, several outgoingSynSender threads
# will exist and will collectively create 8 connections with peers.
class outgoingSynSender(threading.Thread): class outgoingSynSender(threading.Thread):
def __init__(self): def __init__(self):
threading.Thread.__init__(self) threading.Thread.__init__(self)
@ -70,18 +75,24 @@ class outgoingSynSender(threading.Thread):
alreadyAttemptedConnectionsListLock.release() alreadyAttemptedConnectionsListLock.release()
# print 'choosing new sample' # print 'choosing new sample'
random.seed() random.seed()
HOST, = random.sample(shared.knownNodes[self.streamNumber], 1) HOST, = random.sample(shared.knownNodes[
self.streamNumber], 1)
time.sleep(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. # 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: if (time.time() - alreadyAttemptedConnectionsListResetTime) > 1800:
alreadyAttemptedConnectionsList.clear() alreadyAttemptedConnectionsList.clear()
alreadyAttemptedConnectionsListResetTime = int(time.time()) alreadyAttemptedConnectionsListResetTime = int(
time.time())
alreadyAttemptedConnectionsListLock.acquire() alreadyAttemptedConnectionsListLock.acquire()
alreadyAttemptedConnectionsList[HOST] = 0 alreadyAttemptedConnectionsList[HOST] = 0
alreadyAttemptedConnectionsListLock.release() alreadyAttemptedConnectionsListLock.release()
PORT, timeNodeLastSeen = shared.knownNodes[self.streamNumber][HOST] PORT, timeNodeLastSeen = shared.knownNodes[
self.streamNumber][HOST]
sock = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM) sock = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM)
#This option apparently avoids the TIME_WAIT state so that we can rebind faster # This option apparently avoids the TIME_WAIT state so that we
# can rebind faster
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.settimeout(20) sock.settimeout(20)
if shared.config.get('bitmessagesettings', 'socksproxytype') == 'none' and verbose >= 2: if shared.config.get('bitmessagesettings', 'socksproxytype') == 'none' and verbose >= 2:
@ -95,53 +106,68 @@ class outgoingSynSender(threading.Thread):
print '(Using SOCKS4a) Trying an outgoing connection to', HOST, ':', PORT print '(Using SOCKS4a) Trying an outgoing connection to', HOST, ':', PORT
shared.printLock.release() shared.printLock.release()
proxytype = socks.PROXY_TYPE_SOCKS4 proxytype = socks.PROXY_TYPE_SOCKS4
sockshostname = shared.config.get('bitmessagesettings', 'sockshostname') sockshostname = shared.config.get(
socksport = shared.config.getint('bitmessagesettings', 'socksport') '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. rdns = True # Do domain name lookups through the proxy; though this setting doesn't really matter since we won't be doing any domain name lookups anyway.
if shared.config.getboolean('bitmessagesettings', 'socksauthentication'): if shared.config.getboolean('bitmessagesettings', 'socksauthentication'):
socksusername = shared.config.get('bitmessagesettings', 'socksusername') socksusername = shared.config.get(
sockspassword = shared.config.get('bitmessagesettings', 'sockspassword') 'bitmessagesettings', 'socksusername')
sock.setproxy(proxytype, sockshostname, socksport, rdns, socksusername, sockspassword) sockspassword = shared.config.get(
'bitmessagesettings', 'sockspassword')
sock.setproxy(
proxytype, sockshostname, socksport, rdns, socksusername, sockspassword)
else: else:
sock.setproxy(proxytype, sockshostname, socksport, rdns) sock.setproxy(
proxytype, sockshostname, socksport, rdns)
elif shared.config.get('bitmessagesettings', 'socksproxytype') == 'SOCKS5': elif shared.config.get('bitmessagesettings', 'socksproxytype') == 'SOCKS5':
if verbose >= 2: if verbose >= 2:
shared.printLock.acquire() shared.printLock.acquire()
print '(Using SOCKS5) Trying an outgoing connection to', HOST, ':', PORT print '(Using SOCKS5) Trying an outgoing connection to', HOST, ':', PORT
shared.printLock.release() shared.printLock.release()
proxytype = socks.PROXY_TYPE_SOCKS5 proxytype = socks.PROXY_TYPE_SOCKS5
sockshostname = shared.config.get('bitmessagesettings', 'sockshostname') sockshostname = shared.config.get(
socksport = shared.config.getint('bitmessagesettings', 'socksport') '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. rdns = True # Do domain name lookups through the proxy; though this setting doesn't really matter since we won't be doing any domain name lookups anyway.
if shared.config.getboolean('bitmessagesettings', 'socksauthentication'): if shared.config.getboolean('bitmessagesettings', 'socksauthentication'):
socksusername = shared.config.get('bitmessagesettings', 'socksusername') socksusername = shared.config.get(
sockspassword = shared.config.get('bitmessagesettings', 'sockspassword') 'bitmessagesettings', 'socksusername')
sock.setproxy(proxytype, sockshostname, socksport, rdns, socksusername, sockspassword) sockspassword = shared.config.get(
'bitmessagesettings', 'sockspassword')
sock.setproxy(
proxytype, sockshostname, socksport, rdns, socksusername, sockspassword)
else: else:
sock.setproxy(proxytype, sockshostname, socksport, rdns) sock.setproxy(
proxytype, sockshostname, socksport, rdns)
try: try:
sock.connect((HOST, PORT)) sock.connect((HOST, PORT))
rd = receiveDataThread() rd = receiveDataThread()
rd.daemon = True # close the main program even if there are threads left rd.daemon = True # close the main program even if there are threads left
objectsOfWhichThisRemoteNodeIsAlreadyAware = {} objectsOfWhichThisRemoteNodeIsAlreadyAware = {}
rd.setup(sock,HOST,PORT,self.streamNumber,objectsOfWhichThisRemoteNodeIsAlreadyAware) rd.setup(sock, HOST, PORT, self.streamNumber,
objectsOfWhichThisRemoteNodeIsAlreadyAware)
rd.start() rd.start()
shared.printLock.acquire() shared.printLock.acquire()
print self, 'connected to', HOST, 'during an outgoing attempt.' print self, 'connected to', HOST, 'during an outgoing attempt.'
shared.printLock.release() shared.printLock.release()
sd = sendDataThread() sd = sendDataThread()
sd.setup(sock,HOST,PORT,self.streamNumber,objectsOfWhichThisRemoteNodeIsAlreadyAware) sd.setup(sock, HOST, PORT, self.streamNumber,
objectsOfWhichThisRemoteNodeIsAlreadyAware)
sd.start() sd.start()
sd.sendVersionMessage() sd.sendVersionMessage()
except socks.GeneralProxyError, err: except socks.GeneralProxyError as err:
if verbose >= 2: if verbose >= 2:
shared.printLock.acquire() shared.printLock.acquire()
print 'Could NOT connect to', HOST, 'during outgoing attempt.', err print 'Could NOT connect to', HOST, 'during outgoing attempt.', err
shared.printLock.release() shared.printLock.release()
PORT, timeLastSeen = shared.knownNodes[self.streamNumber][HOST] 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. 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() shared.knownNodesLock.acquire()
del shared.knownNodes[self.streamNumber][HOST] del shared.knownNodes[self.streamNumber][HOST]
@ -149,14 +175,15 @@ class outgoingSynSender(threading.Thread):
shared.printLock.acquire() shared.printLock.acquire()
print 'deleting ', HOST, 'from shared.knownNodes because it is more than 48 hours old and we could not connect to it.' print 'deleting ', HOST, 'from shared.knownNodes because it is more than 48 hours old and we could not connect to it.'
shared.printLock.release() shared.printLock.release()
except socks.Socks5AuthError, err: except socks.Socks5AuthError as err:
shared.UISignalQueue.put(('updateStatusBar',"SOCKS5 Authentication problem: "+str(err))) shared.UISignalQueue.put((
except socks.Socks5Error, err: 'updateStatusBar', "SOCKS5 Authentication problem: " + str(err)))
except socks.Socks5Error as err:
pass pass
print 'SOCKS5 error. (It is possible that the server wants authentication).)', str(err) print 'SOCKS5 error. (It is possible that the server wants authentication).)', str(err)
except socks.Socks4Error, err: except socks.Socks4Error as err:
print 'Socks4Error:', err print 'Socks4Error:', err
except socket.error, err: except socket.error as err:
if shared.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) print 'Bitmessage MIGHT be having trouble connecting to the SOCKS server. ' + str(err)
else: else:
@ -164,7 +191,8 @@ class outgoingSynSender(threading.Thread):
shared.printLock.acquire() shared.printLock.acquire()
print 'Could NOT connect to', HOST, 'during outgoing attempt.', err print 'Could NOT connect to', HOST, 'during outgoing attempt.', err
shared.printLock.release() shared.printLock.release()
PORT, timeLastSeen = shared.knownNodes[self.streamNumber][HOST] 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. 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() shared.knownNodesLock.acquire()
del shared.knownNodes[self.streamNumber][HOST] del shared.knownNodes[self.streamNumber][HOST]
@ -172,18 +200,28 @@ class outgoingSynSender(threading.Thread):
shared.printLock.acquire() shared.printLock.acquire()
print 'deleting ', HOST, 'from knownNodes because it is more than 48 hours old and we could not connect to it.' print 'deleting ', HOST, 'from knownNodes because it is more than 48 hours old and we could not connect to it.'
shared.printLock.release() shared.printLock.release()
except Exception, err: except Exception as err:
sys.stderr.write('An exception has occurred in the outgoingSynSender thread that was not caught by other exception types: %s\n' % err) sys.stderr.write(
'An exception has occurred in the outgoingSynSender thread that was not caught by other exception types: %s\n' % err)
time.sleep(0.1) time.sleep(0.1)
#Only one singleListener thread will ever exist. It creates the receiveDataThread and sendDataThread for each incoming connection. Note that it cannot set the stream number because it is not known yet- the other node will have to tell us its stream number in a version message. If we don't care about their stream, we will close the connection (within the recversion function of the recieveData thread) # Only one singleListener thread will ever exist. It creates the
# receiveDataThread and sendDataThread for each incoming connection. Note
# that it cannot set the stream number because it is not known yet- the
# other node will have to tell us its stream number in a version message.
# If we don't care about their stream, we will close the connection
# (within the recversion function of the recieveData thread)
class singleListener(threading.Thread): class singleListener(threading.Thread):
def __init__(self): def __init__(self):
threading.Thread.__init__(self) threading.Thread.__init__(self)
def run(self): 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. # 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 shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS': while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS':
time.sleep(300) time.sleep(300)
@ -193,14 +231,16 @@ class singleListener(threading.Thread):
HOST = '' # Symbolic name meaning all available interfaces HOST = '' # Symbolic name meaning all available interfaces
PORT = shared.config.getint('bitmessagesettings', 'port') PORT = shared.config.getint('bitmessagesettings', 'port')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#This option apparently avoids the TIME_WAIT state so that we can rebind faster # This option apparently avoids the TIME_WAIT state so that we can
# rebind faster
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((HOST, PORT)) sock.bind((HOST, PORT))
sock.listen(2) sock.listen(2)
while True: 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. # 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 shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS': while shared.config.get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS':
time.sleep(10) time.sleep(10)
while len(shared.connectedHostsList) > 220: while len(shared.connectedHostsList) > 220:
@ -210,7 +250,10 @@ class singleListener(threading.Thread):
time.sleep(10) time.sleep(10)
a, (HOST, PORT) = sock.accept() a, (HOST, PORT) = sock.accept()
#The following code will, unfortunately, block an incoming connection if someone else on the same LAN is already connected because the two computers will share the same external IP. This is here to prevent connection flooding. # The following code will, unfortunately, block an incoming
# connection if someone else on the same LAN is already connected
# because the two computers will share the same external IP. This
# is here to prevent connection flooding.
while HOST in shared.connectedHostsList: while HOST in shared.connectedHostsList:
shared.printLock.acquire() shared.printLock.acquire()
print 'We are already connected to', HOST + '. Ignoring connection.' print 'We are already connected to', HOST + '. Ignoring connection.'
@ -221,41 +264,55 @@ class singleListener(threading.Thread):
a.settimeout(20) a.settimeout(20)
sd = sendDataThread() sd = sendDataThread()
sd.setup(a,HOST,PORT,-1,objectsOfWhichThisRemoteNodeIsAlreadyAware) sd.setup(
a, HOST, PORT, -1, objectsOfWhichThisRemoteNodeIsAlreadyAware)
sd.start() sd.start()
rd = receiveDataThread() rd = receiveDataThread()
rd.daemon = True # close the main program even if there are threads left rd.daemon = True # close the main program even if there are threads left
rd.setup(a,HOST,PORT,-1,objectsOfWhichThisRemoteNodeIsAlreadyAware) rd.setup(
a, HOST, PORT, -1, objectsOfWhichThisRemoteNodeIsAlreadyAware)
rd.start() rd.start()
shared.printLock.acquire() shared.printLock.acquire()
print self, 'connected to', HOST, 'during INCOMING request.' print self, 'connected to', HOST, 'during INCOMING request.'
shared.printLock.release() shared.printLock.release()
#This thread is created either by the synSenderThread(for outgoing connections) or the singleListenerThread(for incoming connectiosn). # This thread is created either by the synSenderThread(for outgoing
# connections) or the singleListenerThread(for incoming connectiosn).
class receiveDataThread(threading.Thread): class receiveDataThread(threading.Thread):
def __init__(self): def __init__(self):
threading.Thread.__init__(self) threading.Thread.__init__(self)
self.data = '' self.data = ''
self.verackSent = False self.verackSent = False
self.verackReceived = False self.verackReceived = False
def setup(self,sock,HOST,port,streamNumber,objectsOfWhichThisRemoteNodeIsAlreadyAware): def setup(
self,
sock,
HOST,
port,
streamNumber,
objectsOfWhichThisRemoteNodeIsAlreadyAware):
self.sock = sock self.sock = sock
self.HOST = HOST self.HOST = HOST
self.PORT = port self.PORT = port
self.streamNumber = streamNumber self.streamNumber = streamNumber
self.payloadLength = 0 # This is the protocol payload length thus it doesn't include the 24 byte message header self.payloadLength = 0 # This is the protocol payload length thus it doesn't include the 24 byte message header
self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave = {} self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave = {}
shared.connectedHostsList[self.HOST] = 0 #The very fact that this receiveData thread exists shows that we are connected to the remote host. Let's add it to this list so that an outgoingSynSender thread doesn't try to connect to it. shared.connectedHostsList[
self.HOST] = 0 # The very fact that this receiveData thread exists shows that we are connected to the remote host. Let's add it to this list so that an outgoingSynSender thread doesn't try to connect to it.
self.connectionIsOrWasFullyEstablished = False # set to true after the remote node and I accept each other's version messages. This is needed to allow the user interface to accurately reflect the current number of connections. self.connectionIsOrWasFullyEstablished = False # set to true after the remote node and I accept each other's version messages. This is needed to allow the user interface to accurately reflect the current number of connections.
if self.streamNumber == -1: # This was an incoming connection. Send out a version message if we accept the other node's version message. if self.streamNumber == -1: # This was an incoming connection. Send out a version message if we accept the other node's version message.
self.initiatedConnection = False self.initiatedConnection = False
else: else:
self.initiatedConnection = True self.initiatedConnection = True
selfInitiatedConnections[streamNumber][self] = 0 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.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.objectsOfWhichThisRemoteNodeIsAlreadyAware = objectsOfWhichThisRemoteNodeIsAlreadyAware self.objectsOfWhichThisRemoteNodeIsAlreadyAware = objectsOfWhichThisRemoteNodeIsAlreadyAware
def run(self): def run(self):
@ -270,7 +327,7 @@ class receiveDataThread(threading.Thread):
print 'Timeout occurred waiting for data from', self.HOST + '. Closing receiveData thread. (ID:', str(id(self)) + ')' print 'Timeout occurred waiting for data from', self.HOST + '. Closing receiveData thread. (ID:', str(id(self)) + ')'
shared.printLock.release() shared.printLock.release()
break break
except Exception, err: except Exception as err:
shared.printLock.acquire() shared.printLock.acquire()
print 'sock.recv error. Closing receiveData thread (HOST:', self.HOST, 'ID:', str(id(self)) + ').', err print 'sock.recv error. Closing receiveData thread (HOST:', self.HOST, 'ID:', str(id(self)) + ').', err
shared.printLock.release() shared.printLock.release()
@ -284,9 +341,6 @@ class receiveDataThread(threading.Thread):
else: else:
self.processData() self.processData()
try: try:
del selfInitiatedConnections[self.streamNumber][self] del selfInitiatedConnections[self.streamNumber][self]
shared.printLock.acquire() shared.printLock.acquire()
@ -297,12 +351,13 @@ class receiveDataThread(threading.Thread):
shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST)) shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST))
try: try:
del shared.connectedHostsList[self.HOST] del shared.connectedHostsList[self.HOST]
except Exception, err: except Exception as err:
shared.printLock.acquire() shared.printLock.acquire()
print 'Could not delete', self.HOST, 'from shared.connectedHostsList.', err print 'Could not delete', self.HOST, 'from shared.connectedHostsList.', err
shared.printLock.release() shared.printLock.release()
try: try:
del numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[self.HOST] del numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[
self.HOST]
except: except:
pass pass
shared.UISignalQueue.put(('updateNetworkStatusTab', 'no data')) shared.UISignalQueue.put(('updateNetworkStatusTab', 'no data'))
@ -333,10 +388,13 @@ class receiveDataThread(threading.Thread):
self.data = self.data[self.payloadLength + 24:] self.data = self.data[self.payloadLength + 24:]
self.processData() self.processData()
return return
#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. # 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 and self.connectionIsOrWasFullyEstablished: # 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). if self.initiatedConnection and self.connectionIsOrWasFullyEstablished: # 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).
shared.knownNodesLock.acquire() shared.knownNodesLock.acquire()
shared.knownNodes[self.streamNumber][self.HOST] = (self.PORT,int(time.time())) shared.knownNodes[self.streamNumber][
self.HOST] = (self.PORT, int(time.time()))
shared.knownNodesLock.release() 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.) 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] remoteCommand = self.data[4:16]
@ -368,31 +426,37 @@ class receiveDataThread(threading.Thread):
elif remoteCommand == 'alert\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished: elif remoteCommand == 'alert\x00\x00\x00\x00\x00\x00\x00' and self.connectionIsOrWasFullyEstablished:
pass pass
self.data = self.data[self.payloadLength+24:]#take this message out and then process the next message self.data = self.data[
self.payloadLength + 24:] # take this message out and then process the next message
if self.data == '': if self.data == '':
while len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) > 0: while len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) > 0:
random.seed() random.seed()
objectHash, = random.sample(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave, 1) objectHash, = random.sample(
self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave, 1)
if objectHash in shared.inventory: if objectHash in shared.inventory:
shared.printLock.acquire() shared.printLock.acquire()
print 'Inventory (in memory) already has object listed in inv message.' print 'Inventory (in memory) already has object listed in inv message.'
shared.printLock.release() shared.printLock.release()
del self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[objectHash] del self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[
objectHash]
elif isInSqlInventory(objectHash): elif isInSqlInventory(objectHash):
if verbose >= 3: if verbose >= 3:
shared.printLock.acquire() shared.printLock.acquire()
print 'Inventory (SQL on disk) already has object listed in inv message.' print 'Inventory (SQL on disk) already has object listed in inv message.'
shared.printLock.release() shared.printLock.release()
del self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[objectHash] del self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[
objectHash]
else: else:
self.sendgetdata(objectHash) 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. 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: if len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) == 0:
shared.printLock.acquire() shared.printLock.acquire()
print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave)
shared.printLock.release() shared.printLock.release()
try: try:
del numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[self.HOST] #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. del numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[
self.HOST] # 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.
except: except:
pass pass
break break
@ -401,34 +465,40 @@ class receiveDataThread(threading.Thread):
print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave)
shared.printLock.release() shared.printLock.release()
try: try:
del numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[self.HOST] #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. del numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[
self.HOST] # 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.
except: except:
pass pass
if len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) > 0: if len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) > 0:
shared.printLock.acquire() shared.printLock.acquire()
print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) print '(concerning', self.HOST + ')', 'number of objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave is now', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave)
shared.printLock.release() shared.printLock.release()
numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[self.HOST] = len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) #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. numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[self.HOST] = len(
self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) # 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: if len(self.ackDataThatWeHaveYetToSend) > 0:
self.data = self.ackDataThatWeHaveYetToSend.pop() self.data = self.ackDataThatWeHaveYetToSend.pop()
self.processData() self.processData()
def isProofOfWorkSufficient(
self,
def isProofOfWorkSufficient(self,data,nonceTrialsPerByte=0,payloadLengthExtraBytes=0): data,
nonceTrialsPerByte=0,
payloadLengthExtraBytes=0):
if nonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte: if nonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte:
nonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte nonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte
if payloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes: if payloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes:
payloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes payloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes
POW, = unpack('>Q',hashlib.sha512(hashlib.sha512(data[:8]+ hashlib.sha512(data[8:]).digest()).digest()).digest()[0:8]) POW, = unpack('>Q', hashlib.sha512(hashlib.sha512(data[
:8] + hashlib.sha512(data[8:]).digest()).digest()).digest()[0:8])
# print 'POW:', POW # print 'POW:', POW
return POW <= 2 ** 64 / ((len(data) + payloadLengthExtraBytes) * (nonceTrialsPerByte)) return POW <= 2 ** 64 / ((len(data) + payloadLengthExtraBytes) * (nonceTrialsPerByte))
def sendpong(self): def sendpong(self):
print 'Sending pong' print 'Sending pong'
try: try:
self.sock.sendall('\xE9\xBE\xB4\xD9\x70\x6F\x6E\x67\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xcf\x83\xe1\x35') self.sock.sendall(
except Exception, err: '\xE9\xBE\xB4\xD9\x70\x6F\x6E\x67\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xcf\x83\xe1\x35')
except Exception as err:
# if not 'Bad file descriptor' in err: # if not 'Bad file descriptor' in err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('sock.sendall error: %s\n' % err) sys.stderr.write('sock.sendall error: %s\n' % err)
@ -437,7 +507,7 @@ class receiveDataThread(threading.Thread):
def recverack(self): def recverack(self):
print 'verack received' print 'verack received'
self.verackReceived = True self.verackReceived = True
if self.verackSent == True: if self.verackSent:
# We have thus both sent and received a verack. # We have thus both sent and received a verack.
self.connectionFullyEstablished() self.connectionFullyEstablished()
@ -445,16 +515,19 @@ class receiveDataThread(threading.Thread):
self.connectionIsOrWasFullyEstablished = True self.connectionIsOrWasFullyEstablished = True
if not self.initiatedConnection: if not self.initiatedConnection:
shared.UISignalQueue.put(('setStatusIcon', 'green')) shared.UISignalQueue.put(('setStatusIcon', 'green'))
self.sock.settimeout(600) #We'll send out a pong every 5 minutes to make sure the connection stays alive if there has been no other traffic to send lately. self.sock.settimeout(
600) # We'll send out a pong every 5 minutes to make sure the connection stays alive if there has been no other traffic to send lately.
shared.UISignalQueue.put(('updateNetworkStatusTab', 'no data')) shared.UISignalQueue.put(('updateNetworkStatusTab', 'no data'))
remoteNodeIncomingPort, remoteNodeSeenTime = shared.knownNodes[self.streamNumber][self.HOST] remoteNodeIncomingPort, remoteNodeSeenTime = shared.knownNodes[
self.streamNumber][self.HOST]
shared.printLock.acquire() shared.printLock.acquire()
print 'Connection fully established with', self.HOST, remoteNodeIncomingPort print 'Connection fully established with', self.HOST, remoteNodeIncomingPort
print 'The size of the connectedHostsList is now', len(shared.connectedHostsList) print 'The size of the connectedHostsList is now', len(shared.connectedHostsList)
print 'The length of sendDataQueues is now:', len(shared.sendDataQueues) print 'The length of sendDataQueues is now:', len(shared.sendDataQueues)
print 'broadcasting addr from within connectionFullyEstablished function.' print 'broadcasting addr from within connectionFullyEstablished function.'
shared.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.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. self.sendaddr() # This is one large addr message to this one peer.
if not self.initiatedConnection and len(shared.connectedHostsList) > 200: if not self.initiatedConnection and len(shared.connectedHostsList) > 200:
shared.printLock.acquire() shared.printLock.acquire()
@ -466,9 +539,12 @@ class receiveDataThread(threading.Thread):
def sendBigInv(self): def sendBigInv(self):
shared.sqlLock.acquire() shared.sqlLock.acquire()
#Select all hashes which are younger than two days old and in this stream. # Select all hashes which are younger than two days old and in this
t = (int(time.time())-maximumAgeOfObjectsThatIAdvertiseToOthers,int(time.time())-lengthOfTimeToHoldOnToAllPubkeys,self.streamNumber) # stream.
shared.sqlSubmitQueue.put('''SELECT hash FROM inventory WHERE ((receivedtime>? and objecttype<>'pubkey') or (receivedtime>? and objecttype='pubkey')) and streamnumber=?''') t = (int(time.time()) - maximumAgeOfObjectsThatIAdvertiseToOthers, int(
time.time()) - lengthOfTimeToHoldOnToAllPubkeys, self.streamNumber)
shared.sqlSubmitQueue.put(
'''SELECT hash FROM inventory WHERE ((receivedtime>? and objecttype<>'pubkey') or (receivedtime>? and objecttype='pubkey')) and streamnumber=?''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
@ -477,7 +553,8 @@ class receiveDataThread(threading.Thread):
hash, = row hash, = row
if hash not in self.objectsOfWhichThisRemoteNodeIsAlreadyAware: if hash not in self.objectsOfWhichThisRemoteNodeIsAlreadyAware:
bigInvList[hash] = 0 bigInvList[hash] = 0
#We also have messages in our inventory in memory (which is a python dictionary). Let's fetch those too. # We also have messages in our inventory in memory (which is a python
# dictionary). Let's fetch those too.
for hash, storedValue in shared.inventory.items(): for hash, storedValue in shared.inventory.items():
if hash not in self.objectsOfWhichThisRemoteNodeIsAlreadyAware: if hash not in self.objectsOfWhichThisRemoteNodeIsAlreadyAware:
objectType, streamNumber, payload, receivedTime = storedValue objectType, streamNumber, payload, receivedTime = storedValue
@ -485,18 +562,22 @@ class receiveDataThread(threading.Thread):
bigInvList[hash] = 0 bigInvList[hash] = 0
numberOfObjectsInInvMessage = 0 numberOfObjectsInInvMessage = 0
payload = '' 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. # Now let us start appending all of these hashes together. They will be
# sent out in a big inv message to our new peer.
for hash, storedValue in bigInvList.items(): for hash, storedValue in bigInvList.items():
payload += hash payload += hash
numberOfObjectsInInvMessage += 1 numberOfObjectsInInvMessage += 1
if numberOfObjectsInInvMessage >= 50000: # We can only send a max of 50000 items per inv message but we may have more objects to advertise. They must be split up into multiple inv messages. if numberOfObjectsInInvMessage >= 50000: # We can only send a max of 50000 items per inv message but we may have more objects to advertise. They must be split up into multiple inv messages.
self.sendinvMessageToJustThisOnePeer(numberOfObjectsInInvMessage,payload) self.sendinvMessageToJustThisOnePeer(
numberOfObjectsInInvMessage, payload)
payload = '' payload = ''
numberOfObjectsInInvMessage = 0 numberOfObjectsInInvMessage = 0
if numberOfObjectsInInvMessage > 0: if numberOfObjectsInInvMessage > 0:
self.sendinvMessageToJustThisOnePeer(numberOfObjectsInInvMessage,payload) self.sendinvMessageToJustThisOnePeer(
numberOfObjectsInInvMessage, payload)
#Self explanatory. Notice that there is also a broadcastinv function for broadcasting invs to everyone in our stream. # Self explanatory. Notice that there is also a broadcastinv function for
# broadcasting invs to everyone in our stream.
def sendinvMessageToJustThisOnePeer(self, numberOfObjects, payload): def sendinvMessageToJustThisOnePeer(self, numberOfObjects, payload):
payload = encodeVarint(numberOfObjects) + payload payload = encodeVarint(numberOfObjects) + payload
headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits.
@ -508,7 +589,7 @@ class receiveDataThread(threading.Thread):
shared.printLock.release() shared.printLock.release()
try: try:
self.sock.sendall(headerData + payload) self.sock.sendall(headerData + payload)
except Exception, err: except Exception as err:
# if not 'Bad file descriptor' in err: # if not 'Bad file descriptor' in err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('sock.sendall error: %s\n' % err) sys.stderr.write('sock.sendall error: %s\n' % err)
@ -524,7 +605,8 @@ class receiveDataThread(threading.Thread):
readPosition = 8 # bypass the nonce readPosition = 8 # bypass the nonce
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4]) 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. # This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0: if embeddedTime == 0:
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8]) embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
readPosition += 8 readPosition += 8
@ -540,10 +622,14 @@ class receiveDataThread(threading.Thread):
if len(data) < 180: if len(data) < 180:
print 'The payload length of this broadcast packet is unreasonably low. Someone is probably trying funny business. Ignoring message.' print 'The payload length of this broadcast packet is unreasonably low. Someone is probably trying funny business. Ignoring message.'
return 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). # Let us check to make sure the stream number is correct (thus
broadcastVersion, broadcastVersionLength = decodeVarint(data[readPosition:readPosition+10]) # preventing an individual from sending broadcasts out on the wrong
# streams or all streams).
broadcastVersion, broadcastVersionLength = decodeVarint(
data[readPosition:readPosition + 10])
if broadcastVersion >= 2: if broadcastVersion >= 2:
streamNumber, streamNumberLength = decodeVarint(data[readPosition+broadcastVersionLength:readPosition+broadcastVersionLength+10]) streamNumber, streamNumberLength = decodeVarint(data[
readPosition + broadcastVersionLength:readPosition + broadcastVersionLength + 10])
if streamNumber != self.streamNumber: 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.' 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 return
@ -560,15 +646,20 @@ class receiveDataThread(threading.Thread):
return return
# It is valid so far. Let's let our peers know about it. # It is valid so far. Let's let our peers know about it.
objectType = 'broadcast' objectType = 'broadcast'
shared.inventory[self.inventoryHash] = (objectType, self.streamNumber, data, embeddedTime) shared.inventory[self.inventoryHash] = (
objectType, self.streamNumber, data, embeddedTime)
shared.inventoryLock.release() shared.inventoryLock.release()
self.broadcastinv(self.inventoryHash) self.broadcastinv(self.inventoryHash)
shared.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.
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
# 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. # values are mostly the same values used for msg messages although
# broadcast messages are processed faster.
if len(data) > 100000000: # Size is greater than 100 megabytes if len(data) > 100000000: # Size is greater than 100 megabytes
lengthOfTimeWeShouldUseToProcessThisMessage = 100 # seconds. lengthOfTimeWeShouldUseToProcessThisMessage = 100 # seconds.
elif len(data) > 10000000: # Between 100 and 10 megabytes elif len(data) > 10000000: # Between 100 and 10 megabytes
@ -578,8 +669,8 @@ class receiveDataThread(threading.Thread):
else: # Less than 1 megabyte else: # Less than 1 megabyte
lengthOfTimeWeShouldUseToProcessThisMessage = .6 # seconds. lengthOfTimeWeShouldUseToProcessThisMessage = .6 # seconds.
sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \
sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - (time.time()- self.messageProcessingStartTime) (time.time() - self.messageProcessingStartTime)
if sleepTime > 0: if sleepTime > 0:
shared.printLock.acquire() shared.printLock.acquire()
print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.'
@ -589,28 +680,36 @@ class receiveDataThread(threading.Thread):
print 'Total message processing time:', time.time() - self.messageProcessingStartTime, 'seconds.' print 'Total message processing time:', time.time() - self.messageProcessingStartTime, 'seconds.'
shared.printLock.release() shared.printLock.release()
#A broadcast message has a valid time and POW and requires processing. The recbroadcast function calls this one. # A broadcast message has a valid time and POW and requires processing.
# The recbroadcast function calls this one.
def processbroadcast(self, readPosition, data): def processbroadcast(self, readPosition, data):
broadcastVersion, broadcastVersionLength = decodeVarint(data[readPosition:readPosition+9]) broadcastVersion, broadcastVersionLength = decodeVarint(
data[readPosition:readPosition + 9])
readPosition += broadcastVersionLength readPosition += broadcastVersionLength
if broadcastVersion < 1 or broadcastVersion > 2: if broadcastVersion < 1 or broadcastVersion > 2:
print 'Cannot decode incoming broadcast versions higher than 2. Assuming the sender isn\' being silly, you should upgrade Bitmessage because this message shall be ignored.' print 'Cannot decode incoming broadcast versions higher than 2. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.'
return return
if broadcastVersion == 1: if broadcastVersion == 1:
beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table
sendersAddressVersion, sendersAddressVersionLength = decodeVarint(data[readPosition:readPosition+9]) sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
data[readPosition:readPosition + 9])
if sendersAddressVersion <= 1 or sendersAddressVersion >= 3: if sendersAddressVersion <= 1 or sendersAddressVersion >= 3:
#Cannot decode senderAddressVersion higher than 2. Assuming the sender isn\' being silly, you should upgrade Bitmessage because this message shall be ignored. # Cannot decode senderAddressVersion higher than 2. Assuming
# the sender isn\'t being silly, you should upgrade Bitmessage
# because this message shall be ignored.
return return
readPosition += sendersAddressVersionLength readPosition += sendersAddressVersionLength
if sendersAddressVersion == 2: if sendersAddressVersion == 2:
sendersStream, sendersStreamLength = decodeVarint(data[readPosition:readPosition+9]) sendersStream, sendersStreamLength = decodeVarint(
data[readPosition:readPosition + 9])
readPosition += sendersStreamLength readPosition += sendersStreamLength
behaviorBitfield = data[readPosition:readPosition + 4] behaviorBitfield = data[readPosition:readPosition + 4]
readPosition += 4 readPosition += 4
sendersPubSigningKey = '\x04' + data[readPosition:readPosition+64] sendersPubSigningKey = '\x04' + \
data[readPosition:readPosition + 64]
readPosition += 64 readPosition += 64
sendersPubEncryptionKey = '\x04' + data[readPosition:readPosition+64] sendersPubEncryptionKey = '\x04' + \
data[readPosition:readPosition + 64]
readPosition += 64 readPosition += 64
endOfPubkeyPosition = readPosition endOfPubkeyPosition = readPosition
sendersHash = data[readPosition:readPosition + 20] sendersHash = data[readPosition:readPosition + 20]
@ -620,7 +719,10 @@ class receiveDataThread(threading.Thread):
print 'Time spent deciding that we are not interested in this v1 broadcast:', time.time() - self.messageProcessingStartTime print 'Time spent deciding that we are not interested in this v1 broadcast:', time.time() - self.messageProcessingStartTime
shared.printLock.release() shared.printLock.release()
return 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. # 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 readPosition += 20
sha = hashlib.new('sha512') sha = hashlib.new('sha512')
@ -630,16 +732,19 @@ class receiveDataThread(threading.Thread):
if ripe.digest() != sendersHash: if ripe.digest() != sendersHash:
# The sender of this message lied. # The sender of this message lied.
return return
messageEncodingType, messageEncodingTypeLength = decodeVarint(data[readPosition:readPosition+9]) messageEncodingType, messageEncodingTypeLength = decodeVarint(
data[readPosition:readPosition + 9])
if messageEncodingType == 0: if messageEncodingType == 0:
return return
readPosition += messageEncodingTypeLength readPosition += messageEncodingTypeLength
messageLength, messageLengthLength = decodeVarint(data[readPosition:readPosition+9]) messageLength, messageLengthLength = decodeVarint(
data[readPosition:readPosition + 9])
readPosition += messageLengthLength readPosition += messageLengthLength
message = data[readPosition:readPosition + messageLength] message = data[readPosition:readPosition + messageLength]
readPosition += messageLength readPosition += messageLength
readPositionAtBottomOfMessage = readPosition readPositionAtBottomOfMessage = readPosition
signatureLength, signatureLengthLength = decodeVarint(data[readPosition:readPosition+9]) signatureLength, signatureLengthLength = decodeVarint(
data[readPosition:readPosition + 9])
readPosition += signatureLengthLength readPosition += signatureLengthLength
signature = data[readPosition:readPosition + signatureLength] signature = data[readPosition:readPosition + signatureLength]
try: try:
@ -647,24 +752,34 @@ class receiveDataThread(threading.Thread):
print 'ECDSA verify failed' print 'ECDSA verify failed'
return return
print 'ECDSA verify passed' print 'ECDSA verify passed'
except Exception, err: except Exception as err:
print 'ECDSA verify failed', err print 'ECDSA verify failed', err
return return
# verify passed # verify passed
# Let's store the public key in case we want to reply to this person. # 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.) # We don't have the correct nonce or time (which would let us
t = (ripe.digest(),'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF'+'\xFF\xFF\xFF\xFF'+data[beginningOfPubkeyPosition:endOfPubkeyPosition],int(time.time()),'yes') # 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')
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''') shared.sqlSubmitQueue.put(
'''INSERT INTO pubkeys VALUES (?,?,?,?)''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release() 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. # 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.digest()) self.possibleNewPubkey(ripe.digest())
fromAddress = encodeAddress(sendersAddressVersion,sendersStream,ripe.digest()) fromAddress = encodeAddress(
sendersAddressVersion, sendersStream, ripe.digest())
shared.printLock.acquire() shared.printLock.acquire()
print 'fromAddress:', fromAddress print 'fromAddress:', fromAddress
shared.printLock.release() shared.printLock.release()
@ -686,20 +801,26 @@ class receiveDataThread(threading.Thread):
subject = '' subject = ''
toAddress = '[Broadcast subscribers]' toAddress = '[Broadcast subscribers]'
if messageEncodingType <> 0: if messageEncodingType != 0:
shared.sqlLock.acquire() shared.sqlLock.acquire()
t = (self.inventoryHash,toAddress,fromAddress,subject,int(time.time()),body,'inbox',messageEncodingType,0) t = (self.inventoryHash, toAddress, fromAddress, subject, int(
shared.sqlSubmitQueue.put('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''') time.time()), body, 'inbox', messageEncodingType, 0)
shared.sqlSubmitQueue.put(
'''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release() shared.sqlLock.release()
shared.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 we are behaving as an API then we might need to run an
# outside command to let some program know that a new
# message has arrived.
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'): if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
try: try:
apiNotifyPath = shared.config.get('bitmessagesettings','apinotifypath') apiNotifyPath = shared.config.get(
'bitmessagesettings', 'apinotifypath')
except: except:
apiNotifyPath = '' apiNotifyPath = ''
if apiNotifyPath != '': if apiNotifyPath != '':
@ -710,7 +831,8 @@ class receiveDataThread(threading.Thread):
print 'Time spent processing this interesting broadcast:', time.time() - self.messageProcessingStartTime print 'Time spent processing this interesting broadcast:', time.time() - self.messageProcessingStartTime
shared.printLock.release() shared.printLock.release()
if broadcastVersion == 2: if broadcastVersion == 2:
cleartextStreamNumber, cleartextStreamNumberLength = decodeVarint(data[readPosition:readPosition+10]) cleartextStreamNumber, cleartextStreamNumberLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += cleartextStreamNumberLength readPosition += cleartextStreamNumberLength
initialDecryptionSuccessful = False initialDecryptionSuccessful = False
for key, cryptorObject in shared.MyECSubscriptionCryptorObjects.items(): for key, cryptorObject in shared.MyECSubscriptionCryptorObjects.items():
@ -720,7 +842,7 @@ class receiveDataThread(threading.Thread):
initialDecryptionSuccessful = True initialDecryptionSuccessful = True
print 'EC decryption successful using key associated with ripe hash:', key.encode('hex') print 'EC decryption successful using key associated with ripe hash:', key.encode('hex')
break break
except Exception, err: except Exception as err:
pass pass
# print 'cryptorObject.decrypt Exception:', err # print 'cryptorObject.decrypt Exception:', err
if not initialDecryptionSuccessful: if not initialDecryptionSuccessful:
@ -729,30 +851,38 @@ class receiveDataThread(threading.Thread):
print 'Length of time program spent failing to decrypt this v2 broadcast:', time.time() - self.messageProcessingStartTime, 'seconds.' print 'Length of time program spent failing to decrypt this v2 broadcast:', time.time() - self.messageProcessingStartTime, 'seconds.'
shared.printLock.release() shared.printLock.release()
return return
#At this point this is a broadcast I have decrypted and thus am interested in. # At this point this is a broadcast I have decrypted and thus am
signedBroadcastVersion, readPosition = decodeVarint(decryptedData[:10]) # interested in.
signedBroadcastVersion, readPosition = decodeVarint(
decryptedData[:10])
beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table beginningOfPubkeyPosition = readPosition # used when we add the pubkey to our pubkey table
sendersAddressVersion, sendersAddressVersionLength = decodeVarint(decryptedData[readPosition:readPosition+9]) sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
decryptedData[readPosition:readPosition + 9])
if sendersAddressVersion < 2 or sendersAddressVersion > 3: if sendersAddressVersion < 2 or sendersAddressVersion > 3:
print 'Cannot decode senderAddressVersion other than 2 or 3. Assuming the sender isn\' being silly, you should upgrade Bitmessage because this message shall be ignored.' 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 return
readPosition += sendersAddressVersionLength readPosition += sendersAddressVersionLength
sendersStream, sendersStreamLength = decodeVarint(decryptedData[readPosition:readPosition+9]) sendersStream, sendersStreamLength = decodeVarint(
decryptedData[readPosition:readPosition + 9])
if sendersStream != cleartextStreamNumber: 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.' 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 return
readPosition += sendersStreamLength readPosition += sendersStreamLength
behaviorBitfield = decryptedData[readPosition:readPosition + 4] behaviorBitfield = decryptedData[readPosition:readPosition + 4]
readPosition += 4 readPosition += 4
sendersPubSigningKey = '\x04' + decryptedData[readPosition:readPosition+64] sendersPubSigningKey = '\x04' + \
decryptedData[readPosition:readPosition + 64]
readPosition += 64 readPosition += 64
sendersPubEncryptionKey = '\x04' + decryptedData[readPosition:readPosition+64] sendersPubEncryptionKey = '\x04' + \
decryptedData[readPosition:readPosition + 64]
readPosition += 64 readPosition += 64
if sendersAddressVersion >= 3: if sendersAddressVersion >= 3:
requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(decryptedData[readPosition:readPosition+10]) requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += varintLength readPosition += varintLength
print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte
requiredPayloadLengthExtraBytes, varintLength = decodeVarint(decryptedData[readPosition:readPosition+10]) requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += varintLength readPosition += varintLength
print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes
endOfPubkeyPosition = readPosition endOfPubkeyPosition = readPosition
@ -765,40 +895,51 @@ class receiveDataThread(threading.Thread):
if toRipe != ripe.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.' print 'The encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.'
return return
messageEncodingType, messageEncodingTypeLength = decodeVarint(decryptedData[readPosition:readPosition+9]) messageEncodingType, messageEncodingTypeLength = decodeVarint(
decryptedData[readPosition:readPosition + 9])
if messageEncodingType == 0: if messageEncodingType == 0:
return return
readPosition += messageEncodingTypeLength readPosition += messageEncodingTypeLength
messageLength, messageLengthLength = decodeVarint(decryptedData[readPosition:readPosition+9]) messageLength, messageLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 9])
readPosition += messageLengthLength readPosition += messageLengthLength
message = decryptedData[readPosition:readPosition + messageLength] message = decryptedData[readPosition:readPosition + messageLength]
readPosition += messageLength readPosition += messageLength
readPositionAtBottomOfMessage = readPosition readPositionAtBottomOfMessage = readPosition
signatureLength, signatureLengthLength = decodeVarint(decryptedData[readPosition:readPosition+9]) signatureLength, signatureLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 9])
readPosition += signatureLengthLength readPosition += signatureLengthLength
signature = decryptedData[readPosition:readPosition+signatureLength] signature = decryptedData[
readPosition:readPosition + signatureLength]
try: try:
if not highlevelcrypto.verify(decryptedData[:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')): if not highlevelcrypto.verify(decryptedData[:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')):
print 'ECDSA verify failed' print 'ECDSA verify failed'
return return
print 'ECDSA verify passed' print 'ECDSA verify passed'
except Exception, err: except Exception as err:
print 'ECDSA verify failed', err print 'ECDSA verify failed', err
return return
# verify passed # verify passed
#Let's store the public key in case we want to reply to this person. # Let's store the public key in case we want to reply to this
t = (ripe.digest(),'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF'+'\xFF\xFF\xFF\xFF'+decryptedData[beginningOfPubkeyPosition:endOfPubkeyPosition],int(time.time()),'yes') # person.
t = (ripe.digest(), '\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + decryptedData[
beginningOfPubkeyPosition:endOfPubkeyPosition], int(time.time()), 'yes')
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''') shared.sqlSubmitQueue.put(
'''INSERT INTO pubkeys VALUES (?,?,?,?)''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release() 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. # 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.digest()) self.possibleNewPubkey(ripe.digest())
fromAddress = encodeAddress(sendersAddressVersion,sendersStream,ripe.digest()) fromAddress = encodeAddress(
sendersAddressVersion, sendersStream, ripe.digest())
shared.printLock.acquire() shared.printLock.acquire()
print 'fromAddress:', fromAddress print 'fromAddress:', fromAddress
shared.printLock.release() shared.printLock.release()
@ -820,20 +961,26 @@ class receiveDataThread(threading.Thread):
subject = '' subject = ''
toAddress = '[Broadcast subscribers]' toAddress = '[Broadcast subscribers]'
if messageEncodingType <> 0: if messageEncodingType != 0:
shared.sqlLock.acquire() shared.sqlLock.acquire()
t = (self.inventoryHash,toAddress,fromAddress,subject,int(time.time()),body,'inbox',messageEncodingType,0) t = (self.inventoryHash, toAddress, fromAddress, subject, int(
shared.sqlSubmitQueue.put('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''') time.time()), body, 'inbox', messageEncodingType, 0)
shared.sqlSubmitQueue.put(
'''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release() shared.sqlLock.release()
shared.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 we are behaving as an API then we might need to run an
# outside command to let some program know that a new message
# has arrived.
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'): if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
try: try:
apiNotifyPath = shared.config.get('bitmessagesettings','apinotifypath') apiNotifyPath = shared.config.get(
'bitmessagesettings', 'apinotifypath')
except: except:
apiNotifyPath = '' apiNotifyPath = ''
if apiNotifyPath != '': if apiNotifyPath != '':
@ -844,7 +991,6 @@ class receiveDataThread(threading.Thread):
print 'Time spent processing this interesting broadcast:', time.time() - self.messageProcessingStartTime print 'Time spent processing this interesting broadcast:', time.time() - self.messageProcessingStartTime
shared.printLock.release() shared.printLock.release()
# We have received a msg message. # We have received a msg message.
def recmsg(self, data): def recmsg(self, data):
self.messageProcessingStartTime = time.time() self.messageProcessingStartTime = time.time()
@ -856,7 +1002,8 @@ class receiveDataThread(threading.Thread):
readPosition = 8 readPosition = 8
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4]) 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. # This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0: if embeddedTime == 0:
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8]) embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
readPosition += 8 readPosition += 8
@ -869,7 +1016,8 @@ class receiveDataThread(threading.Thread):
if embeddedTime < int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept: if embeddedTime < int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept:
print 'The time in the msg message is too old. Ignoring it. Time:', embeddedTime print 'The time in the msg message is too old. Ignoring it. Time:', embeddedTime
return return
streamNumberAsClaimedByMsg, streamNumberAsClaimedByMsgLength = decodeVarint(data[readPosition:readPosition+9]) streamNumberAsClaimedByMsg, streamNumberAsClaimedByMsgLength = decodeVarint(
data[readPosition:readPosition + 9])
if streamNumberAsClaimedByMsg != self.streamNumber: 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.' 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 return
@ -886,15 +1034,19 @@ class receiveDataThread(threading.Thread):
return return
# This msg message is valid. Let's let our peers know about it. # This msg message is valid. Let's let our peers know about it.
objectType = 'msg' objectType = 'msg'
shared.inventory[self.inventoryHash] = (objectType, self.streamNumber, data, embeddedTime) shared.inventory[self.inventoryHash] = (
objectType, self.streamNumber, data, embeddedTime)
shared.inventoryLock.release() shared.inventoryLock.release()
self.broadcastinv(self.inventoryHash) self.broadcastinv(self.inventoryHash)
shared.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.
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
# 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. # values are based on test timings and you may change them at-will.
if len(data) > 100000000: # Size is greater than 100 megabytes 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. 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 elif len(data) > 10000000: # Between 100 and 10 megabytes
@ -904,8 +1056,8 @@ class receiveDataThread(threading.Thread):
else: # Less than 1 megabyte else: # Less than 1 megabyte
lengthOfTimeWeShouldUseToProcessThisMessage = .6 # seconds. Actual length of time it took my computer to decrypt and verify the signature of a 100 KB message: 0.15 seconds. Actual length of time it takes in practice when processing a real message: 0.25 seconds. lengthOfTimeWeShouldUseToProcessThisMessage = .6 # seconds. Actual length of time it took my computer to decrypt and verify the signature of a 100 KB message: 0.15 seconds. Actual length of time it takes in practice when processing a real message: 0.25 seconds.
sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \
sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - (time.time()- self.messageProcessingStartTime) (time.time() - self.messageProcessingStartTime)
if sleepTime > 0: if sleepTime > 0:
shared.printLock.acquire() shared.printLock.acquire()
print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.'
@ -915,8 +1067,8 @@ class receiveDataThread(threading.Thread):
print 'Total message processing time:', time.time() - self.messageProcessingStartTime, 'seconds.' print 'Total message processing time:', time.time() - self.messageProcessingStartTime, 'seconds.'
shared.printLock.release() shared.printLock.release()
# A msg message has a valid time and POW and requires processing. The
#A msg message has a valid time and POW and requires processing. The recmsg function calls this one. # recmsg function calls this one.
def processmsg(self, readPosition, encryptedData): def processmsg(self, readPosition, encryptedData):
initialDecryptionSuccessful = False initialDecryptionSuccessful = False
# Let's check whether this is a message acknowledgement bound for us. # Let's check whether this is a message acknowledgement bound for us.
@ -927,12 +1079,14 @@ class receiveDataThread(threading.Thread):
del ackdataForWhichImWatching[encryptedData[readPosition:]] del ackdataForWhichImWatching[encryptedData[readPosition:]]
t = ('ackreceived', encryptedData[readPosition:]) t = ('ackreceived', encryptedData[readPosition:])
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('UPDATE sent SET status=? WHERE ackdata=?') shared.sqlSubmitQueue.put(
'UPDATE sent SET status=? WHERE ackdata=?')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release() shared.sqlLock.release()
shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(encryptedData[readPosition:],'Acknowledgement of the message received just now. '+ unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'),localtime(int(time.time()))),'utf-8')))) shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (encryptedData[readPosition:], 'Acknowledgement of the message received just now. ' + unicode(
strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))
return return
else: else:
shared.printLock.acquire() shared.printLock.acquire()
@ -940,15 +1094,17 @@ class receiveDataThread(threading.Thread):
# print 'ackdataForWhichImWatching', ackdataForWhichImWatching # print 'ackdataForWhichImWatching', ackdataForWhichImWatching
shared.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. # 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(): for key, cryptorObject in shared.myECCryptorObjects.items():
try: try:
decryptedData = cryptorObject.decrypt(encryptedData[readPosition:]) 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. toRipe = key # This is the RIPE hash of my pubkeys. We need this below to compare to the destination_ripe included in the encrypted data.
initialDecryptionSuccessful = True initialDecryptionSuccessful = True
print 'EC decryption successful using key associated with ripe hash:', key.encode('hex') print 'EC decryption successful using key associated with ripe hash:', key.encode('hex')
break break
except Exception, err: except Exception as err:
pass pass
# print 'cryptorObject.decrypt Exception:', err # print 'cryptorObject.decrypt Exception:', err
if not initialDecryptionSuccessful: if not initialDecryptionSuccessful:
@ -958,14 +1114,17 @@ class receiveDataThread(threading.Thread):
shared.printLock.release() shared.printLock.release()
else: else:
# This is a message bound for me. # This is a message bound for me.
toAddress = shared.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 readPosition = 0
messageVersion, messageVersionLength = decodeVarint(decryptedData[readPosition:readPosition+10]) messageVersion, messageVersionLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += messageVersionLength readPosition += messageVersionLength
if messageVersion != 1: if messageVersion != 1:
print 'Cannot understand message versions other than one. Ignoring message.' print 'Cannot understand message versions other than one. Ignoring message.'
return return
sendersAddressVersionNumber, sendersAddressVersionNumberLength = decodeVarint(decryptedData[readPosition:readPosition+10]) sendersAddressVersionNumber, sendersAddressVersionNumberLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += sendersAddressVersionNumberLength readPosition += sendersAddressVersionNumberLength
if sendersAddressVersionNumber == 0: if sendersAddressVersionNumber == 0:
print 'Cannot understand sendersAddressVersionNumber = 0. Ignoring message.' print 'Cannot understand sendersAddressVersionNumber = 0. Ignoring message.'
@ -976,22 +1135,27 @@ class receiveDataThread(threading.Thread):
if len(decryptedData) < 170: if len(decryptedData) < 170:
print 'Length of the unencrypted data is unreasonably short. Sanity check failed. Ignoring message.' print 'Length of the unencrypted data is unreasonably short. Sanity check failed. Ignoring message.'
return return
sendersStreamNumber, sendersStreamNumberLength = decodeVarint(decryptedData[readPosition:readPosition+10]) sendersStreamNumber, sendersStreamNumberLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
if sendersStreamNumber == 0: if sendersStreamNumber == 0:
print 'sender\'s stream number is 0. Ignoring message.' print 'sender\'s stream number is 0. Ignoring message.'
return return
readPosition += sendersStreamNumberLength readPosition += sendersStreamNumberLength
behaviorBitfield = decryptedData[readPosition:readPosition + 4] behaviorBitfield = decryptedData[readPosition:readPosition + 4]
readPosition += 4 readPosition += 4
pubSigningKey = '\x04' + decryptedData[readPosition:readPosition+64] pubSigningKey = '\x04' + decryptedData[
readPosition:readPosition + 64]
readPosition += 64 readPosition += 64
pubEncryptionKey = '\x04' + decryptedData[readPosition:readPosition+64] pubEncryptionKey = '\x04' + decryptedData[
readPosition:readPosition + 64]
readPosition += 64 readPosition += 64
if sendersAddressVersionNumber >= 3: if sendersAddressVersionNumber >= 3:
requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(decryptedData[readPosition:readPosition+10]) requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += varintLength readPosition += varintLength
print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte
requiredPayloadLengthExtraBytes, varintLength = decodeVarint(decryptedData[readPosition:readPosition+10]) requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += varintLength readPosition += varintLength
print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes
endOfThePublicKeyPosition = readPosition # needed for when we store the pubkey in our database of pubkeys for later use. endOfThePublicKeyPosition = readPosition # needed for when we store the pubkey in our database of pubkeys for later use.
@ -1004,27 +1168,32 @@ class receiveDataThread(threading.Thread):
shared.printLock.release() shared.printLock.release()
return return
readPosition += 20 readPosition += 20
messageEncodingType, messageEncodingTypeLength = decodeVarint(decryptedData[readPosition:readPosition+10]) messageEncodingType, messageEncodingTypeLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += messageEncodingTypeLength readPosition += messageEncodingTypeLength
messageLength, messageLengthLength = decodeVarint(decryptedData[readPosition:readPosition+10]) messageLength, messageLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += messageLengthLength readPosition += messageLengthLength
message = decryptedData[readPosition:readPosition + messageLength] message = decryptedData[readPosition:readPosition + messageLength]
# print 'First 150 characters of message:', repr(message[:150]) # print 'First 150 characters of message:', repr(message[:150])
readPosition += messageLength readPosition += messageLength
ackLength, ackLengthLength = decodeVarint(decryptedData[readPosition:readPosition+10]) ackLength, ackLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += ackLengthLength readPosition += ackLengthLength
ackData = decryptedData[readPosition:readPosition + ackLength] ackData = decryptedData[readPosition:readPosition + ackLength]
readPosition += ackLength readPosition += ackLength
positionOfBottomOfAckData = readPosition # needed to mark the end of what is covered by the signature positionOfBottomOfAckData = readPosition # needed to mark the end of what is covered by the signature
signatureLength, signatureLengthLength = decodeVarint(decryptedData[readPosition:readPosition+10]) signatureLength, signatureLengthLength = decodeVarint(
decryptedData[readPosition:readPosition + 10])
readPosition += signatureLengthLength readPosition += signatureLengthLength
signature = decryptedData[readPosition:readPosition+signatureLength] signature = decryptedData[
readPosition:readPosition + signatureLength]
try: try:
if not highlevelcrypto.verify(decryptedData[:positionOfBottomOfAckData], signature, pubSigningKey.encode('hex')): if not highlevelcrypto.verify(decryptedData[:positionOfBottomOfAckData], signature, pubSigningKey.encode('hex')):
print 'ECDSA verify failed' print 'ECDSA verify failed'
return return
print 'ECDSA verify passed' print 'ECDSA verify passed'
except Exception, err: except Exception as err:
print 'ECDSA verify failed', err print 'ECDSA verify failed', err
return return
shared.printLock.acquire() shared.printLock.acquire()
@ -1035,22 +1204,33 @@ class receiveDataThread(threading.Thread):
sha.update(pubSigningKey + pubEncryptionKey) sha.update(pubSigningKey + pubEncryptionKey)
ripe = hashlib.new('ripemd160') ripe = hashlib.new('ripemd160')
ripe.update(sha.digest()) ripe.update(sha.digest())
#Let's store the public key in case we want to reply to this person. # Let's store the public key in case we want to reply to this
t = (ripe.digest(),'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF'+'\xFF\xFF\xFF\xFF'+decryptedData[messageVersionLength:endOfThePublicKeyPosition],int(time.time()),'yes') # person.
t = (ripe.digest(), '\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF' + '\xFF\xFF\xFF\xFF' + decryptedData[
messageVersionLength:endOfThePublicKeyPosition], int(time.time()), 'yes')
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''') shared.sqlSubmitQueue.put(
'''INSERT INTO pubkeys VALUES (?,?,?,?)''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release() 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. # 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.
self.possibleNewPubkey(ripe.digest()) self.possibleNewPubkey(ripe.digest())
fromAddress = encodeAddress(sendersAddressVersionNumber,sendersStreamNumber,ripe.digest()) fromAddress = encodeAddress(
#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. 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 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: if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(fromAddress): # If I'm not friendly with this person:
requiredNonceTrialsPerByte = shared.config.getint(toAddress,'noncetrialsperbyte') requiredNonceTrialsPerByte = shared.config.getint(
requiredPayloadLengthExtraBytes = shared.config.getint(toAddress,'payloadlengthextrabytes') toAddress, 'noncetrialsperbyte')
requiredPayloadLengthExtraBytes = shared.config.getint(
toAddress, 'payloadlengthextrabytes')
if not self.isProofOfWorkSufficient(encryptedData, requiredNonceTrialsPerByte, requiredPayloadLengthExtraBytes): if not self.isProofOfWorkSufficient(encryptedData, requiredNonceTrialsPerByte, requiredPayloadLengthExtraBytes):
print 'Proof of work in msg message insufficient only because it does not meet our higher requirement.' print 'Proof of work in msg message insufficient only because it does not meet our higher requirement.'
return return
@ -1058,7 +1238,8 @@ class receiveDataThread(threading.Thread):
if shared.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,) t = (fromAddress,)
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''SELECT label FROM blacklist where address=? and enabled='1' ''') shared.sqlSubmitQueue.put(
'''SELECT label FROM blacklist where address=? and enabled='1' ''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
@ -1070,7 +1251,8 @@ class receiveDataThread(threading.Thread):
else: # We're using a whitelist else: # We're using a whitelist
t = (fromAddress,) t = (fromAddress,)
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''SELECT label FROM whitelist where address=? and enabled='1' ''') shared.sqlSubmitQueue.put(
'''SELECT label FROM whitelist where address=? and enabled='1' ''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
@ -1089,7 +1271,8 @@ class receiveDataThread(threading.Thread):
bodyPositionIndex = string.find(message, '\nBody:') bodyPositionIndex = string.find(message, '\nBody:')
if bodyPositionIndex > 1: if bodyPositionIndex > 1:
subject = message[8:bodyPositionIndex] subject = message[8:bodyPositionIndex]
subject = subject[:500] #Only save and show the first 500 characters of the subject. Any more is probably an attak. subject = subject[
:500] # Only save and show the first 500 characters of the subject. Any more is probably an attak.
body = message[bodyPositionIndex + 6:] body = message[bodyPositionIndex + 6:]
else: else:
subject = '' subject = ''
@ -1102,56 +1285,73 @@ class receiveDataThread(threading.Thread):
else: else:
body = 'Unknown encoding type.\n\n' + repr(message) body = 'Unknown encoding type.\n\n' + repr(message)
subject = '' subject = ''
if messageEncodingType <> 0: if messageEncodingType != 0:
shared.sqlLock.acquire() shared.sqlLock.acquire()
t = (self.inventoryHash,toAddress,fromAddress,subject,int(time.time()),body,'inbox',messageEncodingType,0) t = (self.inventoryHash, toAddress, fromAddress, subject, int(
shared.sqlSubmitQueue.put('''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''') time.time()), body, 'inbox', messageEncodingType, 0)
shared.sqlSubmitQueue.put(
'''INSERT INTO inbox VALUES (?,?,?,?,?,?,?,?,?)''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release() shared.sqlLock.release()
shared.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 we are behaving as an API then we might need to run an
# outside command to let some program know that a new message
# has arrived.
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'): if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
try: try:
apiNotifyPath = shared.config.get('bitmessagesettings','apinotifypath') apiNotifyPath = shared.config.get(
'bitmessagesettings', 'apinotifypath')
except: except:
apiNotifyPath = '' apiNotifyPath = ''
if apiNotifyPath != '': if apiNotifyPath != '':
call([apiNotifyPath, "newMessage"]) call([apiNotifyPath, "newMessage"])
#Let us now check and see whether our receiving address is behaving as a mailing list # Let us now check and see whether our receiving address is
# behaving as a mailing list
if shared.safeConfigGetBoolean(toAddress, 'mailinglist'): if shared.safeConfigGetBoolean(toAddress, 'mailinglist'):
try: try:
mailingListName = shared.config.get(toAddress, 'mailinglistname') mailingListName = shared.config.get(
toAddress, 'mailinglistname')
except: except:
mailingListName = '' mailingListName = ''
# Let us send out this message as a broadcast # Let us send out this message as a broadcast
subject = self.addMailingListNameToSubject(subject,mailingListName) subject = self.addMailingListNameToSubject(
subject, mailingListName)
# Let us now send this message out as a broadcast # Let us now send this message out as a broadcast
message = strftime("%a, %Y-%m-%d %H:%M:%S UTC",gmtime()) + ' Message ostensibly from ' + fromAddress + ':\n\n' + body message = strftime("%a, %Y-%m-%d %H:%M:%S UTC", 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. 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. 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]' toAddress = '[Broadcast subscribers]'
ripe = '' ripe = ''
shared.sqlLock.acquire() shared.sqlLock.acquire()
t = ('',toAddress,ripe,fromAddress,subject,message,ackdata,int(time.time()),'broadcastqueued',1,1,'sent',2) t = ('', toAddress, ripe, fromAddress, subject, message, ackdata, int(
shared.sqlSubmitQueue.put('''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)''') time.time()), 'broadcastqueued', 1, 1, 'sent', 2)
shared.sqlSubmitQueue.put(
'''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release() shared.sqlLock.release()
shared.UISignalQueue.put(('displayNewSentMessage',(toAddress,'[Broadcast subscribers]',fromAddress,subject,message,ackdata))) shared.UISignalQueue.put(('displayNewSentMessage', (
toAddress, '[Broadcast subscribers]', fromAddress, subject, message, ackdata)))
shared.workerQueue.put(('sendbroadcast', '')) shared.workerQueue.put(('sendbroadcast', ''))
if self.isAckDataValid(ackData): if self.isAckDataValid(ackData):
print 'ackData is valid. Will process it.' 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. 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 # Display timing data
timeRequiredToAttemptToDecryptMessage = time.time()- self.messageProcessingStartTime timeRequiredToAttemptToDecryptMessage = time.time(
successfullyDecryptMessageTimings.append(timeRequiredToAttemptToDecryptMessage) ) - self.messageProcessingStartTime
successfullyDecryptMessageTimings.append(
timeRequiredToAttemptToDecryptMessage)
sum = 0 sum = 0
for item in successfullyDecryptMessageTimings: for item in successfullyDecryptMessageTimings:
sum += item sum += item
@ -1190,7 +1390,8 @@ class receiveDataThread(threading.Thread):
del neededPubkeys[toRipe] del neededPubkeys[toRipe]
t = (toRipe,) t = (toRipe,)
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''UPDATE sent SET status='doingmsgpow' WHERE toripe=? AND status='awaitingpubkey' and folder='sent' ''') shared.sqlSubmitQueue.put(
'''UPDATE sent SET status='doingmsgpow' WHERE toripe=? AND status='awaitingpubkey' and folder='sent' ''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
@ -1214,7 +1415,8 @@ class receiveDataThread(threading.Thread):
readPosition = 8 # for the nonce readPosition = 8 # for the nonce
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4]) 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. # This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0: if embeddedTime == 0:
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8]) embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
readPosition += 8 readPosition += 8
@ -1231,9 +1433,11 @@ class receiveDataThread(threading.Thread):
print 'The embedded time in this pubkey message more than several hours in the future. This is irrational. Ignoring message.' print 'The embedded time in this pubkey message more than several hours in the future. This is irrational. Ignoring message.'
shared.printLock.release() shared.printLock.release()
return return
addressVersion, varintLength = decodeVarint(data[readPosition:readPosition+10]) addressVersion, varintLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += varintLength readPosition += varintLength
streamNumber, varintLength = decodeVarint(data[readPosition:readPosition+10]) streamNumber, varintLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += varintLength readPosition += varintLength
if self.streamNumber != streamNumber: if self.streamNumber != streamNumber:
print 'stream number embedded in this pubkey doesn\'t match our stream number. Ignoring.' print 'stream number embedded in this pubkey doesn\'t match our stream number. Ignoring.'
@ -1250,15 +1454,18 @@ class receiveDataThread(threading.Thread):
shared.inventoryLock.release() shared.inventoryLock.release()
return return
objectType = 'pubkey' objectType = 'pubkey'
shared.inventory[inventoryHash] = (objectType, self.streamNumber, data, embeddedTime) shared.inventory[inventoryHash] = (
objectType, self.streamNumber, data, embeddedTime)
shared.inventoryLock.release() shared.inventoryLock.release()
self.broadcastinv(inventoryHash) self.broadcastinv(inventoryHash)
shared.UISignalQueue.put(('incrementNumberOfPubkeysProcessed','no data')) shared.UISignalQueue.put((
'incrementNumberOfPubkeysProcessed', 'no data'))
self.processpubkey(data) self.processpubkey(data)
lengthOfTimeWeShouldUseToProcessThisMessage = .2 lengthOfTimeWeShouldUseToProcessThisMessage = .2
sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - (time.time()- self.pubkeyProcessingStartTime) sleepTime = lengthOfTimeWeShouldUseToProcessThisMessage - \
(time.time() - self.pubkeyProcessingStartTime)
if sleepTime > 0: if sleepTime > 0:
shared.printLock.acquire() shared.printLock.acquire()
print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.' print 'Timing attack mitigation: Sleeping for', sleepTime, 'seconds.'
@ -1272,16 +1479,19 @@ class receiveDataThread(threading.Thread):
readPosition = 8 # for the nonce readPosition = 8 # for the nonce
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4]) 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. # This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0: if embeddedTime == 0:
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8]) embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
readPosition += 8 readPosition += 8
else: else:
readPosition += 4 readPosition += 4
addressVersion, varintLength = decodeVarint(data[readPosition:readPosition+10]) addressVersion, varintLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += varintLength readPosition += varintLength
streamNumber, varintLength = decodeVarint(data[readPosition:readPosition+10]) streamNumber, varintLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += varintLength readPosition += varintLength
if addressVersion == 0: if addressVersion == 0:
print '(Within processpubkey) addressVersion of 0 doesn\'t make sense.' print '(Within processpubkey) addressVersion of 0 doesn\'t make sense.'
@ -1298,14 +1508,17 @@ class receiveDataThread(threading.Thread):
bitfieldBehaviors = data[readPosition:readPosition + 4] bitfieldBehaviors = data[readPosition:readPosition + 4]
readPosition += 4 readPosition += 4
publicSigningKey = data[readPosition:readPosition + 64] 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. # 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 readPosition += 64
publicEncryptionKey = data[readPosition:readPosition + 64] publicEncryptionKey = data[readPosition:readPosition + 64]
if len(publicEncryptionKey) < 64: if len(publicEncryptionKey) < 64:
print 'publicEncryptionKey length less than 64. Sanity check failed.' print 'publicEncryptionKey length less than 64. Sanity check failed.'
return return
sha = hashlib.new('sha512') sha = hashlib.new('sha512')
sha.update('\x04'+publicSigningKey+'\x04'+publicEncryptionKey) sha.update(
'\x04' + publicSigningKey + '\x04' + publicEncryptionKey)
ripeHasher = hashlib.new('ripemd160') ripeHasher = hashlib.new('ripemd160')
ripeHasher.update(sha.digest()) ripeHasher.update(sha.digest())
ripe = ripeHasher.digest() ripe = ripeHasher.digest()
@ -1319,7 +1532,8 @@ class receiveDataThread(threading.Thread):
t = (ripe,) t = (ripe,)
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''SELECT usedpersonally FROM pubkeys WHERE hash=? AND usedpersonally='yes' ''') shared.sqlSubmitQueue.put(
'''SELECT usedpersonally FROM pubkeys WHERE hash=? AND usedpersonally='yes' ''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
@ -1328,9 +1542,11 @@ class receiveDataThread(threading.Thread):
t = (ripe, data, embeddedTime, 'yes') t = (ripe, data, embeddedTime, 'yes')
else: else:
print 'We have NOT used this pubkey personally. Inserting in database.' print 'We have NOT used this pubkey personally. Inserting in database.'
t = (ripe,data,embeddedTime,'no') #This will also update the embeddedTime. t = (ripe, data, embeddedTime, 'no')
# This will also update the embeddedTime.
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''') shared.sqlSubmitQueue.put(
'''INSERT INTO pubkeys VALUES (?,?,?,?)''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
@ -1344,16 +1560,21 @@ class receiveDataThread(threading.Thread):
bitfieldBehaviors = data[readPosition:readPosition + 4] bitfieldBehaviors = data[readPosition:readPosition + 4]
readPosition += 4 readPosition += 4
publicSigningKey = '\x04' + data[readPosition:readPosition + 64] 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. # 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 readPosition += 64
publicEncryptionKey = '\x04' + data[readPosition:readPosition + 64] publicEncryptionKey = '\x04' + data[readPosition:readPosition + 64]
readPosition += 64 readPosition += 64
specifiedNonceTrialsPerByte, specifiedNonceTrialsPerByteLength = decodeVarint(data[readPosition:readPosition+10]) specifiedNonceTrialsPerByte, specifiedNonceTrialsPerByteLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += specifiedNonceTrialsPerByteLength readPosition += specifiedNonceTrialsPerByteLength
specifiedPayloadLengthExtraBytes, specifiedPayloadLengthExtraBytesLength = decodeVarint(data[readPosition:readPosition+10]) specifiedPayloadLengthExtraBytes, specifiedPayloadLengthExtraBytesLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += specifiedPayloadLengthExtraBytesLength readPosition += specifiedPayloadLengthExtraBytesLength
endOfSignedDataPosition = readPosition endOfSignedDataPosition = readPosition
signatureLength, signatureLengthLength = decodeVarint(data[readPosition:readPosition+10]) signatureLength, signatureLengthLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += signatureLengthLength readPosition += signatureLengthLength
signature = data[readPosition:readPosition + signatureLength] signature = data[readPosition:readPosition + signatureLength]
try: try:
@ -1361,7 +1582,7 @@ class receiveDataThread(threading.Thread):
print 'ECDSA verify failed (within processpubkey)' print 'ECDSA verify failed (within processpubkey)'
return return
print 'ECDSA verify passed (within processpubkey)' print 'ECDSA verify passed (within processpubkey)'
except Exception, err: except Exception as err:
print 'ECDSA verify failed (within processpubkey)', err print 'ECDSA verify failed (within processpubkey)', err
return return
@ -1380,7 +1601,8 @@ class receiveDataThread(threading.Thread):
t = (ripe,) t = (ripe,)
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''SELECT usedpersonally FROM pubkeys WHERE hash=? AND usedpersonally='yes' ''') shared.sqlSubmitQueue.put(
'''SELECT usedpersonally FROM pubkeys WHERE hash=? AND usedpersonally='yes' ''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
@ -1389,9 +1611,11 @@ class receiveDataThread(threading.Thread):
t = (ripe, data, embeddedTime, 'yes') t = (ripe, data, embeddedTime, 'yes')
else: else:
print 'We have NOT used this pubkey personally. Inserting in database.' print 'We have NOT used this pubkey personally. Inserting in database.'
t = (ripe,data,embeddedTime,'no') #This will also update the embeddedTime. t = (ripe, data, embeddedTime, 'no')
# This will also update the embeddedTime.
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''INSERT INTO pubkeys VALUES (?,?,?,?)''') shared.sqlSubmitQueue.put(
'''INSERT INTO pubkeys VALUES (?,?,?,?)''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
@ -1399,7 +1623,6 @@ class receiveDataThread(threading.Thread):
# shared.workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe))) # shared.workerQueue.put(('newpubkey',(addressVersion,streamNumber,ripe)))
self.possibleNewPubkey(ripe) self.possibleNewPubkey(ripe)
# We have received a getpubkey message # We have received a getpubkey message
def recgetpubkey(self, data): def recgetpubkey(self, data):
if not self.isProofOfWorkSufficient(data): if not self.isProofOfWorkSufficient(data):
@ -1411,7 +1634,8 @@ class receiveDataThread(threading.Thread):
readPosition = 8 # bypass the nonce readPosition = 8 # bypass the nonce
embeddedTime, = unpack('>I', data[readPosition:readPosition + 4]) 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. # This section is used for the transition from 32 bit time to 64 bit
# time in the protocol.
if embeddedTime == 0: if embeddedTime == 0:
embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8]) embeddedTime, = unpack('>Q', data[readPosition:readPosition + 8])
readPosition += 8 readPosition += 8
@ -1424,10 +1648,12 @@ class receiveDataThread(threading.Thread):
if embeddedTime < int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept: if embeddedTime < int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept:
print 'The time in this getpubkey message is too old. Ignoring it. Time:', embeddedTime print 'The time in this getpubkey message is too old. Ignoring it. Time:', embeddedTime
return return
requestedAddressVersionNumber, addressVersionLength = decodeVarint(data[readPosition:readPosition+10]) requestedAddressVersionNumber, addressVersionLength = decodeVarint(
data[readPosition:readPosition + 10])
readPosition += addressVersionLength readPosition += addressVersionLength
streamNumber, streamNumberLength = decodeVarint(data[readPosition:readPosition+10]) streamNumber, streamNumberLength = decodeVarint(
if streamNumber <> self.streamNumber: data[readPosition:readPosition + 10])
if streamNumber != self.streamNumber:
print 'The streamNumber', streamNumber, 'doesn\'t match our stream number:', self.streamNumber print 'The streamNumber', streamNumber, 'doesn\'t match our stream number:', self.streamNumber
return return
readPosition += streamNumberLength readPosition += streamNumberLength
@ -1444,7 +1670,8 @@ class receiveDataThread(threading.Thread):
return return
objectType = 'getpubkey' objectType = 'getpubkey'
shared.inventory[inventoryHash] = (objectType, self.streamNumber, data, embeddedTime) shared.inventory[inventoryHash] = (
objectType, self.streamNumber, data, embeddedTime)
shared.inventoryLock.release() shared.inventoryLock.release()
# This getpubkey request is valid so far. Forward to peers. # This getpubkey request is valid so far. Forward to peers.
self.broadcastinv(inventoryHash) self.broadcastinv(inventoryHash)
@ -1468,11 +1695,13 @@ class receiveDataThread(threading.Thread):
if requestedHash in shared.myAddressesByHash: # if this address hash is one of mine if requestedHash in shared.myAddressesByHash: # if this address hash is one of mine
if decodeAddress(shared.myAddressesByHash[requestedHash])[1] != requestedAddressVersionNumber: if decodeAddress(shared.myAddressesByHash[requestedHash])[1] != requestedAddressVersionNumber:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('(Within the recgetpubkey function) Someone requested one of my pubkeys but the requestedAddressVersionNumber doesn\'t match my actual address version number. That shouldn\'t have happened. Ignoring.\n') sys.stderr.write(
'(Within the recgetpubkey function) Someone requested one of my pubkeys but the requestedAddressVersionNumber doesn\'t match my actual address version number. That shouldn\'t have happened. Ignoring.\n')
shared.printLock.release() shared.printLock.release()
return return
try: try:
lastPubkeySendTime = int(shared.config.get(shared.myAddressesByHash[requestedHash],'lastpubkeysendtime')) lastPubkeySendTime = int(shared.config.get(
shared.myAddressesByHash[requestedHash], 'lastpubkeysendtime'))
except: except:
lastPubkeySendTime = 0 lastPubkeySendTime = 0
if lastPubkeySendTime < time.time() - lengthOfTimeToHoldOnToAllPubkeys: # If the last time we sent our pubkey was 28 days ago if lastPubkeySendTime < time.time() - lengthOfTimeToHoldOnToAllPubkeys: # If the last time we sent our pubkey was 28 days ago
@ -1480,9 +1709,11 @@ class receiveDataThread(threading.Thread):
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.' 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.'
shared.printLock.release() shared.printLock.release()
if requestedAddressVersionNumber == 2: if requestedAddressVersionNumber == 2:
shared.workerQueue.put(('doPOWForMyV2Pubkey',requestedHash)) shared.workerQueue.put((
'doPOWForMyV2Pubkey', requestedHash))
elif requestedAddressVersionNumber == 3: elif requestedAddressVersionNumber == 3:
shared.workerQueue.put(('doPOWForMyV3Pubkey',requestedHash)) shared.workerQueue.put((
'doPOWForMyV3Pubkey', requestedHash))
else: else:
shared.printLock.acquire() shared.printLock.acquire()
print 'Found getpubkey-requested-hash in my list of EC hashes BUT we already sent it recently. Ignoring request. The lastPubkeySendTime is:', lastPubkeySendTime print 'Found getpubkey-requested-hash in my list of EC hashes BUT we already sent it recently. Ignoring request. The lastPubkeySendTime is:', lastPubkeySendTime
@ -1492,7 +1723,6 @@ class receiveDataThread(threading.Thread):
print 'This getpubkey request is not for any of my keys.' print 'This getpubkey request is not for any of my keys.'
shared.printLock.release() shared.printLock.release()
# We have received an inv message # We have received an inv message
def recinv(self, data): def recinv(self, data):
totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave = 0 # ..from all peers, counting duplicates seperately (because they take up memory) totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave = 0 # ..from all peers, counting duplicates seperately (because they take up memory)
@ -1516,7 +1746,8 @@ class receiveDataThread(threading.Thread):
print 'We already have', totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave, 'items yet to retrieve from peers and over 1000 from this node in particular. Ignoring this inv message.' print 'We already have', totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave, 'items yet to retrieve from peers and over 1000 from this node in particular. Ignoring this inv message.'
shared.printLock.release() shared.printLock.release()
return return
self.objectsOfWhichThisRemoteNodeIsAlreadyAware[data[lengthOfVarint:32+lengthOfVarint]] = 0 self.objectsOfWhichThisRemoteNodeIsAlreadyAware[
data[lengthOfVarint:32 + lengthOfVarint]] = 0
if data[lengthOfVarint:32 + lengthOfVarint] in shared.inventory: if data[lengthOfVarint:32 + lengthOfVarint] in shared.inventory:
shared.printLock.acquire() shared.printLock.acquire()
print 'Inventory (in memory) has inventory item already.' print 'Inventory (in memory) has inventory item already.'
@ -1534,12 +1765,15 @@ class receiveDataThread(threading.Thread):
print 'We already have', totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave, 'items yet to retrieve from peers and over', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave), 'from this node in particular. Ignoring the rest of this inv message.' print 'We already have', totalNumberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave, 'items yet to retrieve from peers and over', len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave), 'from this node in particular. Ignoring the rest of this inv message.'
shared.printLock.release() shared.printLock.release()
break break
self.objectsOfWhichThisRemoteNodeIsAlreadyAware[data[lengthOfVarint+(32*i):32+lengthOfVarint+(32*i)]] = 0 self.objectsOfWhichThisRemoteNodeIsAlreadyAware[data[
self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[data[lengthOfVarint+(32*i):32+lengthOfVarint+(32*i)]] = 0 lengthOfVarint + (32 * i):32 + lengthOfVarint + (32 * i)]] = 0
numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[self.HOST] = len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave) self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave[
data[lengthOfVarint + (32 * i):32 + lengthOfVarint + (32 * i)]] = 0
numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer[
self.HOST] = len(self.objectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHave)
# Send a getdata message to our peer to request the object with the given
#Send a getdata message to our peer to request the object with the given hash # hash
def sendgetdata(self, hash): def sendgetdata(self, hash):
shared.printLock.acquire() shared.printLock.acquire()
print 'sending getdata to retrieve object with hash:', hash.encode('hex') print 'sending getdata to retrieve object with hash:', hash.encode('hex')
@ -1547,11 +1781,12 @@ class receiveDataThread(threading.Thread):
payload = '\x01' + hash payload = '\x01' + hash
headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits.
headerData += 'getdata\x00\x00\x00\x00\x00' headerData += 'getdata\x00\x00\x00\x00\x00'
headerData += pack('>L',len(payload)) #payload length. Note that we add an extra 8 for the nonce. headerData += pack('>L', len(
payload)) # payload length. Note that we add an extra 8 for the nonce.
headerData += hashlib.sha512(payload).digest()[:4] headerData += hashlib.sha512(payload).digest()[:4]
try: try:
self.sock.sendall(headerData + payload) self.sock.sendall(headerData + payload)
except Exception, err: except Exception as err:
# if not 'Bad file descriptor' in err: # if not 'Bad file descriptor' in err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('sock.sendall error: %s\n' % err) sys.stderr.write('sock.sendall error: %s\n' % err)
@ -1559,27 +1794,31 @@ class receiveDataThread(threading.Thread):
# We have received a getdata request from our peer # We have received a getdata request from our peer
def recgetdata(self, data): def recgetdata(self, data):
numberOfRequestedInventoryItems, lengthOfVarint = decodeVarint(data[:10]) numberOfRequestedInventoryItems, lengthOfVarint = decodeVarint(
data[:10])
if len(data) < lengthOfVarint + (32 * numberOfRequestedInventoryItems): if len(data) < lengthOfVarint + (32 * numberOfRequestedInventoryItems):
print 'getdata message does not contain enough data. Ignoring.' print 'getdata message does not contain enough data. Ignoring.'
return return
for i in xrange(numberOfRequestedInventoryItems): for i in xrange(numberOfRequestedInventoryItems):
hash = data[lengthOfVarint+(i*32):32+lengthOfVarint+(i*32)] hash = data[lengthOfVarint + (
i * 32):32 + lengthOfVarint + (i * 32)]
shared.printLock.acquire() shared.printLock.acquire()
print 'received getdata request for item:', hash.encode('hex') print 'received getdata request for item:', hash.encode('hex')
shared.printLock.release() shared.printLock.release()
# print 'inventory is', shared.inventory # print 'inventory is', shared.inventory
if hash in shared.inventory: if hash in shared.inventory:
objectType, streamNumber, payload, receivedTime = shared.inventory[hash] objectType, streamNumber, payload, receivedTime = shared.inventory[
hash]
self.sendData(objectType, payload) self.sendData(objectType, payload)
else: else:
t = (hash,) t = (hash,)
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''select objecttype, payload from inventory where hash=?''') shared.sqlSubmitQueue.put(
'''select objecttype, payload from inventory where hash=?''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
if queryreturn <> []: if queryreturn != []:
for row in queryreturn: for row in queryreturn:
objectType, payload = row objectType, payload = row
self.sendData(objectType, payload) self.sendData(objectType, payload)
@ -1610,13 +1849,14 @@ class receiveDataThread(threading.Thread):
shared.printLock.release() shared.printLock.release()
headerData += 'broadcast\x00\x00\x00' headerData += 'broadcast\x00\x00\x00'
else: else:
sys.stderr.write('Error: sendData has been asked to send a strange objectType: %s\n' % str(objectType)) sys.stderr.write(
'Error: sendData has been asked to send a strange objectType: %s\n' % str(objectType))
return return
headerData += pack('>L', len(payload)) # payload length. headerData += pack('>L', len(payload)) # payload length.
headerData += hashlib.sha512(payload).digest()[:4] headerData += hashlib.sha512(payload).digest()[:4]
try: try:
self.sock.sendall(headerData + payload) self.sock.sendall(headerData + payload)
except Exception, err: except Exception as err:
# if not 'Bad file descriptor' in err: # if not 'Bad file descriptor' in err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('sock.sendall error: %s\n' % err) sys.stderr.write('sock.sendall error: %s\n' % err)
@ -1629,12 +1869,12 @@ class receiveDataThread(threading.Thread):
shared.printLock.release() shared.printLock.release()
shared.broadcastToSendDataQueues((self.streamNumber, 'sendinv', hash)) shared.broadcastToSendDataQueues((self.streamNumber, 'sendinv', hash))
# We have received an addr message. # We have received an addr message.
def recaddr(self, data): def recaddr(self, data):
listOfAddressDetailsToBroadcastToPeers = [] listOfAddressDetailsToBroadcastToPeers = []
numberOfAddressesIncluded = 0 numberOfAddressesIncluded = 0
numberOfAddressesIncluded, lengthOfNumberOfAddresses = decodeVarint(data[:10]) numberOfAddressesIncluded, lengthOfNumberOfAddresses = decodeVarint(
data[:10])
if verbose >= 1: if verbose >= 1:
shared.printLock.acquire() shared.printLock.acquire()
@ -1656,17 +1896,20 @@ class receiveDataThread(threading.Thread):
print 'Skipping IPv6 address.', repr(data[16 + lengthOfNumberOfAddresses + (34 * i):28 + lengthOfNumberOfAddresses + (34 * i)]) print 'Skipping IPv6 address.', repr(data[16 + lengthOfNumberOfAddresses + (34 * i):28 + lengthOfNumberOfAddresses + (34 * i)])
shared.printLock.release() shared.printLock.release()
continue continue
except Exception, err: except Exception as err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('ERROR TRYING TO UNPACK recaddr (to test for an IPv6 address). Message: %s\n' % str(err)) sys.stderr.write(
'ERROR TRYING TO UNPACK recaddr (to test for an IPv6 address). Message: %s\n' % str(err))
shared.printLock.release() shared.printLock.release()
break # giving up on unpacking any more. We should still be connected however. break # giving up on unpacking any more. We should still be connected however.
try: try:
recaddrStream, = unpack('>I',data[4+lengthOfNumberOfAddresses+(34*i):8+lengthOfNumberOfAddresses+(34*i)]) recaddrStream, = unpack('>I', data[4 + lengthOfNumberOfAddresses + (
except Exception, err: 34 * i):8 + lengthOfNumberOfAddresses + (34 * i)])
except Exception as err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('ERROR TRYING TO UNPACK recaddr (recaddrStream). Message: %s\n' % str(err)) sys.stderr.write(
'ERROR TRYING TO UNPACK recaddr (recaddrStream). Message: %s\n' % str(err))
shared.printLock.release() shared.printLock.release()
break # giving up on unpacking any more. We should still be connected however. break # giving up on unpacking any more. We should still be connected however.
if recaddrStream == 0: if recaddrStream == 0:
@ -1674,22 +1917,28 @@ class receiveDataThread(threading.Thread):
if recaddrStream != self.streamNumber and recaddrStream != (self.streamNumber * 2) and recaddrStream != ((self.streamNumber * 2) + 1): # if the embedded stream number is not in my stream or either of my child streams then ignore it. Someone might be trying funny business. if recaddrStream != self.streamNumber and recaddrStream != (self.streamNumber * 2) and recaddrStream != ((self.streamNumber * 2) + 1): # if the embedded stream number is not in my stream or either of my child streams then ignore it. Someone might be trying funny business.
continue continue
try: try:
recaddrServices, = unpack('>Q',data[8+lengthOfNumberOfAddresses+(34*i):16+lengthOfNumberOfAddresses+(34*i)]) recaddrServices, = unpack('>Q', data[8 + lengthOfNumberOfAddresses + (
except Exception, err: 34 * i):16 + lengthOfNumberOfAddresses + (34 * i)])
except Exception as err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('ERROR TRYING TO UNPACK recaddr (recaddrServices). Message: %s\n' % str(err)) sys.stderr.write(
'ERROR TRYING TO UNPACK recaddr (recaddrServices). Message: %s\n' % str(err))
shared.printLock.release() shared.printLock.release()
break # giving up on unpacking any more. We should still be connected however. break # giving up on unpacking any more. We should still be connected however.
try: try:
recaddrPort, = unpack('>H',data[32+lengthOfNumberOfAddresses+(34*i):34+lengthOfNumberOfAddresses+(34*i)]) recaddrPort, = unpack('>H', data[32 + lengthOfNumberOfAddresses + (
except Exception, err: 34 * i):34 + lengthOfNumberOfAddresses + (34 * i)])
except Exception as err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('ERROR TRYING TO UNPACK recaddr (recaddrPort). Message: %s\n' % str(err)) sys.stderr.write(
'ERROR TRYING TO UNPACK recaddr (recaddrPort). Message: %s\n' % str(err))
shared.printLock.release() shared.printLock.release()
break # giving up on unpacking any more. We should still be connected however. break # giving up on unpacking any more. We should still be connected however.
#print 'Within recaddr(): IP', recaddrIP, ', Port', recaddrPort, ', i', i # print 'Within recaddr(): IP', recaddrIP, ', Port',
hostFromAddrMessage = socket.inet_ntoa(data[28+lengthOfNumberOfAddresses+(34*i):32+lengthOfNumberOfAddresses+(34*i)]) # recaddrPort, ', i', i
hostFromAddrMessage = socket.inet_ntoa(data[
28 + lengthOfNumberOfAddresses + (34 * i):32 + lengthOfNumberOfAddresses + (34 * i)])
# print 'hostFromAddrMessage', hostFromAddrMessage # print 'hostFromAddrMessage', hostFromAddrMessage
if data[28 + lengthOfNumberOfAddresses + (34 * i)] == '\x7F': if data[28 + lengthOfNumberOfAddresses + (34 * i)] == '\x7F':
print 'Ignoring IP address in loopback range:', hostFromAddrMessage print 'Ignoring IP address in loopback range:', hostFromAddrMessage
@ -1697,7 +1946,8 @@ class receiveDataThread(threading.Thread):
if isHostInPrivateIPRange(hostFromAddrMessage): if isHostInPrivateIPRange(hostFromAddrMessage):
print 'Ignoring IP address in private range:', hostFromAddrMessage print 'Ignoring IP address in private range:', hostFromAddrMessage
continue continue
timeSomeoneElseReceivedMessageFromThisNode, = unpack('>I',data[lengthOfNumberOfAddresses+(34*i):4+lengthOfNumberOfAddresses+(34*i)]) #This is the 'time' value in the received addr message. timeSomeoneElseReceivedMessageFromThisNode, = unpack('>I', data[lengthOfNumberOfAddresses + (
34 * i):4 + lengthOfNumberOfAddresses + (34 * i)]) # This is the 'time' value in the received addr message.
if recaddrStream not in shared.knownNodes: # knownNodes is a dictionary of dictionaries with one outer dictionary for each stream. If the outer stream dictionary doesn't exist yet then we must make it. if recaddrStream not in shared.knownNodes: # knownNodes is a dictionary of dictionaries with one outer dictionary for each stream. If the outer stream dictionary doesn't exist yet then we must make it.
shared.knownNodesLock.acquire() shared.knownNodesLock.acquire()
shared.knownNodes[recaddrStream] = {} shared.knownNodes[recaddrStream] = {}
@ -1705,16 +1955,22 @@ class receiveDataThread(threading.Thread):
if hostFromAddrMessage not in shared.knownNodes[recaddrStream]: if hostFromAddrMessage not in shared.knownNodes[recaddrStream]:
if len(shared.knownNodes[recaddrStream]) < 20000 and timeSomeoneElseReceivedMessageFromThisNode > (int(time.time()) - 10800) and timeSomeoneElseReceivedMessageFromThisNode < (int(time.time()) + 10800): # If we have more than 20000 nodes in our list already then just forget about adding more. Also, make sure that the time that someone else received a message from this node is within three hours from now. if len(shared.knownNodes[recaddrStream]) < 20000 and timeSomeoneElseReceivedMessageFromThisNode > (int(time.time()) - 10800) and timeSomeoneElseReceivedMessageFromThisNode < (int(time.time()) + 10800): # If we have more than 20000 nodes in our list already then just forget about adding more. Also, make sure that the time that someone else received a message from this node is within three hours from now.
shared.knownNodesLock.acquire() shared.knownNodesLock.acquire()
shared.knownNodes[recaddrStream][hostFromAddrMessage] = (recaddrPort, timeSomeoneElseReceivedMessageFromThisNode) shared.knownNodes[recaddrStream][hostFromAddrMessage] = (
recaddrPort, timeSomeoneElseReceivedMessageFromThisNode)
shared.knownNodesLock.release() shared.knownNodesLock.release()
needToWriteKnownNodesToDisk = True needToWriteKnownNodesToDisk = True
hostDetails = (timeSomeoneElseReceivedMessageFromThisNode, recaddrStream, recaddrServices, hostFromAddrMessage, recaddrPort) hostDetails = (
listOfAddressDetailsToBroadcastToPeers.append(hostDetails) timeSomeoneElseReceivedMessageFromThisNode,
recaddrStream, recaddrServices, hostFromAddrMessage, recaddrPort)
listOfAddressDetailsToBroadcastToPeers.append(
hostDetails)
else: else:
PORT, timeLastReceivedMessageFromThisNode = shared.knownNodes[recaddrStream][hostFromAddrMessage]#PORT in this case is either the port we used to connect to the remote node, or the port that was specified by someone else in a past addr message. PORT, timeLastReceivedMessageFromThisNode = shared.knownNodes[recaddrStream][
hostFromAddrMessage] # PORT in this case is either the port we used to connect to the remote node, or the port that was specified by someone else in a past addr message.
if (timeLastReceivedMessageFromThisNode < timeSomeoneElseReceivedMessageFromThisNode) and (timeSomeoneElseReceivedMessageFromThisNode < int(time.time())): if (timeLastReceivedMessageFromThisNode < timeSomeoneElseReceivedMessageFromThisNode) and (timeSomeoneElseReceivedMessageFromThisNode < int(time.time())):
shared.knownNodesLock.acquire() shared.knownNodesLock.acquire()
shared.knownNodes[recaddrStream][hostFromAddrMessage] = (PORT, timeSomeoneElseReceivedMessageFromThisNode) shared.knownNodes[recaddrStream][hostFromAddrMessage] = (
PORT, timeSomeoneElseReceivedMessageFromThisNode)
shared.knownNodesLock.release() shared.knownNodesLock.release()
if PORT != recaddrPort: if PORT != recaddrPort:
print 'Strange occurance: The port specified in an addr message', str(recaddrPort), 'does not match the port', str(PORT), 'that this program (or some other peer) used to connect to it', str(hostFromAddrMessage), '. Perhaps they changed their port or are using a strange NAT configuration.' print 'Strange occurance: The port specified in an addr message', str(recaddrPort), 'does not match the port', str(PORT), 'that this program (or some other peer) used to connect to it', str(hostFromAddrMessage), '. Perhaps they changed their port or are using a strange NAT configuration.'
@ -1724,7 +1980,8 @@ class receiveDataThread(threading.Thread):
pickle.dump(shared.knownNodes, output) pickle.dump(shared.knownNodes, output)
output.close() output.close()
shared.knownNodesLock.release() shared.knownNodesLock.release()
self.broadcastaddr(listOfAddressDetailsToBroadcastToPeers) #no longer broadcast self.broadcastaddr(
listOfAddressDetailsToBroadcastToPeers) # no longer broadcast
shared.printLock.acquire() shared.printLock.acquire()
print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.' print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.'
shared.printLock.release() shared.printLock.release()
@ -1743,17 +2000,20 @@ class receiveDataThread(threading.Thread):
print 'Skipping IPv6 address.', repr(data[20 + lengthOfNumberOfAddresses + (38 * i):32 + lengthOfNumberOfAddresses + (38 * i)]) print 'Skipping IPv6 address.', repr(data[20 + lengthOfNumberOfAddresses + (38 * i):32 + lengthOfNumberOfAddresses + (38 * i)])
shared.printLock.release() shared.printLock.release()
continue continue
except Exception, err: except Exception as err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('ERROR TRYING TO UNPACK recaddr (to test for an IPv6 address). Message: %s\n' % str(err)) sys.stderr.write(
'ERROR TRYING TO UNPACK recaddr (to test for an IPv6 address). Message: %s\n' % str(err))
shared.printLock.release() shared.printLock.release()
break # giving up on unpacking any more. We should still be connected however. break # giving up on unpacking any more. We should still be connected however.
try: try:
recaddrStream, = unpack('>I',data[8+lengthOfNumberOfAddresses+(38*i):12+lengthOfNumberOfAddresses+(38*i)]) recaddrStream, = unpack('>I', data[8 + lengthOfNumberOfAddresses + (
except Exception, err: 38 * i):12 + lengthOfNumberOfAddresses + (38 * i)])
except Exception as err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('ERROR TRYING TO UNPACK recaddr (recaddrStream). Message: %s\n' % str(err)) sys.stderr.write(
'ERROR TRYING TO UNPACK recaddr (recaddrStream). Message: %s\n' % str(err))
shared.printLock.release() shared.printLock.release()
break # giving up on unpacking any more. We should still be connected however. break # giving up on unpacking any more. We should still be connected however.
if recaddrStream == 0: if recaddrStream == 0:
@ -1761,22 +2021,28 @@ class receiveDataThread(threading.Thread):
if recaddrStream != self.streamNumber and recaddrStream != (self.streamNumber * 2) and recaddrStream != ((self.streamNumber * 2) + 1): # if the embedded stream number is not in my stream or either of my child streams then ignore it. Someone might be trying funny business. if recaddrStream != self.streamNumber and recaddrStream != (self.streamNumber * 2) and recaddrStream != ((self.streamNumber * 2) + 1): # if the embedded stream number is not in my stream or either of my child streams then ignore it. Someone might be trying funny business.
continue continue
try: try:
recaddrServices, = unpack('>Q',data[12+lengthOfNumberOfAddresses+(38*i):20+lengthOfNumberOfAddresses+(38*i)]) recaddrServices, = unpack('>Q', data[12 + lengthOfNumberOfAddresses + (
except Exception, err: 38 * i):20 + lengthOfNumberOfAddresses + (38 * i)])
except Exception as err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('ERROR TRYING TO UNPACK recaddr (recaddrServices). Message: %s\n' % str(err)) sys.stderr.write(
'ERROR TRYING TO UNPACK recaddr (recaddrServices). Message: %s\n' % str(err))
shared.printLock.release() shared.printLock.release()
break # giving up on unpacking any more. We should still be connected however. break # giving up on unpacking any more. We should still be connected however.
try: try:
recaddrPort, = unpack('>H',data[36+lengthOfNumberOfAddresses+(38*i):38+lengthOfNumberOfAddresses+(38*i)]) recaddrPort, = unpack('>H', data[36 + lengthOfNumberOfAddresses + (
except Exception, err: 38 * i):38 + lengthOfNumberOfAddresses + (38 * i)])
except Exception as err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('ERROR TRYING TO UNPACK recaddr (recaddrPort). Message: %s\n' % str(err)) sys.stderr.write(
'ERROR TRYING TO UNPACK recaddr (recaddrPort). Message: %s\n' % str(err))
shared.printLock.release() shared.printLock.release()
break # giving up on unpacking any more. We should still be connected however. break # giving up on unpacking any more. We should still be connected however.
#print 'Within recaddr(): IP', recaddrIP, ', Port', recaddrPort, ', i', i # print 'Within recaddr(): IP', recaddrIP, ', Port',
hostFromAddrMessage = socket.inet_ntoa(data[32+lengthOfNumberOfAddresses+(38*i):36+lengthOfNumberOfAddresses+(38*i)]) # recaddrPort, ', i', i
hostFromAddrMessage = socket.inet_ntoa(data[
32 + lengthOfNumberOfAddresses + (38 * i):36 + lengthOfNumberOfAddresses + (38 * i)])
# print 'hostFromAddrMessage', hostFromAddrMessage # print 'hostFromAddrMessage', hostFromAddrMessage
if data[32 + lengthOfNumberOfAddresses + (38 * i)] == '\x7F': if data[32 + lengthOfNumberOfAddresses + (38 * i)] == '\x7F':
print 'Ignoring IP address in loopback range:', hostFromAddrMessage print 'Ignoring IP address in loopback range:', hostFromAddrMessage
@ -1787,7 +2053,8 @@ class receiveDataThread(threading.Thread):
if data[32 + lengthOfNumberOfAddresses + (38 * i):34 + lengthOfNumberOfAddresses + (38 * i)] == '\xC0A8': if data[32 + lengthOfNumberOfAddresses + (38 * i):34 + lengthOfNumberOfAddresses + (38 * i)] == '\xC0A8':
print 'Ignoring IP address in private range:', hostFromAddrMessage print 'Ignoring IP address in private range:', hostFromAddrMessage
continue continue
timeSomeoneElseReceivedMessageFromThisNode, = unpack('>Q',data[lengthOfNumberOfAddresses+(38*i):8+lengthOfNumberOfAddresses+(38*i)]) #This is the 'time' value in the received addr message. 64-bit. timeSomeoneElseReceivedMessageFromThisNode, = unpack('>Q', data[lengthOfNumberOfAddresses + (
38 * i):8 + lengthOfNumberOfAddresses + (38 * i)]) # This is the 'time' value in the received addr message. 64-bit.
if recaddrStream not in shared.knownNodes: # knownNodes is a dictionary of dictionaries with one outer dictionary for each stream. If the outer stream dictionary doesn't exist yet then we must make it. if recaddrStream not in shared.knownNodes: # knownNodes is a dictionary of dictionaries with one outer dictionary for each stream. If the outer stream dictionary doesn't exist yet then we must make it.
shared.knownNodesLock.acquire() shared.knownNodesLock.acquire()
shared.knownNodes[recaddrStream] = {} shared.knownNodes[recaddrStream] = {}
@ -1795,19 +2062,25 @@ class receiveDataThread(threading.Thread):
if hostFromAddrMessage not in shared.knownNodes[recaddrStream]: if hostFromAddrMessage not in shared.knownNodes[recaddrStream]:
if len(shared.knownNodes[recaddrStream]) < 20000 and timeSomeoneElseReceivedMessageFromThisNode > (int(time.time()) - 10800) and timeSomeoneElseReceivedMessageFromThisNode < (int(time.time()) + 10800): # If we have more than 20000 nodes in our list already then just forget about adding more. Also, make sure that the time that someone else received a message from this node is within three hours from now. if len(shared.knownNodes[recaddrStream]) < 20000 and timeSomeoneElseReceivedMessageFromThisNode > (int(time.time()) - 10800) and timeSomeoneElseReceivedMessageFromThisNode < (int(time.time()) + 10800): # If we have more than 20000 nodes in our list already then just forget about adding more. Also, make sure that the time that someone else received a message from this node is within three hours from now.
shared.knownNodesLock.acquire() shared.knownNodesLock.acquire()
shared.knownNodes[recaddrStream][hostFromAddrMessage] = (recaddrPort, timeSomeoneElseReceivedMessageFromThisNode) shared.knownNodes[recaddrStream][hostFromAddrMessage] = (
recaddrPort, timeSomeoneElseReceivedMessageFromThisNode)
shared.knownNodesLock.release() shared.knownNodesLock.release()
shared.printLock.acquire() shared.printLock.acquire()
print 'added new node', hostFromAddrMessage, 'to knownNodes in stream', recaddrStream print 'added new node', hostFromAddrMessage, 'to knownNodes in stream', recaddrStream
shared.printLock.release() shared.printLock.release()
needToWriteKnownNodesToDisk = True needToWriteKnownNodesToDisk = True
hostDetails = (timeSomeoneElseReceivedMessageFromThisNode, recaddrStream, recaddrServices, hostFromAddrMessage, recaddrPort) hostDetails = (
listOfAddressDetailsToBroadcastToPeers.append(hostDetails) timeSomeoneElseReceivedMessageFromThisNode,
recaddrStream, recaddrServices, hostFromAddrMessage, recaddrPort)
listOfAddressDetailsToBroadcastToPeers.append(
hostDetails)
else: else:
PORT, timeLastReceivedMessageFromThisNode = shared.knownNodes[recaddrStream][hostFromAddrMessage]#PORT in this case is either the port we used to connect to the remote node, or the port that was specified by someone else in a past addr message. PORT, timeLastReceivedMessageFromThisNode = shared.knownNodes[recaddrStream][
hostFromAddrMessage] # PORT in this case is either the port we used to connect to the remote node, or the port that was specified by someone else in a past addr message.
if (timeLastReceivedMessageFromThisNode < timeSomeoneElseReceivedMessageFromThisNode) and (timeSomeoneElseReceivedMessageFromThisNode < int(time.time())): if (timeLastReceivedMessageFromThisNode < timeSomeoneElseReceivedMessageFromThisNode) and (timeSomeoneElseReceivedMessageFromThisNode < int(time.time())):
shared.knownNodesLock.acquire() shared.knownNodesLock.acquire()
shared.knownNodes[recaddrStream][hostFromAddrMessage] = (PORT, timeSomeoneElseReceivedMessageFromThisNode) shared.knownNodes[recaddrStream][hostFromAddrMessage] = (
PORT, timeSomeoneElseReceivedMessageFromThisNode)
shared.knownNodesLock.release() shared.knownNodesLock.release()
if PORT != recaddrPort: if PORT != recaddrPort:
print 'Strange occurance: The port specified in an addr message', str(recaddrPort), 'does not match the port', str(PORT), 'that this program (or some other peer) used to connect to it', str(hostFromAddrMessage), '. Perhaps they changed their port or are using a strange NAT configuration.' print 'Strange occurance: The port specified in an addr message', str(recaddrPort), 'does not match the port', str(PORT), 'that this program (or some other peer) used to connect to it', str(hostFromAddrMessage), '. Perhaps they changed their port or are using a strange NAT configuration.'
@ -1822,17 +2095,22 @@ class receiveDataThread(threading.Thread):
print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.' print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.'
shared.printLock.release() shared.printLock.release()
# Function runs when we want to broadcast an addr message to all of our
#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. # 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): def broadcastaddr(self, listOfAddressDetailsToBroadcastToPeers):
numberOfAddressesInAddrMessage = len(listOfAddressDetailsToBroadcastToPeers) numberOfAddressesInAddrMessage = len(
listOfAddressDetailsToBroadcastToPeers)
payload = '' payload = ''
for hostDetails in listOfAddressDetailsToBroadcastToPeers: for hostDetails in listOfAddressDetailsToBroadcastToPeers:
timeLastReceivedMessageFromThisNode, streamNumber, services, host, port = hostDetails timeLastReceivedMessageFromThisNode, streamNumber, services, host, port = hostDetails
payload += pack('>Q',timeLastReceivedMessageFromThisNode) #now uses 64-bit time payload += pack(
'>Q', timeLastReceivedMessageFromThisNode) # now uses 64-bit time
payload += pack('>I', streamNumber) payload += pack('>I', streamNumber)
payload += pack('>q',services) #service bit flags offered by this node payload += pack(
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + socket.inet_aton(host) '>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 += pack('>H', port) # remote port
payload = encodeVarint(numberOfAddressesInAddrMessage) + payload payload = encodeVarint(numberOfAddressesInAddrMessage) + payload
@ -1845,7 +2123,8 @@ class receiveDataThread(threading.Thread):
shared.printLock.acquire() shared.printLock.acquire()
print 'Broadcasting addr with', numberOfAddressesInAddrMessage, 'entries.' print 'Broadcasting addr with', numberOfAddressesInAddrMessage, 'entries.'
shared.printLock.release() shared.printLock.release()
shared.broadcastToSendDataQueues((self.streamNumber, 'sendaddr', datatosend)) shared.broadcastToSendDataQueues((
self.streamNumber, 'sendaddr', datatosend))
# Send a big addr message to our peer # Send a big addr message to our peer
def sendaddr(self): def sendaddr(self):
@ -1854,7 +2133,9 @@ class receiveDataThread(threading.Thread):
addrsInChildStreamRight = {} addrsInChildStreamRight = {}
# print 'knownNodes', shared.knownNodes # print 'knownNodes', shared.knownNodes
#We are going to share a maximum number of 1000 addrs with our peer. 500 from this stream, 250 from the left child stream, and 250 from the right child stream. # We are going to share a maximum number of 1000 addrs with our peer.
# 500 from this stream, 250 from the left child stream, and 250 from
# the right child stream.
shared.knownNodesLock.acquire() shared.knownNodesLock.acquire()
if len(shared.knownNodes[self.streamNumber]) > 0: if len(shared.knownNodes[self.streamNumber]) > 0:
for i in range(500): for i in range(500):
@ -1862,21 +2143,26 @@ class receiveDataThread(threading.Thread):
HOST, = random.sample(shared.knownNodes[self.streamNumber], 1) HOST, = random.sample(shared.knownNodes[self.streamNumber], 1)
if isHostInPrivateIPRange(HOST): if isHostInPrivateIPRange(HOST):
continue continue
addrsInMyStream[HOST] = shared.knownNodes[self.streamNumber][HOST] addrsInMyStream[HOST] = shared.knownNodes[
self.streamNumber][HOST]
if len(shared.knownNodes[self.streamNumber * 2]) > 0: if len(shared.knownNodes[self.streamNumber * 2]) > 0:
for i in range(250): for i in range(250):
random.seed() random.seed()
HOST, = random.sample(shared.knownNodes[self.streamNumber*2], 1) HOST, = random.sample(shared.knownNodes[
self.streamNumber * 2], 1)
if isHostInPrivateIPRange(HOST): if isHostInPrivateIPRange(HOST):
continue continue
addrsInChildStreamLeft[HOST] = shared.knownNodes[self.streamNumber*2][HOST] addrsInChildStreamLeft[HOST] = shared.knownNodes[
self.streamNumber * 2][HOST]
if len(shared.knownNodes[(self.streamNumber * 2) + 1]) > 0: if len(shared.knownNodes[(self.streamNumber * 2) + 1]) > 0:
for i in range(250): for i in range(250):
random.seed() random.seed()
HOST, = random.sample(shared.knownNodes[(self.streamNumber*2)+1], 1) HOST, = random.sample(shared.knownNodes[
(self.streamNumber * 2) + 1], 1)
if isHostInPrivateIPRange(HOST): if isHostInPrivateIPRange(HOST):
continue continue
addrsInChildStreamRight[HOST] = shared.knownNodes[(self.streamNumber*2)+1][HOST] addrsInChildStreamRight[HOST] = shared.knownNodes[
(self.streamNumber * 2) + 1][HOST]
shared.knownNodesLock.release() shared.knownNodesLock.release()
numberOfAddressesInAddrMessage = 0 numberOfAddressesInAddrMessage = 0
payload = '' payload = ''
@ -1885,28 +2171,37 @@ class receiveDataThread(threading.Thread):
PORT, timeLastReceivedMessageFromThisNode = value PORT, timeLastReceivedMessageFromThisNode = value
if timeLastReceivedMessageFromThisNode > (int(time.time()) - maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old.. if timeLastReceivedMessageFromThisNode > (int(time.time()) - maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old..
numberOfAddressesInAddrMessage += 1 numberOfAddressesInAddrMessage += 1
payload += pack('>Q',timeLastReceivedMessageFromThisNode) #64-bit time payload += pack(
'>Q', timeLastReceivedMessageFromThisNode) # 64-bit time
payload += pack('>I', self.streamNumber) payload += pack('>I', self.streamNumber)
payload += pack('>q',1) #service bit flags offered by this node payload += pack(
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + socket.inet_aton(HOST) '>q', 1) # 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 += pack('>H', PORT) # remote port
for HOST, value in addrsInChildStreamLeft.items(): for HOST, value in addrsInChildStreamLeft.items():
PORT, timeLastReceivedMessageFromThisNode = value PORT, timeLastReceivedMessageFromThisNode = value
if timeLastReceivedMessageFromThisNode > (int(time.time()) - maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old.. if timeLastReceivedMessageFromThisNode > (int(time.time()) - maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old..
numberOfAddressesInAddrMessage += 1 numberOfAddressesInAddrMessage += 1
payload += pack('>Q',timeLastReceivedMessageFromThisNode) #64-bit time payload += pack(
'>Q', timeLastReceivedMessageFromThisNode) # 64-bit time
payload += pack('>I', self.streamNumber * 2) payload += pack('>I', self.streamNumber * 2)
payload += pack('>q',1) #service bit flags offered by this node payload += pack(
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + socket.inet_aton(HOST) '>q', 1) # 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 += pack('>H', PORT) # remote port
for HOST, value in addrsInChildStreamRight.items(): for HOST, value in addrsInChildStreamRight.items():
PORT, timeLastReceivedMessageFromThisNode = value PORT, timeLastReceivedMessageFromThisNode = value
if timeLastReceivedMessageFromThisNode > (int(time.time()) - maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old.. if timeLastReceivedMessageFromThisNode > (int(time.time()) - maximumAgeOfNodesThatIAdvertiseToOthers): # If it is younger than 3 hours old..
numberOfAddressesInAddrMessage += 1 numberOfAddressesInAddrMessage += 1
payload += pack('>Q',timeLastReceivedMessageFromThisNode) #64-bit time payload += pack(
'>Q', timeLastReceivedMessageFromThisNode) # 64-bit time
payload += pack('>I', (self.streamNumber * 2) + 1) payload += pack('>I', (self.streamNumber * 2) + 1)
payload += pack('>q',1) #service bit flags offered by this node payload += pack(
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + socket.inet_aton(HOST) '>q', 1) # 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 += pack('>H', PORT) # remote port
payload = encodeVarint(numberOfAddressesInAddrMessage) + payload payload = encodeVarint(numberOfAddressesInAddrMessage) + payload
@ -1920,7 +2215,7 @@ class receiveDataThread(threading.Thread):
shared.printLock.acquire() shared.printLock.acquire()
print 'Sending addr with', numberOfAddressesInAddrMessage, 'entries.' print 'Sending addr with', numberOfAddressesInAddrMessage, 'entries.'
shared.printLock.release() shared.printLock.release()
except Exception, err: except Exception as err:
# if not 'Bad file descriptor' in err: # if not 'Bad file descriptor' in err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('sock.sendall error: %s\n' % err) sys.stderr.write('sock.sendall error: %s\n' % err)
@ -1944,13 +2239,16 @@ class receiveDataThread(threading.Thread):
# print 'myExternalIP', self.myExternalIP # print 'myExternalIP', self.myExternalIP
self.remoteNodeIncomingPort, = unpack('>H', data[70:72]) self.remoteNodeIncomingPort, = unpack('>H', data[70:72])
# print 'remoteNodeIncomingPort', self.remoteNodeIncomingPort # print 'remoteNodeIncomingPort', self.remoteNodeIncomingPort
useragentLength, lengthOfUseragentVarint = decodeVarint(data[80:84]) useragentLength, lengthOfUseragentVarint = decodeVarint(
data[80:84])
readPosition = 80 + lengthOfUseragentVarint readPosition = 80 + lengthOfUseragentVarint
useragent = data[readPosition:readPosition + useragentLength] useragent = data[readPosition:readPosition + useragentLength]
readPosition += useragentLength readPosition += useragentLength
numberOfStreamsInVersionMessage, lengthOfNumberOfStreamsInVersionMessage = decodeVarint(data[readPosition:]) numberOfStreamsInVersionMessage, lengthOfNumberOfStreamsInVersionMessage = decodeVarint(
data[readPosition:])
readPosition += lengthOfNumberOfStreamsInVersionMessage readPosition += lengthOfNumberOfStreamsInVersionMessage
self.streamNumber, lengthOfRemoteStreamNumber = decodeVarint(data[readPosition:]) self.streamNumber, lengthOfRemoteStreamNumber = decodeVarint(
data[readPosition:])
shared.printLock.acquire() shared.printLock.acquire()
print 'Remote node useragent:', useragent, ' stream number:', self.streamNumber print 'Remote node useragent:', useragent, ' stream number:', self.streamNumber
shared.printLock.release() shared.printLock.release()
@ -1960,20 +2258,25 @@ class receiveDataThread(threading.Thread):
print 'Closed connection to', self.HOST, 'because they are interested in stream', self.streamNumber, '.' print 'Closed connection to', self.HOST, 'because they are interested in stream', self.streamNumber, '.'
shared.printLock.release() shared.printLock.release()
return return
shared.connectedHostsList[self.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. shared.connectedHostsList[
#If this was an incoming connection, then the sendData thread doesn't know the stream. We have to set it. self.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.
# If this was an incoming connection, then the sendData thread
# doesn't know the stream. We have to set it.
if not self.initiatedConnection: if not self.initiatedConnection:
shared.broadcastToSendDataQueues((0,'setStreamNumber',(self.HOST,self.streamNumber))) shared.broadcastToSendDataQueues((
0, 'setStreamNumber', (self.HOST, self.streamNumber)))
if data[72:80] == eightBytesOfRandomDataUsedToDetectConnectionsToSelf: if data[72:80] == eightBytesOfRandomDataUsedToDetectConnectionsToSelf:
shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST)) shared.broadcastToSendDataQueues((0, 'shutdown', self.HOST))
shared.printLock.acquire() shared.printLock.acquire()
print 'Closing connection to myself: ', self.HOST print 'Closing connection to myself: ', self.HOST
shared.printLock.release() shared.printLock.release()
return return
shared.broadcastToSendDataQueues((0,'setRemoteProtocolVersion',(self.HOST,self.remoteProtocolVersion))) shared.broadcastToSendDataQueues((0, 'setRemoteProtocolVersion', (
self.HOST, self.remoteProtocolVersion)))
shared.knownNodesLock.acquire() shared.knownNodesLock.acquire()
shared.knownNodes[self.streamNumber][self.HOST] = (self.remoteNodeIncomingPort, int(time.time())) shared.knownNodes[self.streamNumber][self.HOST] = (
self.remoteNodeIncomingPort, int(time.time()))
output = open(shared.appdata + 'knownnodes.dat', 'wb') output = open(shared.appdata + 'knownnodes.dat', 'wb')
pickle.dump(shared.knownNodes, output) pickle.dump(shared.knownNodes, output)
output.close() output.close()
@ -1989,8 +2292,9 @@ class receiveDataThread(threading.Thread):
print 'Sending version message' print 'Sending version message'
shared.printLock.release() shared.printLock.release()
try: try:
self.sock.sendall(assembleVersionMessage(self.HOST,self.PORT,self.streamNumber)) self.sock.sendall(assembleVersionMessage(
except Exception, err: self.HOST, self.PORT, self.streamNumber))
except Exception as err:
# if not 'Bad file descriptor' in err: # if not 'Bad file descriptor' in err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('sock.sendall error: %s\n' % err) sys.stderr.write('sock.sendall error: %s\n' % err)
@ -2002,21 +2306,26 @@ class receiveDataThread(threading.Thread):
print 'Sending verack' print 'Sending verack'
shared.printLock.release() shared.printLock.release()
try: 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') self.sock.sendall(
except Exception, err: '\xE9\xBE\xB4\xD9\x76\x65\x72\x61\x63\x6B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xcf\x83\xe1\x35')
except Exception as err:
# if not 'Bad file descriptor' in err: # if not 'Bad file descriptor' in err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('sock.sendall error: %s\n' % err) sys.stderr.write('sock.sendall error: %s\n' % err)
shared.printLock.release() shared.printLock.release()
#cf 83 e1 35 # cf
# 83
# e1
# 35
self.verackSent = True self.verackSent = True
if self.verackReceived == True: if self.verackReceived:
self.connectionFullyEstablished() self.connectionFullyEstablished()
# Every connection to a peer has a sendDataThread (and also a
#Every connection to a peer has a sendDataThread (and also a receiveDataThread). # receiveDataThread).
class sendDataThread(threading.Thread): class sendDataThread(threading.Thread):
def __init__(self): def __init__(self):
threading.Thread.__init__(self) threading.Thread.__init__(self)
self.mailbox = Queue.Queue() self.mailbox = Queue.Queue()
@ -2026,27 +2335,36 @@ class sendDataThread(threading.Thread):
shared.printLock.release() shared.printLock.release()
self.data = '' self.data = ''
def setup(self,sock,HOST,PORT,streamNumber,objectsOfWhichThisRemoteNodeIsAlreadyAware): def setup(
self,
sock,
HOST,
PORT,
streamNumber,
objectsOfWhichThisRemoteNodeIsAlreadyAware):
self.sock = sock self.sock = sock
self.HOST = HOST self.HOST = HOST
self.PORT = PORT self.PORT = PORT
self.streamNumber = streamNumber self.streamNumber = streamNumber
self.remoteProtocolVersion = -1 #This must be set using setRemoteProtocolVersion command which is sent through the self.mailbox queue. self.remoteProtocolVersion = - \
self.lastTimeISentData = int(time.time()) #If this value increases beyond five minutes ago, we'll send a pong message to keep the connection alive. 1 # This must be set using setRemoteProtocolVersion command which is sent through the self.mailbox queue.
self.lastTimeISentData = int(
time.time()) # If this value increases beyond five minutes ago, we'll send a pong message to keep the connection alive.
self.objectsOfWhichThisRemoteNodeIsAlreadyAware = objectsOfWhichThisRemoteNodeIsAlreadyAware self.objectsOfWhichThisRemoteNodeIsAlreadyAware = objectsOfWhichThisRemoteNodeIsAlreadyAware
shared.printLock.acquire() shared.printLock.acquire()
print 'The streamNumber of this sendDataThread (ID:', str(id(self)) + ') at setup() is', self.streamNumber print 'The streamNumber of this sendDataThread (ID:', str(id(self)) + ') at setup() is', self.streamNumber
shared.printLock.release() shared.printLock.release()
def sendVersionMessage(self): def sendVersionMessage(self):
datatosend = assembleVersionMessage(self.HOST,self.PORT,self.streamNumber)#the IP and port of the remote host, and my streamNumber. datatosend = assembleVersionMessage(
self.HOST, self.PORT, self.streamNumber) # the IP and port of the remote host, and my streamNumber.
shared.printLock.acquire() shared.printLock.acquire()
print 'Sending version packet: ', repr(datatosend) print 'Sending version packet: ', repr(datatosend)
shared.printLock.release() shared.printLock.release()
try: try:
self.sock.sendall(datatosend) self.sock.sendall(datatosend)
except Exception, err: except Exception as err:
# if not 'Bad file descriptor' in err: # if not 'Bad file descriptor' in err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('sock.sendall error: %s\n' % err) sys.stderr.write('sock.sendall error: %s\n' % err)
@ -2076,7 +2394,12 @@ class sendDataThread(threading.Thread):
print 'len of sendDataQueues', len(shared.sendDataQueues) print 'len of sendDataQueues', len(shared.sendDataQueues)
shared.printLock.release() shared.printLock.release()
break break
#When you receive an incoming connection, a sendDataThread is created even though you don't yet know what stream number the remote peer is interested in. They will tell you in a version message and if you too are interested in that stream then you will continue on with the connection and will set the streamNumber of this send data thread here: # When you receive an incoming connection, a sendDataThread is
# created even though you don't yet know what stream number the
# remote peer is interested in. They will tell you in a version
# message and if you too are interested in that stream then you
# will continue on with the connection and will set the
# streamNumber of this send data thread here:
elif command == 'setStreamNumber': elif command == 'setStreamNumber':
hostInMessage, specifiedStreamNumber = data hostInMessage, specifiedStreamNumber = data
if hostInMessage == self.HOST: if hostInMessage == self.HOST:
@ -2093,7 +2416,10 @@ class sendDataThread(threading.Thread):
self.remoteProtocolVersion = specifiedRemoteProtocolVersion self.remoteProtocolVersion = specifiedRemoteProtocolVersion
elif command == 'sendaddr': elif command == 'sendaddr':
try: try:
#To prevent some network analysis, 'leak' the data out to our peer after waiting a random amount of time unless we have a long list of messages in our queue to send. # To prevent some network analysis, 'leak' the data out
# to our peer after waiting a random amount of time
# unless we have a long list of messages in our queue
# to send.
random.seed() random.seed()
time.sleep(random.randrange(0, 10)) time.sleep(random.randrange(0, 10))
self.sock.sendall(data) self.sock.sendall(data)
@ -2115,7 +2441,8 @@ class sendDataThread(threading.Thread):
headerData += 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00' headerData += 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00'
headerData += pack('>L', len(payload)) headerData += pack('>L', len(payload))
headerData += hashlib.sha512(payload).digest()[:4] headerData += hashlib.sha512(payload).digest()[:4]
#To prevent some network analysis, 'leak' the data out to our peer after waiting a random amount of time # To prevent some network analysis, 'leak' the data out
# to our peer after waiting a random amount of time
random.seed() random.seed()
time.sleep(random.randrange(0, 10)) time.sleep(random.randrange(0, 10))
try: try:
@ -2138,7 +2465,8 @@ class sendDataThread(threading.Thread):
print 'Sending pong to', self.HOST, 'to keep connection alive.' print 'Sending pong to', self.HOST, 'to keep connection alive.'
shared.printLock.release() shared.printLock.release()
try: try:
self.sock.sendall('\xE9\xBE\xB4\xD9\x70\x6F\x6E\x67\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xcf\x83\xe1\x35') self.sock.sendall(
'\xE9\xBE\xB4\xD9\x70\x6F\x6E\x67\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xcf\x83\xe1\x35')
self.lastTimeISentData = int(time.time()) self.lastTimeISentData = int(time.time())
except: except:
print 'send pong failed' print 'send pong failed'
@ -2156,7 +2484,6 @@ class sendDataThread(threading.Thread):
shared.printLock.release() shared.printLock.release()
def isInSqlInventory(hash): def isInSqlInventory(hash):
t = (hash,) t = (hash,)
shared.sqlLock.acquire() shared.sqlLock.acquire()
@ -2169,6 +2496,7 @@ def isInSqlInventory(hash):
else: else:
return True return True
def convertIntToString(n): def convertIntToString(n):
a = __builtins__.hex(n) a = __builtins__.hex(n)
if a[-1:] == 'L': if a[-1:] == 'L':
@ -2178,11 +2506,11 @@ def convertIntToString(n):
else: else:
return ('0' + a[2:]).decode('hex') return ('0' + a[2:]).decode('hex')
def convertStringToInt(s): def convertStringToInt(s):
return int(s.encode('hex'), 16) return int(s.encode('hex'), 16)
# This function expects that pubkey begin with \x04 # This function expects that pubkey begin with \x04
def calculateBitcoinAddressFromPubkey(pubkey): def calculateBitcoinAddressFromPubkey(pubkey):
if len(pubkey) != 65: if len(pubkey) != 65:
@ -2194,7 +2522,8 @@ def calculateBitcoinAddressFromPubkey(pubkey):
ripe.update(sha.digest()) ripe.update(sha.digest())
ripeWithProdnetPrefix = '\x00' + ripe.digest() ripeWithProdnetPrefix = '\x00' + ripe.digest()
checksum = hashlib.sha256(hashlib.sha256(ripeWithProdnetPrefix).digest()).digest()[:4] checksum = hashlib.sha256(hashlib.sha256(
ripeWithProdnetPrefix).digest()).digest()[:4]
binaryBitcoinAddress = ripeWithProdnetPrefix + checksum binaryBitcoinAddress = ripeWithProdnetPrefix + checksum
numberOfZeroBytesOnBinaryBitcoinAddress = 0 numberOfZeroBytesOnBinaryBitcoinAddress = 0
while binaryBitcoinAddress[0] == '\x00': while binaryBitcoinAddress[0] == '\x00':
@ -2203,6 +2532,7 @@ def calculateBitcoinAddressFromPubkey(pubkey):
base58encoded = arithmetic.changebase(binaryBitcoinAddress, 256, 58) base58encoded = arithmetic.changebase(binaryBitcoinAddress, 256, 58)
return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded
def calculateTestnetAddressFromPubkey(pubkey): def calculateTestnetAddressFromPubkey(pubkey):
if len(pubkey) != 65: if len(pubkey) != 65:
print 'Could not calculate Bitcoin address from pubkey because function was passed a pubkey that was', len(pubkey), 'bytes long rather than 65.' print 'Could not calculate Bitcoin address from pubkey because function was passed a pubkey that was', len(pubkey), 'bytes long rather than 65.'
@ -2213,7 +2543,8 @@ def calculateTestnetAddressFromPubkey(pubkey):
ripe.update(sha.digest()) ripe.update(sha.digest())
ripeWithProdnetPrefix = '\x6F' + ripe.digest() ripeWithProdnetPrefix = '\x6F' + ripe.digest()
checksum = hashlib.sha256(hashlib.sha256(ripeWithProdnetPrefix).digest()).digest()[:4] checksum = hashlib.sha256(hashlib.sha256(
ripeWithProdnetPrefix).digest()).digest()[:4]
binaryBitcoinAddress = ripeWithProdnetPrefix + checksum binaryBitcoinAddress = ripeWithProdnetPrefix + checksum
numberOfZeroBytesOnBinaryBitcoinAddress = 0 numberOfZeroBytesOnBinaryBitcoinAddress = 0
while binaryBitcoinAddress[0] == '\x00': while binaryBitcoinAddress[0] == '\x00':
@ -2223,7 +2554,6 @@ def calculateTestnetAddressFromPubkey(pubkey):
return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded
def signal_handler(signal, frame): def signal_handler(signal, frame):
if shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'): if shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'):
shared.doCleanShutdown() shared.doCleanShutdown()
@ -2232,7 +2562,6 @@ def signal_handler(signal, frame):
print 'Unfortunately you cannot use Ctrl+C when running the UI because the UI captures the signal.' print 'Unfortunately you cannot use Ctrl+C when running the UI because the UI captures the signal.'
def connectToStream(streamNumber): def connectToStream(streamNumber):
selfInitiatedConnections[streamNumber] = {} selfInitiatedConnections[streamNumber] = {}
if sys.platform[0:3] == 'win': if sys.platform[0:3] == 'win':
@ -2245,8 +2574,11 @@ def connectToStream(streamNumber):
a.start() a.start()
# Does an EC point multiplication; turns a private key into a public key. # Does an EC point multiplication; turns a private key into a public key.
def pointMult(secret): def pointMult(secret):
#ctx = OpenSSL.BN_CTX_new() #This value proved to cause Seg Faults on Linux. It turns out that it really didn't speed up EC_POINT_mul anyway. # ctx = OpenSSL.BN_CTX_new() #This value proved to cause Seg Faults on
# Linux. It turns out that it really didn't speed up EC_POINT_mul anyway.
k = OpenSSL.EC_KEY_new_by_curve_name(OpenSSL.get_curve('secp256k1')) k = OpenSSL.EC_KEY_new_by_curve_name(OpenSSL.get_curve('secp256k1'))
priv_key = OpenSSL.BN_bin2bn(secret, 32, 0) priv_key = OpenSSL.BN_bin2bn(secret, 32, 0)
group = OpenSSL.EC_KEY_get0_group(k) group = OpenSSL.EC_KEY_get0_group(k)
@ -2271,7 +2603,6 @@ def pointMult(secret):
return mb.raw return mb.raw
def assembleVersionMessage(remoteHost, remotePort, myStreamNumber): def assembleVersionMessage(remoteHost, remotePort, myStreamNumber):
shared.softwareVersion shared.softwareVersion
payload = '' payload = ''
@ -2279,20 +2610,27 @@ def assembleVersionMessage(remoteHost,remotePort,myStreamNumber):
payload += pack('>q', 1) # bitflags of the services I offer. payload += pack('>q', 1) # bitflags of the services I offer.
payload += pack('>q', int(time.time())) 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. payload += pack(
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + socket.inet_aton(remoteHost) '>q', 1) # boolservices of remote connection. How can I even know this for sure? This is probably 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 payload += pack('>H', remotePort) # remote IPv6 and port
payload += pack('>q', 1) # bitflags of the services I offer. payload += pack('>q', 1) # bitflags of the services I offer.
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + pack('>L',2130706433) # = 127.0.0.1. This will be ignored by the remote host. The actual remote connected IP will be used. payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + pack(
payload += pack('>H',shared.config.getint('bitmessagesettings', 'port'))#my external IPv6 and port '>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
random.seed() random.seed()
payload += eightBytesOfRandomDataUsedToDetectConnectionsToSelf payload += eightBytesOfRandomDataUsedToDetectConnectionsToSelf
userAgent = '/PyBitmessage:' + shared.softwareVersion + '/' #Length of userAgent must be less than 253. userAgent = '/PyBitmessage:' + shared.softwareVersion + \
payload += pack('>B',len(userAgent)) #user agent string length. If the user agent is more than 252 bytes long, this code isn't going to work. '/' # Length of userAgent must be less than 253.
payload += pack('>B', len(
userAgent)) # user agent string length. If the user agent is more than 252 bytes long, this code isn't going to work.
payload += userAgent payload += userAgent
payload += encodeVarint(1) #The number of streams about which I care. PyBitmessage currently only supports 1 per connection. payload += encodeVarint(
1) # The number of streams about which I care. PyBitmessage currently only supports 1 per connection.
payload += encodeVarint(myStreamNumber) payload += encodeVarint(myStreamNumber)
datatosend = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. datatosend = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits.
@ -2301,6 +2639,7 @@ def assembleVersionMessage(remoteHost,remotePort,myStreamNumber):
datatosend = datatosend + hashlib.sha512(payload).digest()[0:4] datatosend = datatosend + hashlib.sha512(payload).digest()[0:4]
return datatosend + payload return datatosend + payload
def isHostInPrivateIPRange(host): def isHostInPrivateIPRange(host):
if host[:3] == '10.': if host[:3] == '10.':
return True return True
@ -2312,8 +2651,13 @@ def isHostInPrivateIPRange(host):
return True return True
return False return False
#This thread exists because SQLITE3 is so un-threadsafe that we must submit queries to it and it puts results back in a different queue. They won't let us just use locks. # This thread exists because SQLITE3 is so un-threadsafe that we must
# submit queries to it and it puts results back in a different queue. They
# won't let us just use locks.
class sqlThread(threading.Thread): class sqlThread(threading.Thread):
def __init__(self): def __init__(self):
threading.Thread.__init__(self) threading.Thread.__init__(self)
@ -2322,36 +2666,56 @@ class sqlThread(threading.Thread):
self.conn.text_factory = str self.conn.text_factory = str
self.cur = self.conn.cursor() self.cur = self.conn.cursor()
try: 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)''' ) self.cur.execute(
self.cur.execute( '''CREATE TABLE sent (msgid blob, toaddress text, toripe blob, fromaddress text, subject text, message text, ackdata blob, lastactiontime integer, status text, pubkeyretrynumber integer, msgretrynumber integer, folder text, encodingtype int)''' ) '''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)''' )
self.cur.execute( '''CREATE TABLE subscriptions (label text, address text, enabled bool)''' ) self.cur.execute(
self.cur.execute( '''CREATE TABLE addressbook (label text, address text)''' ) '''CREATE TABLE sent (msgid blob, toaddress text, toripe blob, fromaddress text, subject text, message text, ackdata blob, lastactiontime integer, status text, pubkeyretrynumber integer, msgretrynumber integer, folder text, encodingtype int)''' )
self.cur.execute( '''CREATE TABLE blacklist (label text, address text, enabled bool)''' ) self.cur.execute(
self.cur.execute( '''CREATE TABLE whitelist (label text, address text, enabled bool)''' ) '''CREATE TABLE subscriptions (label text, address text, enabled bool)''' )
self.cur.execute(
'''CREATE TABLE addressbook (label text, address text)''' )
self.cur.execute(
'''CREATE TABLE blacklist (label text, address text, enabled bool)''' )
self.cur.execute(
'''CREATE TABLE whitelist (label text, address text, enabled bool)''' )
# Explanation of what is in the pubkeys table: # Explanation of what is in the pubkeys table:
# The hash is the RIPEMD160 hash that is encoded in the Bitmessage address. # The hash is the RIPEMD160 hash that is encoded in the Bitmessage address.
# transmitdata is literally the data that was included in the Bitmessage pubkey message when it arrived, except for the 24 byte protocol header- ie, it starts with the POW nonce. # transmitdata is literally the data that was included in the Bitmessage pubkey message when it arrived, except for the 24 byte protocol header- ie, it starts with the POW nonce.
# time is the time that the pubkey was broadcast on the network same as with every other type of Bitmessage object. # time is the time that the pubkey was broadcast on the network same as with every other type of Bitmessage object.
# usedpersonally is set to "yes" if we have used the key personally. This keeps us from deleting it because we may want to reply to a message in the future. This field is not a bool because we may need more flexability in the future and it doesn't take up much more space anyway. # usedpersonally is set to "yes" if we have used the key
self.cur.execute( '''CREATE TABLE pubkeys (hash blob, transmitdata blob, time int, usedpersonally text, UNIQUE(hash) ON CONFLICT REPLACE)''' ) # personally. This keeps us from deleting it because we may want to
self.cur.execute( '''CREATE TABLE inventory (hash blob, objecttype text, streamnumber int, payload blob, receivedtime integer, UNIQUE(hash) ON CONFLICT REPLACE)''' ) # reply to a message in the future. This field is not a bool
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. # because we may need more flexability in the future and it doesn't
self.cur.execute( '''INSERT INTO subscriptions VALUES('Bitmessage new releases/announcements','BM-GtovgYdgs7qXPkoYaRgrLFuFKz1SFpsw',1)''') # take up much more space anyway.
self.cur.execute( '''CREATE TABLE settings (key blob, value blob, UNIQUE(key) ON CONFLICT REPLACE)''' ) self.cur.execute(
'''CREATE TABLE pubkeys (hash blob, transmitdata blob, time int, usedpersonally text, UNIQUE(hash) ON CONFLICT REPLACE)''' )
self.cur.execute(
'''CREATE TABLE inventory (hash blob, objecttype text, streamnumber int, payload blob, receivedtime integer, 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','1')''') self.cur.execute( '''INSERT INTO settings VALUES('version','1')''')
self.cur.execute( '''INSERT INTO settings VALUES('lastvacuumtime',?)''',(int(time.time()),)) self.cur.execute( '''INSERT INTO settings VALUES('lastvacuumtime',?)''', (
int(time.time()),))
self.conn.commit() self.conn.commit()
print 'Created messages database file' print 'Created messages database file'
except Exception, err: except Exception as err:
if str(err) == 'table inbox already exists': if str(err) == 'table inbox already exists':
shared.printLock.acquire() shared.printLock.acquire()
print 'Database file already exists.' print 'Database file already exists.'
shared.printLock.release() shared.printLock.release()
else: else:
sys.stderr.write('ERROR trying to create database file (message.dat). Error message: %s\n' % str(err)) sys.stderr.write(
'ERROR trying to create database file (message.dat). Error message: %s\n' % str(err))
os._exit(0) os._exit(0)
#People running earlier versions of PyBitmessage do not have the usedpersonally field in their pubkeys table. Let's add it. # People running earlier versions of PyBitmessage do not have the
# usedpersonally field in their pubkeys table. Let's add it.
if shared.config.getint('bitmessagesettings', 'settingsversion') == 2: if shared.config.getint('bitmessagesettings', 'settingsversion') == 2:
item = '''ALTER TABLE pubkeys ADD usedpersonally text DEFAULT 'no' ''' item = '''ALTER TABLE pubkeys ADD usedpersonally text DEFAULT 'no' '''
parameters = '' parameters = ''
@ -2362,7 +2726,9 @@ class sqlThread(threading.Thread):
with open(shared.appdata + 'keys.dat', 'wb') as configfile: with open(shared.appdata + 'keys.dat', 'wb') as configfile:
shared.config.write(configfile) shared.config.write(configfile)
#People running earlier versions of PyBitmessage do not have the encodingtype field in their inbox and sent tables or the read field in the inbox table. Let's add them. # People running earlier versions of PyBitmessage do not have the
# encodingtype field in their inbox and sent tables or the read field
# in the inbox table. Let's add them.
if shared.config.getint('bitmessagesettings', 'settingsversion') == 3: if shared.config.getint('bitmessagesettings', 'settingsversion') == 3:
item = '''ALTER TABLE inbox ADD encodingtype int DEFAULT '2' ''' item = '''ALTER TABLE inbox ADD encodingtype int DEFAULT '2' '''
parameters = '' parameters = ''
@ -2382,49 +2748,70 @@ class sqlThread(threading.Thread):
shared.config.write(configfile) shared.config.write(configfile)
if shared.config.getint('bitmessagesettings', 'settingsversion') == 4: if shared.config.getint('bitmessagesettings', 'settingsversion') == 4:
shared.config.set('bitmessagesettings','defaultnoncetrialsperbyte',str(shared.networkDefaultProofOfWorkNonceTrialsPerByte)) shared.config.set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(
shared.config.set('bitmessagesettings','defaultpayloadlengthextrabytes',str(shared.networkDefaultPayloadLengthExtraBytes)) shared.networkDefaultProofOfWorkNonceTrialsPerByte))
shared.config.set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(
shared.networkDefaultPayloadLengthExtraBytes))
shared.config.set('bitmessagesettings', 'settingsversion', '5') shared.config.set('bitmessagesettings', 'settingsversion', '5')
if shared.config.getint('bitmessagesettings', 'settingsversion') == 5: if shared.config.getint('bitmessagesettings', 'settingsversion') == 5:
shared.config.set('bitmessagesettings','maxacceptablenoncetrialsperbyte','0') shared.config.set(
shared.config.set('bitmessagesettings','maxacceptablepayloadlengthextrabytes','0') 'bitmessagesettings', 'maxacceptablenoncetrialsperbyte', '0')
shared.config.set(
'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', '0')
shared.config.set('bitmessagesettings', 'settingsversion', '6') shared.config.set('bitmessagesettings', 'settingsversion', '6')
with open(shared.appdata + 'keys.dat', 'wb') as configfile: with open(shared.appdata + 'keys.dat', 'wb') as configfile:
shared.config.write(configfile) shared.config.write(configfile)
#From now on, let us keep a 'version' embedded in the messages.dat file so that when we make changes to the database, the database version we are on can stay embedded in the messages.dat file. Let us check to see if the settings table exists yet. # From now on, let us keep a 'version' embedded in the messages.dat
# file so that when we make changes to the database, the database
# version we are on can stay embedded in the messages.dat file. Let us
# check to see if the settings table exists yet.
item = '''SELECT name FROM sqlite_master WHERE type='table' AND name='settings';''' item = '''SELECT name FROM sqlite_master WHERE type='table' AND name='settings';'''
parameters = '' parameters = ''
self.cur.execute(item, parameters) self.cur.execute(item, parameters)
if self.cur.fetchall() == []: if self.cur.fetchall() == []:
# The settings table doesn't exist. We need to make it. # The settings table doesn't exist. We need to make it.
print 'In messages.dat database, creating new \'settings\' table.' print 'In messages.dat database, creating new \'settings\' table.'
self.cur.execute( '''CREATE TABLE settings (key text, value blob, UNIQUE(key) ON CONFLICT REPLACE)''' ) self.cur.execute(
'''CREATE TABLE settings (key text, value blob, UNIQUE(key) ON CONFLICT REPLACE)''' )
self.cur.execute( '''INSERT INTO settings VALUES('version','1')''') self.cur.execute( '''INSERT INTO settings VALUES('version','1')''')
self.cur.execute( '''INSERT INTO settings VALUES('lastvacuumtime',?)''',(int(time.time()),)) self.cur.execute( '''INSERT INTO settings VALUES('lastvacuumtime',?)''', (
int(time.time()),))
print 'In messages.dat database, removing an obsolete field from the pubkeys table.' print 'In messages.dat database, removing an obsolete field from the pubkeys table.'
self.cur.execute( '''CREATE TEMPORARY TABLE pubkeys_backup(hash blob, transmitdata blob, time int, usedpersonally text, UNIQUE(hash) ON CONFLICT REPLACE);''') self.cur.execute(
self.cur.execute( '''INSERT INTO pubkeys_backup SELECT hash, transmitdata, time, usedpersonally FROM pubkeys;''') '''CREATE TEMPORARY TABLE pubkeys_backup(hash blob, transmitdata blob, time int, usedpersonally text, UNIQUE(hash) ON CONFLICT REPLACE);''')
self.cur.execute(
'''INSERT INTO pubkeys_backup SELECT hash, transmitdata, time, usedpersonally FROM pubkeys;''')
self.cur.execute( '''DROP TABLE pubkeys''') self.cur.execute( '''DROP TABLE pubkeys''')
self.cur.execute( '''CREATE TABLE pubkeys (hash blob, transmitdata blob, time int, usedpersonally text, UNIQUE(hash) ON CONFLICT REPLACE)''' ) self.cur.execute(
self.cur.execute( '''INSERT INTO pubkeys SELECT hash, transmitdata, time, usedpersonally FROM pubkeys_backup;''') '''CREATE TABLE pubkeys (hash blob, transmitdata blob, time int, usedpersonally text, UNIQUE(hash) ON CONFLICT REPLACE)''' )
self.cur.execute(
'''INSERT INTO pubkeys SELECT hash, transmitdata, time, usedpersonally FROM pubkeys_backup;''')
self.cur.execute( '''DROP TABLE pubkeys_backup;''') self.cur.execute( '''DROP TABLE pubkeys_backup;''')
print 'Deleting all pubkeys from inventory. They will be redownloaded and then saved with the correct times.' print 'Deleting all pubkeys from inventory. They will be redownloaded and then saved with the correct times.'
self.cur.execute( '''delete from inventory where objecttype = 'pubkey';''') self.cur.execute(
'''delete from inventory where objecttype = 'pubkey';''')
print 'replacing Bitmessage announcements mailing list with a new one.' print 'replacing Bitmessage announcements mailing list with a new one.'
self.cur.execute( '''delete from subscriptions where address='BM-BbkPSZbzPwpVcYZpU4yHwf9ZPEapN5Zx' ''') self.cur.execute(
self.cur.execute( '''INSERT INTO subscriptions VALUES('Bitmessage new releases/announcements','BM-GtovgYdgs7qXPkoYaRgrLFuFKz1SFpsw',1)''') '''delete from subscriptions where address='BM-BbkPSZbzPwpVcYZpU4yHwf9ZPEapN5Zx' ''')
self.cur.execute(
'''INSERT INTO subscriptions VALUES('Bitmessage new releases/announcements','BM-GtovgYdgs7qXPkoYaRgrLFuFKz1SFpsw',1)''')
print 'Commiting.' print 'Commiting.'
self.conn.commit() self.conn.commit()
print 'Vacuuming message.dat. You might notice that the file size gets much smaller.' print 'Vacuuming message.dat. You might notice that the file size gets much smaller.'
self.cur.execute( ''' VACUUM ''') self.cur.execute( ''' VACUUM ''')
#After code refactoring, the possible status values for sent messages as changed. # After code refactoring, the possible status values for sent messages
self.cur.execute( '''update sent set status='doingmsgpow' where status='doingpow' ''') # as changed.
self.cur.execute( '''update sent set status='msgsent' where status='sentmessage' ''') self.cur.execute(
self.cur.execute( '''update sent set status='doingpubkeypow' where status='findingpubkey' ''') '''update sent set status='doingmsgpow' where status='doingpow' ''')
self.cur.execute( '''update sent set status='broadcastqueued' where status='broadcastpending' ''') self.cur.execute(
'''update sent set status='msgsent' where status='sentmessage' ''')
self.cur.execute(
'''update sent set status='doingpubkeypow' where status='findingpubkey' ''')
self.cur.execute(
'''update sent set status='broadcastqueued' where status='broadcastpending' ''')
self.conn.commit() self.conn.commit()
try: try:
@ -2432,20 +2819,24 @@ class sqlThread(threading.Thread):
t = ('1234', testpayload, '12345678', 'no') t = ('1234', testpayload, '12345678', 'no')
self.cur.execute( '''INSERT INTO pubkeys VALUES(?,?,?,?)''', t) self.cur.execute( '''INSERT INTO pubkeys VALUES(?,?,?,?)''', t)
self.conn.commit() self.conn.commit()
self.cur.execute('''SELECT transmitdata FROM pubkeys WHERE hash='1234' ''') self.cur.execute(
'''SELECT transmitdata FROM pubkeys WHERE hash='1234' ''')
queryreturn = self.cur.fetchall() queryreturn = self.cur.fetchall()
for row in queryreturn: for row in queryreturn:
transmitdata, = row transmitdata, = row
self.cur.execute('''DELETE FROM pubkeys WHERE hash='1234' ''') self.cur.execute('''DELETE FROM pubkeys WHERE hash='1234' ''')
self.conn.commit() self.conn.commit()
if transmitdata == '': if transmitdata == '':
sys.stderr.write('Problem: The version of SQLite you have cannot store Null values. Please download and install the latest revision of your version of Python (for example, the latest Python 2.7 revision) and try again.\n') sys.stderr.write(
sys.stderr.write('PyBitmessage will now exit very abruptly. You may now see threading errors related to this abrupt exit but the problem you need to solve is related to SQLite.\n\n') 'Problem: The version of SQLite you have cannot store Null values. Please download and install the latest revision of your version of Python (for example, the latest Python 2.7 revision) and try again.\n')
sys.stderr.write(
'PyBitmessage will now exit very abruptly. You may now see threading errors related to this abrupt exit but the problem you need to solve is related to SQLite.\n\n')
os._exit(0) os._exit(0)
except Exception, err: except Exception as err:
print err print err
#Let us check to see the last time we vaccumed the messages.dat file. If it has been more than a month let's do it now. # Let us check to see the last time we vaccumed the messages.dat file.
# If it has been more than a month let's do it now.
item = '''SELECT value FROM settings WHERE key='lastvacuumtime';''' item = '''SELECT value FROM settings WHERE key='lastvacuumtime';'''
parameters = '' parameters = ''
self.cur.execute(item, parameters) self.cur.execute(item, parameters)
@ -2475,7 +2866,8 @@ class sqlThread(threading.Thread):
shared.printLock.release() shared.printLock.release()
self.conn.commit() self.conn.commit()
self.conn.close() self.conn.close()
shutil.move(shared.lookupAppdataFolder()+'messages.dat','messages.dat') shutil.move(
shared.lookupAppdataFolder() + 'messages.dat', 'messages.dat')
self.conn = sqlite3.connect('messages.dat') self.conn = sqlite3.connect('messages.dat')
self.conn.text_factory = str self.conn.text_factory = str
self.cur = self.conn.cursor() self.cur = self.conn.cursor()
@ -2485,7 +2877,8 @@ class sqlThread(threading.Thread):
shared.printLock.release() shared.printLock.release()
self.conn.commit() self.conn.commit()
self.conn.close() self.conn.close()
shutil.move('messages.dat',shared.lookupAppdataFolder()+'messages.dat') shutil.move(
'messages.dat', shared.lookupAppdataFolder() + 'messages.dat')
self.conn = sqlite3.connect(shared.appdata + 'messages.dat') self.conn = sqlite3.connect(shared.appdata + 'messages.dat')
self.conn.text_factory = str self.conn.text_factory = str
self.cur = self.conn.cursor() self.cur = self.conn.cursor()
@ -2500,9 +2893,10 @@ class sqlThread(threading.Thread):
# print 'parameters', parameters # print 'parameters', parameters
try: try:
self.cur.execute(item, parameters) self.cur.execute(item, parameters)
except Exception, err: except Exception as err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('\nMajor error occurred when trying to execute a SQL statement within the sqlThread. Please tell Atheros about this error message or post it in the forum! Error occurred while trying to execute statement: "'+str(item) + '" Here are the parameters; you might want to censor this data with asterisks (***) as it can contain private information: '+str(repr(parameters))+'\nHere is the actual error message thrown by the sqlThread: '+ str(err)+'\n') sys.stderr.write('\nMajor error occurred when trying to execute a SQL statement within the sqlThread. Please tell Atheros about this error message or post it in the forum! Error occurred while trying to execute statement: "' + str(
item) + '" Here are the parameters; you might want to censor this data with asterisks (***) as it can contain private information: ' + str(repr(parameters)) + '\nHere is the actual error message thrown by the sqlThread: ' + str(err) + '\n')
sys.stderr.write('This program shall now abruptly exit!\n') sys.stderr.write('This program shall now abruptly exit!\n')
shared.printLock.release() shared.printLock.release()
os._exit(0) os._exit(0)
@ -2524,7 +2918,10 @@ It resends messages when there has been no response:
resends msg messages in 4 days (then 8 days, then 16 days, etc...) resends msg messages in 4 days (then 8 days, then 16 days, etc...)
''' '''
class singleCleaner(threading.Thread): class singleCleaner(threading.Thread):
def __init__(self): def __init__(self):
threading.Thread.__init__(self) threading.Thread.__init__(self)
@ -2533,47 +2930,59 @@ class singleCleaner(threading.Thread):
while True: while True:
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.UISignalQueue.put(('updateStatusBar','Doing housekeeping (Flushing inventory in memory to disk...)')) shared.UISignalQueue.put((
'updateStatusBar', 'Doing housekeeping (Flushing inventory in memory to disk...)'))
for hash, storedValue in shared.inventory.items(): for hash, storedValue in shared.inventory.items():
objectType, streamNumber, payload, receivedTime = storedValue objectType, streamNumber, payload, receivedTime = storedValue
if int(time.time()) - 3600 > receivedTime: if int(time.time()) - 3600 > receivedTime:
t = (hash, objectType, streamNumber, payload, receivedTime) t = (hash, objectType, streamNumber, payload, receivedTime)
shared.sqlSubmitQueue.put('''INSERT INTO inventory VALUES (?,?,?,?,?)''') shared.sqlSubmitQueue.put(
'''INSERT INTO inventory VALUES (?,?,?,?,?)''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
del shared.inventory[hash] del shared.inventory[hash]
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.UISignalQueue.put(('updateStatusBar', '')) shared.UISignalQueue.put(('updateStatusBar', ''))
shared.sqlLock.release() shared.sqlLock.release()
shared.broadcastToSendDataQueues((0, 'pong', 'no data')) #commands the sendData threads to send out a pong message if they haven't sent anything else in the last five minutes. The socket timeout-time is 10 minutes. shared.broadcastToSendDataQueues((
#If we are running as a daemon then we are going to fill up the UI queue which will never be handled by a UI. We should clear it to save memory. 0, 'pong', 'no data')) # commands the sendData threads to send out a pong message if they haven't sent anything else in the last five minutes. The socket timeout-time is 10 minutes.
# If we are running as a daemon then we are going to fill up the UI
# queue which will never be handled by a UI. We should clear it to
# save memory.
if shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'): if shared.safeConfigGetBoolean('bitmessagesettings', 'daemon'):
shared.UISignalQueue.queue.clear() shared.UISignalQueue.queue.clear()
if timeWeLastClearedInventoryAndPubkeysTables < int(time.time()) - 7380: if timeWeLastClearedInventoryAndPubkeysTables < int(time.time()) - 7380:
timeWeLastClearedInventoryAndPubkeysTables = int(time.time()) timeWeLastClearedInventoryAndPubkeysTables = int(time.time())
#inventory (moves data from the inventory data structure to the on-disk sql database) # inventory (moves data from the inventory data structure to
# the on-disk sql database)
shared.sqlLock.acquire() shared.sqlLock.acquire()
#inventory (clears pubkeys after 28 days and everything else after 2 days and 12 hours) # inventory (clears pubkeys after 28 days and everything else
t = (int(time.time())-lengthOfTimeToLeaveObjectsInInventory,int(time.time())-lengthOfTimeToHoldOnToAllPubkeys) # after 2 days and 12 hours)
shared.sqlSubmitQueue.put('''DELETE FROM inventory WHERE (receivedtime<? AND objecttype<>'pubkey') OR (receivedtime<? AND objecttype='pubkey') ''') t = (int(time.time()) - lengthOfTimeToLeaveObjectsInInventory, int(
time.time()) - lengthOfTimeToHoldOnToAllPubkeys)
shared.sqlSubmitQueue.put(
'''DELETE FROM inventory WHERE (receivedtime<? AND objecttype<>'pubkey') OR (receivedtime<? AND objecttype='pubkey') ''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
# pubkeys # pubkeys
t = (int(time.time()) - lengthOfTimeToHoldOnToAllPubkeys,) t = (int(time.time()) - lengthOfTimeToHoldOnToAllPubkeys,)
shared.sqlSubmitQueue.put('''DELETE FROM pubkeys WHERE time<? AND usedpersonally='no' ''') shared.sqlSubmitQueue.put(
'''DELETE FROM pubkeys WHERE time<? AND usedpersonally='no' ''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
t = () t = ()
shared.sqlSubmitQueue.put('''select toaddress, toripe, fromaddress, subject, message, ackdata, lastactiontime, status, pubkeyretrynumber, msgretrynumber FROM sent WHERE ((status='awaitingpubkey' OR status='msgsent') AND folder='sent') ''') #If the message's folder='trash' then we'll ignore it. shared.sqlSubmitQueue.put(
'''select toaddress, toripe, fromaddress, subject, message, ackdata, lastactiontime, status, pubkeyretrynumber, msgretrynumber FROM sent WHERE ((status='awaitingpubkey' OR status='msgsent') AND folder='sent') ''') # If the message's folder='trash' then we'll ignore it.
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
for row in queryreturn: for row in queryreturn:
if len(row) < 5: if len(row) < 5:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('Something went wrong in the singleCleaner thread: a query did not return the requested fields. '+repr(row)) sys.stderr.write(
'Something went wrong in the singleCleaner thread: a query did not return the requested fields. ' + repr(row))
time.sleep(3) time.sleep(3)
shared.printLock.release() shared.printLock.release()
break break
@ -2582,13 +2991,17 @@ class singleCleaner(threading.Thread):
if int(time.time()) - lastactiontime > (maximumAgeOfAnObjectThatIAmWillingToAccept * (2 ** (pubkeyretrynumber))): if int(time.time()) - lastactiontime > (maximumAgeOfAnObjectThatIAmWillingToAccept * (2 ** (pubkeyretrynumber))):
print 'It has been a long time and we haven\'t heard a response to our getpubkey request. Sending again.' print 'It has been a long time and we haven\'t heard a response to our getpubkey request. Sending again.'
try: try:
del neededPubkeys[toripe] #We need to take this entry out of the neededPubkeys structure because the shared.workerQueue checks to see whether the entry is already present and will not do the POW and send the message because it assumes that it has already done it recently. del neededPubkeys[
toripe] # We need to take this entry out of the neededPubkeys structure because the shared.workerQueue checks to see whether the entry is already present and will not do the POW and send the message because it assumes that it has already done it recently.
except: except:
pass pass
shared.UISignalQueue.put(('updateStatusBar','Doing work necessary to again attempt to request a public key...')) shared.UISignalQueue.put((
t = (int(time.time()),pubkeyretrynumber+1,toripe) 'updateStatusBar', 'Doing work necessary to again attempt to request a public key...'))
shared.sqlSubmitQueue.put('''UPDATE sent SET lastactiontime=?, pubkeyretrynumber=?, status='msgqueued' WHERE toripe=?''') t = (int(
time.time()), pubkeyretrynumber + 1, toripe)
shared.sqlSubmitQueue.put(
'''UPDATE sent SET lastactiontime=?, pubkeyretrynumber=?, status='msgqueued' WHERE toripe=?''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
@ -2596,26 +3009,34 @@ class singleCleaner(threading.Thread):
else: # status == msgsent else: # status == msgsent
if int(time.time()) - lastactiontime > (maximumAgeOfAnObjectThatIAmWillingToAccept * (2 ** (msgretrynumber))): if int(time.time()) - lastactiontime > (maximumAgeOfAnObjectThatIAmWillingToAccept * (2 ** (msgretrynumber))):
print 'It has been a long time and we haven\'t heard an acknowledgement to our msg. Sending again.' print 'It has been a long time and we haven\'t heard an acknowledgement to our msg. Sending again.'
t = (int(time.time()),msgretrynumber+1,'msgqueued',ackdata) t = (int(
shared.sqlSubmitQueue.put('''UPDATE sent SET lastactiontime=?, msgretrynumber=?, status=? WHERE ackdata=?''') time.time()), msgretrynumber + 1, 'msgqueued', ackdata)
shared.sqlSubmitQueue.put(
'''UPDATE sent SET lastactiontime=?, msgretrynumber=?, status=? WHERE ackdata=?''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.workerQueue.put(('sendmessage', '')) shared.workerQueue.put(('sendmessage', ''))
shared.UISignalQueue.put(('updateStatusBar','Doing work necessary to again attempt to deliver a message...')) shared.UISignalQueue.put((
'updateStatusBar', 'Doing work necessary to again attempt to deliver a message...'))
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release() shared.sqlLock.release()
time.sleep(300) time.sleep(300)
#This thread, of which there is only one, does the heavy lifting: calculating POWs. # This thread, of which there is only one, does the heavy lifting:
# calculating POWs.
class singleWorker(threading.Thread): class singleWorker(threading.Thread):
def __init__(self): def __init__(self):
# QThread.__init__(self, parent) # QThread.__init__(self, parent)
threading.Thread.__init__(self) threading.Thread.__init__(self)
def run(self): def run(self):
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''SELECT toripe FROM sent WHERE ((status='awaitingpubkey' OR status='doingpubkeypow') AND folder='sent')''') shared.sqlSubmitQueue.put(
'''SELECT toripe FROM sent WHERE ((status='awaitingpubkey' OR status='doingpubkeypow') AND folder='sent')''')
shared.sqlSubmitQueue.put('') shared.sqlSubmitQueue.put('')
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
@ -2623,9 +3044,11 @@ class singleWorker(threading.Thread):
toripe, = row toripe, = row
neededPubkeys[toripe] = 0 neededPubkeys[toripe] = 0
#Initialize the ackdataForWhichImWatching data structure using data from the sql database. # Initialize the ackdataForWhichImWatching data structure using data
# from the sql database.
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''SELECT ackdata FROM sent where (status='msgsent' OR status='doingmsgpow')''') shared.sqlSubmitQueue.put(
'''SELECT ackdata FROM sent where (status='msgsent' OR status='doingmsgpow')''')
shared.sqlSubmitQueue.put('') shared.sqlSubmitQueue.put('')
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
@ -2635,7 +3058,8 @@ class singleWorker(threading.Thread):
ackdataForWhichImWatching[ackdata] = 0 ackdataForWhichImWatching[ackdata] = 0
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''SELECT DISTINCT toaddress FROM sent WHERE (status='doingpubkeypow' AND folder='sent')''') shared.sqlSubmitQueue.put(
'''SELECT DISTINCT toaddress FROM sent WHERE (status='doingpubkeypow' AND folder='sent')''')
shared.sqlSubmitQueue.put('') shared.sqlSubmitQueue.put('')
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
@ -2643,10 +3067,15 @@ class singleWorker(threading.Thread):
toaddress, = row toaddress, = row
self.requestPubKey(toaddress) self.requestPubKey(toaddress)
time.sleep(10) #give some time for the GUI to start before we start on existing POW tasks. time.sleep(
10) # give some time for the GUI to start before we start on existing POW tasks.
self.sendMsg() #just in case there are any pending tasks for msg messages that have yet to be sent. self.sendMsg()
self.sendBroadcast() #just in case there are any tasks for Broadcasts that have yet to be sent. # just in case there are any pending tasks for msg
# messages that have yet to be sent.
self.sendBroadcast()
# just in case there are any tasks for Broadcasts
# that have yet to be sent.
while True: while True:
command, data = shared.workerQueue.get() command, data = shared.workerQueue.get()
@ -2677,7 +3106,8 @@ class singleWorker(threading.Thread):
shared.printLock.release()""" shared.printLock.release()"""
else: else:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('Probable programming error: The command sent to the workerThread is weird. It is: %s\n' % command) sys.stderr.write(
'Probable programming error: The command sent to the workerThread is weird. It is: %s\n' % command)
shared.printLock.release() shared.printLock.release()
shared.workerQueue.task_done() shared.workerQueue.task_done()
@ -2691,32 +3121,42 @@ class singleWorker(threading.Thread):
myAddress = addressInKeysFile myAddress = addressInKeysFile
break""" break"""
myAddress = shared.myAddressesByHash[hash] myAddress = shared.myAddressesByHash[hash]
status,addressVersionNumber,streamNumber,hash = decodeAddress(myAddress) status, addressVersionNumber, streamNumber, hash = decodeAddress(
embeddedTime = int(time.time()+random.randrange(-300, 300)) #the current time plus or minus five minutes myAddress)
embeddedTime = int(time.time() + random.randrange(
-300, 300)) # the current time plus or minus five minutes
payload = pack('>I', (embeddedTime)) payload = pack('>I', (embeddedTime))
payload += encodeVarint(addressVersionNumber) # Address version number payload += encodeVarint(addressVersionNumber) # Address version number
payload += encodeVarint(streamNumber) payload += encodeVarint(streamNumber)
payload += '\x00\x00\x00\x01' # bitfield of features supported by me (see the wiki). payload += '\x00\x00\x00\x01' # bitfield of features supported by me (see the wiki).
try: try:
privSigningKeyBase58 = shared.config.get(myAddress, 'privsigningkey') privSigningKeyBase58 = shared.config.get(
privEncryptionKeyBase58 = shared.config.get(myAddress, 'privencryptionkey') myAddress, 'privsigningkey')
except Exception, err: privEncryptionKeyBase58 = shared.config.get(
myAddress, 'privencryptionkey')
except Exception as err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('Error within doPOWForMyV2Pubkey. Could not read the keys from the keys.dat file for a requested address. %s\n' % err) sys.stderr.write(
'Error within doPOWForMyV2Pubkey. Could not read the keys from the keys.dat file for a requested address. %s\n' % err)
shared.printLock.release() shared.printLock.release()
return return
privSigningKeyHex = shared.decodeWalletImportFormat(privSigningKeyBase58).encode('hex') privSigningKeyHex = shared.decodeWalletImportFormat(
privEncryptionKeyHex = shared.decodeWalletImportFormat(privEncryptionKeyBase58).encode('hex') privSigningKeyBase58).encode('hex')
pubSigningKey = highlevelcrypto.privToPub(privSigningKeyHex).decode('hex') privEncryptionKeyHex = shared.decodeWalletImportFormat(
pubEncryptionKey = highlevelcrypto.privToPub(privEncryptionKeyHex).decode('hex') privEncryptionKeyBase58).encode('hex')
pubSigningKey = highlevelcrypto.privToPub(
privSigningKeyHex).decode('hex')
pubEncryptionKey = highlevelcrypto.privToPub(
privEncryptionKeyHex).decode('hex')
payload += pubSigningKey[1:] payload += pubSigningKey[1:]
payload += pubEncryptionKey[1:] payload += pubEncryptionKey[1:]
# Do the POW for this pubkey message # Do the POW for this pubkey message
target = 2**64 / ((len(payload)+shared.networkDefaultPayloadLengthExtraBytes+8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes +
8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte)
print '(For pubkey message) Doing proof of work...' print '(For pubkey message) Doing proof of work...'
initialHash = hashlib.sha512(payload).digest() initialHash = hashlib.sha512(payload).digest()
trialValue, nonce = proofofwork.run(target, initialHash) trialValue, nonce = proofofwork.run(target, initialHash)
@ -2732,51 +3172,66 @@ class singleWorker(threading.Thread):
inventoryHash = calculateInventoryHash(payload) inventoryHash = calculateInventoryHash(payload)
objectType = 'pubkey' objectType = 'pubkey'
shared.inventory[inventoryHash] = (objectType, streamNumber, payload, embeddedTime) shared.inventory[inventoryHash] = (
objectType, streamNumber, payload, embeddedTime)
shared.printLock.acquire() shared.printLock.acquire()
print 'broadcasting inv with hash:', inventoryHash.encode('hex') print 'broadcasting inv with hash:', inventoryHash.encode('hex')
shared.printLock.release() shared.printLock.release()
shared.broadcastToSendDataQueues((streamNumber, 'sendinv', inventoryHash)) shared.broadcastToSendDataQueues((
streamNumber, 'sendinv', inventoryHash))
shared.UISignalQueue.put(('updateStatusBar', '')) shared.UISignalQueue.put(('updateStatusBar', ''))
shared.config.set(myAddress,'lastpubkeysendtime',str(int(time.time()))) shared.config.set(
myAddress, 'lastpubkeysendtime', str(int(time.time())))
with open(shared.appdata + 'keys.dat', 'wb') as configfile: with open(shared.appdata + 'keys.dat', 'wb') as configfile:
shared.config.write(configfile) shared.config.write(configfile)
def doPOWForMyV3Pubkey(self, hash): # This function also broadcasts out the pubkey message once it is done with the POW def doPOWForMyV3Pubkey(self, hash): # This function also broadcasts out the pubkey message once it is done with the POW
myAddress = shared.myAddressesByHash[hash] myAddress = shared.myAddressesByHash[hash]
status,addressVersionNumber,streamNumber,hash = decodeAddress(myAddress) status, addressVersionNumber, streamNumber, hash = decodeAddress(
embeddedTime = int(time.time()+random.randrange(-300, 300)) #the current time plus or minus five minutes myAddress)
embeddedTime = int(time.time() + random.randrange(
-300, 300)) # the current time plus or minus five minutes
payload = pack('>I', (embeddedTime)) payload = pack('>I', (embeddedTime))
payload += encodeVarint(addressVersionNumber) # Address version number payload += encodeVarint(addressVersionNumber) # Address version number
payload += encodeVarint(streamNumber) payload += encodeVarint(streamNumber)
payload += '\x00\x00\x00\x01' # bitfield of features supported by me (see the wiki). payload += '\x00\x00\x00\x01' # bitfield of features supported by me (see the wiki).
try: try:
privSigningKeyBase58 = shared.config.get(myAddress, 'privsigningkey') privSigningKeyBase58 = shared.config.get(
privEncryptionKeyBase58 = shared.config.get(myAddress, 'privencryptionkey') myAddress, 'privsigningkey')
except Exception, err: privEncryptionKeyBase58 = shared.config.get(
myAddress, 'privencryptionkey')
except Exception as err:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('Error within doPOWForMyV3Pubkey. Could not read the keys from the keys.dat file for a requested address. %s\n' % err) sys.stderr.write(
'Error within doPOWForMyV3Pubkey. Could not read the keys from the keys.dat file for a requested address. %s\n' % err)
shared.printLock.release() shared.printLock.release()
return return
privSigningKeyHex = shared.decodeWalletImportFormat(privSigningKeyBase58).encode('hex') privSigningKeyHex = shared.decodeWalletImportFormat(
privEncryptionKeyHex = shared.decodeWalletImportFormat(privEncryptionKeyBase58).encode('hex') privSigningKeyBase58).encode('hex')
pubSigningKey = highlevelcrypto.privToPub(privSigningKeyHex).decode('hex') privEncryptionKeyHex = shared.decodeWalletImportFormat(
pubEncryptionKey = highlevelcrypto.privToPub(privEncryptionKeyHex).decode('hex') privEncryptionKeyBase58).encode('hex')
pubSigningKey = highlevelcrypto.privToPub(
privSigningKeyHex).decode('hex')
pubEncryptionKey = highlevelcrypto.privToPub(
privEncryptionKeyHex).decode('hex')
payload += pubSigningKey[1:] payload += pubSigningKey[1:]
payload += pubEncryptionKey[1:] payload += pubEncryptionKey[1:]
payload += encodeVarint(shared.config.getint(myAddress,'noncetrialsperbyte')) payload += encodeVarint(shared.config.getint(
payload += encodeVarint(shared.config.getint(myAddress,'payloadlengthextrabytes')) myAddress, 'noncetrialsperbyte'))
payload += encodeVarint(shared.config.getint(
myAddress, 'payloadlengthextrabytes'))
signature = highlevelcrypto.sign(payload, privSigningKeyHex) signature = highlevelcrypto.sign(payload, privSigningKeyHex)
payload += encodeVarint(len(signature)) payload += encodeVarint(len(signature))
payload += signature payload += signature
# Do the POW for this pubkey message # Do the POW for this pubkey message
target = 2**64 / ((len(payload)+shared.networkDefaultPayloadLengthExtraBytes+8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes +
8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte)
print '(For pubkey message) Doing proof of work...' print '(For pubkey message) Doing proof of work...'
initialHash = hashlib.sha512(payload).digest() initialHash = hashlib.sha512(payload).digest()
trialValue, nonce = proofofwork.run(target, initialHash) trialValue, nonce = proofofwork.run(target, initialHash)
@ -2793,43 +3248,57 @@ class singleWorker(threading.Thread):
inventoryHash = calculateInventoryHash(payload) inventoryHash = calculateInventoryHash(payload)
objectType = 'pubkey' objectType = 'pubkey'
shared.inventory[inventoryHash] = (objectType, streamNumber, payload, embeddedTime) shared.inventory[inventoryHash] = (
objectType, streamNumber, payload, embeddedTime)
shared.printLock.acquire() shared.printLock.acquire()
print 'broadcasting inv with hash:', inventoryHash.encode('hex') print 'broadcasting inv with hash:', inventoryHash.encode('hex')
shared.printLock.release() shared.printLock.release()
shared.broadcastToSendDataQueues((streamNumber, 'sendinv', inventoryHash)) shared.broadcastToSendDataQueues((
streamNumber, 'sendinv', inventoryHash))
shared.UISignalQueue.put(('updateStatusBar', '')) shared.UISignalQueue.put(('updateStatusBar', ''))
shared.config.set(myAddress,'lastpubkeysendtime',str(int(time.time()))) shared.config.set(
myAddress, 'lastpubkeysendtime', str(int(time.time())))
with open(shared.appdata + 'keys.dat', 'wb') as configfile: with open(shared.appdata + 'keys.dat', 'wb') as configfile:
shared.config.write(configfile) shared.config.write(configfile)
def sendBroadcast(self): def sendBroadcast(self):
shared.sqlLock.acquire() shared.sqlLock.acquire()
t = ('broadcastqueued',) t = ('broadcastqueued',)
shared.sqlSubmitQueue.put('''SELECT fromaddress, subject, message, ackdata FROM sent WHERE status=? and folder='sent' ''') shared.sqlSubmitQueue.put(
'''SELECT fromaddress, subject, message, ackdata FROM sent WHERE status=? and folder='sent' ''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
for row in queryreturn: for row in queryreturn:
fromaddress, subject, body, ackdata = row fromaddress, subject, body, ackdata = row
status,addressVersionNumber,streamNumber,ripe = decodeAddress(fromaddress) status, addressVersionNumber, streamNumber, ripe = decodeAddress(
fromaddress)
if addressVersionNumber == 2 and int(time.time()) < encryptedBroadcastSwitchoverTime: if addressVersionNumber == 2 and int(time.time()) < encryptedBroadcastSwitchoverTime:
#We need to convert our private keys to public keys in order to include them. # We need to convert our private keys to public keys in order
# to include them.
try: try:
privSigningKeyBase58 = shared.config.get(fromaddress, 'privsigningkey') privSigningKeyBase58 = shared.config.get(
privEncryptionKeyBase58 = shared.config.get(fromaddress, 'privencryptionkey') fromaddress, 'privsigningkey')
privEncryptionKeyBase58 = shared.config.get(
fromaddress, 'privencryptionkey')
except: except:
shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,'Error! Could not find sender address (your address) in the keys.dat file.'))) shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (
ackdata, 'Error! Could not find sender address (your address) in the keys.dat file.')))
continue continue
privSigningKeyHex = shared.decodeWalletImportFormat(privSigningKeyBase58).encode('hex') privSigningKeyHex = shared.decodeWalletImportFormat(
privEncryptionKeyHex = shared.decodeWalletImportFormat(privEncryptionKeyBase58).encode('hex') privSigningKeyBase58).encode('hex')
privEncryptionKeyHex = shared.decodeWalletImportFormat(
privEncryptionKeyBase58).encode('hex')
pubSigningKey = highlevelcrypto.privToPub(privSigningKeyHex).decode('hex') #At this time these pubkeys are 65 bytes long because they include the encoding byte which we won't be sending in the broadcast message. pubSigningKey = highlevelcrypto.privToPub(privSigningKeyHex).decode(
pubEncryptionKey = highlevelcrypto.privToPub(privEncryptionKeyHex).decode('hex') 'hex') # At this time these pubkeys are 65 bytes long because they include the encoding byte which we won't be sending in the broadcast message.
pubEncryptionKey = highlevelcrypto.privToPub(
privEncryptionKeyHex).decode('hex')
payload = pack('>Q',(int(time.time())+random.randrange(-300, 300)))#the current time plus or minus five minutes payload = pack('>Q', (int(time.time()) + random.randrange(
-300, 300))) # the current time plus or minus five minutes
payload += encodeVarint(1) # broadcast version payload += encodeVarint(1) # broadcast version
payload += encodeVarint(addressVersionNumber) payload += encodeVarint(addressVersionNumber)
payload += encodeVarint(streamNumber) payload += encodeVarint(streamNumber)
@ -2838,16 +3307,19 @@ class singleWorker(threading.Thread):
payload += pubEncryptionKey[1:] payload += pubEncryptionKey[1:]
payload += ripe payload += ripe
payload += '\x02' # message encoding type payload += '\x02' # message encoding type
payload += encodeVarint(len('Subject:' + subject + '\n' + 'Body:' + body)) #Type 2 is simple UTF-8 message encoding. payload += encodeVarint(len(
'Subject:' + subject + '\n' + 'Body:' + body)) # Type 2 is simple UTF-8 message encoding.
payload += 'Subject:' + subject + '\n' + 'Body:' + body payload += 'Subject:' + subject + '\n' + 'Body:' + body
signature = highlevelcrypto.sign(payload, privSigningKeyHex) signature = highlevelcrypto.sign(payload, privSigningKeyHex)
payload += encodeVarint(len(signature)) payload += encodeVarint(len(signature))
payload += signature payload += signature
target = 2**64 / ((len(payload)+shared.networkDefaultPayloadLengthExtraBytes+8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) target = 2 ** 64 / ((len(
payload) + shared.networkDefaultPayloadLengthExtraBytes + 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte)
print '(For broadcast message) Doing proof of work...' print '(For broadcast message) Doing proof of work...'
shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,'Doing work necessary to send broadcast...'))) shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (
ackdata, 'Doing work necessary to send broadcast...')))
initialHash = hashlib.sha512(payload).digest() initialHash = hashlib.sha512(payload).digest()
trialValue, nonce = proofofwork.run(target, initialHash) trialValue, nonce = proofofwork.run(target, initialHash)
print '(For broadcast message) Found proof of work', trialValue, 'Nonce:', nonce print '(For broadcast message) Found proof of work', trialValue, 'Nonce:', nonce
@ -2856,36 +3328,51 @@ class singleWorker(threading.Thread):
inventoryHash = calculateInventoryHash(payload) inventoryHash = calculateInventoryHash(payload)
objectType = 'broadcast' objectType = 'broadcast'
shared.inventory[inventoryHash] = (objectType, streamNumber, payload, int(time.time())) shared.inventory[inventoryHash] = (
objectType, streamNumber, payload, int(time.time()))
print 'Broadcasting inv for my broadcast (within sendBroadcast function):', inventoryHash.encode('hex') print 'Broadcasting inv for my broadcast (within sendBroadcast function):', inventoryHash.encode('hex')
shared.broadcastToSendDataQueues((streamNumber, 'sendinv', inventoryHash)) shared.broadcastToSendDataQueues((
streamNumber, 'sendinv', inventoryHash))
shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,'Broadcast sent on '+unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'),localtime(int(time.time()))),'utf-8')))) shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, 'Broadcast sent on ' + unicode(
strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))
#Update the status of the message in the 'sent' table to have a 'broadcastsent' status # Update the status of the message in the 'sent' table to have
# a 'broadcastsent' status
shared.sqlLock.acquire() shared.sqlLock.acquire()
t = ('broadcastsent',int(time.time()),fromaddress, subject, body,'broadcastqueued') t = ('broadcastsent', int(
shared.sqlSubmitQueue.put('UPDATE sent SET status=?, lastactiontime=? WHERE fromaddress=? AND subject=? AND message=? AND status=?') time.time()), fromaddress, subject, body, 'broadcastqueued')
shared.sqlSubmitQueue.put(
'UPDATE sent SET status=?, lastactiontime=? WHERE fromaddress=? AND subject=? AND message=? AND status=?')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release() shared.sqlLock.release()
elif addressVersionNumber == 3 or int(time.time()) > encryptedBroadcastSwitchoverTime: elif addressVersionNumber == 3 or int(time.time()) > encryptedBroadcastSwitchoverTime:
#We need to convert our private keys to public keys in order to include them. # We need to convert our private keys to public keys in order
# to include them.
try: try:
privSigningKeyBase58 = shared.config.get(fromaddress, 'privsigningkey') privSigningKeyBase58 = shared.config.get(
privEncryptionKeyBase58 = shared.config.get(fromaddress, 'privencryptionkey') fromaddress, 'privsigningkey')
privEncryptionKeyBase58 = shared.config.get(
fromaddress, 'privencryptionkey')
except: except:
shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,'Error! Could not find sender address (your address) in the keys.dat file.'))) shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (
ackdata, 'Error! Could not find sender address (your address) in the keys.dat file.')))
continue continue
privSigningKeyHex = shared.decodeWalletImportFormat(privSigningKeyBase58).encode('hex') privSigningKeyHex = shared.decodeWalletImportFormat(
privEncryptionKeyHex = shared.decodeWalletImportFormat(privEncryptionKeyBase58).encode('hex') privSigningKeyBase58).encode('hex')
privEncryptionKeyHex = shared.decodeWalletImportFormat(
privEncryptionKeyBase58).encode('hex')
pubSigningKey = highlevelcrypto.privToPub(privSigningKeyHex).decode('hex') #At this time these pubkeys are 65 bytes long because they include the encoding byte which we won't be sending in the broadcast message. pubSigningKey = highlevelcrypto.privToPub(privSigningKeyHex).decode(
pubEncryptionKey = highlevelcrypto.privToPub(privEncryptionKeyHex).decode('hex') 'hex') # At this time these pubkeys are 65 bytes long because they include the encoding byte which we won't be sending in the broadcast message.
pubEncryptionKey = highlevelcrypto.privToPub(
privEncryptionKeyHex).decode('hex')
payload = pack('>Q',(int(time.time())+random.randrange(-300, 300)))#the current time plus or minus five minutes payload = pack('>Q', (int(time.time()) + random.randrange(
-300, 300))) # the current time plus or minus five minutes
payload += encodeVarint(2) # broadcast version payload += encodeVarint(2) # broadcast version
payload += encodeVarint(streamNumber) payload += encodeVarint(streamNumber)
@ -2896,21 +3383,29 @@ class singleWorker(threading.Thread):
dataToEncrypt += pubSigningKey[1:] dataToEncrypt += pubSigningKey[1:]
dataToEncrypt += pubEncryptionKey[1:] dataToEncrypt += pubEncryptionKey[1:]
if addressVersionNumber >= 3: if addressVersionNumber >= 3:
dataToEncrypt += encodeVarint(shared.config.getint(fromaddress,'noncetrialsperbyte')) dataToEncrypt += encodeVarint(shared.config.getint(
dataToEncrypt += encodeVarint(shared.config.getint(fromaddress,'payloadlengthextrabytes')) fromaddress, 'noncetrialsperbyte'))
dataToEncrypt += encodeVarint(shared.config.getint(
fromaddress, 'payloadlengthextrabytes'))
dataToEncrypt += '\x02' # message encoding type dataToEncrypt += '\x02' # message encoding type
dataToEncrypt += encodeVarint(len('Subject:' + subject + '\n' + 'Body:' + body)) #Type 2 is simple UTF-8 message encoding. dataToEncrypt += encodeVarint(len(
'Subject:' + subject + '\n' + 'Body:' + body)) # Type 2 is simple UTF-8 message encoding.
dataToEncrypt += 'Subject:' + subject + '\n' + 'Body:' + body dataToEncrypt += 'Subject:' + subject + '\n' + 'Body:' + body
signature = highlevelcrypto.sign(dataToEncrypt,privSigningKeyHex) signature = highlevelcrypto.sign(
dataToEncrypt, privSigningKeyHex)
dataToEncrypt += encodeVarint(len(signature)) dataToEncrypt += encodeVarint(len(signature))
dataToEncrypt += signature dataToEncrypt += signature
privEncryptionKey = hashlib.sha512(encodeVarint(addressVersionNumber)+encodeVarint(streamNumber)+ripe).digest()[:32] privEncryptionKey = hashlib.sha512(encodeVarint(
addressVersionNumber) + encodeVarint(streamNumber) + ripe).digest()[:32]
pubEncryptionKey = pointMult(privEncryptionKey) pubEncryptionKey = pointMult(privEncryptionKey)
payload += highlevelcrypto.encrypt(dataToEncrypt,pubEncryptionKey.encode('hex')) payload += highlevelcrypto.encrypt(
dataToEncrypt, pubEncryptionKey.encode('hex'))
target = 2**64 / ((len(payload)+shared.networkDefaultPayloadLengthExtraBytes+8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) target = 2 ** 64 / ((len(
payload) + shared.networkDefaultPayloadLengthExtraBytes + 8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte)
print '(For broadcast message) Doing proof of work...' print '(For broadcast message) Doing proof of work...'
shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,'Doing work necessary to send broadcast...'))) shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (
ackdata, 'Doing work necessary to send broadcast...')))
initialHash = hashlib.sha512(payload).digest() initialHash = hashlib.sha512(payload).digest()
trialValue, nonce = proofofwork.run(target, initialHash) trialValue, nonce = proofofwork.run(target, initialHash)
print '(For broadcast message) Found proof of work', trialValue, 'Nonce:', nonce print '(For broadcast message) Found proof of work', trialValue, 'Nonce:', nonce
@ -2919,29 +3414,37 @@ class singleWorker(threading.Thread):
inventoryHash = calculateInventoryHash(payload) inventoryHash = calculateInventoryHash(payload)
objectType = 'broadcast' objectType = 'broadcast'
shared.inventory[inventoryHash] = (objectType, streamNumber, payload, int(time.time())) shared.inventory[inventoryHash] = (
objectType, streamNumber, payload, int(time.time()))
print 'sending inv (within sendBroadcast function)' print 'sending inv (within sendBroadcast function)'
shared.broadcastToSendDataQueues((streamNumber, 'sendinv', inventoryHash)) shared.broadcastToSendDataQueues((
streamNumber, 'sendinv', inventoryHash))
shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,'Broadcast sent on '+unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'),localtime(int(time.time()))),'utf-8')))) shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, 'Broadcast sent on ' + unicode(
strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))
#Update the status of the message in the 'sent' table to have a 'broadcastsent' status # Update the status of the message in the 'sent' table to have
# a 'broadcastsent' status
shared.sqlLock.acquire() shared.sqlLock.acquire()
t = ('broadcastsent',int(time.time()),fromaddress, subject, body,'broadcastqueued') t = ('broadcastsent', int(
shared.sqlSubmitQueue.put('UPDATE sent SET status=?, lastactiontime=? WHERE fromaddress=? AND subject=? AND message=? AND status=?') time.time()), fromaddress, subject, body, 'broadcastqueued')
shared.sqlSubmitQueue.put(
'UPDATE sent SET status=?, lastactiontime=? WHERE fromaddress=? AND subject=? AND message=? AND status=?')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release() shared.sqlLock.release()
else: else:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('Error: In the singleWorker thread, the sendBroadcast function doesn\'t understand the address version.\n') sys.stderr.write(
'Error: In the singleWorker thread, the sendBroadcast function doesn\'t understand the address version.\n')
shared.printLock.release() shared.printLock.release()
def sendMsg(self): def sendMsg(self):
# Check to see if there are any messages queued to be sent # Check to see if there are any messages queued to be sent
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''SELECT DISTINCT toaddress FROM sent WHERE (status='msgqueued' AND folder='sent')''') shared.sqlSubmitQueue.put(
'''SELECT DISTINCT toaddress FROM sent WHERE (status='msgqueued' AND folder='sent')''')
shared.sqlSubmitQueue.put('') shared.sqlSubmitQueue.put('')
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
@ -2949,14 +3452,16 @@ class singleWorker(threading.Thread):
toaddress, = row toaddress, = row
toripe = decodeAddress(toaddress)[3] toripe = decodeAddress(toaddress)[3]
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''SELECT hash FROM pubkeys WHERE hash=? ''') shared.sqlSubmitQueue.put(
'''SELECT hash FROM pubkeys WHERE hash=? ''')
shared.sqlSubmitQueue.put((toripe,)) shared.sqlSubmitQueue.put((toripe,))
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
if queryreturn != []: # If we have the needed pubkey, set the status to doingmsgpow (we'll do it further down) if queryreturn != []: # If we have the needed pubkey, set the status to doingmsgpow (we'll do it further down)
t = (toaddress,) t = (toaddress,)
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''UPDATE sent SET status='doingmsgpow' WHERE toaddress=? AND status='msgqueued' ''') shared.sqlSubmitQueue.put(
'''UPDATE sent SET status='doingmsgpow' WHERE toaddress=? AND status='msgqueued' ''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
@ -2966,157 +3471,211 @@ class singleWorker(threading.Thread):
# We already sent a request for the pubkey # We already sent a request for the pubkey
t = (toaddress,) t = (toaddress,)
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''UPDATE sent SET status='awaitingpubkey' WHERE toaddress=? AND status='msgqueued' ''') shared.sqlSubmitQueue.put(
'''UPDATE sent SET status='awaitingpubkey' WHERE toaddress=? AND status='msgqueued' ''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release() shared.sqlLock.release()
shared.UISignalQueue.put(('updateSentItemStatusByHash',(toripe,'Encryption key was requested earlier.'))) shared.UISignalQueue.put(('updateSentItemStatusByHash', (
toripe, 'Encryption key was requested earlier.')))
else: else:
# We have not yet sent a request for the pubkey # We have not yet sent a request for the pubkey
t = (toaddress,) t = (toaddress,)
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''UPDATE sent SET status='doingpubkeypow' WHERE toaddress=? AND status='msgqueued' ''') shared.sqlSubmitQueue.put(
'''UPDATE sent SET status='doingpubkeypow' WHERE toaddress=? AND status='msgqueued' ''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release() shared.sqlLock.release()
shared.UISignalQueue.put(('updateSentItemStatusByHash',(toripe,'Sending a request for the recipient\'s encryption key.'))) shared.UISignalQueue.put(('updateSentItemStatusByHash', (
toripe, 'Sending a request for the recipient\'s encryption key.')))
self.requestPubKey(toaddress) self.requestPubKey(toaddress)
shared.sqlLock.acquire() shared.sqlLock.acquire()
#Get all messages that are ready to be sent, and also all messages which we have sent in the last 28 days which were previously marked as 'toodifficult'. If the user as raised the maximum acceptable difficulty then those messages may now be sendable. # Get all messages that are ready to be sent, and also all messages
shared.sqlSubmitQueue.put('''SELECT toaddress, toripe, fromaddress, subject, message, ackdata, status FROM sent WHERE (status='doingmsgpow' or status='forcepow' or (status='toodifficult' and lastactiontime>?)) and folder='sent' ''') # which we have sent in the last 28 days which were previously marked
# as 'toodifficult'. If the user as raised the maximum acceptable
# difficulty then those messages may now be sendable.
shared.sqlSubmitQueue.put(
'''SELECT toaddress, toripe, fromaddress, subject, message, ackdata, status FROM sent WHERE (status='doingmsgpow' or status='forcepow' or (status='toodifficult' and lastactiontime>?)) and folder='sent' ''')
shared.sqlSubmitQueue.put((int(time.time()) - 2419200,)) shared.sqlSubmitQueue.put((int(time.time()) - 2419200,))
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
for row in queryreturn: # For each message we need to send.. for row in queryreturn: # For each message we need to send..
toaddress, toripe, fromaddress, subject, message, ackdata, status = row toaddress, toripe, fromaddress, subject, message, ackdata, status = row
#There is a remote possibility that we may no longer have the recipient's pubkey. Let us make sure we still have it or else the sendMsg function will appear to freeze. This can happen if the user sends a message but doesn't let the POW function finish, then leaves their client off for a long time which could cause the needed pubkey to expire and be deleted. # There is a remote possibility that we may no longer have the
# recipient's pubkey. Let us make sure we still have it or else the
# sendMsg function will appear to freeze. This can happen if the
# user sends a message but doesn't let the POW function finish,
# then leaves their client off for a long time which could cause
# the needed pubkey to expire and be deleted.
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''SELECT hash FROM pubkeys WHERE hash=? ''') shared.sqlSubmitQueue.put(
'''SELECT hash FROM pubkeys WHERE hash=? ''')
shared.sqlSubmitQueue.put((toripe,)) shared.sqlSubmitQueue.put((toripe,))
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
if queryreturn == [] and toripe not in neededPubkeys: if queryreturn == [] and toripe not in neededPubkeys:
#We no longer have the needed pubkey and we haven't requested it. # We no longer have the needed pubkey and we haven't requested
# it.
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('For some reason, the status of a message in our outbox is \'doingmsgpow\' even though we lack the pubkey. Here is the RIPE hash of the needed pubkey: %s\n' % toripe.encode('hex')) sys.stderr.write(
'For some reason, the status of a message in our outbox is \'doingmsgpow\' even though we lack the pubkey. Here is the RIPE hash of the needed pubkey: %s\n' % toripe.encode('hex'))
shared.printLock.release() shared.printLock.release()
t = (toaddress,) t = (toaddress,)
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''UPDATE sent SET status='msgqueued' WHERE toaddress=? AND status='doingmsgpow' ''') shared.sqlSubmitQueue.put(
'''UPDATE sent SET status='msgqueued' WHERE toaddress=? AND status='doingmsgpow' ''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release() shared.sqlLock.release()
shared.UISignalQueue.put(('updateSentItemStatusByHash',(toripe,'Sending a request for the recipient\'s encryption key.'))) shared.UISignalQueue.put(('updateSentItemStatusByHash', (
toripe, 'Sending a request for the recipient\'s encryption key.')))
self.requestPubKey(toaddress) self.requestPubKey(toaddress)
continue continue
ackdataForWhichImWatching[ackdata] = 0 ackdataForWhichImWatching[ackdata] = 0
toStatus,toAddressVersionNumber,toStreamNumber,toHash = decodeAddress(toaddress) toStatus, toAddressVersionNumber, toStreamNumber, toHash = decodeAddress(
fromStatus,fromAddressVersionNumber,fromStreamNumber,fromHash = decodeAddress(fromaddress) toaddress)
shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,'Looking up the receiver\'s public key'))) fromStatus, fromAddressVersionNumber, fromStreamNumber, fromHash = decodeAddress(
fromaddress)
shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (
ackdata, 'Looking up the receiver\'s public key')))
shared.printLock.acquire() shared.printLock.acquire()
print 'Found a message in our database that needs to be sent with this pubkey.' print 'Found a message in our database that needs to be sent with this pubkey.'
print 'First 150 characters of message:', repr(message[:150]) print 'First 150 characters of message:', repr(message[:150])
shared.printLock.release() shared.printLock.release()
#mark the pubkey as 'usedpersonally' so that we don't ever delete it. # mark the pubkey as 'usedpersonally' so that we don't ever delete
# it.
shared.sqlLock.acquire() shared.sqlLock.acquire()
t = (toripe,) t = (toripe,)
shared.sqlSubmitQueue.put('''UPDATE pubkeys SET usedpersonally='yes' WHERE hash=?''') shared.sqlSubmitQueue.put(
'''UPDATE pubkeys SET usedpersonally='yes' WHERE hash=?''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
#Let us fetch the recipient's public key out of our database. If the required proof of work difficulty is too hard then we'll abort. # Let us fetch the recipient's public key out of our database. If
shared.sqlSubmitQueue.put('SELECT transmitdata FROM pubkeys WHERE hash=?') # the required proof of work difficulty is too hard then we'll
# abort.
shared.sqlSubmitQueue.put(
'SELECT transmitdata FROM pubkeys WHERE hash=?')
shared.sqlSubmitQueue.put((toripe,)) shared.sqlSubmitQueue.put((toripe,))
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
if queryreturn == []: if queryreturn == []:
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('(within sendMsg) The needed pubkey was not found. This should never happen. Aborting send.\n') sys.stderr.write(
'(within sendMsg) The needed pubkey was not found. This should never happen. Aborting send.\n')
shared.printLock.release() shared.printLock.release()
return return
for row in queryreturn: for row in queryreturn:
pubkeyPayload, = row pubkeyPayload, = row
#The pubkey message is stored the way we originally received it which means that we need to read beyond things like the nonce and time to get to the actual public keys. # The pubkey message is stored the way we originally received it
# which means that we need to read beyond things like the nonce and
# time to get to the actual public keys.
readPosition = 8 # to bypass the nonce readPosition = 8 # to bypass the nonce
pubkeyEmbeddedTime, = unpack('>I',pubkeyPayload[readPosition:readPosition+4]) pubkeyEmbeddedTime, = unpack(
#This section is used for the transition from 32 bit time to 64 bit time in the protocol. '>I', pubkeyPayload[readPosition:readPosition + 4])
# This section is used for the transition from 32 bit time to 64
# bit time in the protocol.
if pubkeyEmbeddedTime == 0: if pubkeyEmbeddedTime == 0:
pubkeyEmbeddedTime, = unpack('>Q',pubkeyPayload[readPosition:readPosition+8]) pubkeyEmbeddedTime, = unpack(
'>Q', pubkeyPayload[readPosition:readPosition + 8])
readPosition += 8 readPosition += 8
else: else:
readPosition += 4 readPosition += 4
readPosition += 1 # to bypass the address version whose length is definitely 1 readPosition += 1 # to bypass the address version whose length is definitely 1
streamNumber, streamNumberLength = decodeVarint(pubkeyPayload[readPosition:readPosition+10]) streamNumber, streamNumberLength = decodeVarint(
pubkeyPayload[readPosition:readPosition + 10])
readPosition += streamNumberLength readPosition += streamNumberLength
behaviorBitfield = pubkeyPayload[readPosition:readPosition + 4] behaviorBitfield = pubkeyPayload[readPosition:readPosition + 4]
readPosition += 4 # to bypass the bitfield of behaviors readPosition += 4 # to bypass the bitfield of behaviors
#pubSigningKeyBase256 = pubkeyPayload[readPosition:readPosition+64] #We don't use this key for anything here. # pubSigningKeyBase256 =
# pubkeyPayload[readPosition:readPosition+64] #We don't use this
# key for anything here.
readPosition += 64 readPosition += 64
pubEncryptionKeyBase256 = pubkeyPayload[readPosition:readPosition+64] pubEncryptionKeyBase256 = pubkeyPayload[
readPosition:readPosition + 64]
readPosition += 64 readPosition += 64
if toAddressVersionNumber == 2: if toAddressVersionNumber == 2:
requiredAverageProofOfWorkNonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte requiredAverageProofOfWorkNonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte
requiredPayloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes requiredPayloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes
shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,'Doing work necessary to send message. (There is no required difficulty for version 2 addresses like this.)'))) shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (
ackdata, 'Doing work necessary to send message. (There is no required difficulty for version 2 addresses like this.)')))
elif toAddressVersionNumber == 3: elif toAddressVersionNumber == 3:
requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(pubkeyPayload[readPosition:readPosition+10]) requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
pubkeyPayload[readPosition:readPosition + 10])
readPosition += varintLength readPosition += varintLength
requiredPayloadLengthExtraBytes, varintLength = decodeVarint(pubkeyPayload[readPosition:readPosition+10]) requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
pubkeyPayload[readPosition:readPosition + 10])
readPosition += varintLength readPosition += varintLength
if requiredAverageProofOfWorkNonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte: # We still have to meet a minimum POW difficulty regardless of what they say is allowed in order to get our message to propagate through the network. if requiredAverageProofOfWorkNonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte: # We still have to meet a minimum POW difficulty regardless of what they say is allowed in order to get our message to propagate through the network.
requiredAverageProofOfWorkNonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte requiredAverageProofOfWorkNonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte
if requiredPayloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes: if requiredPayloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes:
requiredPayloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes requiredPayloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes
shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,'Doing work necessary to send message.\nReceiver\'s required difficulty: '+str(float(requiredAverageProofOfWorkNonceTrialsPerByte)/shared.networkDefaultProofOfWorkNonceTrialsPerByte)+' and '+ str(float(requiredPayloadLengthExtraBytes)/shared.networkDefaultPayloadLengthExtraBytes)))) shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, 'Doing work necessary to send message.\nReceiver\'s required difficulty: ' + str(float(
requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte) + ' and ' + str(float(requiredPayloadLengthExtraBytes) / shared.networkDefaultPayloadLengthExtraBytes))))
if status != 'forcepow': if status != 'forcepow':
if (requiredAverageProofOfWorkNonceTrialsPerByte > shared.config.getint('bitmessagesettings', 'maxacceptablenoncetrialsperbyte') and shared.config.getint('bitmessagesettings', 'maxacceptablenoncetrialsperbyte') != 0) or (requiredPayloadLengthExtraBytes > shared.config.getint('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes') and shared.config.getint('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes') != 0): if (requiredAverageProofOfWorkNonceTrialsPerByte > shared.config.getint('bitmessagesettings', 'maxacceptablenoncetrialsperbyte') and shared.config.getint('bitmessagesettings', 'maxacceptablenoncetrialsperbyte') != 0) or (requiredPayloadLengthExtraBytes > shared.config.getint('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes') and shared.config.getint('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes') != 0):
#The demanded difficulty is more than we are willing to do. # The demanded difficulty is more than we are willing
# to do.
shared.sqlLock.acquire() shared.sqlLock.acquire()
t = (ackdata,) t = (ackdata,)
shared.sqlSubmitQueue.put('''UPDATE sent SET status='toodifficult' WHERE ackdata=? ''') shared.sqlSubmitQueue.put(
'''UPDATE sent SET status='toodifficult' WHERE ackdata=? ''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release() shared.sqlLock.release()
shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,'Problem: The work demanded by the recipient (' + str(float(requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte) + ' and ' + str(float(requiredPayloadLengthExtraBytes) / shared.networkDefaultPayloadLengthExtraBytes) + ') is more difficult than you are willing to do. ' + unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'),localtime(int(time.time()))),'utf-8')))) shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, 'Problem: The work demanded by the recipient (' + str(float(requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte) + ' and ' + str(float(
requiredPayloadLengthExtraBytes) / shared.networkDefaultPayloadLengthExtraBytes) + ') is more difficult than you are willing to do. ' + unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))
continue continue
embeddedTime = pack('>Q', (int(time.time()) + random.randrange(
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. We will use this time both for our message and for the ackdata packed within our message.
if fromAddressVersionNumber == 2: if fromAddressVersionNumber == 2:
payload = '\x01' # Message version. payload = '\x01' # Message version.
payload += encodeVarint(fromAddressVersionNumber) payload += encodeVarint(fromAddressVersionNumber)
payload += encodeVarint(fromStreamNumber) payload += encodeVarint(fromStreamNumber)
payload += '\x00\x00\x00\x01' # Bitfield of features and behaviors that can be expected from me. (See https://bitmessage.org/wiki/Protocol_specification#Pubkey_bitfield_features ) payload += '\x00\x00\x00\x01' # Bitfield of features and behaviors that can be expected from me. (See https://bitmessage.org/wiki/Protocol_specification#Pubkey_bitfield_features )
#We need to convert our private keys to public keys in order to include them. # We need to convert our private keys to public keys in order
# to include them.
try: try:
privSigningKeyBase58 = shared.config.get(fromaddress, 'privsigningkey') privSigningKeyBase58 = shared.config.get(
privEncryptionKeyBase58 = shared.config.get(fromaddress, 'privencryptionkey') fromaddress, 'privsigningkey')
privEncryptionKeyBase58 = shared.config.get(
fromaddress, 'privencryptionkey')
except: except:
shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,'Error! Could not find sender address (your address) in the keys.dat file.'))) shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (
ackdata, 'Error! Could not find sender address (your address) in the keys.dat file.')))
continue continue
privSigningKeyHex = shared.decodeWalletImportFormat(privSigningKeyBase58).encode('hex') privSigningKeyHex = shared.decodeWalletImportFormat(
privEncryptionKeyHex = shared.decodeWalletImportFormat(privEncryptionKeyBase58).encode('hex') privSigningKeyBase58).encode('hex')
privEncryptionKeyHex = shared.decodeWalletImportFormat(
privEncryptionKeyBase58).encode('hex')
pubSigningKey = highlevelcrypto.privToPub(privSigningKeyHex).decode('hex') pubSigningKey = highlevelcrypto.privToPub(
pubEncryptionKey = highlevelcrypto.privToPub(privEncryptionKeyHex).decode('hex') privSigningKeyHex).decode('hex')
pubEncryptionKey = highlevelcrypto.privToPub(
privEncryptionKeyHex).decode('hex')
payload += pubSigningKey[1:] #The \x04 on the beginning of the public keys are not sent. This way there is only one acceptable way to encode and send a public key. payload += pubSigningKey[
1:] # The \x04 on the beginning of the public keys are not sent. This way there is only one acceptable way to encode and send a public key.
payload += pubEncryptionKey[1:] payload += pubEncryptionKey[1:]
payload += toHash # This hash will be checked by the receiver of the message to verify that toHash belongs to them. This prevents a Surreptitious Forwarding Attack. payload += toHash # This hash will be checked by the receiver of the message to verify that toHash belongs to them. This prevents a Surreptitious Forwarding Attack.
payload += '\x02' # Type 2 is simple UTF-8 message encoding as specified on the Protocol Specification on the Bitmessage Wiki. payload += '\x02' # Type 2 is simple UTF-8 message encoding as specified on the Protocol Specification on the Bitmessage Wiki.
messageToTransmit = 'Subject:' + subject + '\n' + 'Body:' + message messageToTransmit = 'Subject:' + \
subject + '\n' + 'Body:' + message
payload += encodeVarint(len(messageToTransmit)) payload += encodeVarint(len(messageToTransmit))
payload += 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. 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.
payload += encodeVarint(len(fullAckPayload)) payload += encodeVarint(len(fullAckPayload))
payload += fullAckPayload payload += fullAckPayload
signature = highlevelcrypto.sign(payload, privSigningKeyHex) signature = highlevelcrypto.sign(payload, privSigningKeyHex)
@ -3129,36 +3688,54 @@ class singleWorker(threading.Thread):
payload += encodeVarint(fromStreamNumber) payload += encodeVarint(fromStreamNumber)
payload += '\x00\x00\x00\x01' # Bitfield of features and behaviors that can be expected from me. (See https://bitmessage.org/wiki/Protocol_specification#Pubkey_bitfield_features ) payload += '\x00\x00\x00\x01' # Bitfield of features and behaviors that can be expected from me. (See https://bitmessage.org/wiki/Protocol_specification#Pubkey_bitfield_features )
#We need to convert our private keys to public keys in order to include them. # We need to convert our private keys to public keys in order
# to include them.
try: try:
privSigningKeyBase58 = shared.config.get(fromaddress, 'privsigningkey') privSigningKeyBase58 = shared.config.get(
privEncryptionKeyBase58 = shared.config.get(fromaddress, 'privencryptionkey') fromaddress, 'privsigningkey')
privEncryptionKeyBase58 = shared.config.get(
fromaddress, 'privencryptionkey')
except: except:
shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,'Error! Could not find sender address (your address) in the keys.dat file.'))) shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (
ackdata, 'Error! Could not find sender address (your address) in the keys.dat file.')))
continue continue
privSigningKeyHex = shared.decodeWalletImportFormat(privSigningKeyBase58).encode('hex') privSigningKeyHex = shared.decodeWalletImportFormat(
privEncryptionKeyHex = shared.decodeWalletImportFormat(privEncryptionKeyBase58).encode('hex') privSigningKeyBase58).encode('hex')
privEncryptionKeyHex = shared.decodeWalletImportFormat(
privEncryptionKeyBase58).encode('hex')
pubSigningKey = highlevelcrypto.privToPub(privSigningKeyHex).decode('hex') pubSigningKey = highlevelcrypto.privToPub(
pubEncryptionKey = highlevelcrypto.privToPub(privEncryptionKeyHex).decode('hex') privSigningKeyHex).decode('hex')
pubEncryptionKey = highlevelcrypto.privToPub(
privEncryptionKeyHex).decode('hex')
payload += pubSigningKey[1:] #The \x04 on the beginning of the public keys are not sent. This way there is only one acceptable way to encode and send a public key. payload += pubSigningKey[
1:] # The \x04 on the beginning of the public keys are not sent. This way there is only one acceptable way to encode and send a public key.
payload += pubEncryptionKey[1:] payload += pubEncryptionKey[1:]
#If the receiver of our message is in our address book, subscriptions list, or whitelist then we will allow them to do the network-minimum proof of work. Let us check to see if the receiver is in any of those lists. # If the receiver of our message is in our address book,
# subscriptions list, or whitelist then we will allow them to
# do the network-minimum proof of work. Let us check to see if
# the receiver is in any of those lists.
if shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(toaddress): if shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(toaddress):
payload += encodeVarint(shared.networkDefaultProofOfWorkNonceTrialsPerByte) payload += encodeVarint(
payload += encodeVarint(shared.networkDefaultPayloadLengthExtraBytes) shared.networkDefaultProofOfWorkNonceTrialsPerByte)
payload += encodeVarint(
shared.networkDefaultPayloadLengthExtraBytes)
else: else:
payload += encodeVarint(shared.config.getint(fromaddress,'noncetrialsperbyte')) payload += encodeVarint(shared.config.getint(
payload += encodeVarint(shared.config.getint(fromaddress,'payloadlengthextrabytes')) fromaddress, 'noncetrialsperbyte'))
payload += encodeVarint(shared.config.getint(
fromaddress, 'payloadlengthextrabytes'))
payload += toHash # This hash will be checked by the receiver of the message to verify that toHash belongs to them. This prevents a Surreptitious Forwarding Attack. payload += toHash # This hash will be checked by the receiver of the message to verify that toHash belongs to them. This prevents a Surreptitious Forwarding Attack.
payload += '\x02' # Type 2 is simple UTF-8 message encoding as specified on the Protocol Specification on the Bitmessage Wiki. payload += '\x02' # Type 2 is simple UTF-8 message encoding as specified on the Protocol Specification on the Bitmessage Wiki.
messageToTransmit = 'Subject:' + subject + '\n' + 'Body:' + message messageToTransmit = 'Subject:' + \
subject + '\n' + 'Body:' + message
payload += encodeVarint(len(messageToTransmit)) payload += encodeVarint(len(messageToTransmit))
payload += 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. 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.
payload += encodeVarint(len(fullAckPayload)) payload += encodeVarint(len(fullAckPayload))
payload += fullAckPayload payload += fullAckPayload
signature = highlevelcrypto.sign(payload, privSigningKeyHex) signature = highlevelcrypto.sign(payload, privSigningKeyHex)
@ -3166,9 +3743,12 @@ class singleWorker(threading.Thread):
payload += signature payload += signature
# We have assembled the data that will be encrypted. # We have assembled the data that will be encrypted.
encrypted = highlevelcrypto.encrypt(payload,"04"+pubEncryptionKeyBase256.encode('hex')) encrypted = highlevelcrypto.encrypt(
encryptedPayload = embeddedTime + encodeVarint(toStreamNumber) + encrypted payload, "04" + pubEncryptionKeyBase256.encode('hex'))
target = 2**64 / ((len(encryptedPayload)+requiredPayloadLengthExtraBytes+8) * requiredAverageProofOfWorkNonceTrialsPerByte) encryptedPayload = embeddedTime + \
encodeVarint(toStreamNumber) + encrypted
target = 2 ** 64 / ((len(
encryptedPayload) + requiredPayloadLengthExtraBytes + 8) * requiredAverageProofOfWorkNonceTrialsPerByte)
shared.printLock.acquire() shared.printLock.acquire()
print '(For msg message) Doing proof of work. Total required difficulty:', float(requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte, 'Required small message difficulty:', float(requiredPayloadLengthExtraBytes) / shared.networkDefaultPayloadLengthExtraBytes print '(For msg message) Doing proof of work. Total required difficulty:', float(requiredAverageProofOfWorkNonceTrialsPerByte) / shared.networkDefaultProofOfWorkNonceTrialsPerByte, 'Required small message difficulty:', float(requiredPayloadLengthExtraBytes) / shared.networkDefaultPayloadLengthExtraBytes
shared.printLock.release() shared.printLock.release()
@ -3186,30 +3766,37 @@ class singleWorker(threading.Thread):
inventoryHash = calculateInventoryHash(encryptedPayload) inventoryHash = calculateInventoryHash(encryptedPayload)
objectType = 'msg' objectType = 'msg'
shared.inventory[inventoryHash] = (objectType, toStreamNumber, encryptedPayload, int(time.time())) shared.inventory[inventoryHash] = (
shared.UISignalQueue.put(('updateSentItemStatusByAckdata',(ackdata,'Message sent. Waiting on acknowledgement. Sent on ' + unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'),localtime(int(time.time()))),'utf-8')))) objectType, toStreamNumber, encryptedPayload, int(time.time()))
shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, 'Message sent. Waiting on acknowledgement. Sent on ' + unicode(
strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))
print 'Broadcasting inv for my msg(within sendmsg function):', inventoryHash.encode('hex') print 'Broadcasting inv for my msg(within sendmsg function):', inventoryHash.encode('hex')
shared.broadcastToSendDataQueues((streamNumber, 'sendinv', inventoryHash)) shared.broadcastToSendDataQueues((
streamNumber, 'sendinv', inventoryHash))
#Update the status of the message in the 'sent' table to have a 'msgsent' status # Update the status of the message in the 'sent' table to have a
# 'msgsent' status
shared.sqlLock.acquire() shared.sqlLock.acquire()
t = (ackdata,) t = (ackdata,)
shared.sqlSubmitQueue.put('''UPDATE sent SET status='msgsent' WHERE ackdata=? AND (status='doingmsgpow' or status='forcepow') ''') shared.sqlSubmitQueue.put(
'''UPDATE sent SET status='msgsent' WHERE ackdata=? AND (status='doingmsgpow' or status='forcepow') ''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release() shared.sqlLock.release()
def requestPubKey(self, toAddress): def requestPubKey(self, toAddress):
toStatus,addressVersionNumber,streamNumber,ripe = decodeAddress(toAddress) toStatus, addressVersionNumber, streamNumber, ripe = decodeAddress(
toAddress)
if toStatus != 'success': if toStatus != 'success':
shared.printLock.acquire() shared.printLock.acquire()
sys.stderr.write('Very abnormal error occurred in requestPubKey. toAddress is: '+repr(toAddress)+'. Please report this error to Atheros.') sys.stderr.write('Very abnormal error occurred in requestPubKey. toAddress is: ' + repr(
toAddress) + '. Please report this error to Atheros.')
shared.printLock.release() shared.printLock.release()
return return
neededPubkeys[ripe] = 0 neededPubkeys[ripe] = 0
payload = pack('>Q',(int(time.time())+random.randrange(-300, 300)))#the current time plus or minus five minutes. payload = pack('>Q', (int(time.time()) + random.randrange(
-300, 300))) # the current time plus or minus five minutes.
payload += encodeVarint(addressVersionNumber) payload += encodeVarint(addressVersionNumber)
payload += encodeVarint(streamNumber) payload += encodeVarint(streamNumber)
payload += ripe payload += ripe
@ -3219,8 +3806,10 @@ class singleWorker(threading.Thread):
# print 'trial value', trialValue # print 'trial value', trialValue
statusbar = 'Doing the computations necessary to request the recipient\'s public key.' statusbar = 'Doing the computations necessary to request the recipient\'s public key.'
shared.UISignalQueue.put(('updateStatusBar', statusbar)) shared.UISignalQueue.put(('updateStatusBar', statusbar))
shared.UISignalQueue.put(('updateSentItemStatusByHash',(ripe,'Doing work necessary to request encryption key.'))) shared.UISignalQueue.put(('updateSentItemStatusByHash', (
target = 2**64 / ((len(payload)+shared.networkDefaultPayloadLengthExtraBytes+8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) ripe, 'Doing work necessary to request encryption key.')))
target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes +
8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte)
initialHash = hashlib.sha512(payload).digest() initialHash = hashlib.sha512(payload).digest()
trialValue, nonce = proofofwork.run(target, initialHash) trialValue, nonce = proofofwork.run(target, initialHash)
shared.printLock.acquire() shared.printLock.acquire()
@ -3230,24 +3819,30 @@ class singleWorker(threading.Thread):
payload = pack('>Q', nonce) + payload payload = pack('>Q', nonce) + payload
inventoryHash = calculateInventoryHash(payload) inventoryHash = calculateInventoryHash(payload)
objectType = 'getpubkey' objectType = 'getpubkey'
shared.inventory[inventoryHash] = (objectType, streamNumber, payload, int(time.time())) shared.inventory[inventoryHash] = (
objectType, streamNumber, payload, int(time.time()))
print 'sending inv (for the getpubkey message)' print 'sending inv (for the getpubkey message)'
shared.broadcastToSendDataQueues((streamNumber, 'sendinv', inventoryHash)) shared.broadcastToSendDataQueues((
streamNumber, 'sendinv', inventoryHash))
t = (toAddress,) t = (toAddress,)
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''UPDATE sent SET status='awaitingpubkey' WHERE toaddress=? AND status='doingpubkeypow' ''') shared.sqlSubmitQueue.put(
'''UPDATE sent SET status='awaitingpubkey' WHERE toaddress=? AND status='doingpubkeypow' ''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release() shared.sqlLock.release()
shared.UISignalQueue.put(('updateStatusBar','Broacasting the public key request. This program will auto-retry if they are offline.')) shared.UISignalQueue.put((
shared.UISignalQueue.put(('updateSentItemStatusByHash',(ripe,'Sending public key request. Waiting for reply. Requested at ' + unicode(strftime(shared.config.get('bitmessagesettings', 'timeformat'),localtime(int(time.time()))),'utf-8')))) 'updateStatusBar', 'Broacasting the public key request. This program will auto-retry if they are offline.'))
shared.UISignalQueue.put(('updateSentItemStatusByHash', (ripe, 'Sending public key request. Waiting for reply. Requested at ' + 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):
payload = embeddedTime + encodeVarint(toStreamNumber) + ackdata payload = embeddedTime + encodeVarint(toStreamNumber) + ackdata
target = 2**64 / ((len(payload)+shared.networkDefaultPayloadLengthExtraBytes+8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte) target = 2 ** 64 / ((len(payload) + shared.networkDefaultPayloadLengthExtraBytes +
8) * shared.networkDefaultProofOfWorkNonceTrialsPerByte)
shared.printLock.acquire() shared.printLock.acquire()
print '(For ack message) Doing proof of work...' print '(For ack message) Doing proof of work...'
shared.printLock.release() shared.printLock.release()
@ -3268,7 +3863,9 @@ class singleWorker(threading.Thread):
headerData += hashlib.sha512(payload).digest()[:4] headerData += hashlib.sha512(payload).digest()[:4]
return headerData + payload return headerData + payload
class addressGenerator(threading.Thread): class addressGenerator(threading.Thread):
def __init__(self): def __init__(self):
# QThread.__init__(self, parent) # QThread.__init__(self, parent)
threading.Thread.__init__(self) threading.Thread.__init__(self)
@ -3283,23 +3880,29 @@ class addressGenerator(threading.Thread):
elif len(queueValue) == 9: elif len(queueValue) == 9:
command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes = queueValue command, addressVersionNumber, streamNumber, label, numberOfAddressesToMake, deterministicPassphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes = queueValue
else: else:
sys.stderr.write('Programming error: A structure with the wrong number of values was passed into the addressGeneratorQueue. Here is the queueValue: %s\n' % queueValue) sys.stderr.write(
'Programming error: A structure with the wrong number of values was passed into the addressGeneratorQueue. Here is the queueValue: %s\n' % queueValue)
if addressVersionNumber < 3 or addressVersionNumber > 3: if addressVersionNumber < 3 or addressVersionNumber > 3:
sys.stderr.write('Program error: For some reason the address generator queue has been given a request to create at least one version %s address which it cannot do.\n' % addressVersionNumber) sys.stderr.write(
'Program error: For some reason the address generator queue has been given a request to create at least one version %s address which it cannot do.\n' % addressVersionNumber)
if nonceTrialsPerByte == 0: if nonceTrialsPerByte == 0:
nonceTrialsPerByte = shared.config.getint('bitmessagesettings','defaultnoncetrialsperbyte') nonceTrialsPerByte = shared.config.getint(
'bitmessagesettings', 'defaultnoncetrialsperbyte')
if nonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte: if nonceTrialsPerByte < shared.networkDefaultProofOfWorkNonceTrialsPerByte:
nonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte nonceTrialsPerByte = shared.networkDefaultProofOfWorkNonceTrialsPerByte
if payloadLengthExtraBytes == 0: if payloadLengthExtraBytes == 0:
payloadLengthExtraBytes = shared.config.getint('bitmessagesettings','defaultpayloadlengthextrabytes') payloadLengthExtraBytes = shared.config.getint(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
if payloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes: if payloadLengthExtraBytes < shared.networkDefaultPayloadLengthExtraBytes:
payloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes payloadLengthExtraBytes = shared.networkDefaultPayloadLengthExtraBytes
if addressVersionNumber == 3: # currently the only one supported. if addressVersionNumber == 3: # currently the only one supported.
if command == 'createRandomAddress': if command == 'createRandomAddress':
shared.UISignalQueue.put(('updateStatusBar','Generating one new address')) shared.UISignalQueue.put((
'updateStatusBar', 'Generating one new address'))
# This next section is a little bit strange. We're going to generate keys over and over until we # This next section is a little bit strange. We're going to generate keys over and over until we
# find one that starts with either \x00 or \x00\x00. Then when we pack them into a Bitmessage address, # find one that starts with either \x00 or \x00\x00. Then when we pack them into a Bitmessage address,
#we won't store the \x00 or \x00\x00 bytes thus making the address shorter. # we won't store the \x00 or \x00\x00 bytes thus making the
# address shorter.
startTime = time.time() startTime = time.time()
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0
potentialPrivSigningKey = OpenSSL.rand(32) potentialPrivSigningKey = OpenSSL.rand(32)
@ -3307,14 +3910,18 @@ class addressGenerator(threading.Thread):
while True: while True:
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1
potentialPrivEncryptionKey = OpenSSL.rand(32) potentialPrivEncryptionKey = OpenSSL.rand(32)
potentialPubEncryptionKey = pointMult(potentialPrivEncryptionKey) potentialPubEncryptionKey = pointMult(
potentialPrivEncryptionKey)
# print 'potentialPubSigningKey', potentialPubSigningKey.encode('hex') # print 'potentialPubSigningKey', potentialPubSigningKey.encode('hex')
#print 'potentialPubEncryptionKey', potentialPubEncryptionKey.encode('hex') # print 'potentialPubEncryptionKey',
# potentialPubEncryptionKey.encode('hex')
ripe = hashlib.new('ripemd160') ripe = hashlib.new('ripemd160')
sha = hashlib.new('sha512') sha = hashlib.new('sha512')
sha.update(potentialPubSigningKey+potentialPubEncryptionKey) sha.update(
potentialPubSigningKey + potentialPubEncryptionKey)
ripe.update(sha.digest()) ripe.update(sha.digest())
#print 'potential ripe.digest', ripe.digest().encode('hex') # print 'potential ripe.digest',
# ripe.digest().encode('hex')
if eighteenByteRipe: if eighteenByteRipe:
if ripe.digest()[:2] == '\x00\x00': if ripe.digest()[:2] == '\x00\x00':
break break
@ -3328,65 +3935,90 @@ class addressGenerator(threading.Thread):
# An excellent way for us to store our keys is in Wallet Import Format. Let us convert now. # An excellent way for us to store our keys is in Wallet Import Format. Let us convert now.
# https://en.bitcoin.it/wiki/Wallet_import_format # https://en.bitcoin.it/wiki/Wallet_import_format
privSigningKey = '\x80' + potentialPrivSigningKey privSigningKey = '\x80' + potentialPrivSigningKey
checksum = hashlib.sha256(hashlib.sha256(privSigningKey).digest()).digest()[0:4] checksum = hashlib.sha256(hashlib.sha256(
privSigningKeyWIF = arithmetic.changebase(privSigningKey + checksum,256,58) privSigningKey).digest()).digest()[0:4]
privSigningKeyWIF = arithmetic.changebase(
privSigningKey + checksum, 256, 58)
# print 'privSigningKeyWIF',privSigningKeyWIF # print 'privSigningKeyWIF',privSigningKeyWIF
privEncryptionKey = '\x80' + potentialPrivEncryptionKey privEncryptionKey = '\x80' + potentialPrivEncryptionKey
checksum = hashlib.sha256(hashlib.sha256(privEncryptionKey).digest()).digest()[0:4] checksum = hashlib.sha256(hashlib.sha256(
privEncryptionKeyWIF = arithmetic.changebase(privEncryptionKey + checksum,256,58) privEncryptionKey).digest()).digest()[0:4]
privEncryptionKeyWIF = arithmetic.changebase(
privEncryptionKey + checksum, 256, 58)
# print 'privEncryptionKeyWIF',privEncryptionKeyWIF # print 'privEncryptionKeyWIF',privEncryptionKeyWIF
shared.config.add_section(address) shared.config.add_section(address)
shared.config.set(address, 'label', label) shared.config.set(address, 'label', label)
shared.config.set(address, 'enabled', 'true') shared.config.set(address, 'enabled', 'true')
shared.config.set(address, 'decoy', 'false') shared.config.set(address, 'decoy', 'false')
shared.config.set(address,'noncetrialsperbyte',str(nonceTrialsPerByte)) shared.config.set(address, 'noncetrialsperbyte', str(
shared.config.set(address,'payloadlengthextrabytes',str(payloadLengthExtraBytes)) nonceTrialsPerByte))
shared.config.set(address,'privSigningKey',privSigningKeyWIF) shared.config.set(address, 'payloadlengthextrabytes', str(
shared.config.set(address,'privEncryptionKey',privEncryptionKeyWIF) payloadLengthExtraBytes))
shared.config.set(
address, 'privSigningKey', privSigningKeyWIF)
shared.config.set(
address, 'privEncryptionKey', privEncryptionKeyWIF)
with open(shared.appdata + 'keys.dat', 'wb') as configfile: with open(shared.appdata + 'keys.dat', 'wb') as configfile:
shared.config.write(configfile) shared.config.write(configfile)
#It may be the case that this address is being generated as a result of a call to the API. Let us put the result in the necessary queue. # It may be the case that this address is being generated
# as a result of a call to the API. Let us put the result
# in the necessary queue.
apiAddressGeneratorReturnQueue.put(address) apiAddressGeneratorReturnQueue.put(address)
shared.UISignalQueue.put(('updateStatusBar','Done generating address. Doing work necessary to broadcast it...')) shared.UISignalQueue.put((
shared.UISignalQueue.put(('writeNewAddressToTable',(label,address,streamNumber))) 'updateStatusBar', 'Done generating address. Doing work necessary to broadcast it...'))
shared.UISignalQueue.put(('writeNewAddressToTable', (
label, address, streamNumber)))
shared.reloadMyAddressHashes() shared.reloadMyAddressHashes()
shared.workerQueue.put(('doPOWForMyV3Pubkey',ripe.digest())) shared.workerQueue.put((
'doPOWForMyV3Pubkey', ripe.digest()))
elif command == 'createDeterministicAddresses' or command == 'getDeterministicAddress': elif command == 'createDeterministicAddresses' or command == 'getDeterministicAddress':
if len(deterministicPassphrase) == 0: if len(deterministicPassphrase) == 0:
sys.stderr.write('WARNING: You are creating deterministic address(es) using a blank passphrase. Bitmessage will do it but it is rather stupid.') sys.stderr.write(
'WARNING: You are creating deterministic address(es) using a blank passphrase. Bitmessage will do it but it is rather stupid.')
if command == 'createDeterministicAddresses': if command == 'createDeterministicAddresses':
statusbar = 'Generating '+str(numberOfAddressesToMake) + ' new addresses.' statusbar = 'Generating ' + str(
shared.UISignalQueue.put(('updateStatusBar',statusbar)) numberOfAddressesToMake) + ' new addresses.'
shared.UISignalQueue.put((
'updateStatusBar', statusbar))
signingKeyNonce = 0 signingKeyNonce = 0
encryptionKeyNonce = 1 encryptionKeyNonce = 1
listOfNewAddressesToSendOutThroughTheAPI = [] #We fill out this list no matter what although we only need it if we end up passing the info to the API. listOfNewAddressesToSendOutThroughTheAPI = [
] # We fill out this list no matter what although we only need it if we end up passing the info to the API.
for i in range(numberOfAddressesToMake): for i in range(numberOfAddressesToMake):
# This next section is a little bit strange. We're going to generate keys over and over until we # This next section is a little bit strange. We're going to generate keys over and over until we
# find one that has a RIPEMD hash that starts with either \x00 or \x00\x00. Then when we pack them # find one that has a RIPEMD hash that starts with either \x00 or \x00\x00. Then when we pack them
#into a Bitmessage address, we won't store the \x00 or \x00\x00 bytes thus making the address shorter. # into a Bitmessage address, we won't store the \x00 or
# \x00\x00 bytes thus making the address shorter.
startTime = time.time() startTime = time.time()
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0 numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0
while True: while True:
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1
potentialPrivSigningKey = hashlib.sha512(deterministicPassphrase + encodeVarint(signingKeyNonce)).digest()[:32] potentialPrivSigningKey = hashlib.sha512(
potentialPrivEncryptionKey = hashlib.sha512(deterministicPassphrase + encodeVarint(encryptionKeyNonce)).digest()[:32] deterministicPassphrase + encodeVarint(signingKeyNonce)).digest()[:32]
potentialPubSigningKey = pointMult(potentialPrivSigningKey) potentialPrivEncryptionKey = hashlib.sha512(
potentialPubEncryptionKey = pointMult(potentialPrivEncryptionKey) deterministicPassphrase + encodeVarint(encryptionKeyNonce)).digest()[:32]
potentialPubSigningKey = pointMult(
potentialPrivSigningKey)
potentialPubEncryptionKey = pointMult(
potentialPrivEncryptionKey)
# print 'potentialPubSigningKey', potentialPubSigningKey.encode('hex') # print 'potentialPubSigningKey', potentialPubSigningKey.encode('hex')
#print 'potentialPubEncryptionKey', potentialPubEncryptionKey.encode('hex') # print 'potentialPubEncryptionKey',
# potentialPubEncryptionKey.encode('hex')
signingKeyNonce += 2 signingKeyNonce += 2
encryptionKeyNonce += 2 encryptionKeyNonce += 2
ripe = hashlib.new('ripemd160') ripe = hashlib.new('ripemd160')
sha = hashlib.new('sha512') sha = hashlib.new('sha512')
sha.update(potentialPubSigningKey+potentialPubEncryptionKey) sha.update(
potentialPubSigningKey + potentialPubEncryptionKey)
ripe.update(sha.digest()) ripe.update(sha.digest())
#print 'potential ripe.digest', ripe.digest().encode('hex') # print 'potential ripe.digest',
# ripe.digest().encode('hex')
if eighteenByteRipe: if eighteenByteRipe:
if ripe.digest()[:2] == '\x00\x00': if ripe.digest()[:2] == '\x00\x00':
break break
@ -3402,12 +4034,17 @@ class addressGenerator(threading.Thread):
# An excellent way for us to store our keys is in Wallet Import Format. Let us convert now. # An excellent way for us to store our keys is in Wallet Import Format. Let us convert now.
# https://en.bitcoin.it/wiki/Wallet_import_format # https://en.bitcoin.it/wiki/Wallet_import_format
privSigningKey = '\x80' + potentialPrivSigningKey privSigningKey = '\x80' + potentialPrivSigningKey
checksum = hashlib.sha256(hashlib.sha256(privSigningKey).digest()).digest()[0:4] checksum = hashlib.sha256(hashlib.sha256(
privSigningKeyWIF = arithmetic.changebase(privSigningKey + checksum,256,58) privSigningKey).digest()).digest()[0:4]
privSigningKeyWIF = arithmetic.changebase(
privSigningKey + checksum, 256, 58)
privEncryptionKey = '\x80'+potentialPrivEncryptionKey privEncryptionKey = '\x80' + \
checksum = hashlib.sha256(hashlib.sha256(privEncryptionKey).digest()).digest()[0:4] potentialPrivEncryptionKey
privEncryptionKeyWIF = arithmetic.changebase(privEncryptionKey + checksum,256,58) checksum = hashlib.sha256(hashlib.sha256(
privEncryptionKey).digest()).digest()[0:4]
privEncryptionKeyWIF = arithmetic.changebase(
privEncryptionKey + checksum, 256, 58)
try: try:
shared.config.add_section(address) shared.config.add_section(address)
@ -3415,38 +4052,61 @@ class addressGenerator(threading.Thread):
shared.config.set(address, 'label', label) shared.config.set(address, 'label', label)
shared.config.set(address, 'enabled', 'true') shared.config.set(address, 'enabled', 'true')
shared.config.set(address, 'decoy', 'false') shared.config.set(address, 'decoy', 'false')
shared.config.set(address,'noncetrialsperbyte',str(nonceTrialsPerByte)) shared.config.set(address, 'noncetrialsperbyte', str(
shared.config.set(address,'payloadlengthextrabytes',str(payloadLengthExtraBytes)) nonceTrialsPerByte))
shared.config.set(address,'privSigningKey',privSigningKeyWIF) shared.config.set(address, 'payloadlengthextrabytes', str(
shared.config.set(address,'privEncryptionKey',privEncryptionKeyWIF) payloadLengthExtraBytes))
shared.config.set(
address, 'privSigningKey', privSigningKeyWIF)
shared.config.set(
address, 'privEncryptionKey', privEncryptionKeyWIF)
with open(shared.appdata + 'keys.dat', 'wb') as configfile: with open(shared.appdata + 'keys.dat', 'wb') as configfile:
shared.config.write(configfile) shared.config.write(configfile)
shared.UISignalQueue.put(('writeNewAddressToTable',(label,address,str(streamNumber)))) shared.UISignalQueue.put(('writeNewAddressToTable', (
listOfNewAddressesToSendOutThroughTheAPI.append(address) label, address, str(streamNumber))))
listOfNewAddressesToSendOutThroughTheAPI.append(
address)
# if eighteenByteRipe: # if eighteenByteRipe:
# shared.reloadMyAddressHashes()#This is necessary here (rather than just at the end) because otherwise if the human generates a large number of new addresses and uses one before they are done generating, the program will receive a getpubkey message and will ignore it. # shared.reloadMyAddressHashes()#This is
shared.myECCryptorObjects[ripe.digest()] = highlevelcrypto.makeCryptor(potentialPrivEncryptionKey.encode('hex')) # necessary here (rather than just at the end)
shared.myAddressesByHash[ripe.digest()] = address # because otherwise if the human generates a
shared.workerQueue.put(('doPOWForMyV3Pubkey',ripe.digest())) # large number of new addresses and uses one
# before they are done generating, the program
# will receive a getpubkey message and will
# ignore it.
shared.myECCryptorObjects[ripe.digest()] = highlevelcrypto.makeCryptor(
potentialPrivEncryptionKey.encode('hex'))
shared.myAddressesByHash[
ripe.digest()] = address
shared.workerQueue.put((
'doPOWForMyV3Pubkey', ripe.digest()))
except: except:
print address, 'already exists. Not adding it again.' print address, 'already exists. Not adding it again.'
# Done generating addresses. # Done generating addresses.
if command == 'createDeterministicAddresses': if command == 'createDeterministicAddresses':
#It may be the case that this address is being generated as a result of a call to the API. Let us put the result in the necessary queue. # It may be the case that this address is being
apiAddressGeneratorReturnQueue.put(listOfNewAddressesToSendOutThroughTheAPI) # generated as a result of a call to the API. Let us
shared.UISignalQueue.put(('updateStatusBar','Done generating address')) # put the result in the necessary queue.
apiAddressGeneratorReturnQueue.put(
listOfNewAddressesToSendOutThroughTheAPI)
shared.UISignalQueue.put((
'updateStatusBar', 'Done generating address'))
# shared.reloadMyAddressHashes() # shared.reloadMyAddressHashes()
elif command == 'getDeterministicAddress': elif command == 'getDeterministicAddress':
apiAddressGeneratorReturnQueue.put(address) apiAddressGeneratorReturnQueue.put(address)
else: else:
raise Exception("Error in the addressGenerator thread. Thread was given a command it could not understand: "+command) raise Exception(
"Error in the addressGenerator thread. Thread was given a command it could not understand: " + command)
# This is one of several classes that constitute the API # This is one of several classes that constitute the API
# This class was written by Vaibhav Bhatia. Modified by Jonathan Warren (Atheros). # This class was written by Vaibhav Bhatia. Modified by Jonathan Warren (Atheros).
# http://code.activestate.com/recipes/501148-xmlrpc-serverclient-which-does-cookie-handling-and/ # http://code.activestate.com/recipes/501148-xmlrpc-serverclient-which-does-cookie-handling-and/
class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
def do_POST(self): def do_POST(self):
# Handles the HTTP POST request. # Handles the HTTP POST request.
# Attempts to interpret all HTTP POST requests as XML-RPC calls, # Attempts to interpret all HTTP POST requests as XML-RPC calls,
@ -3505,9 +4165,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
self.wfile.flush() self.wfile.flush()
self.connection.shutdown(1) self.connection.shutdown(1)
def APIAuthenticateClient(self): def APIAuthenticateClient(self):
if self.headers.has_key('Authorization'): if 'Authorization' in self.headers:
# handle Basic authentication # handle Basic authentication
(enctype, encstr) = self.headers.get('Authorization').split() (enctype, encstr) = self.headers.get('Authorization').split()
(emailid, password) = encstr.decode('base64').split(':') (emailid, password) = encstr.decode('base64').split(':')
@ -3543,12 +4202,14 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data = '{"addresses":[' data = '{"addresses":['
configSections = shared.config.sections() configSections = shared.config.sections()
for addressInKeysFile in configSections: for addressInKeysFile in configSections:
if addressInKeysFile <> 'bitmessagesettings': if addressInKeysFile != 'bitmessagesettings':
status,addressVersionNumber,streamNumber,hash = decodeAddress(addressInKeysFile) status, addressVersionNumber, streamNumber, hash = decodeAddress(
addressInKeysFile)
data data
if len(data) > 20: if len(data) > 20:
data += ',' data += ','
data += json.dumps({'label':shared.config.get(addressInKeysFile,'label'),'address':addressInKeysFile,'stream':streamNumber,'enabled':shared.config.getboolean(addressInKeysFile,'enabled')},indent=4, separators=(',', ': ')) data += json.dumps({'label': shared.config.get(addressInKeysFile, 'label'), 'address': addressInKeysFile, 'stream':
streamNumber, 'enabled': shared.config.getboolean(addressInKeysFile, 'enabled')}, indent=4, separators=(',', ': '))
data += ']}' data += ']}'
return data return data
elif method == 'createRandomAddress': elif method == 'createRandomAddress':
@ -3557,20 +4218,28 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
elif len(params) == 1: elif len(params) == 1:
label, = params label, = params
eighteenByteRipe = False eighteenByteRipe = False
nonceTrialsPerByte = shared.config.get('bitmessagesettings','defaultnoncetrialsperbyte') nonceTrialsPerByte = shared.config.get(
payloadLengthExtraBytes = shared.config.get('bitmessagesettings','defaultpayloadlengthextrabytes') 'bitmessagesettings', 'defaultnoncetrialsperbyte')
payloadLengthExtraBytes = shared.config.get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 2: elif len(params) == 2:
label, eighteenByteRipe = params label, eighteenByteRipe = params
nonceTrialsPerByte = shared.config.get('bitmessagesettings','defaultnoncetrialsperbyte') nonceTrialsPerByte = shared.config.get(
payloadLengthExtraBytes = shared.config.get('bitmessagesettings','defaultpayloadlengthextrabytes') 'bitmessagesettings', 'defaultnoncetrialsperbyte')
payloadLengthExtraBytes = shared.config.get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 3: elif len(params) == 3:
label, eighteenByteRipe, totalDifficulty = params label, eighteenByteRipe, totalDifficulty = params
nonceTrialsPerByte = int(shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty) nonceTrialsPerByte = int(
payloadLengthExtraBytes = shared.config.get('bitmessagesettings','defaultpayloadlengthextrabytes') shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty)
payloadLengthExtraBytes = shared.config.get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 4: elif len(params) == 4:
label, eighteenByteRipe, totalDifficulty, smallMessageDifficulty = params label, eighteenByteRipe, totalDifficulty, smallMessageDifficulty = params
nonceTrialsPerByte = int(shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty) nonceTrialsPerByte = int(
payloadLengthExtraBytes = int(shared.networkDefaultPayloadLengthExtraBytes * smallMessageDifficulty) shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty)
payloadLengthExtraBytes = int(
shared.networkDefaultPayloadLengthExtraBytes * smallMessageDifficulty)
else: else:
return 'API Error 0000: Too many parameters!' return 'API Error 0000: Too many parameters!'
label = label.decode('base64') label = label.decode('base64')
@ -3580,7 +4249,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
return 'API Error 0017: Label is not valid UTF-8 data.' return 'API Error 0017: Label is not valid UTF-8 data.'
apiAddressGeneratorReturnQueue.queue.clear() apiAddressGeneratorReturnQueue.queue.clear()
streamNumberForAddress = 1 streamNumberForAddress = 1
shared.addressGeneratorQueue.put(('createRandomAddress',3,streamNumberForAddress,label,1,"",eighteenByteRipe,nonceTrialsPerByte,payloadLengthExtraBytes)) shared.addressGeneratorQueue.put((
'createRandomAddress', 3, streamNumberForAddress, label, 1, "", eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes))
return apiAddressGeneratorReturnQueue.get() return apiAddressGeneratorReturnQueue.get()
elif method == 'createDeterministicAddresses': elif method == 'createDeterministicAddresses':
if len(params) == 0: if len(params) == 0:
@ -3591,38 +4261,52 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
addressVersionNumber = 0 addressVersionNumber = 0
streamNumber = 0 streamNumber = 0
eighteenByteRipe = False eighteenByteRipe = False
nonceTrialsPerByte = shared.config.get('bitmessagesettings','defaultnoncetrialsperbyte') nonceTrialsPerByte = shared.config.get(
payloadLengthExtraBytes = shared.config.get('bitmessagesettings','defaultpayloadlengthextrabytes') 'bitmessagesettings', 'defaultnoncetrialsperbyte')
payloadLengthExtraBytes = shared.config.get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 2: elif len(params) == 2:
passphrase, numberOfAddresses = params passphrase, numberOfAddresses = params
addressVersionNumber = 0 addressVersionNumber = 0
streamNumber = 0 streamNumber = 0
eighteenByteRipe = False eighteenByteRipe = False
nonceTrialsPerByte = shared.config.get('bitmessagesettings','defaultnoncetrialsperbyte') nonceTrialsPerByte = shared.config.get(
payloadLengthExtraBytes = shared.config.get('bitmessagesettings','defaultpayloadlengthextrabytes') 'bitmessagesettings', 'defaultnoncetrialsperbyte')
payloadLengthExtraBytes = shared.config.get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 3: elif len(params) == 3:
passphrase, numberOfAddresses, addressVersionNumber = params passphrase, numberOfAddresses, addressVersionNumber = params
streamNumber = 0 streamNumber = 0
eighteenByteRipe = False eighteenByteRipe = False
nonceTrialsPerByte = shared.config.get('bitmessagesettings','defaultnoncetrialsperbyte') nonceTrialsPerByte = shared.config.get(
payloadLengthExtraBytes = shared.config.get('bitmessagesettings','defaultpayloadlengthextrabytes') 'bitmessagesettings', 'defaultnoncetrialsperbyte')
payloadLengthExtraBytes = shared.config.get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 4: elif len(params) == 4:
passphrase, numberOfAddresses, addressVersionNumber, streamNumber = params passphrase, numberOfAddresses, addressVersionNumber, streamNumber = params
eighteenByteRipe = False eighteenByteRipe = False
nonceTrialsPerByte = shared.config.get('bitmessagesettings','defaultnoncetrialsperbyte') nonceTrialsPerByte = shared.config.get(
payloadLengthExtraBytes = shared.config.get('bitmessagesettings','defaultpayloadlengthextrabytes') 'bitmessagesettings', 'defaultnoncetrialsperbyte')
payloadLengthExtraBytes = shared.config.get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 5: elif len(params) == 5:
passphrase, numberOfAddresses, addressVersionNumber, streamNumber, eighteenByteRipe = params passphrase, numberOfAddresses, addressVersionNumber, streamNumber, eighteenByteRipe = params
nonceTrialsPerByte = shared.config.get('bitmessagesettings','defaultnoncetrialsperbyte') nonceTrialsPerByte = shared.config.get(
payloadLengthExtraBytes = shared.config.get('bitmessagesettings','defaultpayloadlengthextrabytes') 'bitmessagesettings', 'defaultnoncetrialsperbyte')
payloadLengthExtraBytes = shared.config.get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 6: elif len(params) == 6:
passphrase, numberOfAddresses, addressVersionNumber, streamNumber, eighteenByteRipe, totalDifficulty = params passphrase, numberOfAddresses, addressVersionNumber, streamNumber, eighteenByteRipe, totalDifficulty = params
nonceTrialsPerByte = int(shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty) nonceTrialsPerByte = int(
payloadLengthExtraBytes = shared.config.get('bitmessagesettings','defaultpayloadlengthextrabytes') shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty)
payloadLengthExtraBytes = shared.config.get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 7: elif len(params) == 7:
passphrase, numberOfAddresses, addressVersionNumber, streamNumber, eighteenByteRipe, totalDifficulty, smallMessageDifficulty = params passphrase, numberOfAddresses, addressVersionNumber, streamNumber, eighteenByteRipe, totalDifficulty, smallMessageDifficulty = params
nonceTrialsPerByte = int(shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty) nonceTrialsPerByte = int(
payloadLengthExtraBytes = int(shared.networkDefaultPayloadLengthExtraBytes * smallMessageDifficulty) shared.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty)
payloadLengthExtraBytes = int(
shared.networkDefaultPayloadLengthExtraBytes * smallMessageDifficulty)
else: else:
return 'API Error 0000: Too many parameters!' return 'API Error 0000: Too many parameters!'
if len(passphrase) == 0: if len(passphrase) == 0:
@ -3642,7 +4326,9 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
return 'API Error 0005: You have (accidentally?) specified too many addresses to make. Maximum 999. This check only exists to prevent mischief; if you really want to create more addresses than this, contact the Bitmessage developers and we can modify the check or you can do it yourself by searching the source code for this message.' return 'API Error 0005: You have (accidentally?) specified too many addresses to make. Maximum 999. This check only exists to prevent mischief; if you really want to create more addresses than this, contact the Bitmessage developers and we can modify the check or you can do it yourself by searching the source code for this message.'
apiAddressGeneratorReturnQueue.queue.clear() apiAddressGeneratorReturnQueue.queue.clear()
print 'Requesting that the addressGenerator create', numberOfAddresses, 'addresses.' print 'Requesting that the addressGenerator create', numberOfAddresses, 'addresses.'
shared.addressGeneratorQueue.put(('createDeterministicAddresses',addressVersionNumber,streamNumber,'unused API address',numberOfAddresses,passphrase,eighteenByteRipe,nonceTrialsPerByte,payloadLengthExtraBytes)) shared.addressGeneratorQueue.put(
('createDeterministicAddresses', addressVersionNumber, streamNumber,
'unused API address', numberOfAddresses, passphrase, eighteenByteRipe, nonceTrialsPerByte, payloadLengthExtraBytes))
data = '{"addresses":[' data = '{"addresses":['
queueReturn = apiAddressGeneratorReturnQueue.get() queueReturn = apiAddressGeneratorReturnQueue.get()
for item in queueReturn: for item in queueReturn:
@ -3666,11 +4352,14 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
return 'API Error 0003: The stream number must be 1. Others aren\'t supported.' return 'API Error 0003: The stream number must be 1. Others aren\'t supported.'
apiAddressGeneratorReturnQueue.queue.clear() apiAddressGeneratorReturnQueue.queue.clear()
print 'Requesting that the addressGenerator create', numberOfAddresses, 'addresses.' print 'Requesting that the addressGenerator create', numberOfAddresses, 'addresses.'
shared.addressGeneratorQueue.put(('getDeterministicAddress',addressVersionNumber,streamNumber,'unused API address',numberOfAddresses,passphrase,eighteenByteRipe)) shared.addressGeneratorQueue.put(
('getDeterministicAddress', addressVersionNumber,
streamNumber, 'unused API address', numberOfAddresses, passphrase, eighteenByteRipe))
return apiAddressGeneratorReturnQueue.get() return apiAddressGeneratorReturnQueue.get()
elif method == 'getAllInboxMessages': elif method == 'getAllInboxMessages':
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''SELECT msgid, toaddress, fromaddress, subject, received, message FROM inbox where folder='inbox' ORDER BY received''') shared.sqlSubmitQueue.put(
'''SELECT msgid, toaddress, fromaddress, subject, received, message FROM inbox where folder='inbox' ORDER BY received''')
shared.sqlSubmitQueue.put('') shared.sqlSubmitQueue.put('')
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
@ -3681,7 +4370,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
message = shared.fixPotentiallyInvalidUTF8Data(message) message = shared.fixPotentiallyInvalidUTF8Data(message)
if len(data) > 25: if len(data) > 25:
data += ',' data += ','
data += json.dumps({'msgid':msgid.encode('hex'),'toAddress':toAddress,'fromAddress':fromAddress,'subject':subject.encode('base64'),'message':message.encode('base64'),'encodingType':2,'receivedTime':received},indent=4, separators=(',', ': ')) data += json.dumps({'msgid': msgid.encode('hex'), 'toAddress': toAddress, 'fromAddress': fromAddress, 'subject': subject.encode(
'base64'), 'message': message.encode('base64'), 'encodingType': 2, 'receivedTime': received}, indent=4, separators=(',', ': '))
data += ']}' data += ']}'
return data return data
elif method == 'trashMessage': elif method == 'trashMessage':
@ -3690,7 +4380,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
msgid = params[0].decode('hex') msgid = params[0].decode('hex')
t = (msgid,) t = (msgid,)
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''UPDATE inbox SET folder='trash' WHERE msgid=?''') shared.sqlSubmitQueue.put(
'''UPDATE inbox SET folder='trash' WHERE msgid=?''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
@ -3709,8 +4400,9 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
return 'API Error 0006: The encoding type must be 2 because that is the only one this program currently supports.' return 'API Error 0006: The encoding type must be 2 because that is the only one this program currently supports.'
subject = subject.decode('base64') subject = subject.decode('base64')
message = message.decode('base64') message = message.decode('base64')
status,addressVersionNumber,streamNumber,toRipe = decodeAddress(toAddress) status, addressVersionNumber, streamNumber, toRipe = decodeAddress(
if status <> 'success': toAddress)
if status != 'success':
shared.printLock.acquire() shared.printLock.acquire()
print 'API Error 0007: Could not decode address:', toAddress, ':', status print 'API Error 0007: Could not decode address:', toAddress, ':', status
shared.printLock.release() shared.printLock.release()
@ -3725,8 +4417,9 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
return 'API Error 0011: The address version number currently must be 2 or 3. Others aren\'t supported. Check the toAddress.' return 'API Error 0011: The address version number currently must be 2 or 3. Others aren\'t supported. Check the toAddress.'
if streamNumber != 1: if streamNumber != 1:
return 'API Error 0012: The stream number must be 1. Others aren\'t supported. Check the toAddress.' return 'API Error 0012: The stream number must be 1. Others aren\'t supported. Check the toAddress.'
status,addressVersionNumber,streamNumber,fromRipe = decodeAddress(fromAddress) status, addressVersionNumber, streamNumber, fromRipe = decodeAddress(
if status <> 'success': fromAddress)
if status != 'success':
shared.printLock.acquire() shared.printLock.acquire()
print 'API Error 0007: Could not decode address:', fromAddress, ':', status print 'API Error 0007: Could not decode address:', fromAddress, ':', status
shared.printLock.release() shared.printLock.release()
@ -3744,7 +4437,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
toAddress = addBMIfNotPresent(toAddress) toAddress = addBMIfNotPresent(toAddress)
fromAddress = addBMIfNotPresent(fromAddress) fromAddress = addBMIfNotPresent(fromAddress)
try: try:
fromAddressEnabled = shared.config.getboolean(fromAddress,'enabled') fromAddressEnabled = shared.config.getboolean(
fromAddress, 'enabled')
except: except:
return 'API Error 0013: Could not find your fromAddress in the keys.dat file.' return 'API Error 0013: Could not find your fromAddress in the keys.dat file.'
if not fromAddressEnabled: if not fromAddressEnabled:
@ -3752,8 +4446,10 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
ackdata = OpenSSL.rand(32) ackdata = OpenSSL.rand(32)
shared.sqlLock.acquire() shared.sqlLock.acquire()
t = ('',toAddress,toRipe,fromAddress,subject,message,ackdata,int(time.time()),'msgqueued',1,1,'sent',2) t = ('', toAddress, toRipe, fromAddress, subject, message, ackdata, int(
shared.sqlSubmitQueue.put('''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)''') time.time()), 'msgqueued', 1, 1, 'sent', 2)
shared.sqlSubmitQueue.put(
'''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
@ -3762,15 +4458,17 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
toLabel = '' toLabel = ''
t = (toAddress,) t = (toAddress,)
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''select label from addressbook where address=?''') shared.sqlSubmitQueue.put(
'''select label from addressbook where address=?''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
if queryreturn <> []: if queryreturn != []:
for row in queryreturn: for row in queryreturn:
toLabel, = row toLabel, = row
# apiSignalQueue.put(('displayNewSentMessage',(toAddress,toLabel,fromAddress,subject,message,ackdata))) # apiSignalQueue.put(('displayNewSentMessage',(toAddress,toLabel,fromAddress,subject,message,ackdata)))
shared.UISignalQueue.put(('displayNewSentMessage',(toAddress,toLabel,fromAddress,subject,message,ackdata))) shared.UISignalQueue.put(('displayNewSentMessage', (
toAddress, toLabel, fromAddress, subject, message, ackdata)))
shared.workerQueue.put(('sendmessage', toAddress)) shared.workerQueue.put(('sendmessage', toAddress))
@ -3789,8 +4487,9 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
subject = subject.decode('base64') subject = subject.decode('base64')
message = message.decode('base64') message = message.decode('base64')
status,addressVersionNumber,streamNumber,fromRipe = decodeAddress(fromAddress) status, addressVersionNumber, streamNumber, fromRipe = decodeAddress(
if status <> 'success': fromAddress)
if status != 'success':
shared.printLock.acquire() shared.printLock.acquire()
print 'API Error 0007: Could not decode address:', fromAddress, ':', status print 'API Error 0007: Could not decode address:', fromAddress, ':', status
shared.printLock.release() shared.printLock.release()
@ -3807,7 +4506,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
return 'API Error 0012: the stream number must be 1. Others aren\'t supported. Check the fromAddress.' return 'API Error 0012: the stream number must be 1. Others aren\'t supported. Check the fromAddress.'
fromAddress = addBMIfNotPresent(fromAddress) fromAddress = addBMIfNotPresent(fromAddress)
try: try:
fromAddressEnabled = shared.config.getboolean(fromAddress,'enabled') fromAddressEnabled = shared.config.getboolean(
fromAddress, 'enabled')
except: except:
return 'API Error 0013: could not find your fromAddress in the keys.dat file.' return 'API Error 0013: could not find your fromAddress in the keys.dat file.'
ackdata = OpenSSL.rand(32) ackdata = OpenSSL.rand(32)
@ -3815,15 +4515,18 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
ripe = '' ripe = ''
shared.sqlLock.acquire() shared.sqlLock.acquire()
t = ('',toAddress,ripe,fromAddress,subject,message,ackdata,int(time.time()),'broadcastqueued',1,1,'sent',2) t = ('', toAddress, ripe, fromAddress, subject, message, ackdata, int(
shared.sqlSubmitQueue.put('''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)''') time.time()), 'broadcastqueued', 1, 1, 'sent', 2)
shared.sqlSubmitQueue.put(
'''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
shared.sqlLock.release() shared.sqlLock.release()
toLabel = '[Broadcast subscribers]' toLabel = '[Broadcast subscribers]'
shared.UISignalQueue.put(('displayNewSentMessage',(toAddress,toLabel,fromAddress,subject,message,ackdata))) shared.UISignalQueue.put(('displayNewSentMessage', (
toAddress, toLabel, fromAddress, subject, message, ackdata)))
shared.workerQueue.put(('sendbroadcast', '')) shared.workerQueue.put(('sendbroadcast', ''))
return ackdata.encode('hex') return ackdata.encode('hex')
@ -3834,7 +4537,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
if len(ackdata) != 64: if len(ackdata) != 64:
return 'API Error 0015: The length of ackData should be 32 bytes (encoded in hex thus 64 characters).' return 'API Error 0015: The length of ackData should be 32 bytes (encoded in hex thus 64 characters).'
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''SELECT status FROM sent where ackdata=?''') shared.sqlSubmitQueue.put(
'''SELECT status FROM sent where ackdata=?''')
shared.sqlSubmitQueue.put((ackdata.decode('hex'),)) shared.sqlSubmitQueue.put((ackdata.decode('hex'),))
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
@ -3859,8 +4563,9 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
if len(params) > 2: if len(params) > 2:
return 'API Error 0000: I need either 1 or 2 parameters!' return 'API Error 0000: I need either 1 or 2 parameters!'
address = addBMIfNotPresent(address) address = addBMIfNotPresent(address)
status,addressVersionNumber,streamNumber,toRipe = decodeAddress(address) status, addressVersionNumber, streamNumber, toRipe = decodeAddress(
if status <> 'success': address)
if status != 'success':
shared.printLock.acquire() shared.printLock.acquire()
print 'API Error 0007: Could not decode address:', address, ':', status print 'API Error 0007: Could not decode address:', address, ':', status
shared.printLock.release() shared.printLock.release()
@ -3875,10 +4580,12 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
return 'API Error 0011: The address version number currently must be 2 or 3. Others aren\'t supported.' return 'API Error 0011: The address version number currently must be 2 or 3. Others aren\'t supported.'
if streamNumber != 1: if streamNumber != 1:
return 'API Error 0012: The stream number must be 1. Others aren\'t supported.' return 'API Error 0012: The stream number must be 1. Others aren\'t supported.'
#First we must check to see if the address is already in the subscriptions list. # First we must check to see if the address is already in the
# subscriptions list.
shared.sqlLock.acquire() shared.sqlLock.acquire()
t = (address,) t = (address,)
shared.sqlSubmitQueue.put('''select * from subscriptions where address=?''') shared.sqlSubmitQueue.put(
'''select * from subscriptions where address=?''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlLock.release() shared.sqlLock.release()
@ -3886,7 +4593,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
return 'API Error 0016: You are already subscribed to that address.' return 'API Error 0016: You are already subscribed to that address.'
t = (label, address, True) t = (label, address, True)
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''INSERT INTO subscriptions VALUES (?,?,?)''') shared.sqlSubmitQueue.put(
'''INSERT INTO subscriptions VALUES (?,?,?)''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
queryreturn = shared.sqlReturnQueue.get() queryreturn = shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
@ -3903,7 +4611,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
address = addBMIfNotPresent(address) address = addBMIfNotPresent(address)
t = (address,) t = (address,)
shared.sqlLock.acquire() shared.sqlLock.acquire()
shared.sqlSubmitQueue.put('''DELETE FROM subscriptions WHERE address=?''') shared.sqlSubmitQueue.put(
'''DELETE FROM subscriptions WHERE address=?''')
shared.sqlSubmitQueue.put(t) shared.sqlSubmitQueue.put(t)
shared.sqlReturnQueue.get() shared.sqlReturnQueue.get()
shared.sqlSubmitQueue.put('commit') shared.sqlSubmitQueue.put('commit')
@ -3916,29 +4625,41 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
return 'Invalid Method: %s' % method return 'Invalid Method: %s' % method
# This thread, of which there is only one, runs the API. # This thread, of which there is only one, runs the API.
class singleAPI(threading.Thread): class singleAPI(threading.Thread):
def __init__(self): def __init__(self):
threading.Thread.__init__(self) threading.Thread.__init__(self)
def run(self): def run(self):
se = SimpleXMLRPCServer((shared.config.get('bitmessagesettings', 'apiinterface'),shared.config.getint('bitmessagesettings', 'apiport')), MySimpleXMLRPCRequestHandler, True, True) se = SimpleXMLRPCServer((shared.config.get('bitmessagesettings', 'apiinterface'), shared.config.getint(
'bitmessagesettings', 'apiport')), MySimpleXMLRPCRequestHandler, True, True)
se.register_introspection_functions() se.register_introspection_functions()
se.serve_forever() se.serve_forever()
selfInitiatedConnections = {} #This is a list of current connections (the thread pointers at least) selfInitiatedConnections = {}
alreadyAttemptedConnectionsList = {} #This is a list of nodes to which we have already attempted a connection # This is a list of current connections (the thread pointers at least)
alreadyAttemptedConnectionsList = {
} # This is a list of nodes to which we have already attempted a connection
ackdataForWhichImWatching = {} ackdataForWhichImWatching = {}
alreadyAttemptedConnectionsListLock = threading.Lock() alreadyAttemptedConnectionsListLock = threading.Lock()
eightBytesOfRandomDataUsedToDetectConnectionsToSelf = pack('>Q',random.randrange(1, 18446744073709551615)) eightBytesOfRandomDataUsedToDetectConnectionsToSelf = pack(
'>Q', random.randrange(1, 18446744073709551615))
neededPubkeys = {} neededPubkeys = {}
successfullyDecryptMessageTimings = [] #A list of the amounts of time it took to successfully decrypt msg messages successfullyDecryptMessageTimings = [
apiAddressGeneratorReturnQueue = Queue.Queue() #The address generator thread uses this queue to get information back to the API thread. ] # A list of the amounts of time it took to successfully decrypt msg messages
alreadyAttemptedConnectionsListResetTime = int(time.time()) #used to clear out the alreadyAttemptedConnectionsList periodically so that we will retry connecting to hosts to which we have already tried to connect. apiAddressGeneratorReturnQueue = Queue.Queue(
) # The address generator thread uses this queue to get information back to the API thread.
alreadyAttemptedConnectionsListResetTime = int(
time.time()) # used to clear out the alreadyAttemptedConnectionsList periodically so that we will retry connecting to hosts to which we have already tried to connect.
numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer = {} numberOfObjectsThatWeHaveYetToCheckAndSeeWhetherWeAlreadyHavePerPeer = {}
if useVeryEasyProofOfWorkForTesting: if useVeryEasyProofOfWorkForTesting:
shared.networkDefaultProofOfWorkNonceTrialsPerByte = int(shared.networkDefaultProofOfWorkNonceTrialsPerByte / 16) shared.networkDefaultProofOfWorkNonceTrialsPerByte = int(
shared.networkDefaultPayloadLengthExtraBytes = int(shared.networkDefaultPayloadLengthExtraBytes / 7000) shared.networkDefaultProofOfWorkNonceTrialsPerByte / 16)
shared.networkDefaultPayloadLengthExtraBytes = int(
shared.networkDefaultPayloadLengthExtraBytes / 7000)
if __name__ == "__main__": if __name__ == "__main__":
# is the application already running? If yes then exit. # is the application already running? If yes then exit.
@ -3952,7 +4673,8 @@ if __name__ == "__main__":
print 'This program requires sqlite version 3 or higher because 2 and lower cannot store NULL values. I see version:', sqlite3.sqlite_version_info print 'This program requires sqlite version 3 or higher because 2 and lower cannot store NULL values. I see version:', sqlite3.sqlite_version_info
os._exit(0) os._exit(0)
#First try to load the config file (the keys.dat file) from the program directory # First try to load the config file (the keys.dat file) from the program
# directory
shared.config = ConfigParser.SafeConfigParser() shared.config = ConfigParser.SafeConfigParser()
shared.config.read('keys.dat') shared.config.read('keys.dat')
try: try:
@ -3960,7 +4682,8 @@ if __name__ == "__main__":
print 'Loading config files from same directory as program' print 'Loading config files from same directory as program'
shared.appdata = '' shared.appdata = ''
except: except:
#Could not load the keys.dat file in the program directory. Perhaps it is in the appdata directory. # Could not load the keys.dat file in the program directory. Perhaps it
# is in the appdata directory.
shared.appdata = shared.lookupAppdataFolder() shared.appdata = shared.lookupAppdataFolder()
shared.config = ConfigParser.SafeConfigParser() shared.config = ConfigParser.SafeConfigParser()
shared.config.read(shared.appdata + 'keys.dat') shared.config.read(shared.appdata + 'keys.dat')
@ -3968,35 +4691,51 @@ if __name__ == "__main__":
shared.config.get('bitmessagesettings', 'settingsversion') shared.config.get('bitmessagesettings', 'settingsversion')
print 'Loading existing config files from', shared.appdata print 'Loading existing config files from', shared.appdata
except: except:
#This appears to be the first time running the program; there is no config file (or it cannot be accessed). Create config file. # This appears to be the first time running the program; there is
# no config file (or it cannot be accessed). Create config file.
shared.config.add_section('bitmessagesettings') shared.config.add_section('bitmessagesettings')
shared.config.set('bitmessagesettings', 'settingsversion', '6') shared.config.set('bitmessagesettings', 'settingsversion', '6')
shared.config.set('bitmessagesettings', 'port', '8444') shared.config.set('bitmessagesettings', 'port', '8444')
shared.config.set('bitmessagesettings','timeformat','%%a, %%d %%b %%Y %%I:%%M %%p') shared.config.set(
'bitmessagesettings', 'timeformat', '%%a, %%d %%b %%Y %%I:%%M %%p')
shared.config.set('bitmessagesettings', 'blackwhitelist', 'black') shared.config.set('bitmessagesettings', 'blackwhitelist', 'black')
shared.config.set('bitmessagesettings', 'startonlogon', 'false') shared.config.set('bitmessagesettings', 'startonlogon', 'false')
if 'linux' in sys.platform: if 'linux' in sys.platform:
shared.config.set('bitmessagesettings','minimizetotray','false')#This isn't implimented yet and when True on Ubuntu causes Bitmessage to disappear while running when minimized. shared.config.set(
'bitmessagesettings', 'minimizetotray', 'false')
# This isn't implimented yet and when True on
# Ubuntu causes Bitmessage to disappear while
# running when minimized.
else: else:
shared.config.set('bitmessagesettings','minimizetotray','true') shared.config.set(
shared.config.set('bitmessagesettings','showtraynotifications','true') 'bitmessagesettings', 'minimizetotray', 'true')
shared.config.set(
'bitmessagesettings', 'showtraynotifications', 'true')
shared.config.set('bitmessagesettings', 'startintray', 'false') shared.config.set('bitmessagesettings', 'startintray', 'false')
shared.config.set('bitmessagesettings', 'socksproxytype', 'none') shared.config.set('bitmessagesettings', 'socksproxytype', 'none')
shared.config.set('bitmessagesettings','sockshostname','localhost') shared.config.set(
'bitmessagesettings', 'sockshostname', 'localhost')
shared.config.set('bitmessagesettings', 'socksport', '9050') shared.config.set('bitmessagesettings', 'socksport', '9050')
shared.config.set('bitmessagesettings','socksauthentication','false') shared.config.set(
'bitmessagesettings', 'socksauthentication', 'false')
shared.config.set('bitmessagesettings', 'socksusername', '') shared.config.set('bitmessagesettings', 'socksusername', '')
shared.config.set('bitmessagesettings', 'sockspassword', '') shared.config.set('bitmessagesettings', 'sockspassword', '')
shared.config.set('bitmessagesettings', 'keysencrypted', 'false') shared.config.set('bitmessagesettings', 'keysencrypted', 'false')
shared.config.set('bitmessagesettings','messagesencrypted','false') shared.config.set(
shared.config.set('bitmessagesettings','defaultnoncetrialsperbyte',str(shared.networkDefaultProofOfWorkNonceTrialsPerByte)) 'bitmessagesettings', 'messagesencrypted', 'false')
shared.config.set('bitmessagesettings','defaultpayloadlengthextrabytes',str(shared.networkDefaultPayloadLengthExtraBytes)) shared.config.set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(
shared.networkDefaultProofOfWorkNonceTrialsPerByte))
shared.config.set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(
shared.networkDefaultPayloadLengthExtraBytes))
shared.config.set('bitmessagesettings', 'minimizeonclose', 'false') shared.config.set('bitmessagesettings', 'minimizeonclose', 'false')
shared.config.set('bitmessagesettings','maxacceptablenoncetrialsperbyte','0') shared.config.set(
shared.config.set('bitmessagesettings','maxacceptablepayloadlengthextrabytes','0') 'bitmessagesettings', 'maxacceptablenoncetrialsperbyte', '0')
shared.config.set(
'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', '0')
if storeConfigFilesInSameDirectoryAsProgramByDefault: if storeConfigFilesInSameDirectoryAsProgramByDefault:
#Just use the same directory as the program and forget about the appdata folder # Just use the same directory as the program and forget about
# the appdata folder
shared.appdata = '' shared.appdata = ''
print 'Creating new config files in same directory as program.' print 'Creating new config files in same directory as program.'
else: else:
@ -4006,9 +4745,11 @@ if __name__ == "__main__":
with open(shared.appdata + 'keys.dat', 'wb') as configfile: with open(shared.appdata + 'keys.dat', 'wb') as configfile:
shared.config.write(configfile) shared.config.write(configfile)
if shared.config.getint('bitmessagesettings', 'settingsversion') == 1: if shared.config.getint('bitmessagesettings', 'settingsversion') == 1:
shared.config.set('bitmessagesettings','settingsversion','4') #If the settings version is equal to 2 or 3 then the sqlThread will modify the pubkeys table and change the settings version to 4. shared.config.set('bitmessagesettings', 'settingsversion', '4')
# If the settings version is equal to 2 or 3 then the
# sqlThread will modify the pubkeys table and change
# the settings version to 4.
shared.config.set('bitmessagesettings', 'socksproxytype', 'none') shared.config.set('bitmessagesettings', 'socksproxytype', 'none')
shared.config.set('bitmessagesettings', 'sockshostname', 'localhost') shared.config.set('bitmessagesettings', 'sockshostname', 'localhost')
shared.config.set('bitmessagesettings', 'socksport', '9050') shared.config.set('bitmessagesettings', 'socksport', '9050')
@ -4021,7 +4762,8 @@ if __name__ == "__main__":
shared.config.write(configfile) shared.config.write(configfile)
try: try:
#We shouldn't have to use the shared.knownNodesLock because this had better be the only thread accessing knownNodes right now. # We shouldn't have to use the shared.knownNodesLock because this had
# better be the only thread accessing knownNodes right now.
pickleFile = open(shared.appdata + 'knownnodes.dat', 'rb') pickleFile = open(shared.appdata + 'knownnodes.dat', 'rb')
shared.knownNodes = pickle.load(pickleFile) shared.knownNodes = pickle.load(pickleFile)
pickleFile.close() pickleFile.close()
@ -4034,7 +4776,11 @@ if __name__ == "__main__":
print 'Bitmessage cannot read future versions of the keys file (keys.dat). Run the newer version of Bitmessage.' print 'Bitmessage cannot read future versions of the keys file (keys.dat). Run the newer version of Bitmessage.'
raise SystemExit raise SystemExit
#DNS bootstrap. This could be programmed to use the SOCKS proxy to do the DNS lookup some day but for now we will just rely on the entries in defaultKnownNodes.py. Hopefully either they are up to date or the user has run Bitmessage recently without SOCKS turned on and received good bootstrap nodes using that method. # DNS bootstrap. This could be programmed to use the SOCKS proxy to do the
# DNS lookup some day but for now we will just rely on the entries in
# defaultKnownNodes.py. Hopefully either they are up to date or the user
# has run Bitmessage recently without SOCKS turned on and received good
# bootstrap nodes using that method.
if shared.config.get('bitmessagesettings', 'socksproxytype') == 'none': if shared.config.get('bitmessagesettings', 'socksproxytype') == 'none':
try: try:
for item in socket.getaddrinfo('bootstrap8080.bitmessage.org', 80): for item in socket.getaddrinfo('bootstrap8080.bitmessage.org', 80):
@ -4075,7 +4821,8 @@ if __name__ == "__main__":
if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'): if shared.safeConfigGetBoolean('bitmessagesettings', 'apienabled'):
try: try:
apiNotifyPath = shared.config.get('bitmessagesettings','apinotifypath') apiNotifyPath = shared.config.get(
'bitmessagesettings', 'apinotifypath')
except: except:
apiNotifyPath = '' apiNotifyPath = ''
if apiNotifyPath != '': if apiNotifyPath != '':
@ -4090,7 +4837,9 @@ if __name__ == "__main__":
# self.singleAPISignalHandlerThread.start() # self.singleAPISignalHandlerThread.start()
# QtCore.QObject.connect(self.singleAPISignalHandlerThread, QtCore.SIGNAL("updateStatusBar(PyQt_PyObject)"), self.updateStatusBar) # QtCore.QObject.connect(self.singleAPISignalHandlerThread, QtCore.SIGNAL("updateStatusBar(PyQt_PyObject)"), self.updateStatusBar)
# QtCore.QObject.connect(self.singleAPISignalHandlerThread, QtCore.SIGNAL("passAddressGeneratorObjectThrough(PyQt_PyObject)"), self.connectObjectToAddressGeneratorSignals) # QtCore.QObject.connect(self.singleAPISignalHandlerThread, QtCore.SIGNAL("passAddressGeneratorObjectThrough(PyQt_PyObject)"), self.connectObjectToAddressGeneratorSignals)
#QtCore.QObject.connect(self.singleAPISignalHandlerThread, QtCore.SIGNAL("displayNewSentMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.displayNewSentMessage) # QtCore.QObject.connect(self.singleAPISignalHandlerThread,
# QtCore.SIGNAL("displayNewSentMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),
# self.displayNewSentMessage)
connectToStream(1) connectToStream(1)
@ -4102,7 +4851,7 @@ if __name__ == "__main__":
try: try:
from PyQt4.QtCore import * from PyQt4.QtCore import *
from PyQt4.QtGui import * from PyQt4.QtGui import *
except Exception, err: except Exception as err:
print 'PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API. You can download PyQt from http://www.riverbankcomputing.com/software/pyqt/download or by searching Google for \'PyQt Download\'. If you want to run in daemon mode, see https://bitmessage.org/wiki/Daemon' print 'PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API. You can download PyQt from http://www.riverbankcomputing.com/software/pyqt/download or by searching Google for \'PyQt Download\'. If you want to run in daemon mode, see https://bitmessage.org/wiki/Daemon'
print 'Error message:', err print 'Error message:', err
os._exit(0) os._exit(0)