From a9b15f83ba8b4ce9b446eb9b3de2a4570b245031 Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Fri, 6 Sep 2013 18:55:12 -0400 Subject: [PATCH 1/8] initial testing inv refactorization --- src/bitmessagemain.py | 11 +++++++++-- src/class_receiveDataThread.py | 18 +++++++----------- src/class_sendDataThread.py | 25 +++++++++++++++++-------- src/class_singleWorker.py | 15 ++++++++++----- src/shared.py | 1 + 5 files changed, 44 insertions(+), 26 deletions(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index a5a4b320..9cbe4471 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -46,6 +46,11 @@ if sys.platform == 'darwin': def connectToStream(streamNumber): selfInitiatedConnections[streamNumber] = {} + shared.inventorySets[streamNumber] = set() + queryData = sqlQuery('''SELECT hash FROM inventory WHERE streamnumber=?''', streamNumber) + for row in queryData: + shared.inventorySets[streamNumber].add(row[0]) + if sys.platform[0:3] == 'win': maximumNumberOfHalfOpenConnections = 9 else: @@ -705,10 +710,11 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): objectType = 'msg' shared.inventory[inventoryHash] = ( objectType, toStreamNumber, encryptedPayload, int(time.time())) + shared.inventorySets[toStreamNumber].add(inventoryHash) with shared.printLock: print 'Broadcasting inv for msg(API disseminatePreEncryptedMsg command):', inventoryHash.encode('hex') shared.broadcastToSendDataQueues(( - toStreamNumber, 'sendinv', inventoryHash)) + toStreamNumber, 'advertiseobject', inventoryHash)) elif method == 'disseminatePubkey': # The device issuing this command to PyBitmessage supplies a pubkey object to be # disseminated to the rest of the Bitmessage network. PyBitmessage accepts this @@ -741,10 +747,11 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): objectType = 'pubkey' shared.inventory[inventoryHash] = ( objectType, pubkeyStreamNumber, payload, int(time.time())) + shared.inventorySets[pubkeyStreamNumber].add(inventoryHash) with shared.printLock: print 'broadcasting inv within API command disseminatePubkey with hash:', inventoryHash.encode('hex') shared.broadcastToSendDataQueues(( - streamNumber, 'sendinv', inventoryHash)) + streamNumber, 'advertiseobject', inventoryHash)) elif method == 'getMessageDataByDestinationHash': # Method will eventually be used by a particular Android app to # select relevant messages. Do not yet add this to the api diff --git a/src/class_receiveDataThread.py b/src/class_receiveDataThread.py index 914d3f84..a8b38bc4 100644 --- a/src/class_receiveDataThread.py +++ b/src/class_receiveDataThread.py @@ -392,6 +392,7 @@ class receiveDataThread(threading.Thread): objectType = 'broadcast' shared.inventory[self.inventoryHash] = ( objectType, self.streamNumber, data, embeddedTime) + shared.inventorySets[self.streamNumber].add(self.inventoryHash) shared.inventoryLock.release() self.broadcastinv(self.inventoryHash) shared.numberOfBroadcastsProcessed += 1 @@ -755,6 +756,7 @@ class receiveDataThread(threading.Thread): objectType = 'msg' shared.inventory[self.inventoryHash] = ( objectType, self.streamNumber, data, embeddedTime) + shared.inventorySets[self.streamNumber].add(self.inventoryHash) shared.inventoryLock.release() self.broadcastinv(self.inventoryHash) shared.numberOfMessagesProcessed += 1 @@ -1153,6 +1155,7 @@ class receiveDataThread(threading.Thread): objectType = 'pubkey' shared.inventory[inventoryHash] = ( objectType, self.streamNumber, data, embeddedTime) + shared.inventorySets[self.streamNumber].add(inventoryHash) shared.inventoryLock.release() self.broadcastinv(inventoryHash) shared.numberOfPubkeysProcessed += 1 @@ -1348,6 +1351,7 @@ class receiveDataThread(threading.Thread): objectType = 'getpubkey' shared.inventory[inventoryHash] = ( objectType, self.streamNumber, data, embeddedTime) + shared.inventorySets[self.streamNumber].add(inventoryHash) shared.inventoryLock.release() # This getpubkey request is valid so far. Forward to peers. self.broadcastinv(inventoryHash) @@ -1442,18 +1446,10 @@ class receiveDataThread(threading.Thread): # 'set' of objects we are aware of and a set of objects in this inv # message so that we can diff one from the other cheaply. startTime = time.time() - currentInventoryList = set() - queryData = sqlQuery('''SELECT hash FROM inventory WHERE streamnumber=?''', - self.streamNumber) - for row in queryData: - currentInventoryList.add(row[0]) - with shared.inventoryLock: - for objectHash, value in shared.inventory.items(): - currentInventoryList.add(objectHash) advertisedSet = set() for i in range(numberOfItemsInInv): advertisedSet.add(data[lengthOfVarint + (32 * i):32 + lengthOfVarint + (32 * i)]) - objectsNewToMe = advertisedSet - currentInventoryList + objectsNewToMe = advertisedSet - shared.inventorySets[self.streamNumber] logger.info('inv message lists %s objects. Of those %s are new to me. It took %s seconds to figure that out.', numberOfItemsInInv, len(objectsNewToMe), time.time()-startTime) for item in objectsNewToMe: if totalNumberOfobjectsThatWeHaveYetToGetFromAllPeers > 200000 and len(self.objectsThatWeHaveYetToGetFromThisPeer) > 1000: # inv flooding attack mitigation @@ -1552,12 +1548,12 @@ class receiveDataThread(threading.Thread): print 'sock.sendall error:', err - # Send an inv message with just one hash to all of our peers + # Advertise this object to all of our peers def broadcastinv(self, hash): with shared.printLock: print 'broadcasting inv with hash:', hash.encode('hex') - shared.broadcastToSendDataQueues((self.streamNumber, 'sendinv', hash)) + shared.broadcastToSendDataQueues((self.streamNumber, 'advertiseobject', hash)) # We have received an addr message. def recaddr(self, data): diff --git a/src/class_sendDataThread.py b/src/class_sendDataThread.py index 867d1d70..0c8bb580 100644 --- a/src/class_sendDataThread.py +++ b/src/class_sendDataThread.py @@ -8,7 +8,8 @@ import random import sys import socket -#import bitmessagemain +from class_objectHashHolder import * +from addresses import * # Every connection to a peer has a sendDataThread (and also a # receiveDataThread). @@ -22,6 +23,9 @@ class sendDataThread(threading.Thread): print 'The length of sendDataQueues at sendDataThread init is:', len(shared.sendDataQueues) self.data = '' + self.objectHashHolderInstance = objectHashHolder(self.mailbox) + self.objectHashHolderInstance.start() + def setup( self, @@ -118,17 +122,20 @@ class sendDataThread(threading.Thread): shared.sendDataQueues.remove(self.mailbox) print 'sendDataThread thread (ID:', str(id(self)) + ') ending now. Was connected to', self.peer break + elif command == 'advertiseobject': + self.objectHashHolderInstance.holdHash(data) elif command == 'sendinv': - if data not in self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware: - payload = '\x01' + data + payload = '' + for hash in data: + if hash not in self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware: + payload += hash + if payload != '': + print 'within sendinv, payload contains', len(payload)/32, 'hashes.' + payload = encodeVarint(len(payload)/32) + payload headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. headerData += 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00' headerData += pack('>L', len(payload)) 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 - random.seed() - time.sleep(random.randrange(0, 10)) try: self.sock.sendall(headerData + payload) self.lastTimeISentData = int(time.time()) @@ -142,6 +149,8 @@ class sendDataThread(threading.Thread): shared.sendDataQueues.remove(self.mailbox) print 'sendDataThread thread (ID:', str(id(self)) + ') ending now. Was connected to', self.peer break + else: + print '(within sendinv) payload was empty. Not sending anything' #testing. elif command == 'pong': self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware.clear() # To save memory, let us clear this data structure from time to time. As its function is to help us keep from sending inv messages to peers which sent us the same inv message mere seconds earlier, it will be fine to clear this data structure from time to time. if self.lastTimeISentData < (int(time.time()) - 298): @@ -167,4 +176,4 @@ class sendDataThread(threading.Thread): with shared.printLock: print 'sendDataThread ID:', id(self), 'ignoring command', command, 'because the thread is not in stream', deststream - + self.objectHashHolderInstance.close() diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index d3c0c784..d8990ede 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -151,12 +151,13 @@ class singleWorker(threading.Thread): objectType = 'pubkey' shared.inventory[inventoryHash] = ( objectType, streamNumber, payload, embeddedTime) + shared.inventorySets[streamNumber].add(inventoryHash) with shared.printLock: print 'broadcasting inv with hash:', inventoryHash.encode('hex') shared.broadcastToSendDataQueues(( - streamNumber, 'sendinv', inventoryHash)) + streamNumber, 'advertiseobject', inventoryHash)) shared.UISignalQueue.put(('updateStatusBar', '')) shared.config.set( myAddress, 'lastpubkeysendtime', str(int(time.time()))) @@ -224,12 +225,13 @@ class singleWorker(threading.Thread): objectType = 'pubkey' shared.inventory[inventoryHash] = ( objectType, streamNumber, payload, embeddedTime) + shared.inventorySets[streamNumber].add(inventoryHash) with shared.printLock: print 'broadcasting inv with hash:', inventoryHash.encode('hex') shared.broadcastToSendDataQueues(( - streamNumber, 'sendinv', inventoryHash)) + streamNumber, 'advertiseobject', inventoryHash)) shared.UISignalQueue.put(('updateStatusBar', '')) # If this is a chan address then we won't send out the pubkey over the # network but rather will only store it in our pubkeys table so that @@ -327,10 +329,11 @@ class singleWorker(threading.Thread): objectType = 'broadcast' shared.inventory[inventoryHash] = ( objectType, streamNumber, payload, int(time.time())) + shared.inventorySets[streamNumber].add(inventoryHash) with shared.printLock: print 'sending inv (within sendBroadcast function) for object:', inventoryHash.encode('hex') shared.broadcastToSendDataQueues(( - streamNumber, 'sendinv', inventoryHash)) + streamNumber, 'advertiseobject', inventoryHash)) shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, tr.translateText("MainWindow", "Broadcast sent on %1").arg(unicode( strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))) @@ -650,6 +653,7 @@ class singleWorker(threading.Thread): objectType = 'msg' shared.inventory[inventoryHash] = ( objectType, toStreamNumber, encryptedPayload, int(time.time())) + shared.inventorySets[toStreamNumber].add(inventoryHash) if shared.safeConfigGetBoolean(toaddress, 'chan'): shared.UISignalQueue.put(('updateSentItemStatusByAckdata', (ackdata, tr.translateText("MainWindow", "Message sent. Sent on %1").arg(unicode( strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))) @@ -659,7 +663,7 @@ class singleWorker(threading.Thread): strftime(shared.config.get('bitmessagesettings', 'timeformat'), localtime(int(time.time()))), 'utf-8'))))) print 'Broadcasting inv for my msg(within sendmsg function):', inventoryHash.encode('hex') shared.broadcastToSendDataQueues(( - streamNumber, 'sendinv', inventoryHash)) + streamNumber, 'advertiseobject', inventoryHash)) # Update the status of the message in the 'sent' table to have a # 'msgsent' status or 'msgsentnoackexpected' status. @@ -706,9 +710,10 @@ class singleWorker(threading.Thread): objectType = 'getpubkey' shared.inventory[inventoryHash] = ( objectType, streamNumber, payload, int(time.time())) + shared.inventorySets[streamNumber].add(inventoryHash) print 'sending inv (for the getpubkey message)' shared.broadcastToSendDataQueues(( - streamNumber, 'sendinv', inventoryHash)) + streamNumber, 'advertiseobject', inventoryHash)) sqlExecute( '''UPDATE sent SET status='awaitingpubkey' WHERE toaddress=? AND status='doingpubkeypow' ''', diff --git a/src/shared.py b/src/shared.py index e7718959..9339987a 100644 --- a/src/shared.py +++ b/src/shared.py @@ -68,6 +68,7 @@ numberOfBroadcastsProcessed = 0 numberOfPubkeysProcessed = 0 numberOfInventoryLookupsPerformed = 0 daemon = False +inventorySets = {} # key = streamNumer, value = a set which holds the inventory object hashes that we are aware of. This is used whenever we receive an inv message from a peer to check to see what items are new to us. We don't delete things out of it; instead, the singleCleaner thread clears and refills it every couple hours. #If changed, these values will cause particularly unexpected behavior: You won't be able to either send or receive messages because the proof of work you do (or demand) won't match that done or demanded by others. Don't change them! networkDefaultProofOfWorkNonceTrialsPerByte = 320 #The amount of work that should be performed (and demanded) per byte of the payload. Double this number to double the work. -- 2.45.1 From 2725281a6db147a627c74a98a36bb58e5803f1ea Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Fri, 6 Sep 2013 18:58:56 -0400 Subject: [PATCH 2/8] initial testing inv refactorization --- src/class_objectHashHolder.py | 39 +++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/class_objectHashHolder.py diff --git a/src/class_objectHashHolder.py b/src/class_objectHashHolder.py new file mode 100644 index 00000000..cc636a8d --- /dev/null +++ b/src/class_objectHashHolder.py @@ -0,0 +1,39 @@ +# objectHashHolder is a timer-driven thread. One objectHashHolder thread is used +# by each sendDataThread. It uses it whenever a sendDataThread needs to +# advertise an object to peers. Instead of sending it out immediately, it must +# wait a random number of seconds for each connection so that different peers +# get different objects at different times. Thus an attacker who is +# connecting to many network nodes who receives a message first from Alice +# cannot be sure if Alice is the node who originated the message. + +import random +import time +import threading + +class objectHashHolder(threading.Thread): + def __init__(self, sendDataThreadMailbox): + threading.Thread.__init__(self) + self.shutdown = False + self.sendDataThreadMailbox = sendDataThreadMailbox # This queue is used to submit data back to our associated sendDataThread. + self.collectionOfLists = {} + for i in range(10): + self.collectionOfLists[i] = [] + + def run(self): + print 'objectHashHolder running.' + iterator = 0 + while not self.shutdown: + if len(self.collectionOfLists[iterator]) > 0: + print 'objectHashHolder is submitting', len(self.collectionOfLists[iterator]), 'items to the queue.' + self.sendDataThreadMailbox.put((0, 'sendinv', self.collectionOfLists[iterator])) + self.collectionOfLists[iterator] = [] + iterator += 1 + iterator %= 10 + time.sleep(1) + print 'objectHashHolder shutting down.' + + def holdHash(self,hash): + self.collectionOfLists[random.randrange(0, 10)].append(hash) + + def close(self): + self.shutdown = True \ No newline at end of file -- 2.45.1 From 831edf0d248ea050b59565550f9df69fc65c8fe0 Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Fri, 6 Sep 2013 21:47:54 -0400 Subject: [PATCH 3/8] completed inv refactorization --- src/class_objectHashHolder.py | 3 --- src/class_sendDataThread.py | 4 ---- src/class_singleCleaner.py | 9 +++++++++ src/shared.py | 2 +- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/class_objectHashHolder.py b/src/class_objectHashHolder.py index cc636a8d..9c392765 100644 --- a/src/class_objectHashHolder.py +++ b/src/class_objectHashHolder.py @@ -20,17 +20,14 @@ class objectHashHolder(threading.Thread): self.collectionOfLists[i] = [] def run(self): - print 'objectHashHolder running.' iterator = 0 while not self.shutdown: if len(self.collectionOfLists[iterator]) > 0: - print 'objectHashHolder is submitting', len(self.collectionOfLists[iterator]), 'items to the queue.' self.sendDataThreadMailbox.put((0, 'sendinv', self.collectionOfLists[iterator])) self.collectionOfLists[iterator] = [] iterator += 1 iterator %= 10 time.sleep(1) - print 'objectHashHolder shutting down.' def holdHash(self,hash): self.collectionOfLists[random.randrange(0, 10)].append(hash) diff --git a/src/class_sendDataThread.py b/src/class_sendDataThread.py index 0c8bb580..b939b06b 100644 --- a/src/class_sendDataThread.py +++ b/src/class_sendDataThread.py @@ -108,7 +108,6 @@ class sendDataThread(threading.Thread): # 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() time.sleep(random.randrange(0, 10)) self.sock.sendall(data) self.lastTimeISentData = int(time.time()) @@ -130,7 +129,6 @@ class sendDataThread(threading.Thread): if hash not in self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware: payload += hash if payload != '': - print 'within sendinv, payload contains', len(payload)/32, 'hashes.' payload = encodeVarint(len(payload)/32) + payload headerData = '\xe9\xbe\xb4\xd9' # magic bits, slighly different from Bitcoin's magic bits. headerData += 'inv\x00\x00\x00\x00\x00\x00\x00\x00\x00' @@ -149,8 +147,6 @@ class sendDataThread(threading.Thread): shared.sendDataQueues.remove(self.mailbox) print 'sendDataThread thread (ID:', str(id(self)) + ') ending now. Was connected to', self.peer break - else: - print '(within sendinv) payload was empty. Not sending anything' #testing. elif command == 'pong': self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware.clear() # To save memory, let us clear this data structure from time to time. As its function is to help us keep from sending inv messages to peers which sent us the same inv message mere seconds earlier, it will be fine to clear this data structure from time to time. if self.lastTimeISentData < (int(time.time()) - 298): diff --git a/src/class_singleCleaner.py b/src/class_singleCleaner.py index 3cc80868..07d56424 100644 --- a/src/class_singleCleaner.py +++ b/src/class_singleCleaner.py @@ -7,6 +7,7 @@ from helper_sql import * '''The singleCleaner class is a timer-driven thread that cleans data structures to free memory, resends messages when a remote node doesn't respond, and sends pong messages to keep connections alive if the network isn't busy. It cleans these data structures in memory: inventory (moves data to the on-disk sql database) + inventorySets (clears then reloads data out of sql database) It cleans these tables on the disk: inventory (clears data more than 2 days and 12 hours old) @@ -109,4 +110,12 @@ class singleCleaner(threading.Thread): shared.workerQueue.put(('sendmessage', '')) shared.UISignalQueue.put(( 'updateStatusBar', 'Doing work necessary to again attempt to deliver a message...')) + + # Let's also clear and reload shared.inventorySets to keep it from + # taking up an unnecessary amount of memory. + for streamNumber in shared.inventorySets: + shared.inventorySets[streamNumber] = set() + queryData = sqlQuery('''SELECT hash FROM inventory WHERE streamnumber=?''', streamNumber) + for row in queryData: + shared.inventorySets[streamNumber].add(row[0]) time.sleep(300) diff --git a/src/shared.py b/src/shared.py index 9339987a..0c0173a3 100644 --- a/src/shared.py +++ b/src/shared.py @@ -304,7 +304,7 @@ def doCleanShutdown(): def broadcastToSendDataQueues(data): # logger.debug('running broadcastToSendDataQueues') for q in sendDataQueues: - q.put((data)) + q.put(data) def flushInventory(): #Note that the singleCleanerThread clears out the inventory dictionary from time to time, although it only clears things that have been in the dictionary for a long time. This clears the inventory dictionary Now. -- 2.45.1 From 804276395610d18f1ed43f0f6934c2811f28ea35 Mon Sep 17 00:00:00 2001 From: bitnukl Date: Sat, 7 Sep 2013 10:46:23 +0000 Subject: [PATCH 4/8] translation updated --- src/translations/bitmessage_de.qm | Bin 61772 -> 62134 bytes src/translations/bitmessage_de.ts | 6 +++--- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/translations/bitmessage_de.qm b/src/translations/bitmessage_de.qm index a81aaaba2c6772bd8f55fa65adf6efa4cf79b438..0e8e68a3353d805d725d86ff0bb32a74ed239e8f 100644 GIT binary patch delta 2593 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 diff --git a/src/translations/bitmessage_de.ts b/src/translations/bitmessage_de.ts index 5f57e33a..3814fa86 100644 --- a/src/translations/bitmessage_de.ts +++ b/src/translations/bitmessage_de.ts @@ -17,7 +17,7 @@ Add sender to your Address Book - Absender zum Adressbuch hinzufügen. + Absender zum Adressbuch hinzufügen @@ -920,7 +920,7 @@ p, li { white-space: pre-wrap; } Ctrl+Q - Strg+Q + Strg+Q @@ -1487,7 +1487,7 @@ Die Zufallszahlen-Option ist standard, jedoch haben deterministische Adressen ei Override automatic language localization (use countycode or language code, e.g. 'en_US' or 'en'): - + Automatische Sprachauswahl überschreiben (verwenden Sie den Landescode oder Sprachcode, z.B. "de_DE" oder "de"): -- 2.45.1 From 5d64919e1f43fd9bdea1351bccac3bcb23d99c2f Mon Sep 17 00:00:00 2001 From: bitnukl Date: Sat, 7 Sep 2013 10:54:26 +0000 Subject: [PATCH 5/8] resized main window to fit translations without scrolling Now all translations fit in wothout scrolling (tested de, eo, fr and ru) --- src/bitmessageqt/bitmessageui.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bitmessageqt/bitmessageui.py b/src/bitmessageqt/bitmessageui.py index f6a76ce1..eb967852 100644 --- a/src/bitmessageqt/bitmessageui.py +++ b/src/bitmessageqt/bitmessageui.py @@ -26,7 +26,7 @@ except AttributeError: class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) - MainWindow.resize(795, 580) + MainWindow.resize(885, 580) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/can-icon-24px.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(icon) -- 2.45.1 From 34203d73ddeb1348ef558933e9b2be3c3f2ee9c9 Mon Sep 17 00:00:00 2001 From: "Grant T. Olson" Date: Sat, 7 Sep 2013 13:31:17 -0400 Subject: [PATCH 6/8] Only UPDATE readStatus if it changed --- src/bitmessagemain.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index a5a4b320..9f976c67 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -414,7 +414,10 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): readStatus = params[1] if not isinstance(readStatus, bool): raise APIError(23, 'Bool expected in readStatus, saw %s instead.' % type(readStatus)) - sqlExecute('''UPDATE inbox set read = ? WHERE msgid=?''', readStatus, msgid) + queryreturn = sqlQuery('''SELECT read FROM inbox WHERE msgid=?''', msgid) + # UPDATE is slow, only update if status is different + if queryreturn != [] and (queryreturn[0][0] == 1) != readStatus: + sqlExecute('''UPDATE inbox set read = ? WHERE msgid=?''', readStatus, msgid) queryreturn = sqlQuery('''SELECT msgid, toaddress, fromaddress, subject, received, message, encodingtype, read FROM inbox WHERE msgid=?''', msgid) data = '{"inboxMessage":[' for row in queryreturn: -- 2.45.1 From f0bf3aad482b53b752212cabc20514529d1f70ff Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Sat, 7 Sep 2013 18:23:20 -0400 Subject: [PATCH 7/8] use locks when accessing dictionary inventory --- src/class_objectHashHolder.py | 2 +- src/class_receiveDataThread.py | 14 +++++++++----- src/class_singleCleaner.py | 32 +++++++++++++++++++------------- 3 files changed, 29 insertions(+), 19 deletions(-) diff --git a/src/class_objectHashHolder.py b/src/class_objectHashHolder.py index 9c392765..90df7fd9 100644 --- a/src/class_objectHashHolder.py +++ b/src/class_objectHashHolder.py @@ -1,5 +1,5 @@ # objectHashHolder is a timer-driven thread. One objectHashHolder thread is used -# by each sendDataThread. It uses it whenever a sendDataThread needs to +# by each sendDataThread. The sendDataThread uses it whenever it needs to # advertise an object to peers. Instead of sending it out immediately, it must # wait a random number of seconds for each connection so that different peers # get different objects at different times. Thus an attacker who is diff --git a/src/class_receiveDataThread.py b/src/class_receiveDataThread.py index a8b38bc4..e751cef0 100644 --- a/src/class_receiveDataThread.py +++ b/src/class_receiveDataThread.py @@ -298,11 +298,12 @@ class receiveDataThread(threading.Thread): bigInvList[hash] = 0 # 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(): - if hash not in self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware: - objectType, streamNumber, payload, receivedTime = storedValue - if streamNumber == self.streamNumber and receivedTime > int(time.time()) - shared.maximumAgeOfObjectsThatIAdvertiseToOthers: - bigInvList[hash] = 0 + with shared.inventoryLock: + for hash, storedValue in shared.inventory.items(): + if hash not in self.someObjectsOfWhichThisRemoteNodeIsAlreadyAware: + objectType, streamNumber, payload, receivedTime = storedValue + if streamNumber == self.streamNumber and receivedTime > int(time.time()) - shared.maximumAgeOfObjectsThatIAdvertiseToOthers: + bigInvList[hash] = 0 numberOfObjectsInInvMessage = 0 payload = '' # Now let us start appending all of these hashes together. They will be @@ -1496,11 +1497,14 @@ class receiveDataThread(threading.Thread): print 'received getdata request for item:', hash.encode('hex') shared.numberOfInventoryLookupsPerformed += 1 + shared.inventoryLock.acquire() if hash in shared.inventory: objectType, streamNumber, payload, receivedTime = shared.inventory[ hash] + shared.inventoryLock.release() self.sendData(objectType, payload) else: + shared.inventoryLock.release() queryreturn = sqlQuery( '''select objecttype, payload from inventory where hash=?''', hash) diff --git a/src/class_singleCleaner.py b/src/class_singleCleaner.py index 07d56424..653a2461 100644 --- a/src/class_singleCleaner.py +++ b/src/class_singleCleaner.py @@ -32,19 +32,20 @@ class singleCleaner(threading.Thread): shared.UISignalQueue.put(( 'updateStatusBar', 'Doing housekeeping (Flushing inventory in memory to disk...)')) - with SqlBulkExecute() as sql: - for hash, storedValue in shared.inventory.items(): - objectType, streamNumber, payload, receivedTime = storedValue - if int(time.time()) - 3600 > receivedTime: - sql.execute( - '''INSERT INTO inventory VALUES (?,?,?,?,?,?)''', - hash, - objectType, - streamNumber, - payload, - receivedTime, - '') - del shared.inventory[hash] + with shared.inventoryLock: # If you use both the inventoryLock and the sqlLock, always use the inventoryLock OUTSIDE of the sqlLock. + with SqlBulkExecute() as sql: + for hash, storedValue in shared.inventory.items(): + objectType, streamNumber, payload, receivedTime = storedValue + if int(time.time()) - 3600 > receivedTime: + sql.execute( + '''INSERT INTO inventory VALUES (?,?,?,?,?,?)''', + hash, + objectType, + streamNumber, + payload, + receivedTime, + '') + del shared.inventory[hash] shared.UISignalQueue.put(('updateStatusBar', '')) 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. @@ -118,4 +119,9 @@ class singleCleaner(threading.Thread): queryData = sqlQuery('''SELECT hash FROM inventory WHERE streamnumber=?''', streamNumber) for row in queryData: shared.inventorySets[streamNumber].add(row[0]) + with shared.inventoryLock: + for hash, storedValue in shared.inventory.items(): + objectType, streamNumber, payload, receivedTime = storedValue + if streamNumber in shared.inventorySets: + shared.inventorySets[streamNumber].add(hash) time.sleep(300) -- 2.45.1 From 90e60d814552c3b26e97a3df8e309dc339210a9a Mon Sep 17 00:00:00 2001 From: Jonathan Warren Date: Mon, 9 Sep 2013 19:26:32 -0400 Subject: [PATCH 8/8] delay addr messages random number of seconds --- src/class_objectHashHolder.py | 23 ++- src/class_receiveDataThread.py | 320 +++++++++++---------------------- src/class_sendDataThread.py | 29 ++- src/class_singleCleaner.py | 20 +++ src/shared.py | 1 + 5 files changed, 160 insertions(+), 233 deletions(-) diff --git a/src/class_objectHashHolder.py b/src/class_objectHashHolder.py index 90df7fd9..c91b1c23 100644 --- a/src/class_objectHashHolder.py +++ b/src/class_objectHashHolder.py @@ -1,6 +1,7 @@ # objectHashHolder is a timer-driven thread. One objectHashHolder thread is used # by each sendDataThread. The sendDataThread uses it whenever it needs to -# advertise an object to peers. Instead of sending it out immediately, it must +# advertise an object to peers in an inv message, or advertise a peer to other +# peers in an addr message. Instead of sending them out immediately, it must # wait a random number of seconds for each connection so that different peers # get different objects at different times. Thus an attacker who is # connecting to many network nodes who receives a message first from Alice @@ -15,22 +16,30 @@ class objectHashHolder(threading.Thread): threading.Thread.__init__(self) self.shutdown = False self.sendDataThreadMailbox = sendDataThreadMailbox # This queue is used to submit data back to our associated sendDataThread. - self.collectionOfLists = {} + self.collectionOfHashLists = {} + self.collectionOfPeerLists = {} for i in range(10): - self.collectionOfLists[i] = [] + self.collectionOfHashLists[i] = [] + self.collectionOfPeerLists[i] = [] def run(self): iterator = 0 while not self.shutdown: - if len(self.collectionOfLists[iterator]) > 0: - self.sendDataThreadMailbox.put((0, 'sendinv', self.collectionOfLists[iterator])) - self.collectionOfLists[iterator] = [] + if len(self.collectionOfHashLists[iterator]) > 0: + self.sendDataThreadMailbox.put((0, 'sendinv', self.collectionOfHashLists[iterator])) + self.collectionOfHashLists[iterator] = [] + if len(self.collectionOfPeerLists[iterator]) > 0: + self.sendDataThreadMailbox.put((0, 'sendaddr', self.collectionOfPeerLists[iterator])) + self.collectionOfPeerLists[iterator] = [] iterator += 1 iterator %= 10 time.sleep(1) def holdHash(self,hash): - self.collectionOfLists[random.randrange(0, 10)].append(hash) + self.collectionOfHashLists[random.randrange(0, 10)].append(hash) + + def holdPeer(self,peerDetails): + self.collectionOfPeerLists[random.randrange(0, 10)].append(peerDetails) def close(self): self.shutdown = True \ No newline at end of file diff --git a/src/class_receiveDataThread.py b/src/class_receiveDataThread.py index e751cef0..643185fa 100644 --- a/src/class_receiveDataThread.py +++ b/src/class_receiveDataThread.py @@ -5,7 +5,6 @@ import threading import shared import hashlib import socket -import pickle import random from struct import unpack, pack import sys @@ -91,7 +90,6 @@ class receiveDataThread(threading.Thread): del self.selfInitiatedConnections[self.streamNumber][self] with shared.printLock: print 'removed self (a receiveDataThread) from selfInitiatedConnections' - except: pass shared.broadcastToSendDataQueues((0, 'shutdown', self.peer)) @@ -175,7 +173,6 @@ class receiveDataThread(threading.Thread): if self.data == '': while len(self.objectsThatWeHaveYetToGetFromThisPeer) > 0: shared.numberOfInventoryLookupsPerformed += 1 - random.seed() objectHash, = random.sample( self.objectsThatWeHaveYetToGetFromThisPeer, 1) if objectHash in shared.inventory: @@ -264,16 +261,18 @@ class receiveDataThread(threading.Thread): 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')) - remoteNodeSeenTime = shared.knownNodes[ - self.streamNumber][self.peer] with shared.printLock: print 'Connection fully established with', self.peer print 'The size of the connectedHostsList is now', len(shared.connectedHostsList) print 'The length of sendDataQueues is now:', len(shared.sendDataQueues) print 'broadcasting addr from within connectionFullyEstablished function.' - self.broadcastaddr([(int(time.time()), self.streamNumber, 1, self.peer.host, - self.peer.port)]) # This lets all of our peers know about this new node. + #self.broadcastaddr([(int(time.time()), self.streamNumber, 1, self.peer.host, + # self.remoteNodeIncomingPort)]) # This lets all of our peers know about this new node. + dataToSend = (int(time.time()), self.streamNumber, 1, self.peer.host, self.remoteNodeIncomingPort) + shared.broadcastToSendDataQueues(( + self.streamNumber, 'advertisepeer', dataToSend)) + self.sendaddr() # This is one large addr message to this one peer. if not self.initiatedConnection and len(shared.connectedHostsList) > 200: with shared.printLock: @@ -1561,7 +1560,7 @@ class receiveDataThread(threading.Thread): # We have received an addr message. def recaddr(self, data): - listOfAddressDetailsToBroadcastToPeers = [] + #listOfAddressDetailsToBroadcastToPeers = [] numberOfAddressesIncluded = 0 numberOfAddressesIncluded, lengthOfNumberOfAddresses = decodeVarint( data[:10]) @@ -1570,227 +1569,113 @@ class receiveDataThread(threading.Thread): with shared.printLock: print 'addr message contains', numberOfAddressesIncluded, 'IP addresses.' + if numberOfAddressesIncluded > 1000 or numberOfAddressesIncluded == 0: + return + if len(data) != lengthOfNumberOfAddresses + (38 * numberOfAddressesIncluded): + print 'addr message does not contain the correct amount of data. Ignoring.' + return - if self.remoteProtocolVersion == 1: - if numberOfAddressesIncluded > 1000 or numberOfAddressesIncluded == 0: - return - if len(data) != lengthOfNumberOfAddresses + (34 * numberOfAddressesIncluded): - print 'addr message does not contain the correct amount of data. Ignoring.' - return - - needToWriteKnownNodesToDisk = False - for i in range(0, numberOfAddressesIncluded): - try: - if data[16 + lengthOfNumberOfAddresses + (34 * i):28 + lengthOfNumberOfAddresses + (34 * i)] != '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF': - with shared.printLock: - print 'Skipping IPv6 address.', repr(data[16 + lengthOfNumberOfAddresses + (34 * i):28 + lengthOfNumberOfAddresses + (34 * i)]) - - continue - except Exception as err: + for i in range(0, numberOfAddressesIncluded): + try: + if data[20 + lengthOfNumberOfAddresses + (38 * i):32 + lengthOfNumberOfAddresses + (38 * i)] != '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF': with shared.printLock: - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (to test for an IPv6 address). Message: %s\n' % str(err)) + print 'Skipping IPv6 address.', repr(data[20 + lengthOfNumberOfAddresses + (38 * i):32 + lengthOfNumberOfAddresses + (38 * i)]) - break # giving up on unpacking any more. We should still be connected however. - - try: - recaddrStream, = unpack('>I', data[4 + lengthOfNumberOfAddresses + ( - 34 * i):8 + lengthOfNumberOfAddresses + (34 * i)]) - except Exception as err: - with shared.printLock: - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (recaddrStream). Message: %s\n' % str(err)) - - break # giving up on unpacking any more. We should still be connected however. - if recaddrStream == 0: continue - 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 - try: - recaddrServices, = unpack('>Q', data[8 + lengthOfNumberOfAddresses + ( - 34 * i):16 + lengthOfNumberOfAddresses + (34 * i)]) - except Exception as err: - with shared.printLock: - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (recaddrServices). Message: %s\n' % str(err)) + except Exception as err: + with shared.printLock: + sys.stderr.write( + 'ERROR TRYING TO UNPACK recaddr (to test for an IPv6 address). Message: %s\n' % str(err)) - break # giving up on unpacking any more. We should still be connected however. + break # giving up on unpacking any more. We should still be connected however. - try: - recaddrPort, = unpack('>H', data[32 + lengthOfNumberOfAddresses + ( - 34 * i):34 + lengthOfNumberOfAddresses + (34 * i)]) - except Exception as err: - with shared.printLock: - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (recaddrPort). Message: %s\n' % str(err)) + try: + recaddrStream, = unpack('>I', data[8 + lengthOfNumberOfAddresses + ( + 38 * i):12 + lengthOfNumberOfAddresses + (38 * i)]) + except Exception as err: + with shared.printLock: + sys.stderr.write( + 'ERROR TRYING TO UNPACK recaddr (recaddrStream). Message: %s\n' % str(err)) - break # giving up on unpacking any more. We should still be connected however. - # print 'Within recaddr(): IP', recaddrIP, ', Port', - # recaddrPort, ', i', i - hostFromAddrMessage = socket.inet_ntoa(data[ - 28 + lengthOfNumberOfAddresses + (34 * i):32 + lengthOfNumberOfAddresses + (34 * i)]) - # print 'hostFromAddrMessage', hostFromAddrMessage - if data[28 + lengthOfNumberOfAddresses + (34 * i)] == '\x7F': - print 'Ignoring IP address in loopback range:', hostFromAddrMessage - continue - if helper_generic.isHostInPrivateIPRange(hostFromAddrMessage): - print 'Ignoring IP address in private range:', hostFromAddrMessage - continue - 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. - shared.knownNodesLock.acquire() - shared.knownNodes[recaddrStream] = {} - shared.knownNodesLock.release() - peerFromAddrMessage = shared.Peer(hostFromAddrMessage, recaddrPort) - if peerFromAddrMessage 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. - shared.knownNodesLock.acquire() - shared.knownNodes[recaddrStream][peerFromAddrMessage] = timeSomeoneElseReceivedMessageFromThisNode - shared.knownNodesLock.release() - needToWriteKnownNodesToDisk = True - hostDetails = ( - timeSomeoneElseReceivedMessageFromThisNode, - recaddrStream, recaddrServices, hostFromAddrMessage, recaddrPort) - listOfAddressDetailsToBroadcastToPeers.append( - hostDetails) - else: - timeLastReceivedMessageFromThisNode = shared.knownNodes[recaddrStream][ - peerFromAddrMessage] # 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())): - shared.knownNodesLock.acquire() - shared.knownNodes[recaddrStream][peerFromAddrMessage] = timeSomeoneElseReceivedMessageFromThisNode - shared.knownNodesLock.release() - if needToWriteKnownNodesToDisk: # Runs if any nodes were new to us. Also, share those nodes with our peers. + break # giving up on unpacking any more. We should still be connected however. + if recaddrStream == 0: + continue + 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 + try: + recaddrServices, = unpack('>Q', data[12 + lengthOfNumberOfAddresses + ( + 38 * i):20 + lengthOfNumberOfAddresses + (38 * i)]) + except Exception as err: + with shared.printLock: + sys.stderr.write( + 'ERROR TRYING TO UNPACK recaddr (recaddrServices). Message: %s\n' % str(err)) + + break # giving up on unpacking any more. We should still be connected however. + + try: + recaddrPort, = unpack('>H', data[36 + lengthOfNumberOfAddresses + ( + 38 * i):38 + lengthOfNumberOfAddresses + (38 * i)]) + except Exception as err: + with shared.printLock: + sys.stderr.write( + 'ERROR TRYING TO UNPACK recaddr (recaddrPort). Message: %s\n' % str(err)) + + break # giving up on unpacking any more. We should still be connected however. + # print 'Within recaddr(): IP', recaddrIP, ', Port', + # recaddrPort, ', i', i + hostFromAddrMessage = socket.inet_ntoa(data[ + 32 + lengthOfNumberOfAddresses + (38 * i):36 + lengthOfNumberOfAddresses + (38 * i)]) + # print 'hostFromAddrMessage', hostFromAddrMessage + if data[32 + lengthOfNumberOfAddresses + (38 * i)] == '\x7F': + print 'Ignoring IP address in loopback range:', hostFromAddrMessage + continue + if data[32 + lengthOfNumberOfAddresses + (38 * i)] == '\x0A': + print 'Ignoring IP address in private range:', hostFromAddrMessage + continue + if data[32 + lengthOfNumberOfAddresses + (38 * i):34 + lengthOfNumberOfAddresses + (38 * i)] == '\xC0A8': + print 'Ignoring IP address in private range:', hostFromAddrMessage + continue + 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. shared.knownNodesLock.acquire() - output = open(shared.appdata + 'knownnodes.dat', 'wb') - pickle.dump(shared.knownNodes, output) - output.close() + shared.knownNodes[recaddrStream] = {} shared.knownNodesLock.release() - self.broadcastaddr( - listOfAddressDetailsToBroadcastToPeers) # no longer broadcast - with shared.printLock: - print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.' - - elif self.remoteProtocolVersion >= 2: # The difference is that in protocol version 2, network addresses use 64 bit times rather than 32 bit times. - if numberOfAddressesIncluded > 1000 or numberOfAddressesIncluded == 0: - return - if len(data) != lengthOfNumberOfAddresses + (38 * numberOfAddressesIncluded): - print 'addr message does not contain the correct amount of data. Ignoring.' - return - - needToWriteKnownNodesToDisk = False - for i in range(0, numberOfAddressesIncluded): - try: - if data[20 + lengthOfNumberOfAddresses + (38 * i):32 + lengthOfNumberOfAddresses + (38 * i)] != '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF': - with shared.printLock: - print 'Skipping IPv6 address.', repr(data[20 + lengthOfNumberOfAddresses + (38 * i):32 + lengthOfNumberOfAddresses + (38 * i)]) - - continue - except Exception as err: - with shared.printLock: - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (to test for an IPv6 address). Message: %s\n' % str(err)) - - break # giving up on unpacking any more. We should still be connected however. - - try: - recaddrStream, = unpack('>I', data[8 + lengthOfNumberOfAddresses + ( - 38 * i):12 + lengthOfNumberOfAddresses + (38 * i)]) - except Exception as err: - with shared.printLock: - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (recaddrStream). Message: %s\n' % str(err)) - - break # giving up on unpacking any more. We should still be connected however. - if recaddrStream == 0: - continue - 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 - try: - recaddrServices, = unpack('>Q', data[12 + lengthOfNumberOfAddresses + ( - 38 * i):20 + lengthOfNumberOfAddresses + (38 * i)]) - except Exception as err: - with shared.printLock: - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (recaddrServices). Message: %s\n' % str(err)) - - break # giving up on unpacking any more. We should still be connected however. - - try: - recaddrPort, = unpack('>H', data[36 + lengthOfNumberOfAddresses + ( - 38 * i):38 + lengthOfNumberOfAddresses + (38 * i)]) - except Exception as err: - with shared.printLock: - sys.stderr.write( - 'ERROR TRYING TO UNPACK recaddr (recaddrPort). Message: %s\n' % str(err)) - - break # giving up on unpacking any more. We should still be connected however. - # print 'Within recaddr(): IP', recaddrIP, ', Port', - # recaddrPort, ', i', i - hostFromAddrMessage = socket.inet_ntoa(data[ - 32 + lengthOfNumberOfAddresses + (38 * i):36 + lengthOfNumberOfAddresses + (38 * i)]) - # print 'hostFromAddrMessage', hostFromAddrMessage - if data[32 + lengthOfNumberOfAddresses + (38 * i)] == '\x7F': - print 'Ignoring IP address in loopback range:', hostFromAddrMessage - continue - if data[32 + lengthOfNumberOfAddresses + (38 * i)] == '\x0A': - print 'Ignoring IP address in private range:', hostFromAddrMessage - continue - if data[32 + lengthOfNumberOfAddresses + (38 * i):34 + lengthOfNumberOfAddresses + (38 * i)] == '\xC0A8': - print 'Ignoring IP address in private range:', hostFromAddrMessage - continue - 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. + peerFromAddrMessage = shared.Peer(hostFromAddrMessage, recaddrPort) + if peerFromAddrMessage 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. shared.knownNodesLock.acquire() - shared.knownNodes[recaddrStream] = {} + shared.knownNodes[recaddrStream][peerFromAddrMessage] = ( + timeSomeoneElseReceivedMessageFromThisNode) shared.knownNodesLock.release() - peerFromAddrMessage = shared.Peer(hostFromAddrMessage, recaddrPort) - if peerFromAddrMessage 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. - shared.knownNodesLock.acquire() - shared.knownNodes[recaddrStream][peerFromAddrMessage] = ( - timeSomeoneElseReceivedMessageFromThisNode) - shared.knownNodesLock.release() - with shared.printLock: - print 'added new node', peerFromAddrMessage, 'to knownNodes in stream', recaddrStream + with shared.printLock: + print 'added new node', peerFromAddrMessage, 'to knownNodes in stream', recaddrStream - needToWriteKnownNodesToDisk = True - hostDetails = ( - timeSomeoneElseReceivedMessageFromThisNode, - recaddrStream, recaddrServices, hostFromAddrMessage, recaddrPort) - listOfAddressDetailsToBroadcastToPeers.append( - hostDetails) - else: - timeLastReceivedMessageFromThisNode = shared.knownNodes[recaddrStream][ - peerFromAddrMessage] # 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())): - shared.knownNodesLock.acquire() - shared.knownNodes[recaddrStream][peerFromAddrMessage] = timeSomeoneElseReceivedMessageFromThisNode - shared.knownNodesLock.release() - if needToWriteKnownNodesToDisk: # Runs if any nodes were new to us. Also, share those nodes with our peers. - shared.knownNodesLock.acquire() - output = open(shared.appdata + 'knownnodes.dat', 'wb') - try: - pickle.dump(shared.knownNodes, output) - output.close() - except Exception as err: - if "Errno 28" in str(err): - logger.fatal('(while receiveDataThread needToWriteKnownNodesToDisk) Alert: Your disk or data storage volume is full. ') - shared.UISignalQueue.put(('alert', (tr.translateText("MainWindow", "Disk full"), tr.translateText("MainWindow", 'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'), True))) - if shared.daemon: - os._exit(0) - shared.knownNodesLock.release() - self.broadcastaddr(listOfAddressDetailsToBroadcastToPeers) - with shared.printLock: - print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.' + shared.needToWriteKnownNodesToDisk = True + hostDetails = ( + timeSomeoneElseReceivedMessageFromThisNode, + recaddrStream, recaddrServices, hostFromAddrMessage, recaddrPort) + #listOfAddressDetailsToBroadcastToPeers.append(hostDetails) + shared.broadcastToSendDataQueues(( + self.streamNumber, 'advertisepeer', hostDetails)) + else: + timeLastReceivedMessageFromThisNode = shared.knownNodes[recaddrStream][ + peerFromAddrMessage] # 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())): + shared.knownNodesLock.acquire() + shared.knownNodes[recaddrStream][peerFromAddrMessage] = timeSomeoneElseReceivedMessageFromThisNode + shared.knownNodesLock.release() + + #if listOfAddressDetailsToBroadcastToPeers != []: + # self.broadcastaddr(listOfAddressDetailsToBroadcastToPeers) + with shared.printLock: + print 'knownNodes currently has', len(shared.knownNodes[self.streamNumber]), 'nodes for this stream.' # Function runs when we want to broadcast an addr message to all of our # peers. Runs when we learn of nodes that we didn't previously know about # and want to share them with our peers. - def broadcastaddr(self, listOfAddressDetailsToBroadcastToPeers): + """def broadcastaddr(self, listOfAddressDetailsToBroadcastToPeers): numberOfAddressesInAddrMessage = len( listOfAddressDetailsToBroadcastToPeers) payload = '' @@ -1816,7 +1701,7 @@ class receiveDataThread(threading.Thread): print 'Broadcasting addr with', numberOfAddressesInAddrMessage, 'entries.' shared.broadcastToSendDataQueues(( - self.streamNumber, 'sendaddr', datatosend)) + self.streamNumber, 'sendaddr', datatosend))""" # Send a big addr message to our peer def sendaddr(self): @@ -1831,7 +1716,6 @@ class receiveDataThread(threading.Thread): shared.knownNodesLock.acquire() if len(shared.knownNodes[self.streamNumber]) > 0: for i in range(500): - random.seed() peer, = random.sample(shared.knownNodes[self.streamNumber], 1) if helper_generic.isHostInPrivateIPRange(peer.host): continue @@ -1839,7 +1723,6 @@ class receiveDataThread(threading.Thread): self.streamNumber][peer] if len(shared.knownNodes[self.streamNumber * 2]) > 0: for i in range(250): - random.seed() peer, = random.sample(shared.knownNodes[ self.streamNumber * 2], 1) if helper_generic.isHostInPrivateIPRange(peer.host): @@ -1848,7 +1731,6 @@ class receiveDataThread(threading.Thread): self.streamNumber * 2][peer] if len(shared.knownNodes[(self.streamNumber * 2) + 1]) > 0: for i in range(250): - random.seed() peer, = random.sample(shared.knownNodes[ (self.streamNumber * 2) + 1], 1) if helper_generic.isHostInPrivateIPRange(peer.host): @@ -1967,10 +1849,8 @@ class receiveDataThread(threading.Thread): self.peer, self.remoteProtocolVersion))) shared.knownNodesLock.acquire() - shared.knownNodes[self.streamNumber][self.peer] = int(time.time()) - output = open(shared.appdata + 'knownnodes.dat', 'wb') - pickle.dump(shared.knownNodes, output) - output.close() + shared.knownNodes[self.streamNumber][shared.Peer(self.peer.host, self.remoteNodeIncomingPort)] = int(time.time()) + shared.needToWriteKnownNodesToDisk = True shared.knownNodesLock.release() self.sendverack() diff --git a/src/class_sendDataThread.py b/src/class_sendDataThread.py index b939b06b..240f9c64 100644 --- a/src/class_sendDataThread.py +++ b/src/class_sendDataThread.py @@ -102,14 +102,31 @@ class sendDataThread(threading.Thread): print 'setting the remote node\'s protocol version in the sendData thread (ID:', id(self), ') to', specifiedRemoteProtocolVersion self.remoteProtocolVersion = specifiedRemoteProtocolVersion + elif command == 'advertisepeer': + self.objectHashHolderInstance.holdPeer(data) elif command == 'sendaddr': + numberOfAddressesInAddrMessage = len( + data) + payload = '' + for hostDetails in data: + timeLastReceivedMessageFromThisNode, streamNumber, services, host, port = hostDetails + payload += pack( + '>Q', timeLastReceivedMessageFromThisNode) # now uses 64-bit time + payload += pack('>I', streamNumber) + payload += pack( + '>q', services) # service bit flags offered by this node + payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + \ + socket.inet_aton(host) + payload += pack('>H', port) + + payload = encodeVarint(numberOfAddressesInAddrMessage) + payload + datatosend = '\xE9\xBE\xB4\xD9addr\x00\x00\x00\x00\x00\x00\x00\x00' + datatosend = datatosend + pack('>L', len(payload)) # payload length + datatosend = datatosend + hashlib.sha512(payload).digest()[0:4] + datatosend = datatosend + payload + 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. - time.sleep(random.randrange(0, 10)) - self.sock.sendall(data) + self.sock.sendall(datatosend) self.lastTimeISentData = int(time.time()) except: print 'sendaddr: self.sock.sendall failed' diff --git a/src/class_singleCleaner.py b/src/class_singleCleaner.py index 653a2461..44cb893c 100644 --- a/src/class_singleCleaner.py +++ b/src/class_singleCleaner.py @@ -2,7 +2,11 @@ import threading import shared import time import sys +import pickle + +import tr#anslate from helper_sql import * +from debug import logger '''The singleCleaner class is a timer-driven thread that cleans data structures to free memory, resends messages when a remote node doesn't respond, and sends pong messages to keep connections alive if the network isn't busy. It cleans these data structures in memory: @@ -124,4 +128,20 @@ class singleCleaner(threading.Thread): objectType, streamNumber, payload, receivedTime = storedValue if streamNumber in shared.inventorySets: shared.inventorySets[streamNumber].add(hash) + + # Let us write out the knowNodes to disk if there is anything new to write out. + if shared.needToWriteKnownNodesToDisk: + shared.knownNodesLock.acquire() + output = open(shared.appdata + 'knownnodes.dat', 'wb') + try: + pickle.dump(shared.knownNodes, output) + output.close() + except Exception as err: + if "Errno 28" in str(err): + logger.fatal('(while receiveDataThread shared.needToWriteKnownNodesToDisk) Alert: Your disk or data storage volume is full. ') + shared.UISignalQueue.put(('alert', (tr.translateText("MainWindow", "Disk full"), tr.translateText("MainWindow", 'Alert: Your disk or data storage volume is full. Bitmessage will now exit.'), True))) + if shared.daemon: + os._exit(0) + shared.knownNodesLock.release() + shared.needToWriteKnownNodesToDisk = False time.sleep(300) diff --git a/src/shared.py b/src/shared.py index 0c0173a3..22a6d890 100644 --- a/src/shared.py +++ b/src/shared.py @@ -69,6 +69,7 @@ numberOfPubkeysProcessed = 0 numberOfInventoryLookupsPerformed = 0 daemon = False inventorySets = {} # key = streamNumer, value = a set which holds the inventory object hashes that we are aware of. This is used whenever we receive an inv message from a peer to check to see what items are new to us. We don't delete things out of it; instead, the singleCleaner thread clears and refills it every couple hours. +needToWriteKnownNodesToDisk = False # If True, the singleCleaner will write it to disk eventually. #If changed, these values will cause particularly unexpected behavior: You won't be able to either send or receive messages because the proof of work you do (or demand) won't match that done or demanded by others. Don't change them! networkDefaultProofOfWorkNonceTrialsPerByte = 320 #The amount of work that should be performed (and demanded) per byte of the payload. Double this number to double the work. -- 2.45.1